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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
031240302/DouYuZB | DYZB/DYZB/Tools/Extension/UIBarButton-Extension.swift | 1 | 1370 | //
// UIBarButton-Extension.swift
// DYZB
//
// Created by kk on 2017/10/11.
// Copyright © 2017年 kk. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
/*
class func createItem(imageName: String, hightLightName: String, size: CGSize) -> UIBarButtonItem {
let btn = UIButton()
btn.setImage(UIImage(named: imageName), for: UIControlState.normal)
btn.setImage(UIImage(named: hightLightName), for: UIControlState.highlighted)
btn.frame = CGRect(origin: CGPoint.zero, size: size)
return UIBarButtonItem(customView: btn)
}
*/
//便利构造函数: 1>convinece开头 2>在构造函数中必须明确调用一个设计的构造函数(self)
convenience init(imageName: String, hightLightName: String? , size: CGSize?) {
//1.生成button
let btn = UIButton()
//2.设置图片
btn.setImage(UIImage(named: imageName), for: UIControlState.normal)
if let hightLightName = hightLightName {
btn.setImage(UIImage(named: hightLightName), for: UIControlState.highlighted)
}
//3.设置尺寸
if let size = size {
btn.frame = CGRect(origin: CGPoint.zero, size: size)
} else {
btn.sizeToFit()
}
//4.生成item
self.init(customView: btn)
}
}
| mit | eecba56b8d43bab7a7aebb153180fd74 | 29.595238 | 103 | 0.614786 | 4.053628 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/Demo/Modules/Demos/Components/QDNavigationTitleViewController.swift | 1 | 8175 | //
// QDNavigationTitleViewController.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/4/10.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
class QDNavigationTitleViewController: QDCommonListViewController {
private lazy var popupMenuView: QMUIPopupMenuView = {
let popupMenuView = QMUIPopupMenuView()
popupMenuView.automaticallyHidesWhenUserTap = true// 点击空白地方自动消失
popupMenuView.preferLayoutDirection = .below
popupMenuView.maximumWidth = 220
popupMenuView.items = [QMUIPopupMenuItem(image: UIImageMake("icon_emotion"), title: "分类 1", handler: nil),
QMUIPopupMenuItem(image: UIImageMake("icon_emotion"), title: "分类 2", handler: nil),
QMUIPopupMenuItem(image: UIImageMake("icon_emotion"), title: "分类 3", handler: nil)]
popupMenuView.didHideClosure = {[weak self] (hidesByUserTap: Bool) -> Void in
self?.titleView.isActive = false
}
return popupMenuView
}()
private var horizontalAlignment: UIControl.ContentHorizontalAlignment = .center
override init(style: UITableView.Style) {
super.init(style: style)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didInitialized() {
super.didInitialized()
titleView.needsLoadingView = true
titleView.qmui_needsDifferentDebugColor = true
horizontalAlignment = titleView.contentHorizontalAlignment
}
deinit {
titleView.delegate = nil
}
override func setNavigationItems(_ isInEditMode: Bool, animated: Bool) {
super.setNavigationItems(isInEditMode, animated: animated)
title = "主标题"
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if popupMenuView.isShowing {
popupMenuView.layout(with: titleView)
}
}
override func initDataSource() {
dataSource = ["显示左边的 loading",
"显示右边的 accessoryView",
"显示副标题",
"切换为上下两行显示",
"水平方向的对齐方式",
"模拟标题的 loading 状态切换",
"标题搭配浮层使用的示例",
"显示 Debug 背景色"]
}
// MARK: QMUITableViewDataSource, QMUITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// 因为有第 6 行的存在,所以每次都要重置一下这几个属性,避免影响其他 Demo 的展示
titleView.isUserInteractionEnabled = false
titleView.delegate = nil
switch indexPath.row {
case 0:
// 切换 loading 的显示/隐藏
titleView.loadingViewHidden = !titleView.loadingViewHidden
break
case 1:
// 切换右边的 accessoryType 类型,可支持自定义的 accessoryView
titleView.accessoryType = titleView.accessoryType == .none ? .disclosureIndicator : .none
break
case 2:
// 切换副标题的显示/隐藏
if titleView.subtitle == nil {
titleView.subtitle = "(副标题)"
} else {
titleView.subtitle = nil
}
break
case 3:
// 切换主副标题的水平/垂直布局
titleView.style = titleView.style == .default ? .subTitleVertical : .default
titleView.subtitle = titleView.style == .subTitleVertical ? "(副标题)" : titleView.subtitle
break
case 4:
// 水平对齐方式
let alertController = QMUIAlertController(title: "水平对齐方式", message: nil, preferredStyle: .sheet)
let action = QMUIAlertAction(title: "左对齐", style: .default) { (_) in
self.titleView.contentHorizontalAlignment = .left
self.horizontalAlignment = self.titleView.contentHorizontalAlignment
self.tableView.reloadData()
}
alertController.add(action: action)
alertController.add(action: QMUIAlertAction(title: "居中对齐", style: .default) { (_) in
self.titleView.contentHorizontalAlignment = .center
self.horizontalAlignment = self.titleView.contentHorizontalAlignment
self.tableView.reloadData()
})
alertController.add(action: QMUIAlertAction(title: "右对齐", style: .default) { (_) in
self.titleView.contentHorizontalAlignment = .right
self.horizontalAlignment = self.titleView.contentHorizontalAlignment
self.tableView.reloadData()
})
alertController.add(action: QMUIAlertAction(title: "取消", style: .cancel, handler: nil))
alertController.show(true)
break
case 5:
// 模拟不同状态之间的切换
titleView.loadingViewHidden = false
titleView.needsLoadingPlaceholderSpace = false
titleView.title = "加载中..."
titleView.subtitle = nil
titleView.style = .default
titleView.accessoryType = .none
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
self.titleView.needsLoadingPlaceholderSpace = true
self.titleView.loadingViewHidden = true
self.titleView.title = "微信"
}
break
case 6:
// 标题搭配浮层的使用示例
titleView.isUserInteractionEnabled = true // 要titleView支持点击,需要打开它的 userInteractionEnabled,这个属性默认是 NO
titleView.title = "点我展开分类"
titleView.accessoryType = .disclosureIndicator
titleView.delegate = self // 要监听 titleView 的点击事件以及状态切换,需要通过 delegate 的形式
break
case 7:
// Debug 背景色
titleView.qmui_shouldShowDebugColor = true
break
default:
break
}
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = (super.tableView(tableView, cellForRowAt: indexPath) as? QMUITableViewCell) else {
return UITableViewCell()
}
cell.accessoryType = .none
cell.detailTextLabel?.text = nil
switch indexPath.row {
case 0:
cell.textLabel?.text = titleView.loadingViewHidden ? "显示左边的 loading" : "隐藏左边的 loading"
break
case 1:
cell.textLabel?.text = titleView.accessoryType == .none ? "显示右边的 accessoryView" : "去掉右边的 accessoryView"
break
case 2:
cell.textLabel?.text = titleView.subtitle != nil ? "去掉副标题" : "显示副标题"
break
case 3:
cell.textLabel?.text = titleView.style == .default ? "切换为上下两行显示" : "切换为水平一行显示"
break
case 4:
var text: String?
if horizontalAlignment == .left {
text = "左对齐"
} else if horizontalAlignment == .right {
text = "右对齐"
} else {
text = "居中对齐"
}
cell.detailTextLabel?.text = text
break
default:
break
}
return cell
}
}
extension QDNavigationTitleViewController: QMUINavigationTitleViewDelegate {
func didChanged(_ active: Bool, for titleView: QMUINavigationTitleView) {
if active {
popupMenuView.layout(with: titleView)
popupMenuView.show(with: true)
}
}
}
| mit | 49093196dd6e1f7b3188be2cf3711add | 36.054187 | 115 | 0.582824 | 5.061911 | false | false | false | false |
kylef/JSONSchema.swift | Sources/Format/duration.swift | 1 | 1580 | import Foundation
/*
https://tools.ietf.org/html/rfc3339
Durations:
dur-second = 1*DIGIT "S"
dur-minute = 1*DIGIT "M" [dur-second]
dur-hour = 1*DIGIT "H" [dur-minute]
dur-time = "T" (dur-hour / dur-minute / dur-second)
dur-day = 1*DIGIT "D"
dur-week = 1*DIGIT "W"
dur-month = 1*DIGIT "M" [dur-day]
dur-year = 1*DIGIT "Y" [dur-month]
dur-date = (dur-day / dur-month / dur-year) [dur-time]
duration = "P" (dur-date / dur-time / dur-week)
*/
var durationExpression: NSRegularExpression = {
let second = "(\\d+S)"
let minute = "((\\d+M)\(second)?)"
let hour = "((\\d+H)\(minute)?)"
let time = "(T(\(hour)|\(minute)|\(second)))"
let day = "(\\d+D)"
let week = "(\\d+W)"
let month = "((\\d+M)\(day)?)"
let year = "((\\d+Y)\(month)?)"
let date = "((\(day)|\(month)|\(year))\(time)?)"
let duration = "^P(\(date)|\(time)|\(week))$"
return try! NSRegularExpression(pattern: duration, options: [])
}()
func isValidDuration(_ value: String) -> Bool {
return durationExpression.numberOfMatches(in: value, range: NSMakeRange(0, value.utf16.count)) != 0
}
func validateDuration(_ context: Context, _ value: String) -> AnySequence<ValidationError> {
guard isValidDuration(value) else {
return AnySequence([
ValidationError(
"'\(value)' is not a valid duration.",
instanceLocation: context.instanceLocation,
keywordLocation: context.keywordLocation
)
])
}
return AnySequence(EmptyCollection())
}
| bsd-3-clause | 52574b8951206b52aa2d0f08d03a27fa | 28.259259 | 101 | 0.575949 | 3.397849 | false | false | false | false |
Jean-Daniel/hadron | swift/Hadron/Stopwatch.swift | 1 | 1267 | //
// Stopwatch.swift
// Psymo
//
// Created by Jean-Daniel Dupas on 22/11/2018.
// Copyright © 2018 Xenonium. All rights reserved.
//
import Foundation
private let ABSOLUTE_TO_NANO_FACTOR : Double = {
var sTimebaseInfo = mach_timebase_info();
mach_timebase_info(&sTimebaseInfo);
return Double(sTimebaseInfo.numer) / Double(sTimebaseInfo.denom)
}()
struct StopWatch {
struct Unit {
fileprivate let factor : Double
func from(hostTime time: UInt64) -> Double {
return Double(time) * factor
}
static var seconds = Unit(factor: ABSOLUTE_TO_NANO_FACTOR / 1e9)
static var milliseconds = Unit(factor: ABSOLUTE_TO_NANO_FACTOR / 1e6)
static var microseconds = Unit(factor: ABSOLUTE_TO_NANO_FACTOR / 1e3)
static var nanoseconds = Unit(factor: ABSOLUTE_TO_NANO_FACTOR)
}
private var _start : UInt64 = 0
private var _stop : UInt64 = 0
mutating func start() {
_start = mach_absolute_time()
}
mutating func stop(unit: Unit) -> Double {
_stop = mach_absolute_time()
return unit.from(hostTime: _stop - _start)
}
static func run(_ unit: Unit = .seconds, function: () throws -> ()) rethrows -> Double {
var sw = StopWatch()
sw.start()
try function()
return sw.stop(unit: unit)
}
}
| mit | 6c8b7c4c69643f43f90dd7f9be55638f | 23.823529 | 90 | 0.663507 | 3.35809 | false | false | false | false |
svachmic/ios-url-remote | URLRemote/Classes/Persistence/DataSource.swift | 1 | 7249 | //
// DataSource.swift
// URLRemote
//
// Created by Michal Švácha on 14/07/2017.
// Copyright © 2017 Svacha, Michal. All rights reserved.
//
import Foundation
import ReactiveKit
/// Wrapper error for error distribution in ReactiveKit Signals.
enum AuthError: Error {
case error(error: Error?)
}
/// Data source authentication protocol encapsulating underlying authentication lyer for sign in/up operations.
protocol DataSourceAuthentication {
/// Returns signal with appropriately logged in DataSource object in the stream.
///
/// - Returns: Non-erroring signal emitting optional DataSource object. Nil when the user is logged out.
func dataSource() -> Signal<DataSource?, NoError>
/// Creates a new user in the persistence layer and loggs the user in.
///
/// - Parameter email: E-mail of the user.
/// - Parameter password: Password of the user.
/// - Returns: Signal emitting DataSource object bound to the user. Emits AuthError on error.
func createUser(email: String, password: String) -> Signal<DataSource, AuthError>
/// Logs the user in with the given credentials.
///
/// - Parameter email: E-mail of the user.
/// - Parameter password: Password of the user.
/// - Returns: Signal emitting DataSource object bound to the user. Emits AuthError on error.
func signIn(email: String, password: String) -> Signal<DataSource, AuthError>
/// Logs the user out.
func logOut()
}
/// Data source protocol encapsulating underlying persistence layer for CRUD operations.
protocol DataSource: class {
// MARK: - Read -
/// Returns a signal with categories from the underlying database structure.
///
/// - Returns: Non-erroring signal with an array of categories.
func categories() -> Signal<[Category], NoError>
/// Returns a signal with entries from the underlying database structure.
///
/// - Returns: Non-erroring signal with an array of entries.
func entries() -> Signal<[Entry], NoError>
/// Returns a signal with entries under a given category from the underlying database structure.
///
/// - Parameter category: Category containing returned entries.
/// - Returns: Non-erroring signal with an array of entries belonging to the given category.
func entries(under category: Category) -> Signal<[Entry], NoError>
// MARK: - Write -
/// Performs writing operation. If the category does not exist a new one is created. Otherwise the old one is updated.
///
/// - Parameter category: Category to be written in the database.
func update(_ category: Category)
// TODO: Should it be handled?
/// Deletes category from the database. Doesn't handle underlying entries.
///
/// - Parameter category: Category to be deleted.
func delete(_ category: Category)
/// Performs writing operation. If the entry does not exist a new one is created. Otherwise the old one is updated.
///
/// - Parameter entry: Entry to be written in the database.
func update(_ entry: Entry)
/// Performs batch writing operation. If any entry does not exist a new one is created.
///
/// - Parameter entries: Entries to be written in the database.
func update(batch entries: [Entry])
/// Adds the entry to the category and persists all changes. If neither of them exist, they are created.
///
/// - Parameter entry: Entry to be persisted and added to the given category.
/// - Parameter category: Category to be persisted holding the given entry.
func add(_ entry: Entry, to category: Category)
/// Moves entry from given source category to the other given category.
///
/// - Parameter entry: Entry to be moved.
/// - Parameter fromCategory: Category that currently owns the entry.
/// - Parameter toCategory: Category that will own the entry after this method gets performed.
func move(_ entry: Entry, from fromCategory: Category, to toCategory: Category)
/// Deletes entry from the database. Doesn't handle belonging to a category.
///
/// - Parameter entry: Entry to be deleted.
func delete(_ entry: Entry)
/// Deletes entry from the persistence layer and also removes it from the given category.
///
/// - Parameter entry: Entry to be deleted.
/// - Parameter category: Category from which the entry should be also removed.
func delete(entry: Entry, from category: Category)
}
/// Extension implementing features on top of basic methods provided by the protocol.
extension DataSource {
// MARK: - Private functions
/// Reindexes all entries under given category. Takes all entries sorted and assigns them their position in linear fashion.
///
/// - Parameter category: Category under which the entries should be reindexed.
private func reindexEntries(under category: Category) {
_ = self.entries(under: category).take(first: 1).observeNext { [unowned self] in
var entries = $0
for index in 0..<entries.count {
let entry = entries[index]
entry.order = index
}
self.update(batch: entries)
}
}
// MARK: - Public functions
/// Filters out category and then entries. Wraps them in a signal and returns.
func entries(under category: Category) -> Signal<[Entry], NoError> {
let categoriesFiltered = categories()
.filter { $0 == category }
return combineLatest(categoriesFiltered, entries()) { (categories, entries) -> [Entry] in
if let cat = categories.dataSource.array[safe: 0] {
return entries.filter { cat.contains(entry: $0) }
}
return []
}
}
/// Removes the entry from the first category and then reindexes it. After that adds the entry to the second category. That way the signals don't clash.
func move(_ entry: Entry, from fromCategory: Category, to toCategory: Category) {
fromCategory.remove(entry: entry)
self.update(fromCategory)
self.reindexEntries(under: fromCategory)
toCategory.add(entry: entry)
self.update(entry)
self.update(toCategory)
}
/// Performs update on each of the entries in the array.
func update(batch entries: [Entry]) {
for entry in entries {
self.update(entry)
}
}
/// First adds the entry to the category, updating its order. and then performs update.
func add(_ entry: Entry, to category: Category) {
// has to be performed before to assure existence of foreign keys
self.update(entry)
category.add(entry: entry)
// has to be also performed after because category modifies the order field
self.update(entry)
self.update(category)
}
/// First removes the entry from the category, then updates the category and then deletes the entry.
func delete(entry: Entry, from category: Category) {
category.remove(entry: entry)
self.update(category)
self.delete(entry)
}
}
| apache-2.0 | 72d2223f2fc55491776b0e531a4063cf | 38.813187 | 156 | 0.657328 | 4.779683 | false | false | false | false |
benlangmuir/swift | SwiftCompilerSources/Sources/SIL/WitnessTable.swift | 1 | 3757 | //===--- WitnessTable.swift -----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SILBridging
public struct WitnessTable : CustomStringConvertible, CustomReflectable {
public let bridged: BridgedWitnessTable
public init(bridged: BridgedWitnessTable) { self.bridged = bridged }
public struct Entry : CustomStringConvertible, CustomReflectable {
fileprivate let bridged: BridgedWitnessTableEntry
public enum Kind {
case invalid
case method
case associatedType
case associatedTypeProtocol
case baseProtocol
}
public var kind: Kind {
switch SILWitnessTableEntry_getKind(bridged) {
case SILWitnessTableEntry_Invalid: return .invalid
case SILWitnessTableEntry_Method: return .method
case SILWitnessTableEntry_AssociatedType: return .associatedType
case SILWitnessTableEntry_AssociatedTypeProtocol: return .associatedTypeProtocol
case SILWitnessTableEntry_BaseProtocol: return .baseProtocol
default:
fatalError("unknown witness table kind")
}
}
public var methodFunction: Function? {
assert(kind == .method)
return SILWitnessTableEntry_getMethodFunction(bridged).function
}
public var description: String {
let stdString = SILWitnessTableEntry_debugDescription(bridged)
return String(_cxxString: stdString)
}
public var customMirror: Mirror { Mirror(self, children: []) }
}
public struct EntryArray : BridgedRandomAccessCollection {
fileprivate let bridged: BridgedArrayRef
public var startIndex: Int { return 0 }
public var endIndex: Int { return Int(bridged.numElements) }
public subscript(_ index: Int) -> Entry {
precondition(index >= 0 && index < endIndex)
return Entry(bridged: BridgedWitnessTableEntry(ptr: bridged.data! + index &* BridgedWitnessTableEntrySize))
}
}
public var entries: EntryArray {
EntryArray(bridged: SILWitnessTable_getEntries(bridged))
}
public var description: String {
let stdString = SILWitnessTable_debugDescription(bridged)
return String(_cxxString: stdString)
}
public var customMirror: Mirror { Mirror(self, children: []) }
}
public struct DefaultWitnessTable : CustomStringConvertible, CustomReflectable {
public let bridged: BridgedDefaultWitnessTable
public init(bridged: BridgedDefaultWitnessTable) { self.bridged = bridged }
public typealias Entry = WitnessTable.Entry
public typealias EntryArray = WitnessTable.EntryArray
public var entries: EntryArray {
EntryArray(bridged: SILDefaultWitnessTable_getEntries(bridged))
}
public var description: String {
let stdString = SILDefaultWitnessTable_debugDescription(bridged)
return String(_cxxString: stdString)
}
public var customMirror: Mirror { Mirror(self, children: []) }
}
extension OptionalBridgedWitnessTable {
public var table: WitnessTable? {
if let p = ptr {
return WitnessTable(bridged: BridgedWitnessTable(ptr: p))
}
return nil
}
}
extension OptionalBridgedDefaultWitnessTable {
public var table: DefaultWitnessTable? {
if let p = ptr {
return DefaultWitnessTable(bridged: BridgedDefaultWitnessTable(ptr: p))
}
return nil
}
}
| apache-2.0 | 24381f8c6eb1f8c3e4c6df66a75886ca | 31.387931 | 113 | 0.691775 | 5.070175 | false | false | false | false |
0x4a616e/ArtlessEdit | ArtlessEdit/OpenFileData.swift | 1 | 873 | //
// OpenFileData.swift
// ArtlessEdit
//
// Created by Jan Gassen on 23/12/14.
// Copyright (c) 2014 Jan Gassen. All rights reserved.
//
import Foundation
class OpenFileData: FileData {
override func load() {
suggestions = []
}
override func update(value: String) {
let path = value.stringByStandardizingPath
var isDir: ObjCBool = false
fileManager.fileExistsAtPath(path, isDirectory: &isDir)
if (isDir) {
currentDirectory = path
currentFiles = fileManager.contentsOfDirectoryAtPath(currentDirectory, error: nil) as [String]? ?? []
suggestions = currentFiles
} else {
let lastComponent = path.lastPathComponent
suggestions = currentFiles.filter({(e : String) -> Bool in e.hasPrefix(lastComponent)})
}
}
} | bsd-3-clause | 460e2e6fc9ce926f1dbd01b365f88dd3 | 25.484848 | 113 | 0.609393 | 4.770492 | false | false | false | false |
overtake/TelegramSwift | packages/InAppSettings/Sources/InAppSettings/VoiceCallSettings.swift | 1 | 11444 | //
// VoiceCallSettings.swift
// Telegram
//
// Created by keepcoder on 18/04/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import Postbox
import SwiftSignalKit
import TelegramCore
import KeyboardKey
public enum VoiceCallDataSaving: Int32 {
case never
case cellular
case always
}
public struct PushToTalkValue : Equatable, Codable {
public struct ModifierFlag : Equatable, Codable {
public let keyCode: UInt16
public let flag: UInt
public init(keyCode: UInt16, flag: UInt) {
self.keyCode = keyCode
self.flag = flag
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(Int32(self.keyCode), forKey: "kc")
try container.encode(Int64(bitPattern: UInt64(flag)), forKey: "f")
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.keyCode = UInt16(try container.decode(Int32.self, forKey: "kc"))
self.flag = UInt(bitPattern: Int(try container.decode(Int64.self, forKey: "f")))
}
}
public var isSpace: Bool {
return keyCodes == [KeyboardKey.Space.rawValue] && modifierFlags.isEmpty && otherMouse.isEmpty
}
public var keyCodes: [UInt16]
public var modifierFlags: [ModifierFlag]
public var string: String
public var otherMouse: [Int]
public init(keyCodes: [UInt16], otherMouse: [Int], modifierFlags: [ModifierFlag], string: String) {
self.keyCodes = keyCodes
self.modifierFlags = modifierFlags
self.string = string
self.otherMouse = otherMouse
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.modifierFlags, forKey: "mf")
try container.encode(self.keyCodes.map { Int32($0) }, forKey: "kc")
try container.encode(string, forKey: "s")
try container.encode(self.otherMouse.map { Int64($0) }, forKey: "om")
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.keyCodes = try container.decode([Int32].self, forKey: "kc").map { UInt16($0) }
self.modifierFlags = try container.decode([ModifierFlag].self, forKey: "mf")
self.string = try container.decode(String.self, forKey: "s")
self.otherMouse = try container.decode([Int64].self, forKey: "om").map { Int($0) }
}
}
public enum VoiceChatInputMode : Int32 {
case none = 0
case always = 1
case pushToTalk = 2
}
public struct VoiceCallSettings: Codable, Equatable {
public enum Tooltip : Int32 {
case camera = 0
}
public let audioInputDeviceId: String?
public let cameraInputDeviceId: String?
public let audioOutputDeviceId: String?
public let mode: VoiceChatInputMode
public let pushToTalk: PushToTalkValue?
public let pushToTalkSoundEffects: Bool
public let noiseSuppression: Bool
public let tooltips:[Tooltip]
public static var defaultSettings: VoiceCallSettings {
return VoiceCallSettings(audioInputDeviceId: nil, cameraInputDeviceId: nil, audioOutputDeviceId: nil, mode: .always, pushToTalk: nil, pushToTalkSoundEffects: false, noiseSuppression: true, tooltips: [.camera])
}
public init(audioInputDeviceId: String?, cameraInputDeviceId: String?, audioOutputDeviceId: String?, mode: VoiceChatInputMode, pushToTalk: PushToTalkValue?, pushToTalkSoundEffects: Bool, noiseSuppression: Bool, tooltips: [Tooltip]) {
self.audioInputDeviceId = audioInputDeviceId
self.cameraInputDeviceId = cameraInputDeviceId
self.audioOutputDeviceId = audioOutputDeviceId
self.pushToTalk = pushToTalk
self.mode = mode
self.pushToTalkSoundEffects = pushToTalkSoundEffects
self.noiseSuppression = noiseSuppression
self.tooltips = tooltips
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.audioInputDeviceId = try container.decodeIfPresent(String.self, forKey: "ai")
self.cameraInputDeviceId = try container.decodeIfPresent(String.self, forKey: "ci")
self.audioOutputDeviceId = try container.decodeIfPresent(String.self, forKey: "ao")
self.pushToTalk = try container.decodeIfPresent(PushToTalkValue.self, forKey: "ptt3")
self.mode = VoiceChatInputMode(rawValue: try container.decodeIfPresent(Int32.self, forKey: "m1") ?? 0) ?? .none
self.pushToTalkSoundEffects = try container.decodeIfPresent(Bool.self, forKey: "se") ?? false
self.noiseSuppression = try container.decodeIfPresent(Bool.self, forKey: "ns") ?? false
self.tooltips = try container.decode([Int32].self, forKey: "tt").compactMap { Tooltip(rawValue: $0) }
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
if let audioInputDeviceId = audioInputDeviceId {
try container.encode(audioInputDeviceId, forKey: "ai")
} else {
try container.encodeNil(forKey: "ai")
}
if let cameraInputDeviceId = cameraInputDeviceId {
try container.encode(cameraInputDeviceId, forKey: "ci")
} else {
try container.encodeNil(forKey: "ci")
}
if let audioOutputDeviceId = audioOutputDeviceId {
try container.encode(audioOutputDeviceId, forKey: "ao")
} else {
try container.encodeNil(forKey: "ao")
}
if let pushToTalk = pushToTalk {
try container.encode(pushToTalk, forKey: "ptt3")
} else {
try container.encodeNil(forKey: "ptt3")
}
try container.encode(self.mode.rawValue, forKey: "m1")
try container.encode(pushToTalkSoundEffects, forKey: "se")
try container.encode(noiseSuppression, forKey: "ns")
try container.encode(self.tooltips.map { $0.rawValue }, forKey: "tt")
}
public func withUpdatedAudioInputDeviceId(_ audioInputDeviceId: String?) -> VoiceCallSettings {
return VoiceCallSettings(audioInputDeviceId: audioInputDeviceId, cameraInputDeviceId: self.cameraInputDeviceId, audioOutputDeviceId: self.audioOutputDeviceId, mode: self.mode, pushToTalk: self.pushToTalk, pushToTalkSoundEffects: self.pushToTalkSoundEffects, noiseSuppression: self.noiseSuppression, tooltips: self.tooltips)
}
public func withUpdatedCameraInputDeviceId(_ cameraInputDeviceId: String?) -> VoiceCallSettings {
return VoiceCallSettings(audioInputDeviceId: self.audioInputDeviceId, cameraInputDeviceId: cameraInputDeviceId, audioOutputDeviceId: self.audioOutputDeviceId, mode: self.mode, pushToTalk: self.pushToTalk, pushToTalkSoundEffects: self.pushToTalkSoundEffects, noiseSuppression: self.noiseSuppression, tooltips: self.tooltips)
}
public func withUpdatedAudioOutputDeviceId(_ audioOutputDeviceId: String?) -> VoiceCallSettings {
return VoiceCallSettings(audioInputDeviceId: self.audioInputDeviceId, cameraInputDeviceId: self.cameraInputDeviceId, audioOutputDeviceId: audioOutputDeviceId, mode: self.mode, pushToTalk: self.pushToTalk, pushToTalkSoundEffects: self.pushToTalkSoundEffects, noiseSuppression: self.noiseSuppression, tooltips: self.tooltips)
}
public func withUpdatedPushToTalk(_ pushToTalk: PushToTalkValue?) -> VoiceCallSettings {
return VoiceCallSettings(audioInputDeviceId: self.audioInputDeviceId, cameraInputDeviceId: self.cameraInputDeviceId, audioOutputDeviceId: self.audioOutputDeviceId, mode: self.mode, pushToTalk: pushToTalk, pushToTalkSoundEffects: self.pushToTalkSoundEffects, noiseSuppression: self.noiseSuppression, tooltips: self.tooltips)
}
public func withUpdatedMode(_ mode: VoiceChatInputMode) -> VoiceCallSettings {
return VoiceCallSettings(audioInputDeviceId: self.audioInputDeviceId, cameraInputDeviceId: self.cameraInputDeviceId, audioOutputDeviceId: self.audioOutputDeviceId, mode: mode, pushToTalk: self.pushToTalk, pushToTalkSoundEffects: self.pushToTalkSoundEffects, noiseSuppression: self.noiseSuppression, tooltips: self.tooltips)
}
public func withUpdatedSoundEffects(_ pushToTalkSoundEffects: Bool) -> VoiceCallSettings {
return VoiceCallSettings(audioInputDeviceId: self.audioInputDeviceId, cameraInputDeviceId: self.cameraInputDeviceId, audioOutputDeviceId: self.audioOutputDeviceId, mode: self.mode, pushToTalk: self.pushToTalk, pushToTalkSoundEffects: pushToTalkSoundEffects, noiseSuppression: self.noiseSuppression, tooltips: self.tooltips)
}
public func withUpdatedNoiseSuppression(_ noiseSuppression: Bool) -> VoiceCallSettings {
return VoiceCallSettings(audioInputDeviceId: self.audioInputDeviceId, cameraInputDeviceId: self.cameraInputDeviceId, audioOutputDeviceId: self.audioOutputDeviceId, mode: self.mode, pushToTalk: self.pushToTalk, pushToTalkSoundEffects: self.pushToTalkSoundEffects, noiseSuppression: noiseSuppression, tooltips: self.tooltips)
}
public func withRemovedTooltip(_ tooltip: Tooltip) -> VoiceCallSettings {
var tooltips = self.tooltips
tooltips.removeAll(where: { $0 == tooltip })
return VoiceCallSettings(audioInputDeviceId: self.audioInputDeviceId, cameraInputDeviceId: self.cameraInputDeviceId, audioOutputDeviceId: self.audioOutputDeviceId, mode: self.mode, pushToTalk: self.pushToTalk, pushToTalkSoundEffects: self.pushToTalkSoundEffects, noiseSuppression: self.noiseSuppression, tooltips: tooltips)
}
public func withUpdatedVisualEffects(_ visualEffects: Bool) -> VoiceCallSettings {
return VoiceCallSettings(audioInputDeviceId: self.audioInputDeviceId, cameraInputDeviceId: self.cameraInputDeviceId, audioOutputDeviceId: self.audioOutputDeviceId, mode: self.mode, pushToTalk: self.pushToTalk, pushToTalkSoundEffects: self.pushToTalkSoundEffects, noiseSuppression: self.noiseSuppression, tooltips: tooltips)
}
}
public func updateVoiceCallSettingsSettingsInteractively(accountManager: AccountManager<TelegramAccountManagerTypes>, _ f: @escaping (VoiceCallSettings) -> VoiceCallSettings) -> Signal<Void, NoError> {
return accountManager.transaction { transaction -> Void in
transaction.updateSharedData(ApplicationSharedPreferencesKeys.voiceCallSettings, { entry in
let currentSettings: VoiceCallSettings
if let entry = entry?.get(VoiceCallSettings.self) {
currentSettings = entry
} else {
currentSettings = VoiceCallSettings.defaultSettings
}
return PreferencesEntry(f(currentSettings))
})
}
}
public func voiceCallSettings(_ accountManager: AccountManager<TelegramAccountManagerTypes>) -> Signal<VoiceCallSettings, NoError> {
return accountManager.sharedData(keys: [ApplicationSharedPreferencesKeys.voiceCallSettings]) |> map { view in
return view.entries[ApplicationSharedPreferencesKeys.voiceCallSettings]?.get(VoiceCallSettings.self) ?? VoiceCallSettings.defaultSettings
}
}
| gpl-2.0 | 14e1cb3f722ffb368e2e195add52953a | 52.471963 | 331 | 0.723062 | 4.478669 | false | false | false | false |
danielsaidi/iExtra | iExtra/UI/Modals/PannableModalPresenter.swift | 1 | 4228 | import UIKit
public final class PannableModalPresenter: NSObject {
// MARK: - Initialization
public override init() {
super.init()
PannableModalPresenter.cache.append(self)
}
deinit {
print("PannableModalPresenter: Deinit")
}
// MARK: - Properties
private static var cache = [PannableModalPresenter]()
private var panGesture: UIPanGestureRecognizer?
private let transition = InteractiveModalTransition()
private weak var viewController: UIViewController?
// MARK: - Public Functions
public static func disablePanGesture(for vc: UIViewController) {
presenter(for: vc)?.panGesture?.isEnabled = false
}
public static func enablePanGesture(for vc: UIViewController) {
presenter(for: vc)?.panGesture?.isEnabled = true
}
public static func present(vc: UIViewController, from: UIViewController) {
let presenter = PannableModalPresenter()
presenter.viewController = vc
vc.transitioningDelegate = presenter
from.present(vc, animated: true) {
presenter.addPanGesture(to: vc.view)
}
}
public static func presenter(for vc: UIViewController) -> PannableModalPresenter? {
return cache.first { $0.viewController == vc }
}
}
// MARK: - Deallocation
private extension PannableModalPresenter {
static func destroy(presenter: PannableModalPresenter?) {
guard let presenter = presenter else { return }
presenter.destroyPanGesture()
guard let index = cache.firstIndex(of: presenter) else { return }
cache.remove(at: index)
}
func destroyPanGesture() {
guard let pan = panGesture else { return }
viewController?.view.removeGestureRecognizer(pan)
panGesture = nil
}
}
// MARK: - Selectors
@objc extension PannableModalPresenter {
func handlePanGesture(pan: UIPanGestureRecognizer) {
guard let view = pan.view else { return }
let percentThreshold: CGFloat = 0.3
let translation = pan.translation(in: view)
let verticalMovement = translation.y / view.bounds.height
let downwardMovement = fmaxf(Float(verticalMovement), 0.0)
let downwardMovementPercent = fminf(downwardMovement, 1.0)
let progress = CGFloat(downwardMovementPercent)
switch pan.state {
case .began:
transition.hasStarted = true
viewController?.dismiss(animated: true)
case .changed:
transition.shouldFinish = progress > percentThreshold
transition.update(progress)
case .cancelled:
transition.hasStarted = false
transition.cancel()
case .ended:
transition.hasStarted = false
transition.shouldFinish ? transition.finish(): transition.cancel()
default:
break
}
}
}
// MARK: - Private Functions
private extension PannableModalPresenter {
func addPanGesture(to view: UIView?) {
guard let view = view else { return }
let action = #selector(handlePanGesture(pan:))
let pan = UIPanGestureRecognizer(target: self, action: action)
view.addGestureRecognizer(pan)
panGesture = pan
}
}
// MARK: - PannableModalDismissAnimatorDelegate
extension PannableModalPresenter: PannableModalDismissAnimatorDelegate {
public func dismissAnimatorDidDismiss(_ animator: PannableModalDismissAnimator) {
PannableModalPresenter.destroy(presenter: self)
}
}
// MARK: - UIViewControllerTransitioningDelegate
extension PannableModalPresenter: UIViewControllerTransitioningDelegate {
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animator = PannableModalDismissAnimator()
animator.delegate = self
return animator
}
public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return transition.hasStarted ? transition: nil
}
}
| mit | 0615cce67fef4d841171fb83358cb590 | 28.774648 | 151 | 0.665799 | 5.18773 | false | false | false | false |
uasys/swift | test/SILOptimizer/specialize_unconditional_checked_cast.swift | 4 | 16295 | // RUN: %target-swift-frontend -Xllvm -sil-disable-pass="Function Signature Optimization" -emit-sil -o - -O %s | %FileCheck %s
//////////////////
// Declarations //
//////////////////
public class C {}
public class D : C {}
public class E {}
public struct NotUInt8 { var value: UInt8 }
public struct NotUInt64 { var value: UInt64 }
var b = NotUInt8(value: 0)
var c = C()
var d = D()
var e = E()
var f = NotUInt64(value: 0)
var o : AnyObject = c
////////////////////////////
// Archetype To Archetype //
////////////////////////////
@inline(never)
public func ArchetypeToArchetype<T1, T2>(t t: T1, t2: T2) -> T2 {
return t as! T2
}
ArchetypeToArchetype(t: b, t2: b)
ArchetypeToArchetype(t: c, t2: c)
ArchetypeToArchetype(t: b, t2: c)
ArchetypeToArchetype(t: c, t2: b)
ArchetypeToArchetype(t: c, t2: d)
ArchetypeToArchetype(t: d, t2: c)
ArchetypeToArchetype(t: c, t2: e)
ArchetypeToArchetype(t: b, t2: f)
// x -> x where x is not a class.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA8NotUInt8V{{.*}}Tg5 : $@convention(thin) (NotUInt8, NotUInt8) -> NotUInt8 {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA1CC{{.*}}Tg5 : $@convention(thin) (@owned C, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x is not a class but y is.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA8NotUInt8V_AA1CCTg5 : $@convention(thin) (NotUInt8, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast_addr
// CHECK-NOT: unconditional_checked_cast_addr
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast_addr
// y -> x where x is not a class but y is.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA1CC_AA8NotUInt8VTg5 : $@convention(thin) (@owned C, NotUInt8) -> NotUInt8 {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA1CC_AA1DCTg5 : $@convention(thin) (@owned C, @owned D) -> @owned D {
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $C
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK: unconditional_checked_cast_addr C in [[STACK]] : $*C to D in
// y -> x where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA1DC_AA1CCTg5 : $@convention(thin) (@owned D, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: upcast {{%[0-9]+}} : $D to $C
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x and y are unrelated classes.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA1CC_AA1ECTg5 : $@convention(thin) (@owned C, @owned E) -> @owned E {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x and y are unrelated non classes.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA8NotUInt8V_AA0H6UInt64VTg5 : $@convention(thin) (NotUInt8, NotUInt64) -> NotUInt64 {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
///////////////////////////
// Archetype To Concrete //
///////////////////////////
@inline(never)
public func ArchetypeToConcreteConvertUInt8<T>(t t: T) -> NotUInt8 {
return t as! NotUInt8
}
ArchetypeToConcreteConvertUInt8(t: b)
ArchetypeToConcreteConvertUInt8(t: c)
ArchetypeToConcreteConvertUInt8(t: f)
// x -> x where x is not a class.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8{{[_0-9a-zA-Z]*}}3Not{{.*}}Tg5 : $@convention(thin) (NotUInt8) -> NotUInt8 {
// CHECK: bb0
// CHECK-NEXT: debug_value %0
// TODO: the second debug_value is redundant and should be removed
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: return %0
// x -> y where y is a class but x is not.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8{{[_0-9a-zA-Z]*}}FAA1CC_Tg5
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x,y are not classes and x is a different type from y.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8{{[_0-9a-zA-Z]*}}3Not{{.*}}Tg5
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{[_0-9a-zA-Z]*}}Tg5 : $@convention(thin) (@owned C) -> @owned C {
// CHECK: bb0
// CHECK-NEXT: debug_value %0
// CHECK: return %0
// x -> y where x is a class but y is not.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{[_0-9a-zA-Z]*}}FAA8NotUInt8V_Tg5
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x,y are classes and x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{[_0-9a-zA-Z]*}}FAA1DC_Tg5 : $@convention(thin) (@owned D) -> @owned C {
// CHECK: bb0
// CHECK-NEXT: debug_value %0
// CHECK: [[UC:%[0-9]+]] = upcast %0
// CHECK-NEXT: return [[UC]]
// x -> y where x,y are classes, but x is unrelated to y.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{[_0-9a-zA-Z]*}}FAA1EC_Tg5
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
@inline(never)
public func ArchetypeToConcreteConvertC<T>(t t: T) -> C {
return t as! C
}
ArchetypeToConcreteConvertC(t: c)
ArchetypeToConcreteConvertC(t: b)
ArchetypeToConcreteConvertC(t: d)
ArchetypeToConcreteConvertC(t: e)
@inline(never)
public func ArchetypeToConcreteConvertD<T>(t t: T) -> D {
return t as! D
}
ArchetypeToConcreteConvertD(t: c)
// x -> y where x,y are classes and x is a sub class of y.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast27ArchetypeToConcreteConvertD{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 : $@convention(thin) (@owned C) -> @owned D {
// CHECK: bb0(%0 : $C):
// CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $C
// CHECK-DAG: store %0 to [[STACK_C]]
// CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK-DAG: unconditional_checked_cast_addr C in [[STACK_C]] : $*C to D in [[STACK_D]] : $*D
// CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]]
// CHECK: return [[LOAD]]
@inline(never)
public func ArchetypeToConcreteConvertE<T>(t t: T) -> E {
return t as! E
}
ArchetypeToConcreteConvertE(t: c)
// x -> y where x,y are classes, but y is unrelated to x. The idea is
// to make sure that the fact that y is concrete does not affect the
// result.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast27ArchetypeToConcreteConvertE{{[_0-9a-zA-Z]*}}FAA1CC_Tg5
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
///////////////////////////
// Concrete to Archetype //
///////////////////////////
@inline(never)
public func ConcreteToArchetypeConvertUInt8<T>(t t: NotUInt8, t2: T) -> T {
return t as! T
}
ConcreteToArchetypeConvertUInt8(t: b, t2: b)
ConcreteToArchetypeConvertUInt8(t: b, t2: c)
ConcreteToArchetypeConvertUInt8(t: b, t2: f)
// x -> x where x is not a class.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{[_0-9a-zA-Z]*}}3Not{{.*}}Tg5 : $@convention(thin) (NotUInt8, NotUInt8) -> NotUInt8 {
// CHECK: bb0(%0 : $NotUInt8, %1 : $NotUInt8):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: return %0
// x -> y where x is not a class but y is a class.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 : $@convention(thin) (NotUInt8, @owned C) -> @owned C {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x,y are different non class types.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{[_0-9a-zA-Z]*}}Not{{.*}}Tg5 : $@convention(thin) (NotUInt8, NotUInt64) -> NotUInt64 {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
@inline(never)
public func ConcreteToArchetypeConvertC<T>(t t: C, t2: T) -> T {
return t as! T
}
ConcreteToArchetypeConvertC(t: c, t2: c)
ConcreteToArchetypeConvertC(t: c, t2: b)
ConcreteToArchetypeConvertC(t: c, t2: d)
ConcreteToArchetypeConvertC(t: c, t2: e)
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{[_0-9a-zA-Z]*}}Tg5 : $@convention(thin) (@owned C, @owned C) -> @owned C {
// CHECK: bb0(%0 : $C, %1 : $C):
// CHECK: strong_release %1
// CHECK: return %0
// x -> y where x is a class but y is not.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{[_0-9a-zA-Z]*}}Not{{.*}}Tg5 : $@convention(thin) (@owned C, NotUInt8) -> NotUInt8 {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{[_0-9a-zA-Z]*}}FAA1DC_Tg5 : $@convention(thin) (@owned C, @owned D) -> @owned D {
// CHECK: bb0(%0 : $C, %1 : $D):
// CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $C
// CHECK-DAG: store %0 to [[STACK_C]]
// CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK-DAG: unconditional_checked_cast_addr C in [[STACK_C]] : $*C to D in [[STACK_D]] : $*D
// CHECK-DAG: strong_release %1
// CHECK-DAG: strong_release %0
// CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]]
// CHECK: return [[LOAD]]
// x -> y where x and y are unrelated classes.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{[_0-9a-zA-Z]*}}FAA1EC_Tg5 : $@convention(thin) (@owned C, @owned E) -> @owned E {
// CHECK: bb0(%0 : $C, %1 : $E):
// CHECK-NEXT: builtin "int_trap"
// CHECK-NEXT: unreachable
// CHECK-NEXT: }
@inline(never)
public func ConcreteToArchetypeConvertD<T>(t t: D, t2: T) -> T {
return t as! T
}
ConcreteToArchetypeConvertD(t: d, t2: c)
// x -> y where x is a subclass of y.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast27ConcreteToArchetypeConvertD{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 : $@convention(thin) (@owned D, @owned C) -> @owned C {
// CHECK: bb0(%0 : $D, %1 : $C):
// CHECK-DAG: [[UC:%[0-9]+]] = upcast %0
// CHECK-DAG: strong_release %1
// CHECK: return [[UC]]
////////////////////////
// Super To Archetype //
////////////////////////
@inline(never)
public func SuperToArchetypeC<T>(c c : C, t : T) -> T {
return c as! T
}
SuperToArchetypeC(c: c, t: c)
SuperToArchetypeC(c: c, t: d)
SuperToArchetypeC(c: c, t: b)
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast17SuperToArchetypeC{{[_0-9a-zA-Z]*}}Tg5 : $@convention(thin) (@owned C, @owned C) -> @owned C {
// CHECK: bb0(%0 : $C, %1 : $C):
// CHECK: strong_release %1
// CHECK: return %0
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast17SuperToArchetypeC{{[_0-9a-zA-Z]*}}FAA1DC_Tg5 : $@convention(thin) (@owned C, @owned D) -> @owned D {
// CHECK: bb0
// CHECK: unconditional_checked_cast_addr C in
// x -> y where x is a class and y is not.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast17SuperToArchetypeC{{[_0-9a-zA-Z]*}}FAA8NotUInt8V_Tg5 : $@convention(thin) (@owned C, NotUInt8) -> NotUInt8 {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
@inline(never)
public func SuperToArchetypeD<T>(d d : D, t : T) -> T {
return d as! T
}
SuperToArchetypeD(d: d, t: c)
SuperToArchetypeD(d: d, t: d)
// *NOTE* The frontend is smart enough to turn this into an upcast. When this
// test is converted to SIL, this should be fixed appropriately.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast17SuperToArchetypeD{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 : $@convention(thin) (@owned D, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast super_to_archetype
// CHECK: upcast
// CHECK-NOT: unconditional_checked_cast super_to_archetype
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast17SuperToArchetypeD{{[_0-9a-zA-Z]*}}Tg5 : $@convention(thin) (@owned D, @owned D) -> @owned D {
// CHECK: bb0(%0 : $D, %1 : $D):
// CHECK: strong_release %1
// CHECK: return %0
//////////////////////////////
// Existential To Archetype //
//////////////////////////////
@inline(never)
public func ExistentialToArchetype<T>(o o : AnyObject, t : T) -> T {
return o as! T
}
// AnyObject -> Class.
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast22ExistentialToArchetype{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 : $@convention(thin) (@owned AnyObject, @owned C) -> @owned C {
// CHECK: unconditional_checked_cast_addr AnyObject in {{%.*}} : $*AnyObject to C
// AnyObject -> Non Class (should always fail)
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast22ExistentialToArchetype{{[_0-9a-zA-Z]*}}FAA8NotUInt8V_Tg5 : $@convention(thin) (@owned AnyObject, NotUInt8) -> NotUInt8 {
// CHECK-NOT: builtin "int_trap"()
// CHECK-NOT: unreachable
// CHECK: return
// AnyObject -> AnyObject
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast22ExistentialToArchetype{{[_0-9a-zA-Z]*}}yXl{{.*}}Tg5 : $@convention(thin) (@owned AnyObject, @owned AnyObject) -> @owned AnyObject {
// CHECK: bb0(%0 : $AnyObject, %1 : $AnyObject):
// CHECK: strong_release %1
// CHECK: return %0
ExistentialToArchetype(o: o, t: c)
ExistentialToArchetype(o: o, t: b)
ExistentialToArchetype(o: o, t: o)
// Ensure that a downcast from an Optional source is not promoted to a
// value cast. We could do the promotion, but the optimizer would need
// to insert the Optional unwrapping logic before the cast.
//
// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast15genericDownCastq_x_q_mtr0_lFAA1CCSg_AA1DCTg5 : $@convention(thin) (@owned Optional<C>, @thick D.Type) -> @owned D {
// CHECK: bb0(%0 : $Optional<C>, %1 : $@thick D.Type):
// CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D
// CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $Optional<C>
// CHECK-DAG: store %0 to [[STACK_C]]
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK-DAG: unconditional_checked_cast_addr Optional<C> in [[STACK_C]] : $*Optional<C> to D in [[STACK_D]] : $*D
// CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]]
// CHECK: return [[LOAD]]
@inline(never)
public func genericDownCast<T, U>(_ a: T, _ : U.Type) -> U {
return a as! U
}
public func callGenericDownCast(_ c: C?) -> D {
return genericDownCast(c, D.self)
}
| apache-2.0 | 51344c7a42f15a18fbc1072d9de3ac40 | 41.215026 | 214 | 0.680209 | 3.205784 | false | false | false | false |
4074/UDatePicker | UDatePicker.swift | 1 | 4611 | //
// DatePickerView.swift
//
// Created by 4074 on 16/6/12.
// Copyright © 2016年 4074. All rights reserved.
//
import UIKit
open class UDatePicker: UIViewController {
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open var picker: UDatePickerView!
public init(frame: CGRect, willDisappear: ((Date?) -> Void)? = nil, didDisappear: ((Date?) -> Void)? = nil) {
super.init(nibName: nil, bundle: nil)
self.modalPresentationStyle = UIModalPresentationStyle.overFullScreen
// init picker view
let view = UDatePickerView(frame: frame)
view.completion = { date in
if willDisappear != nil {
willDisappear!(date)
}
self.dismiss(animated: true) {
if didDisappear != nil {
didDisappear!(date)
}
}
}
picker = view
self.view = view
}
// present the view controller
open func present(_ previous: UIViewController) {
previous.present(self, animated: true, completion: nil)
}
open class UDatePickerView: UIView {
fileprivate var completion: ((Date?) -> Void)?
// current date be shown
open var date = Date() {
didSet {
datePicker.setDate(date, animated: false)
}
}
open var duration = 0.4
// height of views
open var height = (
widget: CGFloat(248),
picker: CGFloat(216),
bar: CGFloat(32)
)
public let widgetView = UIView()
public let blankView = UIView()
public let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight))
public let datePicker = UIDatePicker()
public let barView = UIView()
public let doneButton = UIButton()
override init(frame: CGRect) {
super.init(frame: frame)
initView()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func layoutSubviews() {
let frame = self.frame
// reset frame of views
widgetView.frame = CGRect(x: 0, y: frame.height - height.widget, width: frame.width, height: height.widget)
blankView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height - height.widget)
datePicker.frame = CGRect(x: 0, y: height.bar, width: frame.width, height: height.picker)
barView.frame = CGRect(x: 0, y: 0, width: frame.width, height: height.bar)
blurView.frame = barView.frame
// set button flexible width, with 16 padding
doneButton.sizeToFit()
let width = doneButton.frame.size.width + 16
doneButton.frame = CGRect(x: frame.width - width, y: 0, width: width, height: height.bar)
}
fileprivate func initView() {
self.addSubview(widgetView)
// blur view
widgetView.addSubview(blurView)
blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// blank view
self.addSubview(blankView)
let tapBlankGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleBlankView))
blankView.addGestureRecognizer(tapBlankGesture)
// date picker view
widgetView.addSubview(datePicker)
datePicker.datePickerMode = .date
datePicker.backgroundColor = UIColor.white
// bar view and done button
widgetView.addSubview(barView)
barView.addSubview(doneButton)
doneButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
doneButton.setTitle("Done", for: UIControl.State())
doneButton.setTitleColor(self.tintColor, for: UIControl.State())
doneButton.addTarget(self, action: #selector(self.handleDoneButton), for: .touchUpInside)
}
@objc func handleBlankView() {
if completion != nil {
completion!(nil)
}
}
@objc func handleDoneButton() {
if completion != nil {
completion!(datePicker.date)
}
}
}
}
| mit | 4bee020d1857b85da4d52d25e5953e79 | 32.391304 | 119 | 0.549045 | 5.114317 | false | false | false | false |
aiwalle/LiveProject | LiveProject/Mine/Controller/LJBaseMineController.swift | 1 | 1907 | //
// LJBaseMineController.swift
// LiveProject
//
// Created by liang on 2017/10/24.
// Copyright © 2017年 liang. All rights reserved.
//
import UIKit
private let kLJMineCell = "LJMineCell"
class LJBaseMineController: UIViewController {
lazy var tableView : UITableView = UITableView()
lazy var sections : [LJSettingsSectionModel] = [LJSettingsSectionModel]()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupData()
}
}
extension LJBaseMineController {
func setupUI() {
tableView.frame = view.bounds
tableView.dataSource = self
tableView.delegate = self
tableView.register(UINib(nibName: kLJMineCell, bundle: nil), forCellReuseIdentifier: kLJMineCell)
view.addSubview(tableView)
tableView.separatorStyle = .none
tableView.rowHeight = 55
}
func setupData() {
}
}
extension LJBaseMineController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].itemArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = LJMineCell.cellWithTableView(tableView)
let section = sections[indexPath.section]
cell.itemModel = section.itemArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return sections[section].sectionHeaderHeight
}
}
| mit | d68f97400c6c82eb75cc389643d361ec | 26.2 | 105 | 0.665441 | 5.010526 | false | false | false | false |
jdbateman/Lendivine | Lendivine/MapWithCheckoutViewController.swift | 1 | 4533 | //
// MapWithCheckoutViewController.swift
// Lendivine
//
// Created by john bateman on 4/3/16.
// Copyright © 2016 John Bateman. All rights reserved.
//
// This is the Cart Map View Controller which presents an MKMapView containing pins for each loan in the cart.
import UIKit
import MapKit
class MapWithCheckoutViewController: MapViewController {
var cart:KivaCart?
override func viewDidLoad() {
super.viewDidLoad()
self.kivaAPI = KivaAPI.sharedInstance
cart = KivaCart.sharedInstance
modifyBarButtonItems()
}
func modifyBarButtonItems() {
let loansByListButton = UIBarButtonItem(image: UIImage(named: "Donate-32"), style: .Plain, target: self, action: #selector(MapWithCheckoutViewController.onLoansByListButtonTap))
navigationItem.setRightBarButtonItems([loansByListButton], animated: true)
// remove back button
navigationItem.hidesBackButton = true
}
@IBAction func onCheckoutButtonTapped(sender: AnyObject) {
let loans = cart!.getLoans2()
KivaLoan.getCurrentFundraisingStatus(loans, context: CoreDataContext.sharedInstance().cartScratchContext) {
success, error, fundraising, notFundraising in
if success {
// remove notFundraising loans from the cart
if let notFundraising = notFundraising {
if notFundraising.count > 0 {
if var loans = loans {
for notFRLoan in notFundraising {
if let index = loans.indexOf(notFRLoan) {
loans.removeAtIndex(index)
}
// UIAlertController
var userMessage = "The following loans are no longer raising funds and have been removed from the cart:\n\n"
var allRemovedLoansString = ""
for nfLoan in notFundraising {
if let country = nfLoan.country, name = nfLoan.name, sector = nfLoan.sector {
let removedLoanString = String(format: "%@, %@, %@\n", name, sector, country)
allRemovedLoansString.appendContentsOf(removedLoanString)
}
}
userMessage.appendContentsOf(allRemovedLoansString)
let alertController = UIAlertController(title: "Cart Modified", message: userMessage, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
self.displayKivaWebCartInBrowser()
}
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
} else {
// There are no loans to remove from the cart
self.displayKivaWebCartInBrowser()
}
}
} else {
// Even though an error occured just continue on to the cart on Kiva.org and they will handle any invalid loans in the cart.
print("Non-fatal error confirming fundraising status of loans.")
self.displayKivaWebCartInBrowser()
}
}
}
/*! Clear local cart of all items and present the Kiva web cart in the browser. */
func displayKivaWebCartInBrowser() {
// Display web cart.
self.showEmbeddedBrowser()
// Note: Enable this line if you want to remove all items from local cart view.
// cart?.empty()
}
/* Display url in an embeded webkit browser. */
func showEmbeddedBrowser() {
let controller = KivaCartViewController()
if let kivaAPI = self.kivaAPI {
controller.request = kivaAPI.getKivaCartRequest() // KivaCheckout()
}
// add the view controller to the navigation controller stack
self.navigationController?.pushViewController(controller, animated: true)
}
}
| mit | bec66b88c2ab02d57c82c4087fc946e9 | 42.161905 | 185 | 0.545675 | 5.395238 | false | false | false | false |
lanjing99/RxSwiftDemo | 11-time-based-operators/challenge/RxSwiftPlayground/RxSwift.playground/Pages/window.xcplaygroundpage/Contents.swift | 1 | 4700 | //: Please build the scheme 'RxSwiftPlayground' first
import UIKit
import RxSwift
import RxCocoa
let elementsPerSecond = 3
let windowTimeSpan: RxTimeInterval = 4
let windowMaxCount = 10
let sourceObservable = PublishSubject<String>()
let sourceTimeline = TimelineView<String>.make()
let stack = UIStackView.makeVertical([
UILabel.makeTitle("window"),
UILabel.make("Emitted elements (\(elementsPerSecond) per sec.):"),
sourceTimeline,
UILabel.make("Windowed observables (at most \(windowMaxCount) every \(windowTimeSpan) sec):")])
let timer = DispatchSource.timer(interval: 1.0 / Double(elementsPerSecond), queue: .main) {
sourceObservable.onNext("🐱")
}
_ = sourceObservable.subscribe(sourceTimeline)
//
// CHALLENGE SOLUTION: move side effect out of flatMap
//
// extract the windowed observable itself
let windowedObservable = sourceObservable
.window(timeSpan: windowTimeSpan, count: windowMaxCount, scheduler: MainScheduler.instance)
// the timeline observable produces a new timeline every time
// windowObservable produces a new observable
let timelineObservable = windowedObservable
.do(onNext: { _ in
let timeline = TimelineView<Int>.make()
stack.insert(timeline, at: 4)
stack.keep(atMost: 8)
})
.map { _ in
stack.arrangedSubviews[4] as! TimelineView<Int>
}
// take one of each, guaranteeing that we get the observable
// produced by window AND the latest timeline view creating
_ = Observable
.zip(windowedObservable, timelineObservable) { obs, timeline in
(obs, timeline)
}
.flatMap { tuple -> Observable<(TimelineView<Int>, String?)> in
let obs = tuple.0
let timeline = tuple.1
return obs
.map { value in (timeline, value) }
.concat(Observable.just((timeline, nil)))
}
.subscribe(onNext: { tuple in
let (timeline, value) = tuple
if let value = value {
timeline.add(.Next(value))
} else {
timeline.add(.Completed(true))
}
})
let hostView = setupHostView()
hostView.addSubview(stack)
hostView
// Support code -- DO NOT REMOVE
class TimelineView<E>: TimelineViewBase, ObserverType where E: CustomStringConvertible {
static func make() -> TimelineView<E> {
let view = TimelineView(frame: CGRect(x: 0, y: 0, width: 400, height: 100))
view.setup()
return view
}
public func on(_ event: Event<E>) {
switch event {
case .next(let value):
add(.Next(String(describing: value)))
case .completed:
add(.Completed())
case .error(_):
add(.Error())
}
}
}
/*:
Copyright (c) 2014-2016 Razeware LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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.
*/
/*:
Copyright (c) 2014-2016 Razeware LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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.
*/
| mit | b0bdb03129028c9b5ac4495f3bdd6b8f | 34.854962 | 97 | 0.74026 | 4.373371 | false | false | false | false |
XiaoChenYung/weibo_sina | weibo/weibo/Classes/Module/OAuthController.swift | 1 | 3506 | //
// OAuthController.swift
// weibo
//
// Created by 杨晓晨 on 15/10/9.
// Copyright © 2015年 yangxiaochen. All rights reserved.
//
import UIKit
import SVProgressHUD
class OAuthController: UIViewController, UIWebViewDelegate {
lazy var web: UIWebView = UIWebView()
override func viewDidLoad() {
// view.backgroundColor
super.viewDidLoad()
view = web
web.delegate = self
title = "新浪微博"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
web.loadRequest(NSURLRequest(URL: NetTools.shareTools.oauthUrl()))
// Do any additional setup after loading the view.
}
// MARK: - UIWebViewDelegate
func webViewDidStartLoad(webView: UIWebView) {
SVProgressHUD.show()
}
func webViewDidFinishLoad(webView: UIWebView) {
SVProgressHUD.dismiss()
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let urlString = request.URL!.absoluteString
// 判断是否包含回调地址
if !urlString.hasPrefix(NetTools.shareTools.redirectUri) {
return true
}
print("判断参数")
print(request.URL?.query)
if let query = request.URL?.query where query.hasPrefix("code=") {
print("获取授权码")
// 从 query 中截取授权码
let code = query.substringFromIndex("code=".endIndex)
print(code)
// TODO: 换取 TOKEN
loadAccessToken(code)
} else {
close()
}
return false
}
private func loadAccessToken(code: String) {
NetTools.shareTools.loadAccessToken(code) { (result, error) -> () in
if error != nil || result == nil {
SVProgressHUD.showInfoWithStatus("您的网络不给力")
// 延时一段时间再关闭
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
dispatch_after(when, dispatch_get_main_queue()) {
self.close()
}
return
}
// 字典转模型
UserAccount(dict: result!).loadUserInfo({ (error) -> () in
print(result!)
if error != nil {
print("网络错误")
return
}
// 发送通知切换视图控制器
NSNotificationCenter.defaultCenter().postNotificationName(YCRootViewControllerSwitchNotification, object: false)
self.close()
})
}
}
/// 关闭界面
func close() {
SVProgressHUD.dismiss()
dismissViewControllerAnimated(true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 70b9525d58cea31b051f0764ae09c541 | 29.724771 | 138 | 0.579576 | 5.081942 | false | false | false | false |
AnthonyMDev/Nimble | Sources/Nimble/Matchers/RaisesException.swift | 20 | 7468 | import Foundation
// This matcher requires the Objective-C, and being built by Xcode rather than the Swift Package Manager
#if canImport(Darwin) && !SWIFT_PACKAGE
/// A Nimble matcher that succeeds when the actual expression raises an
/// exception with the specified name, reason, and/or userInfo.
///
/// Alternatively, you can pass a closure to do any arbitrary custom matching
/// to the raised exception. The closure only gets called when an exception
/// is raised.
///
/// nil arguments indicates that the matcher should not attempt to match against
/// that parameter.
public func raiseException(
named: String? = nil,
reason: String? = nil,
userInfo: NSDictionary? = nil,
closure: ((NSException) -> Void)? = nil) -> Predicate<Any> {
return Predicate { actualExpression in
var exception: NSException?
let capture = NMBExceptionCapture(handler: ({ e in
exception = e
}), finally: nil)
do {
try capture.tryBlockThrows {
_ = try actualExpression.evaluate()
}
} catch {
return PredicateResult(status: .fail, message: .fail("unexpected error thrown: <\(error)>"))
}
let failureMessage = FailureMessage()
setFailureMessageForException(
failureMessage,
exception: exception,
named: named,
reason: reason,
userInfo: userInfo,
closure: closure
)
let matches = exceptionMatchesNonNilFieldsOrClosure(
exception,
named: named,
reason: reason,
userInfo: userInfo,
closure: closure
)
return PredicateResult(bool: matches, message: failureMessage.toExpectationMessage())
}
}
// swiftlint:disable:next function_parameter_count
internal func setFailureMessageForException(
_ failureMessage: FailureMessage,
exception: NSException?,
named: String?,
reason: String?,
userInfo: NSDictionary?,
closure: ((NSException) -> Void)?) {
failureMessage.postfixMessage = "raise exception"
if let named = named {
failureMessage.postfixMessage += " with name <\(named)>"
}
if let reason = reason {
failureMessage.postfixMessage += " with reason <\(reason)>"
}
if let userInfo = userInfo {
failureMessage.postfixMessage += " with userInfo <\(userInfo)>"
}
if closure != nil {
failureMessage.postfixMessage += " that satisfies block"
}
if named == nil && reason == nil && userInfo == nil && closure == nil {
failureMessage.postfixMessage = "raise any exception"
}
if let exception = exception {
// swiftlint:disable:next line_length
failureMessage.actualValue = "\(String(describing: type(of: exception))) { name=\(exception.name), reason='\(stringify(exception.reason))', userInfo=\(stringify(exception.userInfo)) }"
} else {
failureMessage.actualValue = "no exception"
}
}
internal func exceptionMatchesNonNilFieldsOrClosure(
_ exception: NSException?,
named: String?,
reason: String?,
userInfo: NSDictionary?,
closure: ((NSException) -> Void)?) -> Bool {
var matches = false
if let exception = exception {
matches = true
if let named = named, exception.name.rawValue != named {
matches = false
}
if reason != nil && exception.reason != reason {
matches = false
}
if let userInfo = userInfo, let exceptionUserInfo = exception.userInfo,
(exceptionUserInfo as NSDictionary) != userInfo {
matches = false
}
if let closure = closure {
let assertions = gatherFailingExpectations {
closure(exception)
}
let messages = assertions.map { $0.message }
if messages.count > 0 {
matches = false
}
}
}
return matches
}
public class NMBObjCRaiseExceptionMatcher: NSObject, NMBMatcher {
// swiftlint:disable identifier_name
internal var _name: String?
internal var _reason: String?
internal var _userInfo: NSDictionary?
internal var _block: ((NSException) -> Void)?
// swiftlint:enable identifier_name
internal init(name: String?, reason: String?, userInfo: NSDictionary?, block: ((NSException) -> Void)?) {
_name = name
_reason = reason
_userInfo = userInfo
_block = block
}
@objc public func matches(_ actualBlock: @escaping () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let block: () -> Any? = ({ _ = actualBlock(); return nil })
let expr = Expression(expression: block, location: location)
do {
let predicate = raiseException(
named: _name,
reason: _reason,
userInfo: _userInfo,
closure: _block
)
let result = try predicate.satisfies(expr)
result.message.update(failureMessage: failureMessage)
return result.toBoolean(expectation: .toMatch)
} catch let error {
failureMessage.stringValue = "unexpected error thrown: <\(error)>"
return false
}
}
@objc public func doesNotMatch(_ actualBlock: @escaping () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
return !matches(actualBlock, failureMessage: failureMessage, location: location)
}
@objc public var named: (_ name: String) -> NMBObjCRaiseExceptionMatcher {
return { name in
return NMBObjCRaiseExceptionMatcher(
name: name,
reason: self._reason,
userInfo: self._userInfo,
block: self._block
)
}
}
@objc public var reason: (_ reason: String?) -> NMBObjCRaiseExceptionMatcher {
return { reason in
return NMBObjCRaiseExceptionMatcher(
name: self._name,
reason: reason,
userInfo: self._userInfo,
block: self._block
)
}
}
@objc public var userInfo: (_ userInfo: NSDictionary?) -> NMBObjCRaiseExceptionMatcher {
return { userInfo in
return NMBObjCRaiseExceptionMatcher(
name: self._name,
reason: self._reason,
userInfo: userInfo,
block: self._block
)
}
}
@objc public var satisfyingBlock: (_ block: ((NSException) -> Void)?) -> NMBObjCRaiseExceptionMatcher {
return { block in
return NMBObjCRaiseExceptionMatcher(
name: self._name,
reason: self._reason,
userInfo: self._userInfo,
block: block
)
}
}
}
extension NMBObjCMatcher {
@objc public class func raiseExceptionMatcher() -> NMBObjCRaiseExceptionMatcher {
return NMBObjCRaiseExceptionMatcher(name: nil, reason: nil, userInfo: nil, block: nil)
}
}
#endif
| apache-2.0 | 17c3d3cb53f14b1ba0bd12dd34cc984e | 34.061033 | 196 | 0.572175 | 5.47909 | false | false | false | false |
ikorn/KornUIKit | KornUIKit/Class/Extension/UIImageViewExtension.swift | 1 | 660 | //
// UIImageViewExtension.swift
// KornUIKit
//
// Created by ikorn on 2017/01/26.
// Copyright © 2017 ikorn. All rights reserved.
//
import UIKit
public extension UIImageView {
public convenience init(image: UIImage, contentMode: UIViewContentMode = .scaleAspectFit, tintColor: UIColor? = nil) {
self.init()
self.contentMode = contentMode
if let tintColor: UIColor = tintColor {
self.image = image.withRenderingMode(.alwaysTemplate)
self.tintColor = tintColor
} else {
self.image = image
}
}
}
| apache-2.0 | 0e13b51d843e131f7e13643f7b2d5439 | 24.346154 | 122 | 0.566009 | 4.845588 | false | false | false | false |
ngageoint/mage-ios | Mage/Mixins/UserTrackingMap.swift | 1 | 5559 | //
// UserTracking.swift
// MAGE
//
// Created by Daniel Barela on 1/25/22.
// Copyright © 2022 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import MapKit
import MaterialComponents
protocol UserTrackingMap {
var mapView: MKMapView? { get set }
var navigationController: UINavigationController? { get }
var userTrackingMapMixin: UserTrackingMapMixin? { get set }
}
class UserTrackingMapMixin: NSObject, MapMixin {
var mapView: MKMapView?
var userTrackingMap: UserTrackingMap
var scheme: MDCContainerScheming?
weak var buttonParentView: UIStackView?
var indexInView: Int = 0
var locationManager: CLLocationManager?
var isTrackingAnimation: Bool = false
var locationAuthorizationStatus: CLAuthorizationStatus = .notDetermined
private lazy var trackingButton: MDCFloatingButton = {
let trackingButton = MDCFloatingButton(shape: .mini)
trackingButton.setImage(UIImage(systemName: "location"), for: .normal)
trackingButton.addTarget(self, action: #selector(onTrackingButtonPressed(_:)), for: .touchUpInside)
trackingButton.accessibilityLabel = "track location"
return trackingButton
}()
init(userTrackingMap: UserTrackingMap, buttonParentView: UIStackView?, indexInView: Int = 0, locationManager: CLLocationManager? = CLLocationManager(), scheme: MDCContainerScheming?) {
self.userTrackingMap = userTrackingMap
self.mapView = userTrackingMap.mapView
self.scheme = scheme
self.buttonParentView = buttonParentView
self.indexInView = indexInView
self.locationManager = locationManager
}
func cleanupMixin() {
locationManager?.delegate = nil
locationManager = nil
}
func applyTheme(scheme: MDCContainerScheming?) {
guard let scheme = scheme else {
return
}
self.scheme = scheme
trackingButton.backgroundColor = scheme.colorScheme.surfaceColor;
trackingButton.tintColor = scheme.colorScheme.primaryColorVariant;
self.trackingButton.setImageTintColor(scheme.colorScheme.primaryColorVariant, for: .normal)
}
func setupMixin() {
guard let buttonParentView = buttonParentView else {
return
}
if buttonParentView.arrangedSubviews.count < indexInView {
buttonParentView.insertArrangedSubview(trackingButton, at: buttonParentView.arrangedSubviews.count)
} else {
buttonParentView.insertArrangedSubview(trackingButton, at: indexInView)
}
applyTheme(scheme: scheme)
locationManager?.delegate = self
setupTrackingButton()
}
@objc func onTrackingButtonPressed(_ sender: UIButton) {
let authorized = locationAuthorizationStatus == .authorizedAlways || locationAuthorizationStatus == .authorizedWhenInUse
if !authorized {
let alert = UIAlertController(title: "Location Services Disabled", message: "MAGE has been denied access to location services. To show your location on the map, please go into your device settings and enable the Location permission.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: { action in
if let url = NSURL(string: UIApplication.openSettingsURLString) as URL? {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}))
userTrackingMap.navigationController?.present(alert, animated: true, completion: nil)
return
}
guard let mapView = userTrackingMap.mapView else {
return
}
switch mapView.userTrackingMode {
case .none:
mapView.setUserTrackingMode(.follow, animated: true)
trackingButton.setImage(UIImage(systemName: "location.fill"), for: .normal)
case .follow:
mapView.setUserTrackingMode(.followWithHeading, animated: true)
trackingButton.setImage(UIImage(systemName: "location.north.line.fill"), for: .normal)
case .followWithHeading:
mapView.setUserTrackingMode(.none, animated: true)
trackingButton.setImage(UIImage(systemName: "location"), for: .normal)
@unknown default:
mapView.setUserTrackingMode(.none, animated: true)
trackingButton.setImage(UIImage(systemName: "location"), for: .normal)
}
}
func setupTrackingButton() {
let authorized = locationAuthorizationStatus == .authorizedAlways || locationAuthorizationStatus == .authorizedWhenInUse
if !authorized {
trackingButton.applySecondaryTheme(withScheme: globalDisabledScheme())
} else {
guard let scheme = scheme else {
return
}
self.trackingButton.backgroundColor = scheme.colorScheme.surfaceColor;
self.trackingButton.tintColor = scheme.colorScheme.primaryColorVariant;
self.trackingButton.setImageTintColor(scheme.colorScheme.primaryColorVariant, for: .normal)
}
}
}
extension UserTrackingMapMixin: CLLocationManagerDelegate {
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
locationAuthorizationStatus = manager.authorizationStatus
setupTrackingButton()
}
}
| apache-2.0 | 2945a74fbdaa12582e23029a8026b195 | 40.789474 | 271 | 0.680461 | 5.396117 | false | false | false | false |
qingpengchen2011/PageMenu | Classes/CAPSPageMenu.swift | 1 | 48698 | // CAPSPageMenu.swift
//
// Niklas Fahl
//
// Copyright (c) 2014 The Board of Trustees of The University of Alabama All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// Neither the name of the University nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import UIKit
@objc public protocol CAPSPageMenuDelegate {
// MARK: - Delegate functions
optional func willMoveToPage(controller: UIViewController, index: Int)
optional func didMoveToPage(controller: UIViewController, index: Int)
}
class MenuItemView: UIView {
// MARK: - Menu item view
var titleLabel : UILabel?
var menuItemSeparator : UIView?
func setUpMenuItemView(menuItemWidth: CGFloat, menuScrollViewHeight: CGFloat, indicatorHeight: CGFloat, separatorPercentageHeight: CGFloat, separatorWidth: CGFloat, separatorRoundEdges: Bool, menuItemSeparatorColor: UIColor) {
titleLabel = UILabel(frame: CGRectMake(0.0, 0.0, menuItemWidth, menuScrollViewHeight - indicatorHeight))
menuItemSeparator = UIView(frame: CGRectMake(menuItemWidth - (separatorWidth / 2), floor(menuScrollViewHeight * ((1.0 - separatorPercentageHeight) / 2.0)), separatorWidth, floor(menuScrollViewHeight * separatorPercentageHeight)))
menuItemSeparator!.backgroundColor = menuItemSeparatorColor
if separatorRoundEdges {
menuItemSeparator!.layer.cornerRadius = menuItemSeparator!.frame.width / 2
}
menuItemSeparator!.hidden = true
self.addSubview(menuItemSeparator!)
self.addSubview(titleLabel!)
}
func setTitleText(text: NSString) {
if titleLabel != nil {
titleLabel!.text = text as String
titleLabel!.numberOfLines = 0
titleLabel!.sizeToFit()
}
}
}
public class CAPSPageMenu: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate {
// MARK: - Properties
let menuScrollView = UIScrollView()
let controllerScrollView = UIScrollView()
var controllerArray : [AnyObject] = []
var menuItems : [MenuItemView] = []
var menuItemWidths : [CGFloat] = []
public var menuHeight : CGFloat = 34.0
public var menuMargin : CGFloat = 15.0
public var menuItemWidth : CGFloat = 111.0
public var selectionIndicatorHeight : CGFloat = 3.0
var totalMenuItemWidthIfDifferentWidths : CGFloat = 0.0
public var scrollAnimationDurationOnMenuItemTap : Int = 500 // Millisecons
var startingMenuMargin : CGFloat = 0.0
var selectionIndicatorView : UIView = UIView()
var currentPageIndex : Int = 0
var lastPageIndex : Int = 0
public var selectionIndicatorColor : UIColor = UIColor.whiteColor()
public var selectedMenuItemLabelColor : UIColor = UIColor.whiteColor()
public var unselectedMenuItemLabelColor : UIColor = UIColor.lightGrayColor()
public var scrollMenuBackgroundColor : UIColor = UIColor.blackColor()
public var viewBackgroundColor : UIColor = UIColor.whiteColor()
public var bottomMenuHairlineColor : UIColor = UIColor.whiteColor()
public var menuItemSeparatorColor : UIColor = UIColor.lightGrayColor()
public var menuItemFont : UIFont = UIFont(name: "HelveticaNeue", size: 15.0)!
public var menuItemSeparatorPercentageHeight : CGFloat = 0.2
public var menuItemSeparatorWidth : CGFloat = 0.5
public var menuItemSeparatorRoundEdges : Bool = false
public var addBottomMenuHairline : Bool = true
public var menuItemWidthBasedOnTitleTextWidth : Bool = false
public var useMenuLikeSegmentedControl : Bool = false
public var centerMenuItems : Bool = false
public var enableHorizontalBounce : Bool = true
public var hideTopMenuBar : Bool = false
var currentOrientationIsPortrait : Bool = true
var pageIndexForOrientationChange : Int = 0
var didLayoutSubviewsAfterRotation : Bool = false
var didScrollAlready : Bool = false
var lastControllerScrollViewContentOffset : CGFloat = 0.0
var lastScrollDirection : CAPSPageMenuScrollDirection = .Other
var startingPageForScroll : Int = 0
var didTapMenuItemToScroll : Bool = false
var pagesAddedDictionary : [Int : Int] = [:]
public weak var delegate : CAPSPageMenuDelegate?
var tapTimer : NSTimer?
var enableControllerScrollViewScroll: Bool!
enum CAPSPageMenuScrollDirection : Int {
case Left
case Right
case Other
}
// MARK: - View life cycle
/**
Initialize PageMenu with view controllers
:param: viewControllers List of view controllers that must be subclasses of UIViewController
:param: frame Frame for page menu view
:param: options Dictionary holding any customization options user might want to set
*/
public init(viewControllers: [AnyObject], frame: CGRect, options: [String: AnyObject]?, enableControllerScrollViewScroll: Bool = true) {
super.init(nibName: nil, bundle: nil)
self.enableControllerScrollViewScroll = enableControllerScrollViewScroll
controllerArray = viewControllers
self.view.frame = frame
if options != nil {
for key : String in options!.keys {
if key == "selectionIndicatorHeight" {
selectionIndicatorHeight = options![key] as! CGFloat
} else if key == "menuItemSeparatorWidth" {
menuItemSeparatorWidth = options![key] as! CGFloat
} else if key == "scrollMenuBackgroundColor" {
scrollMenuBackgroundColor = options![key] as! UIColor
} else if key == "viewBackgroundColor" {
viewBackgroundColor = options![key] as! UIColor
} else if key == "bottomMenuHairlineColor" {
bottomMenuHairlineColor = options![key] as! UIColor
} else if key == "selectionIndicatorColor" {
selectionIndicatorColor = options![key] as! UIColor
} else if key == "menuItemSeparatorColor" {
menuItemSeparatorColor = options![key] as! UIColor
} else if key == "menuMargin" {
menuMargin = options![key] as! CGFloat
} else if key == "menuHeight" {
menuHeight = options![key] as! CGFloat
} else if key == "selectedMenuItemLabelColor" {
selectedMenuItemLabelColor = options![key] as! UIColor
} else if key == "unselectedMenuItemLabelColor" {
unselectedMenuItemLabelColor = options![key] as! UIColor
} else if key == "useMenuLikeSegmentedControl" {
useMenuLikeSegmentedControl = options![key] as! Bool
} else if key == "menuItemSeparatorRoundEdges" {
menuItemSeparatorRoundEdges = options![key] as! Bool
} else if key == "menuItemFont" {
menuItemFont = options![key] as! UIFont
} else if key == "menuItemSeparatorPercentageHeight" {
menuItemSeparatorPercentageHeight = options![key] as! CGFloat
} else if key == "menuItemWidth" {
menuItemWidth = options![key] as! CGFloat
} else if key == "enableHorizontalBounce" {
enableHorizontalBounce = options![key] as! Bool
} else if key == "addBottomMenuHairline" {
addBottomMenuHairline = options![key] as! Bool
} else if key == "menuItemWidthBasedOnTitleTextWidth" {
menuItemWidthBasedOnTitleTextWidth = options![key] as! Bool
} else if key == "scrollAnimationDurationOnMenuItemTap" {
scrollAnimationDurationOnMenuItemTap = options![key] as! Int
} else if key == "centerMenuItems" {
centerMenuItems = options![key] as! Bool
} else if key == "hideTopMenuBar" {
hideTopMenuBar = options![key] as! Bool
}
}
if hideTopMenuBar {
addBottomMenuHairline = false
menuHeight = 0.0
}
}
setUpUserInterface()
if menuScrollView.subviews.count == 0 {
configureUserInterface()
}
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - UI Setup
func setUpUserInterface() {
let viewsDictionary = ["menuScrollView":menuScrollView, "controllerScrollView":controllerScrollView]
// Set up controller scroll view
controllerScrollView.pagingEnabled = true
controllerScrollView.setTranslatesAutoresizingMaskIntoConstraints(false)
controllerScrollView.alwaysBounceHorizontal = enableHorizontalBounce
controllerScrollView.bounces = enableHorizontalBounce
controllerScrollView.frame = CGRectMake(0.0, menuHeight, self.view.frame.width, self.view.frame.height)
self.view.addSubview(controllerScrollView)
let controllerScrollView_constraint_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:|[controllerScrollView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
let controllerScrollView_constraint_V:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:|[controllerScrollView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
self.view.addConstraints(controllerScrollView_constraint_H)
self.view.addConstraints(controllerScrollView_constraint_V)
// Set up menu scroll view
menuScrollView.setTranslatesAutoresizingMaskIntoConstraints(false)
menuScrollView.frame = CGRectMake(0.0, 0.0, self.view.frame.width, menuHeight)
self.view.addSubview(menuScrollView)
let menuScrollView_constraint_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:|[menuScrollView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
let menuScrollView_constraint_V:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:[menuScrollView(\(menuHeight))]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
self.view.addConstraints(menuScrollView_constraint_H)
self.view.addConstraints(menuScrollView_constraint_V)
// Add hairline to menu scroll view
if addBottomMenuHairline {
var menuBottomHairline : UIView = UIView()
menuBottomHairline.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(menuBottomHairline)
let menuBottomHairline_constraint_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:|[menuBottomHairline]|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["menuBottomHairline":menuBottomHairline])
let menuBottomHairline_constraint_V:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(menuHeight)-[menuBottomHairline(0.5)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["menuBottomHairline":menuBottomHairline])
self.view.addConstraints(menuBottomHairline_constraint_H)
self.view.addConstraints(menuBottomHairline_constraint_V)
menuBottomHairline.backgroundColor = bottomMenuHairlineColor
}
// Disable scroll bars
menuScrollView.showsHorizontalScrollIndicator = false
menuScrollView.showsVerticalScrollIndicator = false
controllerScrollView.showsHorizontalScrollIndicator = false
controllerScrollView.showsVerticalScrollIndicator = false
controllerScrollView.scrollEnabled = enableControllerScrollViewScroll
// Set background color behind scroll views and for menu scroll view
self.view.backgroundColor = viewBackgroundColor
menuScrollView.backgroundColor = scrollMenuBackgroundColor
}
func configureUserInterface() {
// Add tap gesture recognizer to controller scroll view to recognize menu item selection
let menuItemTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("handleMenuItemTap:"))
menuItemTapGestureRecognizer.numberOfTapsRequired = 1
menuItemTapGestureRecognizer.numberOfTouchesRequired = 1
menuItemTapGestureRecognizer.delegate = self
menuScrollView.addGestureRecognizer(menuItemTapGestureRecognizer)
// Set delegate for controller scroll view
controllerScrollView.delegate = self
// When the user taps the status bar, the scroll view beneath the touch which is closest to the status bar will be scrolled to top,
// but only if its `scrollsToTop` property is YES, its delegate does not return NO from `shouldScrollViewScrollToTop`, and it is not already at the top.
// If more than one scroll view is found, none will be scrolled.
// Disable scrollsToTop for menu and controller scroll views so that iOS finds scroll views within our pages on status bar tap gesture.
menuScrollView.scrollsToTop = false;
controllerScrollView.scrollsToTop = false;
// Configure menu scroll view
if useMenuLikeSegmentedControl {
menuScrollView.scrollEnabled = false
menuScrollView.contentSize = CGSizeMake(self.view.frame.width, menuHeight)
menuMargin = 0.0
} else {
menuScrollView.contentSize = CGSizeMake((menuItemWidth + menuMargin) * CGFloat(controllerArray.count) + menuMargin, menuHeight)
}
// Configure controller scroll view content size
controllerScrollView.contentSize = CGSizeMake(self.view.frame.width * CGFloat(controllerArray.count), 0.0)
var index : CGFloat = 0.0
for controller in controllerArray {
if controller.isKindOfClass(UIViewController) {
if index == 0.0 {
// Add first two controllers to scrollview and as child view controller
(controller as! UIViewController).viewWillAppear(true)
addPageAtIndex(0)
(controller as! UIViewController).viewDidAppear(true)
}
// Set up menu item for menu scroll view
var menuItemFrame : CGRect = CGRect()
//add by qky
if useMenuLikeSegmentedControl && menuItemWidthBasedOnTitleTextWidth {
var controllerTitle : String? = (controller as! UIViewController).title
var titleText : String = controllerTitle != nil ? controllerTitle! : "Menu \(Int(index) + 1)"
var itemWidthRect : CGRect = (titleText as NSString).boundingRectWithSize(CGSizeMake(1000, 1000), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:menuItemFont], context: nil)
menuItemWidth = itemWidthRect.width
menuItemFrame = CGRectMake(self.view.frame.width / CGFloat(controllerArray.count) * CGFloat(index), 0.0, CGFloat(self.view.frame.width) / CGFloat(controllerArray.count), menuHeight)
totalMenuItemWidthIfDifferentWidths += itemWidthRect.width
menuItemWidths.append(itemWidthRect.width)
}
//add end
else if useMenuLikeSegmentedControl {
menuItemFrame = CGRectMake(self.view.frame.width / CGFloat(controllerArray.count) * CGFloat(index), 0.0, menuItemWidth, menuHeight)
} else if menuItemWidthBasedOnTitleTextWidth {
var controllerTitle : String? = (controller as! UIViewController).title
var titleText : String = controllerTitle != nil ? controllerTitle! : "Menu \(Int(index) + 1)"
var itemWidthRect : CGRect = (titleText as NSString).boundingRectWithSize(CGSizeMake(1000, 1000), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:menuItemFont], context: nil)
menuItemWidth = itemWidthRect.width
menuItemFrame = CGRectMake(totalMenuItemWidthIfDifferentWidths + menuMargin + (menuMargin * index), 0.0, menuItemWidth, menuHeight)
totalMenuItemWidthIfDifferentWidths += itemWidthRect.width
menuItemWidths.append(itemWidthRect.width)
} else {
if centerMenuItems && index == 0.0 {
startingMenuMargin = ((self.view.frame.width - ((CGFloat(controllerArray.count) * menuItemWidth) + (CGFloat(controllerArray.count - 1) * menuMargin))) / 2.0) - menuMargin
if startingMenuMargin < 0.0 {
startingMenuMargin = 0.0
}
menuItemFrame = CGRectMake(startingMenuMargin + menuMargin, 0.0, menuItemWidth, menuHeight)
} else {
menuItemFrame = CGRectMake(menuItemWidth * index + menuMargin * (index + 1) + startingMenuMargin, 0.0, menuItemWidth, menuHeight)
}
}
var menuItemView : MenuItemView = MenuItemView(frame: menuItemFrame)
if useMenuLikeSegmentedControl {
menuItemView.setUpMenuItemView(CGFloat(self.view.frame.width) / CGFloat(controllerArray.count), menuScrollViewHeight: menuHeight, indicatorHeight: selectionIndicatorHeight, separatorPercentageHeight: menuItemSeparatorPercentageHeight, separatorWidth: menuItemSeparatorWidth, separatorRoundEdges: menuItemSeparatorRoundEdges, menuItemSeparatorColor: menuItemSeparatorColor)
} else {
menuItemView.setUpMenuItemView(menuItemWidth, menuScrollViewHeight: menuHeight, indicatorHeight: selectionIndicatorHeight, separatorPercentageHeight: menuItemSeparatorPercentageHeight, separatorWidth: menuItemSeparatorWidth, separatorRoundEdges: menuItemSeparatorRoundEdges, menuItemSeparatorColor: menuItemSeparatorColor)
}
// Configure menu item label font if font is set by user
menuItemView.titleLabel!.font = menuItemFont
menuItemView.titleLabel!.textAlignment = NSTextAlignment.Center
menuItemView.titleLabel!.textColor = unselectedMenuItemLabelColor
// Set title depending on if controller has a title set
if (controller as! UIViewController).title != nil {
menuItemView.titleLabel!.text = controller.title!
} else {
menuItemView.titleLabel!.text = "Menu \(Int(index) + 1)"
}
// Add separator between menu items when using as segmented control
if useMenuLikeSegmentedControl {
if Int(index) < controllerArray.count - 1 {
menuItemView.menuItemSeparator!.hidden = false
}
}
// Add menu item view to menu scroll view
menuScrollView.addSubview(menuItemView)
menuItems.append(menuItemView)
index++
}
}
// Set new content size for menu scroll view if needed
if menuItemWidthBasedOnTitleTextWidth {
//removed by qky
// menuScrollView.contentSize = CGSizeMake((totalMenuItemWidthIfDifferentWidths + menuMargin) + CGFloat(controllerArray.count) * menuMargin, menuHeight)
}
// Set selected color for title label of selected menu item
if menuItems.count > 0 {
if menuItems[currentPageIndex].titleLabel != nil {
menuItems[currentPageIndex].titleLabel!.textColor = selectedMenuItemLabelColor
}
}
// Configure selection indicator view
var selectionIndicatorFrame : CGRect = CGRect()
//add by qky
if useMenuLikeSegmentedControl && menuItemWidthBasedOnTitleTextWidth {
selectionIndicatorFrame = CGRectMake(CGFloat(self.view.frame.width) / CGFloat(controllerArray.count) / 2 - menuItemWidths[0]/2, menuHeight - selectionIndicatorHeight - 10, menuItemWidths[0], selectionIndicatorHeight)
}
//add end
else if useMenuLikeSegmentedControl {
selectionIndicatorFrame = CGRectMake(0.0, menuHeight - selectionIndicatorHeight, self.view.frame.width / CGFloat(controllerArray.count), selectionIndicatorHeight)
} else if menuItemWidthBasedOnTitleTextWidth {
selectionIndicatorFrame = CGRectMake(menuMargin, menuHeight - selectionIndicatorHeight, menuItemWidths[0], selectionIndicatorHeight)
} else {
if centerMenuItems {
selectionIndicatorFrame = CGRectMake(startingMenuMargin + menuMargin, menuHeight - selectionIndicatorHeight, menuItemWidth, selectionIndicatorHeight)
} else {
selectionIndicatorFrame = CGRectMake(menuMargin, menuHeight - selectionIndicatorHeight, menuItemWidth, selectionIndicatorHeight)
}
}
selectionIndicatorView = UIView(frame: selectionIndicatorFrame)
selectionIndicatorView.backgroundColor = selectionIndicatorColor
menuScrollView.addSubview(selectionIndicatorView)
}
// MARK: - Scroll view delegate
public func scrollViewDidScroll(scrollView: UIScrollView) {
if !didLayoutSubviewsAfterRotation {
if scrollView.isEqual(controllerScrollView) {
if scrollView.contentOffset.x >= 0.0 && scrollView.contentOffset.x <= (CGFloat(controllerArray.count - 1) * self.view.frame.width) {
if (currentOrientationIsPortrait && self.interfaceOrientation.isPortrait) || (!currentOrientationIsPortrait && self.interfaceOrientation.isLandscape) {
// Check if scroll direction changed
if !didTapMenuItemToScroll {
if didScrollAlready {
var newScrollDirection : CAPSPageMenuScrollDirection = .Other
if (CGFloat(startingPageForScroll) * scrollView.frame.width > scrollView.contentOffset.x) {
newScrollDirection = .Right
} else if (CGFloat(startingPageForScroll) * scrollView.frame.width < scrollView.contentOffset.x) {
newScrollDirection = .Left
}
if newScrollDirection != .Other {
if lastScrollDirection != newScrollDirection {
var index : Int = newScrollDirection == .Left ? currentPageIndex + 1 : currentPageIndex - 1
if index >= 0 && index < controllerArray.count {
// Check dictionary if page was already added
if pagesAddedDictionary[index] != index {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
}
}
}
lastScrollDirection = newScrollDirection
}
if !didScrollAlready {
if (lastControllerScrollViewContentOffset > scrollView.contentOffset.x) {
if currentPageIndex != controllerArray.count - 1 {
// Add page to the left of current page
var index : Int = currentPageIndex - 1
if pagesAddedDictionary[index] != index && index < controllerArray.count && index >= 0 {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
lastScrollDirection = .Right
}
} else if (lastControllerScrollViewContentOffset < scrollView.contentOffset.x) {
if currentPageIndex != 0 {
// Add page to the right of current page
var index : Int = currentPageIndex + 1
if pagesAddedDictionary[index] != index && index < controllerArray.count && index >= 0 {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
lastScrollDirection = .Left
}
}
didScrollAlready = true
}
lastControllerScrollViewContentOffset = scrollView.contentOffset.x
}
var ratio : CGFloat = 1.0
// Calculate ratio between scroll views
ratio = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width)
if menuScrollView.contentSize.width > self.view.frame.width {
var offset : CGPoint = menuScrollView.contentOffset
offset.x = controllerScrollView.contentOffset.x * ratio
menuScrollView.setContentOffset(offset, animated: false)
}
// Calculate current page
var width : CGFloat = controllerScrollView.frame.size.width;
var page : Int = Int((controllerScrollView.contentOffset.x + (0.5 * width)) / width)
// Update page if changed
if page != currentPageIndex {
lastPageIndex = currentPageIndex
currentPageIndex = page
if pagesAddedDictionary[page] != page && page < controllerArray.count && page >= 0 {
addPageAtIndex(page)
pagesAddedDictionary[page] = page
}
if !didTapMenuItemToScroll {
// Add last page to pages dictionary to make sure it gets removed after scrolling
if pagesAddedDictionary[lastPageIndex] != lastPageIndex {
pagesAddedDictionary[lastPageIndex] = lastPageIndex
}
// Make sure only up to 3 page views are in memory when fast scrolling, otherwise there should only be one in memory
var indexLeftTwo : Int = page - 2
if pagesAddedDictionary[indexLeftTwo] == indexLeftTwo {
pagesAddedDictionary.removeValueForKey(indexLeftTwo)
removePageAtIndex(indexLeftTwo)
}
var indexRightTwo : Int = page + 2
if pagesAddedDictionary[indexRightTwo] == indexRightTwo {
pagesAddedDictionary.removeValueForKey(indexRightTwo)
removePageAtIndex(indexRightTwo)
}
}
}
// Move selection indicator view when swiping
moveSelectionIndicator(page)
}
} else {
var ratio : CGFloat = 1.0
ratio = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width)
if menuScrollView.contentSize.width > self.view.frame.width {
var offset : CGPoint = menuScrollView.contentOffset
offset.x = controllerScrollView.contentOffset.x * ratio
menuScrollView.setContentOffset(offset, animated: false)
}
}
}
} else {
didLayoutSubviewsAfterRotation = false
// Move selection indicator view when swiping
moveSelectionIndicator(currentPageIndex)
}
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if scrollView.isEqual(controllerScrollView) {
// Call didMoveToPage delegate function
var currentController : UIViewController = controllerArray[currentPageIndex] as! UIViewController
delegate?.didMoveToPage?(currentController, index: currentPageIndex)
// Remove all but current page after decelerating
for key in pagesAddedDictionary.keys {
if key != currentPageIndex {
removePageAtIndex(key)
}
}
didScrollAlready = false
startingPageForScroll = currentPageIndex
// Empty out pages in dictionary
pagesAddedDictionary.removeAll(keepCapacity: false)
}
}
func scrollViewDidEndTapScrollingAnimation() {
// Call didMoveToPage delegate function
var currentController : UIViewController = controllerArray[currentPageIndex] as! UIViewController
delegate?.didMoveToPage?(currentController, index: currentPageIndex)
// Remove all but current page after decelerating
for key in pagesAddedDictionary.keys {
if key != currentPageIndex {
removePageAtIndex(key)
}
}
startingPageForScroll = currentPageIndex
didTapMenuItemToScroll = false
// Empty out pages in dictionary
pagesAddedDictionary.removeAll(keepCapacity: false)
}
// MARK: - Handle Selection Indicator
func moveSelectionIndicator(pageIndex: Int) {
if pageIndex >= 0 && pageIndex < controllerArray.count {
UIView.animateWithDuration(0.15, animations: { () -> Void in
var selectionIndicatorWidth : CGFloat = self.selectionIndicatorView.frame.width
var selectionIndicatorX : CGFloat = 0.0
//add by qky
if self.useMenuLikeSegmentedControl && self.menuItemWidthBasedOnTitleTextWidth {
selectionIndicatorX = CGFloat(pageIndex) * (self.view.frame.width / CGFloat(self.controllerArray.count)) + (self.view.frame.width / CGFloat(self.controllerArray.count))/2 - self.menuItemWidths[pageIndex]/2
selectionIndicatorWidth = self.menuItemWidths[pageIndex]
}
//add end
else if self.useMenuLikeSegmentedControl {
selectionIndicatorX = CGFloat(pageIndex) * (self.view.frame.width / CGFloat(self.controllerArray.count))
selectionIndicatorWidth = self.view.frame.width / CGFloat(self.controllerArray.count)
} else if self.menuItemWidthBasedOnTitleTextWidth {
selectionIndicatorWidth = self.menuItemWidths[pageIndex]
selectionIndicatorX += self.menuMargin
if pageIndex > 0 {
for i in 0...(pageIndex - 1) {
selectionIndicatorX += (self.menuMargin + self.menuItemWidths[i])
}
}
} else {
if self.centerMenuItems && pageIndex == 0 {
selectionIndicatorX = self.startingMenuMargin + self.menuMargin
} else {
selectionIndicatorX = self.menuItemWidth * CGFloat(pageIndex) + self.menuMargin * CGFloat(pageIndex + 1) + self.startingMenuMargin
}
}
self.selectionIndicatorView.frame = CGRectMake(selectionIndicatorX, self.selectionIndicatorView.frame.origin.y, selectionIndicatorWidth, self.selectionIndicatorView.frame.height)
// Switch newly selected menu item title label to selected color and old one to unselected color
if self.menuItems.count > 0 {
if self.menuItems[self.lastPageIndex].titleLabel != nil && self.menuItems[self.currentPageIndex].titleLabel != nil {
self.menuItems[self.lastPageIndex].titleLabel!.textColor = self.unselectedMenuItemLabelColor
self.menuItems[self.currentPageIndex].titleLabel!.textColor = self.selectedMenuItemLabelColor
}
}
})
}
}
// MARK: - Tap gesture recognizer selector
func handleMenuItemTap(gestureRecognizer : UITapGestureRecognizer) {
var tappedPoint : CGPoint = gestureRecognizer.locationInView(menuScrollView)
if tappedPoint.y < menuScrollView.frame.height {
// Calculate tapped page
var itemIndex : Int = 0
if useMenuLikeSegmentedControl {
itemIndex = Int(tappedPoint.x / (self.view.frame.width / CGFloat(controllerArray.count)))
} else if menuItemWidthBasedOnTitleTextWidth {
// Base case being first item
var menuItemLeftBound : CGFloat = 0.0
var menuItemRightBound : CGFloat = menuItemWidths[0] + menuMargin + (menuMargin / 2)
if !(tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound) {
for i in 1...controllerArray.count - 1 {
menuItemLeftBound = menuItemRightBound + 1.0
menuItemRightBound = menuItemLeftBound + menuItemWidths[i] + menuMargin
if tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound {
itemIndex = i
break
}
}
}
} else {
var rawItemIndex : CGFloat = ((tappedPoint.x - startingMenuMargin) - menuMargin / 2) / (menuMargin + menuItemWidth)
// Prevent moving to first item when tapping left to first item
if rawItemIndex < 0 {
itemIndex = -1
} else {
itemIndex = Int(rawItemIndex)
}
}
if itemIndex >= 0 && itemIndex < controllerArray.count {
// Update page if changed
if itemIndex != currentPageIndex {
startingPageForScroll = itemIndex
lastPageIndex = currentPageIndex
currentPageIndex = itemIndex
didTapMenuItemToScroll = true
// Add pages in between current and tapped page if necessary
var smallerIndex : Int = lastPageIndex < currentPageIndex ? lastPageIndex : currentPageIndex
var largerIndex : Int = lastPageIndex > currentPageIndex ? lastPageIndex : currentPageIndex
if smallerIndex + 1 != largerIndex {
for index in (smallerIndex + 1)...(largerIndex - 1) {
if pagesAddedDictionary[index] != index {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
}
}
addPageAtIndex(itemIndex)
// Add page from which tap is initiated so it can be removed after tap is done
pagesAddedDictionary[lastPageIndex] = lastPageIndex
}
// Move controller scroll view when tapping menu item
var duration : Double = Double(scrollAnimationDurationOnMenuItemTap) / Double(1000)
UIView.animateWithDuration(duration, animations: { () -> Void in
var xOffset : CGFloat = CGFloat(itemIndex) * self.controllerScrollView.frame.width
self.controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: self.controllerScrollView.contentOffset.y), animated: false)
})
if tapTimer != nil {
tapTimer!.invalidate()
}
var timerInterval : NSTimeInterval = Double(scrollAnimationDurationOnMenuItemTap) * 0.001
tapTimer = NSTimer.scheduledTimerWithTimeInterval(timerInterval, target: self, selector: "scrollViewDidEndTapScrollingAnimation", userInfo: nil, repeats: false)
}
}
}
// MARK: - Remove/Add Page
func addPageAtIndex(index : Int) {
// Call didMoveToPage delegate function
var currentController : UIViewController = controllerArray[index] as! UIViewController
delegate?.willMoveToPage?(currentController, index: index)
var newVC : UIViewController = controllerArray[index] as! UIViewController
newVC.willMoveToParentViewController(self)
newVC.view.frame = CGRectMake(self.view.frame.width * CGFloat(index), menuHeight, self.view.frame.width, self.view.frame.height - menuHeight)
self.addChildViewController(newVC)
self.controllerScrollView.addSubview(newVC.view)
newVC.didMoveToParentViewController(self)
}
func removePageAtIndex(index : Int) {
var oldVC : UIViewController = controllerArray[index] as! UIViewController
oldVC.willMoveToParentViewController(nil)
oldVC.view.removeFromSuperview()
oldVC.removeFromParentViewController()
oldVC.didMoveToParentViewController(nil)
}
// MARK: - Orientation Change
override public func viewDidLayoutSubviews() {
// Configure controller scroll view content size
controllerScrollView.contentSize = CGSizeMake(self.view.frame.width * CGFloat(controllerArray.count), self.view.frame.height - menuHeight)
var oldCurrentOrientationIsPortrait : Bool = currentOrientationIsPortrait
currentOrientationIsPortrait = self.interfaceOrientation.isPortrait
if (oldCurrentOrientationIsPortrait && UIDevice.currentDevice().orientation.isLandscape) || (!oldCurrentOrientationIsPortrait && UIDevice.currentDevice().orientation.isPortrait) {
didLayoutSubviewsAfterRotation = true
//Resize menu items if using as segmented control
if useMenuLikeSegmentedControl {
menuScrollView.contentSize = CGSizeMake(self.view.frame.width, menuHeight)
// Resize selectionIndicator bar
var selectionIndicatorX : CGFloat = CGFloat(currentPageIndex) * (self.view.frame.width / CGFloat(self.controllerArray.count))
var selectionIndicatorWidth : CGFloat = self.view.frame.width / CGFloat(self.controllerArray.count)
selectionIndicatorView.frame = CGRectMake(selectionIndicatorX, self.selectionIndicatorView.frame.origin.y, selectionIndicatorWidth, self.selectionIndicatorView.frame.height)
// Resize menu items
var index : Int = 0
for item : MenuItemView in menuItems as [MenuItemView] {
item.frame = CGRectMake(self.view.frame.width / CGFloat(controllerArray.count) * CGFloat(index), 0.0, self.view.frame.width / CGFloat(controllerArray.count), menuHeight)
item.titleLabel!.frame = CGRectMake(0.0, 0.0, self.view.frame.width / CGFloat(controllerArray.count), menuHeight)
item.menuItemSeparator!.frame = CGRectMake(item.frame.width - (menuItemSeparatorWidth / 2), item.menuItemSeparator!.frame.origin.y, item.menuItemSeparator!.frame.width, item.menuItemSeparator!.frame.height)
index++
}
} else if centerMenuItems {
startingMenuMargin = ((self.view.frame.width - ((CGFloat(controllerArray.count) * menuItemWidth) + (CGFloat(controllerArray.count - 1) * menuMargin))) / 2.0) - menuMargin
if startingMenuMargin < 0.0 {
startingMenuMargin = 0.0
}
var selectionIndicatorX : CGFloat = self.menuItemWidth * CGFloat(currentPageIndex) + self.menuMargin * CGFloat(currentPageIndex + 1) + self.startingMenuMargin
selectionIndicatorView.frame = CGRectMake(selectionIndicatorX, self.selectionIndicatorView.frame.origin.y, self.selectionIndicatorView.frame.width, self.selectionIndicatorView.frame.height)
// Recalculate frame for menu items if centered
var index : Int = 0
for item : MenuItemView in menuItems as [MenuItemView] {
if index == 0 {
item.frame = CGRectMake(startingMenuMargin + menuMargin, 0.0, menuItemWidth, menuHeight)
} else {
item.frame = CGRectMake(menuItemWidth * CGFloat(index) + menuMargin * CGFloat(index + 1) + startingMenuMargin, 0.0, menuItemWidth, menuHeight)
}
index++
}
}
for view : UIView in controllerScrollView.subviews as! [UIView] {
view.frame = CGRectMake(self.view.frame.width * CGFloat(currentPageIndex), menuHeight, controllerScrollView.frame.width, self.view.frame.height - menuHeight)
}
var xOffset : CGFloat = CGFloat(self.currentPageIndex) * controllerScrollView.frame.width
controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: controllerScrollView.contentOffset.y), animated: false)
var ratio : CGFloat = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width)
if menuScrollView.contentSize.width > self.view.frame.width {
var offset : CGPoint = menuScrollView.contentOffset
offset.x = controllerScrollView.contentOffset.x * ratio
menuScrollView.setContentOffset(offset, animated: false)
}
}
// Hsoi 2015-02-05 - Running on iOS 7.1 complained: "'NSInternalInconsistencyException', reason: 'Auto Layout
// still required after sending -viewDidLayoutSubviews to the view controller. ViewController's implementation
// needs to send -layoutSubviews to the view to invoke auto layout.'"
//
// http://stackoverflow.com/questions/15490140/auto-layout-error
//
// Given the SO answer and caveats presented there, we'll call layoutIfNeeded() instead.
self.view.layoutIfNeeded()
}
// MARK: - Move to page index
/**
Move to page at index
:param: index Index of the page to move to
*/
public func moveToPage(index: Int) {
if index >= 0 && index < controllerArray.count {
// Update page if changed
if index != currentPageIndex {
startingPageForScroll = index
lastPageIndex = currentPageIndex
currentPageIndex = index
didTapMenuItemToScroll = true
// Add pages in between current and tapped page if necessary
var smallerIndex : Int = lastPageIndex < currentPageIndex ? lastPageIndex : currentPageIndex
var largerIndex : Int = lastPageIndex > currentPageIndex ? lastPageIndex : currentPageIndex
if smallerIndex + 1 != largerIndex {
for i in (smallerIndex + 1)...(largerIndex - 1) {
if pagesAddedDictionary[i] != i {
addPageAtIndex(i)
pagesAddedDictionary[i] = i
}
}
}
addPageAtIndex(index)
// Add page from which tap is initiated so it can be removed after tap is done
pagesAddedDictionary[lastPageIndex] = lastPageIndex
}
// Move controller scroll view when tapping menu item
var duration : Double = Double(scrollAnimationDurationOnMenuItemTap) / Double(1000)
UIView.animateWithDuration(duration, animations: { () -> Void in
var xOffset : CGFloat = CGFloat(index) * self.controllerScrollView.frame.width
self.controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: self.controllerScrollView.contentOffset.y), animated: false)
})
}
}
}
| bsd-3-clause | 3ae8951bf9a91632c83c9dec049be29e | 53.048835 | 392 | 0.588833 | 6.652732 | false | false | false | false |
IT-Department-Projects/POP-II | iOS App/notesNearby_iOS_finalUITests/notesNearby_iOS_final/IQKeyboardManagerSwift/IQToolbar/IQToolbar.swift | 1 | 9528 | //
// IQToolbar.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// 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
private var kIQToolbarTitleInvocationTarget = "kIQToolbarTitleInvocationTarget"
private var kIQToolbarTitleInvocationSelector = "kIQToolbarTitleInvocationSelector"
/** @abstract IQToolbar for IQKeyboardManager. */
public class IQToolbar: UIToolbar , UIInputViewAudioFeedback {
override public class func initialize() {
superclass()?.initialize()
self.appearance().barTintColor = nil
//Background image
self.appearance().setBackgroundImage(nil, forToolbarPosition: UIBarPosition.any, barMetrics: UIBarMetrics.default)
self.appearance().setBackgroundImage(nil, forToolbarPosition: UIBarPosition.bottom, barMetrics: UIBarMetrics.default)
self.appearance().setBackgroundImage(nil, forToolbarPosition: UIBarPosition.top, barMetrics: UIBarMetrics.default)
self.appearance().setBackgroundImage(nil, forToolbarPosition: UIBarPosition.topAttached, barMetrics: UIBarMetrics.default)
self.appearance().setShadowImage(nil, forToolbarPosition: UIBarPosition.any)
self.appearance().setShadowImage(nil, forToolbarPosition: UIBarPosition.bottom)
self.appearance().setShadowImage(nil, forToolbarPosition: UIBarPosition.top)
self.appearance().setShadowImage(nil, forToolbarPosition: UIBarPosition.topAttached)
//Background color
self.appearance().backgroundColor = nil
}
public var titleFont : UIFont? {
didSet {
if let newItems = items {
for item in newItems {
if let newItem = item as? IQTitleBarButtonItem {
newItem.font = titleFont
break
}
}
}
}
}
public var title : String? {
didSet {
if let newItems = items {
for item in newItems {
if let newItem = item as? IQTitleBarButtonItem {
newItem.title = title
break
}
}
}
}
}
public var doneTitle : String?
public var doneImage : UIImage?
/**
Optional target & action to behave toolbar title button as clickable button
@param target Target object.
@param action Target Selector.
*/
public func setCustomToolbarTitleTarget(_ target: AnyObject?, action: Selector?) {
toolbarTitleInvocation = (target, action)
}
/**
Customized Invocation to be called on title button action. titleInvocation is internally created using setTitleTarget:action: method.
*/
public var toolbarTitleInvocation : (target: AnyObject?, action: Selector?) {
get {
let target: AnyObject? = objc_getAssociatedObject(self, &kIQToolbarTitleInvocationTarget) as AnyObject?
var action : Selector?
if let selectorString = objc_getAssociatedObject(self, &kIQToolbarTitleInvocationSelector) as? String {
action = NSSelectorFromString(selectorString)
}
return (target: target, action: action)
}
set(newValue) {
objc_setAssociatedObject(self, &kIQToolbarTitleInvocationTarget, newValue.target, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if let unwrappedSelector = newValue.action {
objc_setAssociatedObject(self, &kIQToolbarTitleInvocationSelector, NSStringFromSelector(unwrappedSelector), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
} else {
objc_setAssociatedObject(self, &kIQToolbarTitleInvocationSelector, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
if let unwrappedItems = items {
for item in unwrappedItems {
if let newItem = item as? IQTitleBarButtonItem {
newItem.titleInvocation = newValue
break
}
}
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
sizeToFit()
autoresizingMask = UIViewAutoresizing.flexibleWidth
tintColor = UIColor .black
self.isTranslucent = true
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sizeToFit()
autoresizingMask = UIViewAutoresizing.flexibleWidth
tintColor = UIColor .black
self.isTranslucent = true
}
override public func sizeThatFits(_ size: CGSize) -> CGSize {
var sizeThatFit = super.sizeThatFits(size)
sizeThatFit.height = 44
return sizeThatFit
}
override public var tintColor: UIColor! {
didSet {
if let unwrappedItems = items {
for item in unwrappedItems {
item.tintColor = tintColor
}
}
}
}
override public var barStyle: UIBarStyle {
didSet {
if let unwrappedItems = items {
for item in unwrappedItems {
if let newItem = item as? IQTitleBarButtonItem {
if barStyle == .default {
newItem.selectableTextColor = UIColor.init(colorLiteralRed: 0.0, green: 0.5, blue: 1.0, alpha: 1)
} else {
newItem.selectableTextColor = UIColor.yellow
}
break
}
}
}
}
}
override public func layoutSubviews() {
super.layoutSubviews()
struct InternalClass {
static var IQUIToolbarTextButtonClass: AnyClass? = NSClassFromString("UIToolbarTextButton")
static var IQUIToolbarButtonClass: AnyClass? = NSClassFromString("UIToolbarButton")
}
var leftRect = CGRect.null
var rightRect = CGRect.null
var isTitleBarButtonFound = false
let sortedSubviews = self.subviews.sorted(by: { (view1 : UIView, view2 : UIView) -> Bool in
let x1 = view1.frame.minX
let y1 = view1.frame.minY
let x2 = view2.frame.minX
let y2 = view2.frame.minY
if x1 != x2 {
return x1 < x2
} else {
return y1 < y2
}
})
for barButtonItemView in sortedSubviews {
if (isTitleBarButtonFound == true)
{
rightRect = barButtonItemView.frame
break
}
else if (type(of: barButtonItemView) === UIView.self)
{
isTitleBarButtonFound = true
}
else if ((InternalClass.IQUIToolbarTextButtonClass != nil && barButtonItemView.isKind(of: InternalClass.IQUIToolbarTextButtonClass!) == true) || (InternalClass.IQUIToolbarButtonClass != nil && barButtonItemView.isKind(of: InternalClass.IQUIToolbarButtonClass!) == true))
{
leftRect = barButtonItemView.frame
}
}
var x : CGFloat = 16
if (leftRect.isNull == false)
{
x = leftRect.maxX + 16
}
let width : CGFloat = self.frame.width - 32 - (leftRect.isNull ? 0 : leftRect.maxX) - (rightRect.isNull ? 0 : self.frame.width - rightRect.minX)
if let unwrappedItems = items {
for item in unwrappedItems {
if let newItem = item as? IQTitleBarButtonItem {
let titleRect = CGRect(x: x, y: 0, width: width, height: self.frame.size.height)
newItem.customView?.frame = titleRect
break
}
}
}
}
public var enableInputClicksWhenVisible: Bool {
return true
}
}
| mit | 00b98a9f54e7311999b90ec78e447a1a | 35.366412 | 282 | 0.579765 | 5.568673 | false | false | false | false |
andrzejsemeniuk/ASToolkit | ASToolkit/Math.swift | 1 | 3915 | //
// Math.swift
// ASToolkit
//
// Created by andrzej semeniuk on 5/14/16.
// Copyright © 2017 Andrzej Semeniuk. All rights reserved.
//
import Foundation
import CoreGraphics
import GameplayKit
open class Math
{
static open func clamp(_ v:CGFloat, min v0:CGFloat, max v1:CGFloat) -> CGFloat {
return min(v1,max(v0,v))
}
static open func clamp01(_ v:CGFloat) -> CGFloat {
return clamp(v,min:0,max:1)
}
static private var __randomSourceObject :GKRandomSource?
static private var __randomSource :RandomSource = .arc4Random
public enum RandomSource {
case arc4Random, linearCongruential, mersenneTwister
}
static public func randomUseSource(_ source:RandomSource) -> GKRandomSource {
Math.__randomSource = source
switch source
{
case .arc4Random: Math.__randomSourceObject = GKARC4RandomSource()
case .linearCongruential: Math.__randomSourceObject = GKLinearCongruentialRandomSource()
case .mersenneTwister: Math.__randomSourceObject = GKMersenneTwisterRandomSource()
}
return Math.__randomSourceObject!
}
static public func randomGetSource() -> GKRandomSource {
return __randomSourceObject ?? randomUseSource(__randomSource)
}
fileprivate static var __randomDistributionObject :GKRandomDistribution?
fileprivate static let __randomDistributionLowestValue = 0
fileprivate static let __randomDistributionHighestValue = Int.max
fileprivate static let __randomDistributionDelta :Double = Double(__randomDistributionHighestValue - __randomDistributionLowestValue)
fileprivate static var __randomDistribution :RandomDistribution = .uniform
public enum RandomDistribution {
case gaussian,uniform
}
static public func randomUseDistribution(_ distribution:RandomDistribution) -> GKRandomDistribution {
Math.__randomDistribution = distribution
switch distribution
{
case .gaussian: Math.__randomDistributionObject = GKGaussianDistribution(randomSource : randomGetSource(),
lowestValue : Math.__randomDistributionLowestValue,
highestValue : Math.__randomDistributionHighestValue)
case .uniform: Math.__randomDistributionObject = GKRandomDistribution(randomSource : randomGetSource(),
lowestValue : Math.__randomDistributionLowestValue,
highestValue : Math.__randomDistributionHighestValue)
}
return Math.__randomDistributionObject!
}
static public func randomGetDistribution() -> GKRandomDistribution
{
return Math.__randomDistributionObject ?? randomUseDistribution(.uniform)
}
static public func random (from:CGFloat,to:CGFloat) -> CGFloat {
let v = Double(randomGetDistribution().nextInt())
let w = Math.__randomDistributionDelta
let x = CGFloat(v/w)
let y = to-from
return from + x * y
}
static public func random01 () -> CGFloat { return random(from: 0,to: 1) }
static public func random11 () -> CGFloat { return random(from:-1,to:+1) }
static public func arcrandom01 () -> Double { return Double(arc4random()) / Double(UInt32.max) }
static public func arcrandom (from:Double, to:Double) -> Double { return from+arcrandom01()*(to-from) }
}
| mit | c0f9f3036512973d61016e826818a687 | 39.350515 | 171 | 0.592489 | 5.156785 | false | false | false | false |
itechline/bonodom_new | SlideMenuControllerSwift/IdopontokByUserModel.swift | 1 | 751 | //
// IdopontokByUserModel.swift
// Bonodom
//
// Created by Attila Dán on 2016. 07. 15..
// Copyright © 2016. Itechline. All rights reserved.
//
import SwiftyJSON
class IdopontokByUserModel {
var id: Int!
var ingatlan_id: Int!
var datum: String!
var status: Int!
var fel_id: Int!
var felhasznalo: String!
var mobile: String!
required init(json: JSON) {
id = json["idopont_id"].intValue
ingatlan_id = json["idopont_ingatlan_id"].intValue
datum = json["idopont_bejelentkezes"].stringValue
status = json["idopont_statusz"].intValue
fel_id = json["fel_id"].intValue
felhasznalo = json["fel"].stringValue
mobile = json["fel_telefon"].stringValue
}
} | mit | b922f163eaaa203c3e16c46ee1f40130 | 24 | 58 | 0.630174 | 3.187234 | false | false | false | false |
shvets/WebAPI | Sources/WebAPI/MyHitAPI.swift | 1 | 20895 | import Foundation
import SwiftSoup
open class MyHitAPI: HttpService {
public static let SiteUrl = "https://my-hit.org"
let UserAgent = "My Hit User Agent"
public func available() throws -> Bool {
let document = try fetchDocument(MyHitAPI.SiteUrl)
return try document!.select("div[class=container] div[class=row]").size() > 0
}
func getPagePath(path: String, filter: String?=nil, page: Int=1) -> String {
var newPath: String
if page == 1 {
newPath = path
}
else {
var params = [String: String]()
params["p"] = String(page)
if filter != nil {
params["s"] = filter
}
newPath = buildUrl(path: path, params: params as [String : AnyObject])
}
return newPath
}
public func getAllMovies(page: Int=1) throws -> ItemsList {
return try getMovies(path: "/film/", page: page)
}
public func getAllSeries(page: Int=1) throws -> ItemsList {
return try getSeries(path: "/serial/", page: page)
}
public func getPopularMovies(page: Int=1) throws -> ItemsList {
return try getMovies(path: "/film/", filter: "3", page: page)
}
public func getPopularSeries(page: Int=1) throws -> ItemsList {
return try getSeries(path: "/serial/", filter: "3", page: page)
}
public func getMovies(path: String, type: String="movie", selector: String="film-list", filter: String?=nil, page: Int=1) throws -> ItemsList {
var data = [Any]()
var paginationData: ItemsList = [:]
let pagePath = getPagePath(path: path, filter: filter, page: page)
let document = try fetchDocument(MyHitAPI.SiteUrl + pagePath)
let items = try document!.select("div[class='" + selector + "'] div[class='row']")
for item: Element in items.array() {
let link = try item.select("a").get(0)
let href = try link.attr("href")
let name = try link.attr("title")
// let index1 = name.startIndex
// let index2 = name.index(name.endIndex, offsetBy: -18)
// name = name[index1 ..< index2]
let url = try link.select("div img").get(0).attr("src")
let thumb = MyHitAPI.SiteUrl + url
data.append(["type": type, "id": href, "thumb": thumb, "name": name])
}
let starItems = try document!.select("div[class='" + selector + "'] div[class='row star']")
for item: Element in starItems.array() {
let link = try item.select("a").get(0)
let href = try link.attr("href")
let name = try link.attr("title")
let url = try link.select("img").get(0).attr("src")
let thumb = MyHitAPI.SiteUrl + url
data.append(["type": "star", "id": href, "thumb": thumb, "name": name])
}
if items.size() > 0 {
paginationData = try extractPaginationData(pagePath, selector: selector, page: page)
}
return ["movies": data, "pagination": paginationData]
}
public func getSeries(path: String, filter: String?=nil, page: Int=1) throws -> ItemsList {
return try getMovies(path: path, type: "serie", selector: "serial-list", filter: filter, page: page)
}
public func getSoundtracks(page: Int=1) throws -> ItemsList {
var data = [Any]()
var paginationData: ItemsList = [:]
let path = "/soundtrack/"
let selector = "soundtrack-list"
let pagePath = getPagePath(path: path, page: page)
let document = try fetchDocument(MyHitAPI.SiteUrl + pagePath)
let items = try document!.select("div[class='" + selector + "'] div[class='row'] div")
for item: Element in items.array() {
let link1 = try item.select("div b a").get(0)
let link2 = try item.select("a").get(0)
let href = try link1.attr("href")
let name = try link1.text()
let imgBlock = try link2.select("img")
if imgBlock.size() > 0 {
let thumb = MyHitAPI.SiteUrl + (try imgBlock.attr("src"))
//if data.index(where: { elem in (elem as! [String: String])["id"] == href }) == nil {
data.append(["type": "soundtrack", "id": href, "name": name, "thumb": thumb])
//}
}
}
if items.size() > 0 {
paginationData = try extractPaginationData(pagePath, selector: selector, page: page)
}
return ["movies": data, "pagination": paginationData]
}
public func getAlbums(_ path: String) throws -> ItemsList {
var data = [[String: Any]]()
let pagePath = getPagePath(path: path)
let document = try fetchDocument(MyHitAPI.SiteUrl + pagePath)
var allTracks = [[[String: Any]]]()
let tracksBlock = try document?.select("div table[id='soundtrack_modify_table']")
for (index, trackBlock) in tracksBlock!.array().enumerated() {
let trackItems = try trackBlock.select("tbody tr")
allTracks.append([])
for trackItem in trackItems.array() {
let children = trackItem.children()
if children.size() == 5 {
let name = try children.get(1).text()
let duration = try children.get(2).text()
let bitrate = try children.get(3).text()
let url = try children.get(4).select("a").attr("href")
let record = ["url": MyHitAPI.SiteUrl + url, "name": name, "duration": duration, "bitrate": bitrate]
allTracks[index].append(record)
}
}
}
let items = try document!.select("div[class='container'] div[class='row'] div[class='row']")
var index1: Int = -1
for (_, item) in items.array().enumerated() {
let img = try item.select("div a img")
if img.size() > 0 {
index1 = index1 + 1
let src = try img.get(0).attr("src")
let thumb = MyHitAPI.SiteUrl + src
let name = try item.select("div a").attr("title")
var composer = ""
let liItems = try item.select("div ul li")
for li: Element in liItems.array() {
let text = try li.html()
if text.find("Композитор:") != nil {
let index = text.index(text.startIndex, offsetBy: "Композитор:".count)
composer = String(text[index ..< text.endIndex])
}
}
data.append([ "thumb": thumb, "name": name, "composer": composer, "tracks": allTracks[index1]])
}
}
var albums = [Any]()
for (_, album) in data.enumerated() {
let name = album["name"] as! String
let thumb = album["thumb"] as! String
let artist = album["composer"] as! String
let tracks = album["tracks"] as! [[String: Any]]
var tracksData = [[String: Any]]()
for track in tracks {
let url = track["url"]!
let name = track["name"]!
let format = "mp3"
let bitrate = track["bitrate"]!
let duration = track["duration"]!
tracksData.append(["type": "track", "id": url, "name": name, "artist": artist, "thumb": thumb,
"format": format, "bitrate": bitrate, "duration": duration])
}
albums.append(["type": "tracks", "name": name, "thumb": thumb, "artist": artist, "tracks": tracksData])
}
return ["movies": albums]
}
public func getSelections(page: Int=1) throws -> ItemsList {
var data = [Any]()
var paginationData: ItemsList = [:]
let path = "/selection/"
let selector = "selection-list"
let pagePath = getPagePath(path: path, page: page)
let document = try fetchDocument(MyHitAPI.SiteUrl + pagePath)
let items = try document!.select("div[class='" + selector + "'] div[class='row'] div")
for item: Element in items.array() {
let link1 = try item.select("div b a").get(0)
let link2 = try item.select("a").get(0)
let href = try link1.attr("href")
let name = try link1.text()
let thumb = try link2.select("img").attr("src")
if thumb != "" {
if name != "Актёры и актрисы" && name != "Актеры и актрисы" {
data.append(["type": "selection", "id": href, "thumb": MyHitAPI.SiteUrl + thumb, "name": name])
}
}
}
if items.size() > 0 {
paginationData = try extractPaginationData(pagePath, selector: selector, page: page)
}
return ["movies": data, "pagination": paginationData]
}
func getSelectionId(_ path: String) -> String {
let index = path.index(path.startIndex, offsetBy: 2)
return String(path[index ..< path.endIndex])
}
public func getSelection(path: String, page: Int=1) throws -> ItemsList {
var data = [Any]()
var paginationData: ItemsList = [:]
let selector = "selection-view"
let id = self.getSelectionId(path)
let pagePath = getPagePath(path: "/selection/" + id + "/", page: page)
let document = try fetchDocument(MyHitAPI.SiteUrl + pagePath)
let items = try document!.select("div[class='" + selector + "'] div[class='row']")
for item: Element in items.array() {
let link = try item.select("div a").get(0)
let href = try link.attr("href")
let name = try link.attr("title")
// let index1 = name.startIndex
// let index2 = name.index(name.endIndex, offsetBy: -18-1)
//
// name = name[index1 ... index2]
let url = try link.select("div img").get(0).attr("src")
let thumb = MyHitAPI.SiteUrl + url
let type = (href.find("/serial") != nil) ? "serie" : "movie"
data.append(["type": type, "id": href, "thumb": thumb, "name": name])
}
if items.size() > 0 {
paginationData = try extractPaginationData(pagePath, selector: selector, page: page)
}
return ["movies": data, "pagination": paginationData]
}
public func getFilters(mode: String="film") throws -> [Any] {
var data = [Any]()
let document = try fetchDocument(MyHitAPI.SiteUrl + "/" + mode + "/")
var currentGroupName: String = ""
let selector = "sidebar-nav"
let items = try document!.select("div[class='" + selector + "'] ul li")
for item: Element in items.array() {
let clazz = try item.attr("class")
if clazz == "nav-header" {
let name = try item.text().replacingOccurrences(of: ":", with: "")
currentGroupName = name
data.append(["name": name, "items": []])
}
else if clazz == "text-nowrap" {
let link = try item.select("a").get(0)
let href = try link.attr("href")
let name = try link.text()
let currentIndex1 = itemIndex(data, name: currentGroupName)
if currentIndex1 != nil {
let group = (data[currentIndex1!] as! [String: Any])
var items = (group["items"] as! [Any])
items.append(["id": href, "name": name])
let groupName = (group["name"] as! String)
data[currentIndex1!] = ["name": groupName, "items": items]
}
}
else if clazz == "dropdown" {
let currentIndex2 = itemIndex(data, name: currentGroupName)
if currentIndex2 != nil {
let group = (data[currentIndex2!] as! [String: Any])
let groupName = (group["name"] as! String)
data[currentIndex2!] = ["name": groupName, "items": []]
}
let liItems = try item.select("ul li")
var currentGroup = [Any]()
for liItem in liItems.array() {
let link = try liItem.select("a").get(0)
let href = try link.attr("href")
let name = try link.text()
currentGroup.append(["id": href, "name": name])
}
let currentIndex3 = itemIndex(data, name: currentGroupName)
if currentIndex3 != nil {
data[currentIndex3!] = ["name": currentGroupName, "items": currentGroup]
}
}
}
return data
}
func itemIndex(_ collection: [Any], name: String) -> Int? {
return collection.firstIndex { item in
let nm = (item as! [String: Any])["name"]!
return nm as! String == name
}
}
public func search(_ query: String, page: Int=1) throws -> ItemsList {
let path = "/search/"
var params = [String: String]()
params["q"] = query.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
params["p"] = String(page)
let fullPath = buildUrl(path: path, params: params as [String : AnyObject])
return try getMovies(path: fullPath, page: page)
}
public func getSeasons(_ path: String, parentName: String?=nil) -> ItemsList {
let data = [Any]()
// var result = JSON(data: fetchData(MyHitAPI.SiteUrl + path + "/playlist.txt")!)
//
// let playlist = result["playlist"]
//
// if playlist != JSON.null && playlist[0]["playlist"].arrayValue.isEmpty {
// var episodeData = [Any]()
//
// for (_, episode) in playlist {
// let episodeId = episode["file"].stringValue
// let episodeName = episode["comment"].stringValue
// let episodeThumb = MyHitAPI.SiteUrl + episode["poster"].stringValue
//
// episodeData.append([ "type": "episode", "id": episodeId, "name": episodeName, "thumb": episodeThumb])
// }
//
// var season: [String: Any] = ["type": "season", "name": "Сезон 1", "seasonNumber": 1, "episodes": episodeData]
//
// if let parentName = parentName {
// season["parentName"] = parentName
// }
//
// season["parentId"] = path
//
// data.append(season)
// }
// else {
// var index1 = 0
//
// for (_, season) in playlist {
// index1 += 1
//
// let name = season["comment"].stringValue
// let episodes = season["playlist"]
// let thumb = MyHitAPI.SiteUrl + season["poster"].stringValue
//
// var episodeData = [Any]()
//
// var index2 = 0
//
// for (_, episode) in episodes {
// index2 += 1
// let episodeId = episode["file"].stringValue
// let episodeName = episode["comment"].stringValue
// let episodeThumb = MyHitAPI.SiteUrl + episode["poster"].stringValue
//
// episodeData.append([ "type": "episode", "id": episodeId, "name": episodeName, "thumb": episodeThumb])
// }
//
// var season: [String: Any] = ["type": "season", "name": name, "id": path, "seasonNumber": index1, "thumb": thumb, "episodes": episodeData]
//
// if let parentName = parentName {
// season["parentName"] = parentName
// }
//
// season["parentId"] = path
//
// data.append(season)
// }
// }
return ["movies": data]
}
public func getEpisodes(_ path: String, parentName: String, seasonNumber: String, pageSize: Int, page: Int) -> ItemsList {
var data = [Any]()
let seasons = getSeasons(path)["movies"] as! [Any]
if let seasonNumber = Int(seasonNumber) {
let episodes = seasons[seasonNumber-1]
data = (episodes as! [String: Any])["episodes"] as! [Any]
}
var newData: [Any] = []
for index in (page-1)*pageSize ..< page*pageSize {
if index < data.count {
var episode = data[index] as! [String: String]
episode["parentName"] = parentName
newData.append(episode)
}
}
return ["movies": newData]
}
public func getMediaData(pathOrUrl: String) throws -> [String: Any] {
var data = [String: Any]()
var url: String = ""
if pathOrUrl.find("http://") == pathOrUrl.startIndex {
url = pathOrUrl
}
else {
url = MyHitAPI.SiteUrl + pathOrUrl
}
let document = try fetchDocument(url)
let infoRoot = try document?.select("div[class='row']")
if infoRoot!.size() > 0 {
let infoNode = try infoRoot!.select("ul[class='list-unstyled']")
for item: Element in infoNode.array() {
let line = try item.text()
let index = line.find(":")
if index != nil {
let key = String(line[line.startIndex ... index!])
let value = String(sanitize(String(line[line.index(after: index!) ..< line.endIndex])))
if key == "Продолжительность" {
data["duration"] = Int(value.replacingOccurrences(of: "мин.", with: "").trim())! * 60 * 1000
}
else if key == "Режиссер" {
data["directors"] = value.trim().replacingOccurrences(of: ".", with: "").components(separatedBy: ",")
}
else if key == "Жанр" {
data["tags"] = value.trim().components(separatedBy: ",")
}
else {
data[key] = value
}
}
}
let text = try infoNode.get(1).html()
let index = text.index(text.startIndex, offsetBy: "В ролях:".count)
let artists = text[index ..< text.endIndex].components(separatedBy: ",")
data["artists"] = artists
let descriptionNode = try infoRoot?.get(0).select("div[itemprop='description']")
if descriptionNode != nil {
var description = ""
if descriptionNode!.size() > 0 {
description = try descriptionNode!.get(0).text()
}
data["description"] = description
}
}
return data
}
public func getMetadata(_ url: String) throws -> [String: String] {
var data = [[String: String]]()
let sourceUrl = getBaseUrl(url) + "/manifest.f4m"
let document = try fetchDocument(sourceUrl)
let mediaBlock = try document?.select("manifest media")
for media in mediaBlock!.array() {
let width = Int(try media.attr("width"))!
let height = Int(try media.attr("height"))!
let bitrate = Int(try media.attr("bitrate"))! * 1000
let url = try media.attr("url")
data.append([ "width": width.description, "height": height.description, "bitrate": bitrate.description, "url": url ])
}
let bandwidth = extractBandwidth(url)
var location = -1
for (index, item) in data.enumerated() {
let url = item["url"]!
if url.find(bandwidth) != nil {
location = index
break
}
}
return location == -1 ? [:] : data[location]
}
public func extractBandwidth(_ url: String) -> String {
var pattern = "chunklist_b"
var index11 = url.find(pattern)
if index11 == nil {
pattern = "chunklist"
index11 = url.find(pattern)
}
let index1 = url.index(index11!, offsetBy: pattern.count)
let index2 = url.find(".m3u8")
return String(url[index1 ... index2!])
}
public func getUrls(path: String="", url: String="") throws -> [String] {
var urls = [String]()
var sourceUrl: String = ""
if path != "" {
sourceUrl = try getSourceUrl(MyHitAPI.SiteUrl + path)
}
else {
sourceUrl = url
}
if sourceUrl != "" {
for url in try self.getPlayListUrls(sourceUrl) {
urls.append(url["url"]!)
}
}
return urls.reversed()
}
func getSourceUrl(_ url: String) throws -> String {
var name = ""
let content = fetchData(url, headers: getHeaders())
let document = try toDocument(content)
let scripts = try document?.select("div[class='row'] div script")
for script in scripts!.array() {
let html = try script.html()
if html != "" {
let index1 = html.find("file:")
let index2 = html.find(".f4m")
let index21 = html.find(".m3u8")
if index1 != nil && index2 != nil {
let index3 = html.index(index1!, offsetBy: 6)
let text = String(html[index3 ..< index2!])
if text != "" {
name = text + ".m3u8"
}
}
if index1 != nil && index21 != nil {
let index3 = html.index(index1!, offsetBy: 6)
let text = String(html[index3 ..< index21!])
if text != "" {
name = text + ".m3u8"
}
}
}
}
return name
}
func extractPaginationData(_ path: String, selector: String, page: Int) throws -> ItemsList {
let document = try fetchDocument(MyHitAPI.SiteUrl + path)
var pages = 1
let paginationRoot = try document?.select("div[class='" + selector + "'] ~ div[class='row']")
if paginationRoot != nil {
let paginationBlock = paginationRoot!.get(0)
let text = try paginationBlock.text()
let index11 = text.find(":")
let index21 = text.find("(")
if index11 != nil && index21 != nil {
let index1 = text.index(index11!, offsetBy: 1)
let items = Int(String(text[index1 ..< index21!]).trim())
pages = items! / 24
if items! % 24 > 0 {
pages = pages + 1
}
}
}
return [
"page": page,
"pages": pages,
"has_previous": page > 1,
"has_next": page < pages
]
}
func sanitize(_ str: String) -> String {
let result = str.replacingOccurrences(of: " ", with: "")
return result
}
func getEpisodeUrl(url: String, season: String="", episode: String="") -> String {
var episodeUrl = url
if season != "" {
episodeUrl = "\(url)?season=\(season)&episode=\(episode)"
}
return episodeUrl
}
func getHeaders() -> [String: String] {
return [
"User-Agent": UserAgent
]
}
}
| mit | f568e428b4850e133a06cf63082ced74 | 27.304762 | 147 | 0.578879 | 3.790816 | false | false | false | false |
PravinNagargoje/CustomCalendar | Pods/JTAppleCalendar/Sources/UserInteractionFunctions.swift | 1 | 28364 | //
// UserInteractionFunctions.swift
//
// Copyright (c) 2016-2017 JTAppleCalendar (https://github.com/patchthecode/JTAppleCalendar)
//
// 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 JTAppleCalendarView {
/// Returns the cellStatus of a date that is visible on the screen.
/// If the row and column for the date cannot be found,
/// then nil is returned
/// - Paramater row: Int row of the date to find
/// - Paramater column: Int column of the date to find
/// - returns:
/// - CellState: The state of the found cell
public func cellStatusForDate(at row: Int, column: Int) -> CellState? {
guard let section = currentSection() else {
return nil
}
let convertedRow = (row * maxNumberOfDaysInWeek) + column
let indexPathToFind = IndexPath(item: convertedRow, section: section)
if let date = dateOwnerInfoFromPath(indexPathToFind) {
let stateOfCell = cellStateFromIndexPath(indexPathToFind, withDateInfo: date)
return stateOfCell
}
return nil
}
/// Returns the cell status for a given date
/// - Parameter: date Date of the cell you want to find
/// - returns:
/// - CellState: The state of the found cell
public func cellStatus(for date: Date) -> CellState? {
// validate the path
let paths = pathsFromDates([date])
// Jt101 change this function to also return
// information like the dateInfoFromPath function
if paths.isEmpty { return nil }
let cell = cellForItem(at: paths[0]) as? JTAppleCell
let stateOfCell = cellStateFromIndexPath(paths[0], cell: cell)
return stateOfCell
}
/// Returns the cell status for a given point
/// - Parameter: point of the cell you want to find
/// - returns:
/// - CellState: The state of the found cell
public func cellStatus(at point: CGPoint) -> CellState? {
if let indexPath = indexPathForItem(at: point) {
let cell = cellForItem(at: indexPath) as? JTAppleCell
return cellStateFromIndexPath(indexPath, cell: cell)
}
return nil
}
/// Deselect all selected dates
/// - Parameter: this funciton triggers a delegate call by default. Set this to false if you do not want this
public func deselectAllDates(triggerSelectionDelegate: Bool = true) {
deselect(dates: selectedDates, triggerSelectionDelegate: triggerSelectionDelegate)
}
/// Deselect dates
/// - Parameter: Dates - The dates to deselect
/// - Parameter: triggerSelectionDelegate - this funciton triggers a delegate call by default. Set this to false if you do not want this
public func deselect(dates: [Date], triggerSelectionDelegate: Bool = true) {
if allowsMultipleSelection {
selectDates(dates, triggerSelectionDelegate: triggerSelectionDelegate)
} else {
let paths = pathsFromDates(dates)
guard !paths.isEmpty else { return }
if paths.count > 1 { assert(false, "WARNING: you are trying to deselect multiple dates with allowsMultipleSelection == false. Only the first date will be deselected.")}
collectionView(self, didDeselectItemAt: paths[0])
}
}
/// Generates a range of dates from from a startDate to an
/// endDate you provide
/// Parameter startDate: Start date to generate dates from
/// Parameter endDate: End date to generate dates to
/// returns:
/// - An array of the successfully generated dates
public func generateDateRange(from startDate: Date, to endDate: Date) -> [Date] {
if startDate > endDate {
return []
}
var returnDates: [Date] = []
var currentDate = startDate
repeat {
returnDates.append(currentDate)
currentDate = calendar.startOfDay(for: calendar.date(
byAdding: .day, value: 1, to: currentDate)!)
} while currentDate <= endDate
return returnDates
}
/// Registers a class for use in creating supplementary views for the collection view.
/// For now, the calendar only supports: 'UICollectionElementKindSectionHeader' for the forSupplementaryViewOfKind(parameter)
open override func register(_ viewClass: AnyClass?, forSupplementaryViewOfKind elementKind: String, withReuseIdentifier identifier: String) {
super.register(viewClass, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: identifier)
}
/// Registers a class for use in creating supplementary views for the collection view.
/// For now, the calendar only supports: 'UICollectionElementKindSectionHeader' for the forSupplementaryViewOfKind(parameter)
open override func register(_ nib: UINib?, forSupplementaryViewOfKind kind: String, withReuseIdentifier identifier: String) {
super.register(nib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: identifier)
}
/// Dequeues re-usable calendar cells
public func dequeueReusableJTAppleSupplementaryView(withReuseIdentifier identifier: String, for indexPath: IndexPath) -> JTAppleCollectionReusableView {
guard let headerView = dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader,
withReuseIdentifier: identifier,
for: indexPath) as? JTAppleCollectionReusableView else {
developerError(string: "Error initializing Header View with identifier: '\(identifier)'")
return JTAppleCollectionReusableView()
}
return headerView
}
/// Registers a nib for use in creating Decoration views for the collection view.
public func registerDecorationView(nib: UINib?) {
calendarViewLayout.register(nib, forDecorationViewOfKind: decorationViewID)
}
/// Registers a class for use in creating Decoration views for the collection view.
public func register(viewClass className: AnyClass?, forDecorationViewOfKind kind: String) {
calendarViewLayout.register(className, forDecorationViewOfKind: decorationViewID)
}
/// Dequeues a reuable calendar cell
public func dequeueReusableJTAppleCell(withReuseIdentifier identifier: String, for indexPath: IndexPath) -> JTAppleCell {
guard let cell = dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as? JTAppleCell else {
developerError(string: "Error initializing Cell View with identifier: '\(identifier)'")
return JTAppleCell()
}
return cell
}
/// Reloads the data on the calendar view. Scroll delegates are not
// triggered with this function.
/// - Parameter date: An anchordate that the calendar will
/// scroll to after reload completes
/// - Parameter animation: Scroll is animated if this is set to true
/// - Parameter completionHandler: This closure will run after
/// the reload is complete
public func reloadData(completionHandler: (() -> Void)? = nil) {
if isScrollInProgress || isReloadDataInProgress {
delayedExecutionClosure.append {[unowned self] in
self.reloadData(completionHandler: completionHandler)
}
return
}
isReloadDataInProgress = true
let selectedDates = self.selectedDates
let layoutNeedsUpdating = reloadDelegateDataSource()
if layoutNeedsUpdating {
calendarViewLayout.invalidateLayout()
setupMonthInfoAndMap()
self.theSelectedIndexPaths = []
self.theSelectedDates = []
}
// Restore the selected index paths
let restoreAfterReload = {
if !selectedDates.isEmpty { // If layoutNeedsUpdating was false, layoutData would remain and re-selection wouldnt be needed
self.selectDates(selectedDates, triggerSelectionDelegate: false, keepSelectionIfMultiSelectionAllowed: true)
}
}
if !selectedDates.isEmpty { delayedExecutionClosure.append(restoreAfterReload) }
if let validCompletionHandler = completionHandler {
delayedExecutionClosure.append(validCompletionHandler)
}
if !layoutNeedsUpdating { calendarViewLayout.shouldClearCacheOnInvalidate = false }
super.reloadData()
isReloadDataInProgress = false
if !isCalendarLayoutLoaded { return } // Return if the reload is not yet complete and cells have not yet been re-generated
if !delayedExecutionClosure.isEmpty { executeDelayedTasks() }
}
/// Reload the date of specified date-cells on the calendar-view
/// - Parameter dates: Date-cells with these specified
/// dates will be reloaded
public func reloadDates(_ dates: [Date]) {
var paths = [IndexPath]()
for date in dates {
let aPath = pathsFromDates([date])
if !aPath.isEmpty && !paths.contains(aPath[0]) {
paths.append(aPath[0])
let cellState = cellStateFromIndexPath(aPath[0])
if let validCounterPartCell = indexPathOfdateCellCounterPath(date,dateOwner: cellState.dateBelongsTo) {
paths.append(validCounterPartCell)
}
}
}
// Before reloading, set the proposal path,
// so that in the event targetContentOffset gets called. We know the path
calendarViewLayout.setMinVisibleDate()
batchReloadIndexPaths(paths)
}
/// Select a date-cell range
/// - Parameter startDate: Date to start the selection from
/// - Parameter endDate: Date to end the selection from
/// - Parameter triggerDidSelectDelegate: Triggers the delegate
/// function only if the value is set to true.
/// Sometimes it is necessary to setup some dates without triggereing
/// the delegate e.g. For instance, when youre initally setting up data
/// in your viewDidLoad
/// - Parameter keepSelectionIfMultiSelectionAllowed: This is only
/// applicable in allowedMultiSelection = true.
/// This overrides the default toggle behavior of selection.
/// If true, selected cells will remain selected.
public func selectDates(from startDate: Date, to endDate: Date, triggerSelectionDelegate: Bool = true, keepSelectionIfMultiSelectionAllowed: Bool = false) {
selectDates(generateDateRange(from: startDate, to: endDate),
triggerSelectionDelegate: triggerSelectionDelegate,
keepSelectionIfMultiSelectionAllowed: keepSelectionIfMultiSelectionAllowed)
}
/// Deselect all selected dates within a range
public func deselectDates(from start: Date, to end: Date? = nil, triggerSelectionDelegate: Bool = true) {
if selectedDates.isEmpty { return }
let end = end ?? selectedDates.last!
let dates = selectedDates.filter { $0 >= start && $0 <= end }
deselect(dates: dates, triggerSelectionDelegate: triggerSelectionDelegate)
}
/// Select a date-cells
/// - Parameter date: The date-cell with this date will be selected
/// - Parameter triggerDidSelectDelegate: Triggers the delegate function
/// only if the value is set to true.
/// Sometimes it is necessary to setup some dates without triggereing
/// the delegate e.g. For instance, when youre initally setting up data
/// in your viewDidLoad
public func selectDates(_ dates: [Date], triggerSelectionDelegate: Bool = true, keepSelectionIfMultiSelectionAllowed: Bool = false) {
if dates.isEmpty { return }
if (!isCalendarLayoutLoaded || isReloadDataInProgress) {
// If the calendar is not yet fully loaded.
// Add the task to the delayed queue
delayedExecutionClosure.append {[unowned self] in
self.selectDates(dates,
triggerSelectionDelegate: triggerSelectionDelegate,
keepSelectionIfMultiSelectionAllowed: keepSelectionIfMultiSelectionAllowed)
}
return
}
var allIndexPathsToReload: Set<IndexPath> = []
var validDatesToSelect = dates
// If user is trying to select multiple dates with
// multiselection disabled, then only select the last object
if !allowsMultipleSelection, let dateToSelect = dates.last {
validDatesToSelect = [dateToSelect]
}
for date in validDatesToSelect {
let date = calendar.startOfDay(for: date)
let components = calendar.dateComponents([.year, .month, .day], from: date)
let firstDayOfDate = calendar.date(from: components)!
// If the date is not within valid boundaries, then exit
if !(firstDayOfDate >= startOfMonthCache! && firstDayOfDate <= endOfMonthCache!) { continue }
let pathFromDates = self.pathsFromDates([date])
// If the date path youre searching for, doesnt exist, return
if pathFromDates.isEmpty { continue }
let sectionIndexPath = pathFromDates[0]
if !collectionView(self, shouldSelectItemAt: sectionIndexPath) { continue }
// Remove old selections
if self.allowsMultipleSelection == false {
// If single selection is ON
let selectedIndexPaths = self.theSelectedIndexPaths
// made a copy because the array is about to be mutated
for indexPath in selectedIndexPaths {
if indexPath != sectionIndexPath {
let pathsToReload = deselectDate(oldIndexPath: indexPath, shouldTriggerSelecteionDelegate: triggerSelectionDelegate)
allIndexPathsToReload.formUnion(pathsToReload)
}
}
// Add new selections Must be added here. If added in delegate didSelectItemAtIndexPath
let pathsToReload = selectDate(indexPath: sectionIndexPath, date: date, shouldTriggerSelecteionDelegate: triggerSelectionDelegate)
allIndexPathsToReload.formUnion(pathsToReload)
} else {
// If multiple selection is on. Multiple selection behaves differently to singleselection.
// It behaves like a toggle. unless keepSelectionIfMultiSelectionAllowed is true.
// If user wants to force selection if multiselection is enabled, then removed the selected dates from generated dates
if keepSelectionIfMultiSelectionAllowed, selectedDates.contains(date) {
// Just add it to be reloaded
allIndexPathsToReload.insert(sectionIndexPath)
} else {
if self.theSelectedIndexPaths.contains(sectionIndexPath) {
// If this cell is already selected, then deselect it
let pathsToReload = self.deselectDate(oldIndexPath: sectionIndexPath, shouldTriggerSelecteionDelegate: triggerSelectionDelegate)
allIndexPathsToReload.formUnion(pathsToReload)
} else {
// Add new selections
// Must be added here. If added in delegate didSelectItemAtIndexPath
let pathsToReload = self.selectDate(indexPath: sectionIndexPath, date: date, shouldTriggerSelecteionDelegate: triggerSelectionDelegate)
allIndexPathsToReload.formUnion(pathsToReload)
}
}
}
}
// If triggering was false, although the selectDelegates weren't
// called, we do want the cell refreshed.
// Reload to call itemAtIndexPath
if !triggerSelectionDelegate && !allIndexPathsToReload.isEmpty {
self.batchReloadIndexPaths(Array(allIndexPathsToReload))
}
}
/// Scrolls the calendar view to the next section view. It will execute a completion handler at the end of scroll animation if provided.
/// - Paramater direction: Indicates a direction to scroll
/// - Paramater animateScroll: Bool indicating if animation should be enabled
/// - Parameter triggerScrollToDateDelegate: trigger delegate if set to true
/// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation
public func scrollToSegment(_ destination: SegmentDestination,
triggerScrollToDateDelegate: Bool = true,
animateScroll: Bool = true,
extraAddedOffset: CGFloat = 0,
completionHandler: (() -> Void)? = nil) {
if functionIsUnsafeSafeToRun {
delayedExecutionClosure.append {[unowned self] in
self.scrollToSegment(destination,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
animateScroll: animateScroll,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler)
}
}
var xOffset: CGFloat = 0
var yOffset: CGFloat = 0
let fixedScrollSize: CGFloat
if scrollDirection == .horizontal {
if calendarViewLayout.thereAreHeaders || cachedConfiguration.generateOutDates == .tillEndOfGrid {
fixedScrollSize = calendarViewLayout.sizeOfContentForSection(0)
} else {
fixedScrollSize = frame.width
}
let section = CGFloat(Int(contentOffset.x / fixedScrollSize))
xOffset = (fixedScrollSize * section)
switch destination {
case .next:
xOffset += fixedScrollSize
case .previous:
xOffset -= fixedScrollSize
case .end:
xOffset = contentSize.width - frame.width
case .start:
xOffset = 0
}
if xOffset <= 0 {
xOffset = 0
} else if xOffset >= contentSize.width - frame.width {
xOffset = contentSize.width - frame.width
}
} else {
if calendarViewLayout.thereAreHeaders {
guard let section = currentSection() else {
return
}
if (destination == .next && section + 1 >= numberOfSections(in: self)) ||
destination == .previous && section - 1 < 0 ||
numberOfSections(in: self) < 0 {
return
}
switch destination {
case .next:
scrollToHeaderInSection(section + 1, extraAddedOffset: extraAddedOffset)
case .previous:
scrollToHeaderInSection(section - 1, extraAddedOffset: extraAddedOffset)
case .start:
scrollToHeaderInSection(0, extraAddedOffset: extraAddedOffset)
case .end:
scrollToHeaderInSection(numberOfSections(in: self) - 1, extraAddedOffset: extraAddedOffset)
}
return
} else {
fixedScrollSize = frame.height
let section = CGFloat(Int(contentOffset.y / fixedScrollSize))
yOffset = (fixedScrollSize * section) + fixedScrollSize
}
if yOffset <= 0 {
yOffset = 0
} else if yOffset >= contentSize.height - frame.height {
yOffset = contentSize.height - frame.height
}
}
scrollTo(point: CGPoint(x: xOffset, y: yOffset),
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
isAnimationEnabled: animateScroll,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler)
}
/// Scrolls the calendar view to the start of a section view containing a specified date.
/// - Paramater date: The calendar view will scroll to a date-cell containing this date if it exists
/// - Parameter triggerScrollToDateDelegate: Trigger delegate if set to true
/// - Paramater animateScroll: Bool indicating if animation should be enabled
/// - Paramater preferredScrollPositionIndex: Integer indicating the end scroll position on the screen.
/// This value indicates column number for Horizontal scrolling and row number for a vertical scrolling calendar
/// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation
public func scrollToDate(_ date: Date,
triggerScrollToDateDelegate: Bool = true,
animateScroll: Bool = true,
preferredScrollPosition: UICollectionViewScrollPosition? = nil,
extraAddedOffset: CGFloat = 0,
completionHandler: (() -> Void)? = nil) {
// Ensure scrolling to date is safe to run
if functionIsUnsafeSafeToRun {
if !animateScroll { initialScrollDate = date}
delayedExecutionClosure.append {[unowned self] in
self.scrollToDate(date,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
animateScroll: animateScroll,
preferredScrollPosition: preferredScrollPosition,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler)
}
return
}
// Set triggereing of delegate on scroll
self.triggerScrollToDateDelegate = triggerScrollToDateDelegate
// Ensure date is within valid boundary
let components = calendar.dateComponents([.year, .month, .day], from: date)
let firstDayOfDate = calendar.date(from: components)!
if !((firstDayOfDate >= self.startOfMonthCache!) && (firstDayOfDate <= self.endOfMonthCache!)) { return }
// Get valid indexPath of date to scroll to
let retrievedPathsFromDates = self.pathsFromDates([date])
if retrievedPathsFromDates.isEmpty { return }
let sectionIndexPath = self.pathsFromDates([date])[0]
// Ensure valid scroll position is set
var position: UICollectionViewScrollPosition = self.scrollDirection == .horizontal ? .left : .top
if !self.scrollingMode.pagingIsEnabled(),
let validPosition = preferredScrollPosition {
if self.scrollDirection == .horizontal {
if validPosition == .left || validPosition == .right || validPosition == .centeredHorizontally {
position = validPosition
}
} else {
if validPosition == .top || validPosition == .bottom || validPosition == .centeredVertically {
position = validPosition
}
}
}
var point: CGPoint?
switch self.scrollingMode {
case .stopAtEach, .stopAtEachSection, .stopAtEachCalendarFrameWidth, .nonStopToSection:
if self.scrollDirection == .horizontal || (scrollDirection == .vertical && !calendarViewLayout.thereAreHeaders) {
point = self.targetPointForItemAt(indexPath: sectionIndexPath)
}
default:
break
}
handleScroll(point: point,
indexPath: sectionIndexPath,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
isAnimationEnabled: animateScroll,
position: position,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler)
}
/// Scrolls the calendar view to the start of a section view header.
/// If the calendar has no headers registered, then this function does nothing
/// - Paramater date: The calendar view will scroll to the header of
/// a this provided date
public func scrollToHeaderForDate(_ date: Date,
triggerScrollToDateDelegate: Bool = false,
withAnimation animation: Bool = false,
extraAddedOffset: CGFloat = 0,
completionHandler: (() -> Void)? = nil) {
if functionIsUnsafeSafeToRun {
if !animation { initialScrollDate = date}
delayedExecutionClosure.append {[unowned self] in
self.scrollToHeaderForDate(date,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
withAnimation: animation,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler)
}
return
}
let path = pathsFromDates([date])
// Return if date was incalid and no path was returned
if path.isEmpty { return }
scrollToHeaderInSection(
path[0].section,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
withAnimation: animation,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler
)
}
/// Returns the visible dates of the calendar.
/// - returns:
/// - DateSegmentInfo
public func visibleDates()-> DateSegmentInfo {
let emptySegment = DateSegmentInfo(indates: [], monthDates: [], outdates: [])
if !isCalendarLayoutLoaded {
return emptySegment
}
let cellAttributes = calendarViewLayout.visibleElements(excludeHeaders: true)
let indexPaths: [IndexPath] = cellAttributes.map { $0.indexPath }.sorted()
return dateSegmentInfoFrom(visible: indexPaths)
}
/// Returns the visible dates of the calendar.
/// - returns:
/// - DateSegmentInfo
public func visibleDates(_ completionHandler: @escaping (_ dateSegmentInfo: DateSegmentInfo) ->()) {
if functionIsUnsafeSafeToRun {
delayedExecutionClosure.append {[unowned self] in
self.visibleDates(completionHandler)
}
return
}
let retval = visibleDates()
completionHandler(retval)
}
}
| mit | 84d46e10929d573fdba79d9b5e210585 | 49.831541 | 180 | 0.620505 | 5.853075 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/NotificationsCenterOnboardingHostingViewController.swift | 1 | 1592 | import SwiftUI
protocol NotificationsCenterOnboardingDelegate: AnyObject {
func userDidDismissNotificationsCenterOnboardingView()
}
final class NotificationsCenterOnboardingHostingViewController: UIHostingController<NotificationsCenterOnboardingView>, UIAdaptivePresentationControllerDelegate, Themeable, RMessageSuppressing {
// MARK: - Properties
weak var delegate: NotificationsCenterOnboardingDelegate?
var theme: Theme
// MARK: - Lifecycle
init(theme: Theme) {
self.theme = theme
super.init(rootView: NotificationsCenterOnboardingView(theme: theme))
rootView.dismissAction = { [weak self] in
self?.dismiss()
}
view.backgroundColor = theme.colors.paperBackground
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
presentationController?.delegate = self
}
// MARK: - Actions
fileprivate func dismiss() {
dismiss(animated: true, completion: {
self.delegate?.userDidDismissNotificationsCenterOnboardingView()
})
}
// MARK: - UIAdaptivePresentationControllerDelegate
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
delegate?.userDidDismissNotificationsCenterOnboardingView()
}
// MARK: - Themeable
func apply(theme: Theme) {
self.theme = theme
self.rootView.theme = theme
view.backgroundColor = theme.colors.paperBackground
}
}
| mit | 7fd6c89a4fea1a4ad29a2b5f6aeb7006 | 27.428571 | 194 | 0.704146 | 5.64539 | false | false | false | false |
ReactiveKit/Bond | Sources/Bond/UIKit/UITableView+DataSource.swift | 1 | 13703 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if os(iOS) || os(tvOS)
import UIKit
import ReactiveKit
extension SignalProtocol where Element: SectionedDataSourceChangesetConvertible, Error == Never {
/// Binds the signal of data source elements to the given table view.
///
/// - parameters:
/// - tableView: A table view that should display the data from the data source.
/// - animated: Animate partial or batched updates. Default is `true`.
/// - rowAnimation: Row animation for partial or batched updates. Relevant only when `animated` is `true`. Default is `.automatic`.
/// - createCell: A closure that creates (dequeues) cell for the given table view and configures it with the given data source at the given index path.
/// - returns: A disposable object that can terminate the binding. Safe to ignore - the binding will be automatically terminated when the table view is deallocated.
@discardableResult
public func bind(to tableView: UITableView, animated: Bool = true, rowAnimation: UITableView.RowAnimation = .automatic, createCell: @escaping (Element.Changeset.Collection, IndexPath, UITableView) -> UITableViewCell) -> Disposable {
if animated {
let binder = TableViewBinderDataSource<Element.Changeset>(createCell)
binder.rowInsertionAnimation = rowAnimation
binder.rowDeletionAnimation = rowAnimation
binder.rowReloadAnimation = rowAnimation
return bind(to: tableView, using: binder)
} else {
let binder = TableViewBinderDataSource<Element.Changeset>.ReloadingBinder(createCell)
return bind(to: tableView, using: binder)
}
}
/// Binds the signal of data source elements to the given table view.
///
/// - parameters:
/// - tableView: A table view that should display the data from the data source.
/// - binder: A `TableViewBinder` or its subclass that will manage the binding.
/// - returns: A disposable object that can terminate the binding. Safe to ignore - the binding will be automatically terminated when the table view is deallocated.
@discardableResult
public func bind(to tableView: UITableView, using binderDataSource: TableViewBinderDataSource<Element.Changeset>) -> Disposable {
binderDataSource.tableView = tableView
return bind(to: tableView) { (_, changeset) in
binderDataSource.changeset = changeset.asSectionedDataSourceChangeset
}
}
}
extension SignalProtocol where Element: SectionedDataSourceChangesetConvertible, Element.Changeset.Collection: QueryableSectionedDataSourceProtocol, Error == Never {
/// Binds the signal of data source elements to the given table view.
///
/// - parameters:
/// - tableView: A table view that should display the data from the data source.
/// - cellType: A type of the cells that should display the data.
/// - animated: Animate partial or batched updates. Default is `true`.
/// - rowAnimation: Row animation for partial or batched updates. Relevant only when `animated` is `true`. Default is `.automatic`.
/// - configureCell: A closure that configures the cell with the data source item at the respective index path.
/// - returns: A disposable object that can terminate the binding. Safe to ignore - the binding will be automatically terminated when the table view is deallocated.
///
/// Note that the cell type name will be used as a reusable identifier and the binding will automatically register and dequeue the cell.
/// If there exists a nib file in the bundle with the same name as the cell type name, the framework will load the cell from the nib file.
@discardableResult
public func bind<Cell: UITableViewCell>(to tableView: UITableView, cellType: Cell.Type, animated: Bool = true, rowAnimation: UITableView.RowAnimation = .automatic, configureCell: @escaping (Cell, Element.Changeset.Collection.Item) -> Void) -> Disposable {
let identifier = String(describing: Cell.self)
let bundle = Bundle(for: Cell.self)
if let _ = bundle.path(forResource: identifier, ofType: "nib") {
let nib = UINib(nibName: identifier, bundle: bundle)
tableView.register(nib, forCellReuseIdentifier: identifier)
} else {
tableView.register(cellType as AnyClass, forCellReuseIdentifier: identifier)
}
return bind(to: tableView, animated: animated, rowAnimation: rowAnimation, createCell: { (dataSource, indexPath, tableView) -> UITableViewCell in
guard let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as? Cell else {
fatalError(
"Failed to dequeue a cell with identifier \(identifier) matching type \(cellType.self). "
+ "Check that the reuseIdentifier is set properly if using XIBs or Storyboards."
)
}
let item = dataSource.item(at: indexPath)
configureCell(cell, item)
return cell
})
}
/// Binds the signal of data source elements to the given table view.
///
/// - parameters:
/// - tableView: A table view that should display the data from the data source.
/// - cellType: A type of the cells that should display the data.
/// - animated: Animate partial or batched updates. Default is `true`.
/// - rowAnimation: Row animation for partial or batched updates. Relevant only when `animated` is `true`. Default is `.automatic`.
/// - configureCell: A closure that configures the cell with the data source item at the respective index path.
/// - returns: A disposable object that can terminate the binding. Safe to ignore - the binding will be automatically terminated when the table view is deallocated.
///
/// Note that the cell type name will be used as a reusable identifier and the binding will automatically register and dequeue the cell.
/// If there exists a nib file in the bundle with the same name as the cell type name, the framework will load the cell from the nib file.
@discardableResult
public func bind<Cell: UITableViewCell>(to tableView: UITableView, cellType: Cell.Type, using binderDataSource: TableViewBinderDataSource<Element.Changeset>, configureCell: @escaping (Cell, Element.Changeset.Collection.Item) -> Void) -> Disposable {
let identifier = String(describing: Cell.self)
let bundle = Bundle(for: Cell.self)
if let _ = bundle.path(forResource: identifier, ofType: "nib") {
let nib = UINib(nibName: identifier, bundle: bundle)
tableView.register(nib, forCellReuseIdentifier: identifier)
} else {
tableView.register(cellType as AnyClass, forCellReuseIdentifier: identifier)
}
binderDataSource.createCell = { (dataSource, indexPath, tableView) -> UITableViewCell in
guard let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as? Cell else {
fatalError(
"Failed to dequeue a cell with identifier \(identifier) matching type \(cellType.self). "
+ "Check that the reuseIdentifier is set properly if using XIBs or Storyboards."
)
}
let item = dataSource.item(at: indexPath)
configureCell(cell, item)
return cell
}
return bind(to: tableView, using: binderDataSource)
}
}
private var TableViewBinderDataSourceAssociationKey = "TableViewBinderDataSource"
open class TableViewBinderDataSource<Changeset: SectionedDataSourceChangeset>: NSObject, UITableViewDataSource {
public var createCell: ((Changeset.Collection, IndexPath, UITableView) -> UITableViewCell)?
public var changeset: Changeset? = nil {
didSet {
if let changeset = changeset, oldValue != nil {
applyChangeset(changeset)
} else {
tableView?.reloadData()
}
}
}
open weak var tableView: UITableView? = nil {
didSet {
guard let tableView = tableView else { return }
associateWithTableView(tableView)
}
}
open var rowInsertionAnimation: UITableView.RowAnimation = .automatic
open var rowDeletionAnimation: UITableView.RowAnimation = .automatic
open var rowReloadAnimation: UITableView.RowAnimation = .automatic
public override init() {
createCell = nil
}
/// - parameter createCell: A closure that creates cell for a given table view and configures it with the given data source at the given index path.
public init(_ createCell: @escaping (Changeset.Collection, IndexPath, UITableView) -> UITableViewCell) {
self.createCell = createCell
}
open func numberOfSections(in tableView: UITableView) -> Int {
return changeset?.collection.numberOfSections ?? 0
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return changeset?.collection.numberOfItems(inSection: section) ?? 0
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let changeset = changeset else { fatalError() }
if let createCell = createCell {
return createCell(changeset.collection, indexPath, tableView)
} else {
fatalError("Subclass of TableViewBinderDataSource should override and implement tableView(_:cellForRowAt:) method if they do not initialize `createCell` closure.")
}
}
open func applyChangeset(_ changeset: Changeset) {
guard let tableView = tableView else { return }
let diff = changeset.diff.asOrderedCollectionDiff.map { $0.asSectionDataIndexPath }
if diff.isEmpty {
tableView.reloadData()
} else if diff.count == 1 {
applyChangesetDiff(diff)
} else {
tableView.beginUpdates()
applyChangesetDiff(diff)
tableView.endUpdates()
}
}
open func applyChangesetDiff(_ diff: OrderedCollectionDiff<IndexPath>) {
guard let tableView = tableView else { return }
let insertedSections = diff.inserts.filter { $0.count == 1 }.map { $0[0] }
if !insertedSections.isEmpty {
tableView.insertSections(IndexSet(insertedSections), with: rowInsertionAnimation)
}
let insertedItems = diff.inserts.filter { $0.count == 2 }
if !insertedItems.isEmpty {
tableView.insertRows(at: insertedItems, with: rowInsertionAnimation)
}
let deletedSections = diff.deletes.filter { $0.count == 1 }.map { $0[0] }
if !deletedSections.isEmpty {
tableView.deleteSections(IndexSet(deletedSections), with: rowDeletionAnimation)
}
let deletedItems = diff.deletes.filter { $0.count == 2 }
if !deletedItems.isEmpty {
tableView.deleteRows(at: deletedItems, with: rowDeletionAnimation)
}
let updatedItems = diff.updates.filter { $0.count == 2 }
if !updatedItems.isEmpty {
tableView.reloadRows(at: updatedItems, with: rowReloadAnimation)
}
let updatedSections = diff.updates.filter { $0.count == 1 }.map { $0[0] }
if !updatedSections.isEmpty {
tableView.reloadSections(IndexSet(updatedSections), with: rowReloadAnimation)
}
for move in diff.moves {
if move.from.count == 2 && move.to.count == 2 {
tableView.moveRow(at: move.from, to: move.to)
} else if move.from.count == 1 && move.to.count == 1 {
tableView.moveSection(move.from[0], toSection: move.to[0])
}
}
}
private func associateWithTableView(_ tableView: UITableView) {
objc_setAssociatedObject(tableView, &TableViewBinderDataSourceAssociationKey, self, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if tableView.reactive.hasProtocolProxy(for: UITableViewDataSource.self) {
tableView.reactive.dataSource.forwardTo = self
} else {
tableView.dataSource = self
}
}
}
extension TableViewBinderDataSource {
public class ReloadingBinder: TableViewBinderDataSource {
public override func applyChangeset(_ changeset: Changeset) {
tableView?.reloadData()
}
}
}
#endif
| mit | 0c46cbc6ad948fe5c4974a9775213480 | 50.322097 | 259 | 0.676129 | 5.084601 | false | false | false | false |
gerardogrisolini/Webretail | Sources/Webretail/Repositories/AttributeValueRepository.swift | 1 | 1313 | //
// AttributeValueRepository.swift
// Webretail
//
// Created by Gerardo Grisolini on 17/02/17.
//
//
import StORM
struct AttributeValueRepository : AttributeValueProtocol {
func getAll() throws -> [AttributeValue] {
let items = AttributeValue()
try items.query()
return items.rows()
}
func get(id: Int) throws -> AttributeValue? {
let item = AttributeValue()
try item.query(id: id)
return item
}
func add(item: AttributeValue) throws {
item.attributeValueCreated = Int.now()
item.attributeValueUpdated = Int.now()
try item.save {
id in item.attributeValueId = id as! Int
}
}
func update(id: Int, item: AttributeValue) throws {
guard let current = try get(id: id) else {
throw StORMError.noRecordFound
}
current.attributeValueCode = item.attributeValueCode
current.attributeValueName = item.attributeValueName
current.attributeValueTranslates = item.attributeValueTranslates
current.attributeValueUpdated = Int.now()
try current.save()
}
func delete(id: Int) throws {
let item = AttributeValue()
item.attributeValueId = id
try item.delete()
}
}
| apache-2.0 | 2206d6573c8f36f1de541cd5fb5b392c | 23.773585 | 72 | 0.610815 | 4.623239 | false | false | false | false |
hgp691/HGToolBox | HGToolBox/Classes/HGTextInputLeftView.swift | 1 | 16741 | //
// HGTextInputLeftView.swift
// Pods
//
// Created by Horacio Guzmán Parra on 15/08/17.
//
//
import UIKit
@available(iOS 9.0, *)
@IBDesignable
public class HGTextInputLeftView: UIView {
private var _tipo:HGTextInputType = .name
private var _campo:UITextField!
private var _error:UILabel!
private var _contenedor:UIView!
private var _viewIzquierda:UIView!
private var confirmarConCampo:HGTextInputLeftView!
//MARK: VARIABLES DE PADDING DEL CONTENEDOR
@IBInspectable
public var paddingSuperior:CGFloat = 0.0{
didSet{
self.configurarContenedor()
}
}
@IBInspectable
public var paddingInferior:CGFloat = 0.0{
didSet{
self.configurarContenedor()
}
}
@IBInspectable
public var paddingIzquierda:CGFloat = 0.0{
didSet{
self.configurarContenedor()
}
}
@IBInspectable
public var paddingDerecha:CGFloat = 0.0{
didSet{
self.configurarContenedor()
}
}
//MARK: VARIABLES PARA EL BORDE
@IBInspectable
public var radioCampoTexto:CGFloat = 0.0{
didSet{
print("Did set radioCampo")
if radioCampoTexto < 0.0{
radioCampoTexto = 0
}
if self._campo == nil{
self.configurarCampoTexto()
}
self._campo.layer.cornerRadius = radioCampoTexto
}
}
@IBInspectable
public var anchoBorde:CGFloat = 0.0{
didSet{
if self._campo == nil{
self.configurarCampoTexto()
}
if anchoBorde < 0{
anchoBorde = 0
}
self._campo.layer.borderWidth = anchoBorde
}
}
@IBInspectable
public var colorBorde:UIColor = .clear{
didSet{
if self._campo == nil{
self.configurarCampoTexto()
}
self._campo.layer.borderColor = colorBorde.cgColor
}
}
@IBInspectable
public var colorFondo:UIColor = .clear{
didSet{
if self._campo == nil{
self.configurarCampoTexto()
}
self._campo.backgroundColor = colorFondo
}
}
//DEFINE EL TIPO DEL CAMPO DE TEXTO
@IBInspectable
public var tipo:Int = HGTextInputType.name.hashValue{
didSet{
self._tipo = HGTextInputType(value: tipo)
self.configurarLetraCampo()
}
}
//MARK: VARIABLES PARA IMAGEN IZQUIERDA
@IBInspectable
public var imagenIzquierda:UIImage!{
didSet{
if imagenIzquierda != nil{
self.configurarImagenIzquierda()
}else{
}
}
}
//MARK: VARIABLES PARA Fuentes
@IBInspectable
public var tamanoLetra:CGFloat = 17.0{
didSet{
if self.existeFuente(nombre: self.fuente){
self._fuente = UIFont(name: self.fuente, size: self.tamanoLetra)!
}else{
print("No existe fuente \(fuente)")
}
}
}
@IBInspectable
public var fuente:String = "Arial"{
didSet{
if self.existeFuente(nombre: fuente){
self._fuente = UIFont(name: self.fuente, size: self.tamanoLetra)!
}else{
print("No existe fuente fuente \(fuente)")
}
}
}
@IBInspectable
public var colorFuente:UIColor = .white{
didSet{
if self._campo != nil{
self._campo.textColor = colorFuente
}
}
}
private var _fuente:UIFont = UIFont(name: "ArialMT", size: 17.0)!{
didSet{
self.configurarLetraCampo()
self.tamanoError = 10.0
}
}
@IBInspectable
public var mensajeError:String = ""{
didSet{
if self._error != nil{
self._error.text = mensajeError
}
}
}
@IBInspectable
public var tamanoError:CGFloat = 10.0{
didSet{
if self.existeFuente(nombre: self._fuente.fontName) && self._error != nil{
self._error.font = UIFont(name: self._fuente.fontName, size: tamanoError)
}else{
print("no existe fuente tamanoError \(fuente)")
}
}
}
@IBInspectable
public var colorError:UIColor = .red{
didSet{
if self._error != nil{
self._error.textColor = colorError
self._campo.layer.borderColor = self.colorError.cgColor
}
}
}
public var tamañoMinimo:Int = 6
public var tamañoMaximo:Int = 10
public var tipoValidacionContraseña:HGTextInputPWValidationType = .MayusculaYTamaños
public var delegate:UITextFieldDelegate!{
didSet{
if self._campo != nil{
self._campo.delegate = delegate
}
}
}
override public func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.configurarCampoTexto()
}
/// FUNCION QUE CONFIGURA EL CAMPO DE TEXTO
private func configurarCampoTexto(){
self.configurarCampoTextoYErrorTamano()
self.configurarPlaceholder()
}
private func configurarContenedor(){
print("Configurar contenedor")
if self._contenedor == nil{
print("Instancia")
self._contenedor = UIView()
self.addSubview(_contenedor)
self._contenedor.translatesAutoresizingMaskIntoConstraints = false
self._contenedor.backgroundColor = .clear
}
self._contenedor.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: self.paddingIzquierda).isActive = true
self._contenedor.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -self.paddingDerecha).isActive = true
self._contenedor.topAnchor.constraint(equalTo: self.topAnchor, constant: self.paddingSuperior).isActive = true
self._contenedor.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -self.paddingInferior).isActive = true
}
private func configurarCampoTextoYErrorTamano(){
if self._contenedor == nil{
self.configurarContenedor()
}
if self._campo == nil{
self._campo = UITextField()
self._contenedor.addSubview(self._campo)
self._campo.translatesAutoresizingMaskIntoConstraints = false
self._campo.delegate = self.delegate
}
if self._error == nil{
self._error = UILabel()
self._contenedor.addSubview(self._error)
self._error.translatesAutoresizingMaskIntoConstraints = false
self._error.textAlignment = .right
}
//error
self._error.leadingAnchor.constraint(equalTo: self._contenedor.leadingAnchor).isActive = true
self._error.trailingAnchor.constraint(equalTo: self._contenedor.trailingAnchor).isActive = true
self._error.topAnchor.constraint(equalTo: self._contenedor.topAnchor).isActive = true
self._error.heightAnchor.constraint(equalTo: self._contenedor.heightAnchor, multiplier: 0.3).isActive = true
self._campo.leadingAnchor.constraint(equalTo: self._contenedor.leadingAnchor).isActive = true
self._campo.trailingAnchor.constraint(equalTo: self._contenedor.trailingAnchor).isActive = true
self._campo.bottomAnchor.constraint(equalTo: self._contenedor.bottomAnchor).isActive = true
self._campo.topAnchor.constraint(equalTo: self._error.bottomAnchor).isActive = true
}
private func configurarPlaceholder(){
if self._campo != nil{
self._campo.placeholder = self._tipo.placeholder()
}
}
private func configurarImagenIzquierda(){
if self._contenedor == nil{
self.configurarContenedor()
}
if self._campo == nil{
self.configurarCampoTexto()
}
if self._viewIzquierda == nil{
self._viewIzquierda = UIView()
self._viewIzquierda.translatesAutoresizingMaskIntoConstraints = false
self._contenedor.addSubview(self._viewIzquierda)
}
self._viewIzquierda.heightAnchor.constraint(equalTo: self._contenedor.heightAnchor, multiplier: 0.7).isActive = true
let const = imagenIzquierda.size.width / imagenIzquierda.size.height
self._viewIzquierda.widthAnchor.constraint(equalTo: self._viewIzquierda.heightAnchor, multiplier: const).isActive = true
self._viewIzquierda.backgroundColor = .clear
let bgn = UIImageView(image: imagenIzquierda)
bgn.translatesAutoresizingMaskIntoConstraints = false
self._viewIzquierda.addSubview(bgn)
bgn.topAnchor.constraint(equalTo: self._viewIzquierda.topAnchor).isActive = true
bgn.bottomAnchor.constraint(equalTo: self._viewIzquierda.bottomAnchor).isActive = true
bgn.leadingAnchor.constraint(equalTo: self._viewIzquierda.leadingAnchor).isActive = true
bgn.trailingAnchor.constraint(equalTo: self._viewIzquierda.trailingAnchor).isActive = true
print("El campo")
print(self._campo)
self._campo.leftViewMode = .always
self._campo.leftView = self._viewIzquierda
}
private func configurarLetraCampo(){
if self._campo != nil{
self._campo.placeholder = self._tipo.placeholder()
self._campo.font = self._fuente
switch self._tipo {
case .name:
self._campo.keyboardType = .namePhonePad
break
case .email:
self._campo.keyboardType = .emailAddress
self._campo.autocorrectionType = .no
self._campo.autocapitalizationType = .none
break
case .password:
self._campo.isSecureTextEntry = true
self._campo.autocorrectionType = .no
self._campo.keyboardType = .default
break
case .confirmPassword:
self._campo.isSecureTextEntry = true
self._campo.autocorrectionType = .no
self._campo.keyboardType = .default
break
case .cell:
self._campo.keyboardType = .phonePad
self._campo.autocorrectionType = .no
break
}
}
}
private func existeFuente(nombre:String)->Bool{
let fontFamilyNames = UIFont.familyNames
for familyName in fontFamilyNames {
print("Familia \(familyName): ")
for fuente in UIFont.fontNames(forFamilyName: familyName){
print(fuente)
if fuente == nombre{
return true
}
}
}
return false
}
public func confirMarConCampo(campo:HGTextInputLeftView){
if self._tipo == .confirmPassword{
self.confirmarConCampo = campo
}
}
public func setValue(value:String){
if self._campo != nil{
self._campo.text = value
}
}
public func setPlaceHolder(placeholder:String){
if self._campo != nil{
self._campo.placeholder = placeholder
}
}
public func esValido()->Bool{
if self.noEsVacio(){
switch self._tipo {
case .name:
return true
case .email:
return self.validarEmail()
case .password:
return self.validarPW()
case .confirmPassword:
return self.validarPWConfirm()
case .cell:
return true
}
}else{
return false
}
}
//MARK: FUNCIONES DE VALIDACION
private func noEsVacio()->Bool{
self.quitarError()
if (self._campo.text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).characters.count)! > 0{
return true
}
if HGUtils.isSpanish{
self.ponerError(mensaje: "Debe completar")
}else{
self.ponerError(mensaje: "You must complete it")
}
return false
}
private func validarEmail()->Bool{
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
if emailTest.evaluate(with: self._campo.text){
self.quitarError()
return true
}else{
if HGUtils.isSpanish{
self.ponerError(mensaje: "Esto no es un e-mail")
}else{
self.ponerError(mensaje: "This is not an e-mail")
}
return false
}
}
private func validarPW()->Bool{
let pwRegEx = self.tipoValidacionContraseña.Regex(min: self.tamañoMinimo, max: self.tamañoMaximo)
let pwTest = NSPredicate(format:"SELF MATCHES %@", pwRegEx)
if pwTest.evaluate(with: self._campo.text){
self.quitarError()
return true
}else{
if HGUtils.isSpanish{
self.ponerError(mensaje: "No cumple con lo esperado")
}else{
self.ponerError(mensaje: "This is not what is expected")
}
return false
}
}
private func validarPWConfirm()->Bool{
self.quitarError()
if self.value() == self.confirmarConCampo.value(){
return true
}
if HGUtils.isSpanish{
self.ponerError(mensaje: "Las contraseñas deben conincidir")
}else{
self.ponerError(mensaje: "The passwords don't match")
}
return false
}
public func value()->String{
return (self._campo.text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))!
}
private func ponerError(mensaje:String){
self._error.text = mensaje
self._campo.layer.borderWidth = 1.0
self._campo.layer.borderColor = self.colorError.cgColor
}
private func quitarError(){
self._error.text = ""
self._campo.layer.borderWidth = self.anchoBorde
self._campo.layer.borderColor = self.colorBorde.cgColor
}
}
public enum HGTextInputType{
case email
case name
case password
case confirmPassword
case cell
public init(){
self = .name
}
public init(value:Int){
switch value {
case 0:
self = .name
case 1:
self = .email
case 2:
self = .password
case 3:
self = .confirmPassword
case 4:
self = .cell
default:
self = .name
}
}
public func placeholder()->String{
if HGUtils.isSpanish{
switch self{
case .name:
return "Nombre completo"
case .email:
return "Correo"
case .password:
return "Contraseña"
case .confirmPassword:
return "Confirmar Contraseña"
case .cell:
return "Celular"
}
}else{
switch self{
case .name:
return "Full name"
case .email:
return "E-mail"
case .password:
return "Password"
case .confirmPassword:
return "Confirm Password"
case .cell:
return "Cell phone"
}
}
}
}
public enum HGTextInputPWValidationType{
case none
case tamañoMinimo
case tamañoMaximo
case tamañoMinimoYMaximo
case MayusculaYTamaños
case MayusculaSinTamaños
public func Regex(min:Int,max:Int)->String{
switch self {
case .none:
return "[\\s\\S]*"
case .tamañoMinimo:
let reg = "^.{\(min),}$"
return reg
case .tamañoMaximo:
let reg = "^.{0,\(max)}$"
return reg
case .tamañoMinimoYMaximo:
let reg = "^.{\(min),\(max)}$"
return reg
case .MayusculaYTamaños:
let reg = "^.(?=.*[A-Z]).{\(min),\(max)}"
return reg
case .MayusculaSinTamaños:
let reg = ".*[A-Z]+.*"
return reg
}
}
}
| mit | cd803a2f12fa9ee65e74890468a6da9c | 29.962963 | 128 | 0.558074 | 4.300412 | false | false | false | false |
dinhnhat0401/swift_design_partern | BlueLibrarySwift/Album.swift | 1 | 1511 | //
// Album.swift
// BlueLibrarySwift
//
// Created by Đinh Văn Nhật on 2014/12/24.
// Copyright (c) 2014年 Raywenderlich. All rights reserved.
//
import UIKit
class Album: NSObject, NSCoding {
var title : String!
var artist : String!
var genre : String!
var coverUrl : String!
var year : String!
required init(coder decoder: NSCoder) {
super.init()
self.title = decoder.decodeObjectForKey("title") as String?
self.artist = decoder.decodeObjectForKey("artist") as String?
self.genre = decoder.decodeObjectForKey("genre") as String?
self.coverUrl = decoder.decodeObjectForKey("cover_url") as String?
self.year = decoder.decodeObjectForKey("year") as String?
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(title, forKey: "title")
aCoder.encodeObject(artist, forKey: "artist")
aCoder.encodeObject(genre, forKey: "genre")
aCoder.encodeObject(coverUrl, forKey: "cover_url")
aCoder.encodeObject(year, forKey: "year")
}
init(title: String, artist: String, genre: String, coverUrl: String, year: String) {
super.init()
self.title = title
self.artist = artist
self.genre = genre
self.coverUrl = coverUrl
self.year = year
}
func description() -> String {
return "title: \(title)" + "artist: \(artist)" + "genre: \(genre)" + "coverUrl: \(coverUrl)" + "year: \(year)"
}
}
| mit | ae41d02f646cfe3e279092beb39ec553 | 30.354167 | 118 | 0.61794 | 4.067568 | false | false | false | false |
mrarronz/RegionCN | RegionCN/RegionHelper.swift | 1 | 5255 | //
// RegionHelper.swift
// RegionCN
//
// Copyright © 2017年 mrarronz. All rights reserved.
//
import UIKit
public class RegionHelper: NSObject {
public static let shared = RegionHelper()
public var provincesXMLArray: NSArray {
let bundle = Bundle.init(for: self.classForCoder)
let path = bundle.path(forResource: "regions", ofType: "xml")
let xmlData = NSData.init(contentsOfFile: path!)
let xmlDict = NSDictionary.init(xmlData: xmlData! as Data)
let provinces = xmlDict?.object(forKey: "province")
return provinces as! NSArray
}
private var regionTXTData: Array<String> {
let bundle = Bundle.init(for: self.classForCoder)
let filePath = bundle.path(forResource: "region", ofType: "txt")
let regionString = try! NSString.init(contentsOfFile: filePath!, encoding: String.Encoding.utf8.rawValue)
let array: Array<String> = regionString.components(separatedBy: "\n")
return array
}
public var regionTXTArray: Array<Dictionary<String, String>> {
var array = Array<Dictionary<String, String>>()
for item in self.regionTXTData {
let regionString = item.replacingOccurrences(of: "\r", with: "").trimmingCharacters(in: .whitespaces)
let regionCode = regionString.substring(to: regionString.index(regionString.startIndex, offsetBy: 6))
let regionName = regionString.substring(from: regionString.index(regionString.startIndex, offsetBy: 7))
let dictionary = ["regionCode" : regionCode, "regionName" : regionName]
array.append(dictionary)
}
return array
}
/// 根据XML文件中的一个省份查找这个省份下面所有的城市
public func cityList(inProvince: NSDictionary) -> NSArray? {
return inProvince.object(forKey: "city") as? NSArray
}
/// 根据XML城市列表查询某个城市下面所有的区县
public func districtList(inCityList: NSArray?, atIndex: Int) -> NSArray? {
let city: NSDictionary? = inCityList?.object(at: atIndex) as? NSDictionary
let district = city?.object(forKey: "district") as AnyObject
if district.isKind(of: NSArray.classForCoder()) {
return district as? NSArray
} else {
return NSArray.init(object: district)
}
}
/// 根据地区名字查找地区对应的数据字典
public func findRegionByName(regionName: String) -> Dictionary<String, String> {
var dict = Dictionary<String, String>()
for item in self.regionTXTArray {
let name: String = item["regionName"]!
if name == regionName {
dict = item
break
}
}
return dict
}
/// 根据地区编码查找对应的数据字典
public func findRegionByCode(regionCode: String) -> Dictionary<String, String> {
var dict = Dictionary<String, String>()
for item in self.regionTXTArray {
let code: String = item["regionCode"]!
if code == regionCode {
dict = item
break
}
}
return dict
}
/// 查找中国所有省份
public func allProvinces() -> NSArray {
let defaultCountryCode = "100000"
let suffix = "0000"
let predicate = NSPredicate.init(format: "regionCode != %@ AND regionCode ENDSWITH[cd] %@", defaultCountryCode, suffix)
let results: NSArray = (self.regionTXTArray as NSArray).filtered(using: predicate) as NSArray
return results
}
/// 根据省份编码查找该省份下所有的市区县
public func regionsInProvince(provinceCode: String) -> NSArray {
let prefix = provinceCode.substring(to: provinceCode.index(provinceCode.startIndex, offsetBy: 2))
let predicate = NSPredicate.init(format: "regionCode != %@ AND regionCode BEGINSWITH[cd] %@", provinceCode, prefix)
let results: NSArray = (self.regionTXTArray as NSArray).filtered(using: predicate) as NSArray
return results
}
/// 根据省份代码和最后两个数字00查找这个省份下面的所有城市
public func allCitiesInProvince(provinceCode: String) -> NSArray {
let prefix = provinceCode.substring(to: provinceCode.index(provinceCode.startIndex, offsetBy: 2))
let suffix = "00"
let predicate = NSPredicate.init(format: "regionCode != %@ AND regionCode BEGINSWITH[cd] %@ AND regionCode ENDSWITH[cd] %@", provinceCode, prefix, suffix)
let results: NSArray = (self.regionTXTArray as NSArray).filtered(using: predicate) as NSArray
return results
}
/// 根据城市编码查找这个城市下面所有的区县
public func allAreasInCity(cityCode: String) -> NSArray {
let prefix = cityCode.substring(to: cityCode.index(cityCode.startIndex, offsetBy: 4))
let predicate = NSPredicate.init(format: "regionCode != %@ AND regionCode BEGINSWITH[cd] %@", cityCode, prefix)
let results: NSArray = (self.regionTXTArray as NSArray).filtered(using: predicate) as NSArray
return results
}
}
| mit | bb9ee3e194151e529fa2c8c678ffdf79 | 39.341463 | 162 | 0.638452 | 4.337413 | false | false | false | false |
Geor9eLau/WorkHelper | Carthage/Checkouts/SwiftCharts/SwiftCharts/Layers/ChartPointsScatterLayer.swift | 1 | 5720 | //
// ChartPointsScatterLayer.swift
// Examples
//
// Created by ischuetz on 17/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
open class ChartPointsScatterLayer<T: ChartPoint>: ChartPointsLayer<T> {
open let itemSize: CGSize
open let itemFillColor: UIColor
required public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, itemSize: CGSize, itemFillColor: UIColor) {
self.itemSize = itemSize
self.itemFillColor = itemFillColor
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay)
}
override open func chartViewDrawing(context: CGContext, chart: Chart) {
for chartPointModel in self.chartPointsModels {
self.drawChartPointModel(context: context, chartPointModel: chartPointModel)
}
}
open func drawChartPointModel(context: CGContext, chartPointModel: ChartPointLayerModel<T>) {
fatalError("override")
}
}
open class ChartPointsScatterTrianglesLayer<T: ChartPoint>: ChartPointsScatterLayer<T> {
required public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, itemSize: CGSize, itemFillColor: UIColor) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay, itemSize: itemSize, itemFillColor: itemFillColor)
}
override open func drawChartPointModel(context: CGContext, chartPointModel: ChartPointLayerModel<T>) {
let w = self.itemSize.width
let h = self.itemSize.height
let path = CGMutablePath()
path.move(to: CGPoint(x: chartPointModel.screenLoc.x, y: chartPointModel.screenLoc.y - h / 2))
path.addLine(to: CGPoint(x: chartPointModel.screenLoc.x + w / 2, y: chartPointModel.screenLoc.y + h / 2))
path.addLine(to: CGPoint(x: chartPointModel.screenLoc.x - w / 2, y: chartPointModel.screenLoc.y + h / 2))
path.closeSubpath()
context.setFillColor(self.itemFillColor.cgColor)
context.addPath(path)
context.fillPath()
}
}
open class ChartPointsScatterSquaresLayer<T: ChartPoint>: ChartPointsScatterLayer<T> {
required public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, itemSize: CGSize, itemFillColor: UIColor) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay, itemSize: itemSize, itemFillColor: itemFillColor)
}
override open func drawChartPointModel(context: CGContext, chartPointModel: ChartPointLayerModel<T>) {
let w = self.itemSize.width
let h = self.itemSize.height
context.setFillColor(self.itemFillColor.cgColor)
context.fill(CGRect(x: chartPointModel.screenLoc.x - w / 2, y: chartPointModel.screenLoc.y - h / 2, width: w, height: h))
}
}
open class ChartPointsScatterCirclesLayer<T: ChartPoint>: ChartPointsScatterLayer<T> {
required public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, itemSize: CGSize, itemFillColor: UIColor) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay, itemSize: itemSize, itemFillColor: itemFillColor)
}
override open func drawChartPointModel(context: CGContext, chartPointModel: ChartPointLayerModel<T>) {
let w = self.itemSize.width
let h = self.itemSize.height
context.setFillColor(self.itemFillColor.cgColor)
context.fillEllipse(in: CGRect(x: chartPointModel.screenLoc.x - w / 2, y: chartPointModel.screenLoc.y - h / 2, width: w, height: h))
}
}
open class ChartPointsScatterCrossesLayer<T: ChartPoint>: ChartPointsScatterLayer<T> {
open let strokeWidth: CGFloat
required public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, itemSize: CGSize, itemFillColor: UIColor, strokeWidth: CGFloat = 2) {
self.strokeWidth = strokeWidth
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay, itemSize: itemSize, itemFillColor: itemFillColor)
}
required public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float, itemSize: CGSize, itemFillColor: UIColor) {
fatalError("init(xAxis:yAxis:innerFrame:chartPoints:displayDelay:itemSize:itemFillColor:) has not been implemented")
}
override open func drawChartPointModel(context: CGContext, chartPointModel: ChartPointLayerModel<T>) {
let w = self.itemSize.width
let h = self.itemSize.height
func drawLine(_ p1X: CGFloat, p1Y: CGFloat, p2X: CGFloat, p2Y: CGFloat) {
context.setStrokeColor(self.itemFillColor.cgColor)
context.setLineWidth(self.strokeWidth)
context.move(to: CGPoint(x: p1X, y: p1Y))
context.addLine(to: CGPoint(x: p2X, y: p2Y))
context.strokePath()
}
drawLine(chartPointModel.screenLoc.x - w / 2, p1Y: chartPointModel.screenLoc.y - h / 2, p2X: chartPointModel.screenLoc.x + w / 2, p2Y: chartPointModel.screenLoc.y + h / 2)
drawLine(chartPointModel.screenLoc.x + w / 2, p1Y: chartPointModel.screenLoc.y - h / 2, p2X: chartPointModel.screenLoc.x - w / 2, p2Y: chartPointModel.screenLoc.y + h / 2)
}
}
| mit | c070a2dcb70c633f3382b4e1da4e0713 | 49.619469 | 203 | 0.706119 | 4.303988 | false | false | false | false |
willpowell8/UIDesignKit_iOS | UIDesignKit/Classes/Editor/ColourView/HuePicker.swift | 1 | 5879 | import UIKit
open class HuePicker: UIView {
var _h:CGFloat = 0.1111
open var h:CGFloat { // [0,1]
set(value) {
_h = min(1, max(0, value))
currentPoint = CGPoint(x: CGFloat(_h), y: 0)
setNeedsDisplay()
}
get {
return _h
}
}
var image:UIImage?
fileprivate var data:[UInt8]?
fileprivate var currentPoint = CGPoint.zero
open var handleColor:UIColor = UIColor.black
open var onHueChange:((_ hue:CGFloat, _ finished:Bool) -> Void)?
open func setHueFromColor(_ color:UIColor) {
var h:CGFloat = 0
color.getHue(&h, saturation: nil, brightness: nil, alpha: nil)
self.h = h
}
public override init(frame: CGRect) {
super.init(frame: frame)
isUserInteractionEnabled = true
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
isUserInteractionEnabled = true
}
func renderBitmap() {
if bounds.isEmpty {
return
}
let width = UInt(bounds.width)
let height = UInt(bounds.height)
if data == nil {
data = [UInt8](repeating: UInt8(255), count: Int(width * height) * 4)
}
var p = 0.0
var q = 0.0
var t = 0.0
var i = 0
//_ = 255
var double_v:Double = 0
var double_s:Double = 0
let widthRatio:Double = 360 / Double(bounds.width)
var d = data!
for hi in 0..<Int(bounds.width) {
let double_h:Double = widthRatio * Double(hi) / 60
let sector:Int = Int(floor(double_h))
let f:Double = double_h - Double(sector)
let f1:Double = 1.0 - f
double_v = Double(1)
double_s = Double(1)
p = double_v * (1.0 - double_s) * 255
q = double_v * (1.0 - double_s * f) * 255
t = double_v * ( 1.0 - double_s * f1) * 255
let v255 = double_v * 255
i = hi * 4
switch(sector) {
case 0:
d[i+1] = UInt8(v255)
d[i+2] = UInt8(t)
d[i+3] = UInt8(p)
case 1:
d[i+1] = UInt8(q)
d[i+2] = UInt8(v255)
d[i+3] = UInt8(p)
case 2:
d[i+1] = UInt8(p)
d[i+2] = UInt8(v255)
d[i+3] = UInt8(t)
case 3:
d[i+1] = UInt8(p)
d[i+2] = UInt8(q)
d[i+3] = UInt8(v255)
case 4:
d[i+1] = UInt8(t)
d[i+2] = UInt8(p)
d[i+3] = UInt8(v255)
default:
d[i+1] = UInt8(v255)
d[i+2] = UInt8(p)
d[i+3] = UInt8(q)
}
}
var sourcei = 0
for v in 1..<Int(bounds.height) {
for s in 0..<Int(bounds.width) {
sourcei = s * 4
i = (v * Int(width) * 4) + sourcei
d[i+1] = d[sourcei+1]
d[i+2] = d[sourcei+2]
d[i+3] = d[sourcei+3]
}
}
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)
let provider = CGDataProvider(data: Data(bytes: d, count: d.count * MemoryLayout<UInt8>.size) as CFData)
let cgimg = CGImage(width: Int(width), height: Int(height), bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: Int(width) * Int(MemoryLayout<UInt8>.size * 4),
space: colorSpace, bitmapInfo: bitmapInfo, provider: provider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)
image = UIImage(cgImage: cgimg!)
}
fileprivate func handleTouch(_ touch:UITouch, finished:Bool) {
let point = touch.location(in: self)
currentPoint = CGPoint(x: max(0, min(bounds.width, point.x)) / bounds.width , y: 0)
_h = currentPoint.x
onHueChange?(h, finished)
setNeedsDisplay()
}
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
handleTouch(touches.first! as UITouch, finished: false)
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
handleTouch(touches.first! as UITouch, finished: false)
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
handleTouch(touches.first! as UITouch, finished: true)
}
override open func draw(_ rect: CGRect) {
if image == nil {
renderBitmap()
}
if let img = image {
img.draw(in: rect)
}
let handleRect = CGRect(x: bounds.width * currentPoint.x-3, y: 0, width: 6, height: bounds.height)
drawHueDragHandler(frame: handleRect)
}
func drawHueDragHandler(frame: CGRect) {
//// Polygon Drawing
let polygonPath = UIBezierPath()
polygonPath.move(to: CGPoint(x: frame.minX + 4, y: frame.maxY - 6))
polygonPath.addLine(to: CGPoint(x: frame.minX + 7.46, y: frame.maxY))
polygonPath.addLine(to: CGPoint(x: frame.minX + 0.54, y: frame.maxY))
polygonPath.close()
UIColor.black.setFill()
polygonPath.fill()
//// Polygon 2 Drawing
let polygon2Path = UIBezierPath()
polygon2Path.move(to: CGPoint(x: frame.minX + 4, y: frame.minY + 6))
polygon2Path.addLine(to: CGPoint(x: frame.minX + 7.46, y: frame.minY))
polygon2Path.addLine(to: CGPoint(x: frame.minX + 0.54, y: frame.minY))
polygon2Path.close()
UIColor.white.setFill()
polygon2Path.fill()
}
}
| mit | 7543684892d309940caaa6c0a27db5b0 | 31.302198 | 167 | 0.517775 | 3.771007 | false | false | false | false |
steelwheels/KiwiControls | Source/Graphics/KCEclipse.swift | 1 | 1086 | /**
* @file KCEclipse.swift
* @brief Define KCEclipse data structure
* @par Copyright
* Copyright (C) 2016 Steel Wheels Project
*/
import CoreGraphics
import Foundation
public struct KCEclipse
{
public var mCenter: CGPoint
public var mInnerRadius: CGFloat
public var mOuterRadius: CGFloat
private var mBounds: CGRect
public init(center c:CGPoint, innerRadius ir: CGFloat, outerRadius or: CGFloat) {
mCenter = c
mInnerRadius = ir
mOuterRadius = or
mBounds = KCEclipse.calcBounds(center: mCenter, outerRadius: or)
}
public var center: CGPoint {
get { return mCenter }
}
public var innerRadius: CGFloat {
get { return mInnerRadius }
}
public var outerRadius: CGFloat {
get { return mOuterRadius }
}
public var bounds: CGRect {
get { return mBounds }
}
static private func calcBounds(center c: CGPoint, outerRadius or: CGFloat) -> CGRect {
let outdiameter = or * 2
let origin = CGPoint(x: c.x - or, y: c.y - or)
let size = CGSize(width: outdiameter, height: outdiameter)
return CGRect(origin: origin, size: size)
}
}
| lgpl-2.1 | 74717616a42207d1d87eeed283fb8ad5 | 21.163265 | 87 | 0.702578 | 3.232143 | false | false | false | false |
Zahzi/DMX-DIP-Converter | DMX-DIP Converter/Pods/StringBuilder/StringBuilder/StringBuilder.swift | 1 | 840 | //
// StringBuilder.swift
// StringBuilder
//
// Created by Matthew Wyskiel on 9/30/14.
// Copyright (c) 2014 Matthew Wyskiel. All rights reserved.
//
import Foundation
public class StringBuilder {
private(set) var string: String
public init() {
string = ""
}
public init(string: String) {
self.string = string
}
public func append<T>(_ itemToAppend: T) -> Self {
self.string += "\(itemToAppend)"
return self
}
public func insertItem<T>(_ item: T, atIndex index: Int) -> Self {
let mutableString = NSMutableString(string: self.string)
mutableString.insert("\(item)", at: index)
self.string = mutableString as String
return self
}
public func toString() -> String {
return string;
}
}
| gpl-3.0 | 9064829bed7b51d40f583a7aa9a95e66 | 20.538462 | 70 | 0.583333 | 4.263959 | false | false | false | false |
loudnate/LoopKit | LoopKit/GlucoseKit/GlucoseMath.swift | 1 | 7354 | //
// GlucoseMath.swift
// Naterade
//
// Created by Nathan Racklyeft on 1/24/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
import HealthKit
fileprivate extension Collection where Element == (x: Double, y: Double) {
/**
Calculates slope and intercept using linear regression
This implementation is not suited for large datasets.
- parameter points: An array of tuples containing x and y values
- returns: A tuple of slope and intercept values
*/
func linearRegression() -> (slope: Double, intercept: Double) {
var sumX = 0.0
var sumY = 0.0
var sumXY = 0.0
var sumX² = 0.0
var sumY² = 0.0
let count = Double(self.count)
for point in self {
sumX += point.x
sumY += point.y
sumXY += (point.x * point.y)
sumX² += (point.x * point.x)
sumY² += (point.y * point.y)
}
let slope = ((count * sumXY) - (sumX * sumY)) / ((count * sumX²) - (sumX * sumX))
let intercept = (sumY * sumX² - (sumX * sumXY)) / (count * sumX² - (sumX * sumX))
return (slope: slope, intercept: intercept)
}
}
extension BidirectionalCollection where Element: GlucoseSampleValue, Index == Int {
/// Whether the collection contains no calibration entries
/// Runtime: O(n)
var isCalibrated: Bool {
return filter({ $0.isDisplayOnly }).count == 0
}
/// Filters a timeline of glucose samples to only include those after the last calibration.
func filterAfterCalibration() -> [Element] {
var postCalibration = true
return reversed().filter({ (sample) in
if sample.isDisplayOnly {
postCalibration = false
}
return postCalibration
}).reversed()
}
/// Whether the collection can be considered continuous
///
/// - Parameters:
/// - interval: The interval between readings, on average, used to determine if we have a contiguous set of values
/// - Returns: True if the samples are continuous
func isContinuous(within interval: TimeInterval = TimeInterval(minutes: 5)) -> Bool {
if let first = first,
let last = last,
// Ensure that the entries are contiguous
abs(first.startDate.timeIntervalSince(last.startDate)) < interval * TimeInterval(count)
{
return true
}
return false
}
/// Calculates the short-term predicted momentum effect using linear regression
///
/// - Parameters:
/// - duration: The duration of the effects
/// - delta: The time differential for the returned values
/// - Returns: An array of glucose effects
func linearMomentumEffect(
duration: TimeInterval = TimeInterval(minutes: 30),
delta: TimeInterval = TimeInterval(minutes: 5)
) -> [GlucoseEffect] {
guard
self.count > 2, // Linear regression isn't much use without 3 or more entries.
isContinuous() && isCalibrated && hasSingleProvenance,
let firstSample = self.first,
let lastSample = self.last,
let (startDate, endDate) = LoopMath.simulationDateRangeForSamples([lastSample], duration: duration, delta: delta)
else {
return []
}
/// Choose a unit to use during raw value calculation
let unit = HKUnit.milligramsPerDeciliter
let (slope: slope, intercept: _) = self.map { (
x: $0.startDate.timeIntervalSince(firstSample.startDate),
y: $0.quantity.doubleValue(for: unit)
) }.linearRegression()
guard slope.isFinite else {
return []
}
var date = startDate
var values = [GlucoseEffect]()
repeat {
let value = Swift.max(0, date.timeIntervalSince(lastSample.startDate)) * slope
values.append(GlucoseEffect(startDate: date, quantity: HKQuantity(unit: unit, doubleValue: value)))
date = date.addingTimeInterval(delta)
} while date <= endDate
return values
}
}
extension Collection where Element: GlucoseSampleValue, Index == Int {
/// Whether the collection is all from the same source.
/// Runtime: O(n)
var hasSingleProvenance: Bool {
let firstProvenance = self.first?.provenanceIdentifier
for sample in self {
if sample.provenanceIdentifier != firstProvenance {
return false
}
}
return true
}
/// Calculates a timeline of effect velocity (glucose/time) observed in glucose readings that counteract the specified effects.
///
/// - Parameter effects: Glucose effects to be countered, in chronological order
/// - Returns: An array of velocities describing the change in glucose samples compared to the specified effects
func counteractionEffects(to effects: [GlucoseEffect]) -> [GlucoseEffectVelocity] {
let mgdL = HKUnit.milligramsPerDeciliter
let velocityUnit = GlucoseEffectVelocity.perSecondUnit
var velocities = [GlucoseEffectVelocity]()
var effectIndex = 0
var startGlucose: Element! = self.first
for endGlucose in self.dropFirst() {
// Find a valid change in glucose, requiring identical provenance and no calibration
let glucoseChange = endGlucose.quantity.doubleValue(for: mgdL) - startGlucose.quantity.doubleValue(for: mgdL)
let timeInterval = endGlucose.startDate.timeIntervalSince(startGlucose.startDate)
guard timeInterval > .minutes(4) else {
continue
}
defer {
startGlucose = endGlucose
}
guard startGlucose.provenanceIdentifier == endGlucose.provenanceIdentifier,
!startGlucose.isDisplayOnly, !endGlucose.isDisplayOnly
else {
continue
}
// Compare that to a change in insulin effects
guard effects.count > effectIndex else {
break
}
var startEffect: GlucoseEffect?
var endEffect: GlucoseEffect?
for effect in effects[effectIndex..<effects.count] {
if startEffect == nil && effect.startDate >= startGlucose.startDate {
startEffect = effect
} else if endEffect == nil && effect.startDate >= endGlucose.startDate {
endEffect = effect
break
}
effectIndex += 1
}
guard let startEffectValue = startEffect?.quantity.doubleValue(for: mgdL),
let endEffectValue = endEffect?.quantity.doubleValue(for: mgdL)
else {
break
}
let effectChange = endEffectValue - startEffectValue
let discrepancy = glucoseChange - effectChange
let averageVelocity = HKQuantity(unit: velocityUnit, doubleValue: discrepancy / timeInterval)
let effect = GlucoseEffectVelocity(startDate: startGlucose.startDate, endDate: endGlucose.startDate, quantity: averageVelocity)
velocities.append(effect)
}
return velocities
}
}
| mit | f313acdb217abf33c5905a36efb7c7d4 | 33.327103 | 139 | 0.607678 | 4.926895 | false | false | false | false |
hyperoslo/CalendarKit | Source/Timeline/EventResizeHandleDotView.swift | 1 | 738 | import Foundation
import UIKit
public final class EventResizeHandleDotView: UIView {
public var borderColor: UIColor? {
get {
guard let cgColor = layer.borderColor else {return nil}
return UIColor(cgColor: cgColor)
}
set(value) {
layer.borderColor = value?.cgColor
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.height / 2
}
private func configure() {
clipsToBounds = true
backgroundColor = .white
layer.borderWidth = 2
}
}
| mit | 41e68f39dc62348fd446c836a1351651 | 20.705882 | 61 | 0.669377 | 4.419162 | false | true | false | false |
zning1994/practice | Swift学习/code4xcode6/ch7/7.1.4在switch中比较元组类型.playground/section-1.swift | 1 | 558 | // Playground - noun: a place where people can play
var student = (id:"1002", name:"李四", age:32, ChineseScore:80, EnglishScore:89)
var desc:String
switch student {
case (_, _, _, 90...100, 90...100):
desc = "优"
case (_, _, _, 80..<90, 80..<90):
desc = "良"
case (_, _, _, 60..<80, 60..<80):
desc = "中"
case (_, _, _, 60..<80, 90...100), (_, _, _, 90...100, 60..<80):
desc = "偏科"
case (_, _, _, 0..<80, 90...100), (_, _, _, 90...100, 0..<80):
desc = "严重偏科"
default:
desc = "无"
}
println("说明:\(desc)")
| gpl-2.0 | 60ed87597f9bafd3a1a274fcc44776a8 | 21.956522 | 78 | 0.479167 | 2.735751 | false | false | false | false |
sendyhalim/iYomu | Yomu/Screens/SearchManga/SearchedMangaViewModel.swift | 1 | 1056 | //
// SearchedMangaViewModel.swift
// Yomu
//
// Created by Sendy Halim on 6/4/17.
// Copyright © 2017 Sendy Halim. All rights reserved.
//
import RxCocoa
import RxSwift
struct SearchedMangaViewModel {
// MARK: Output
let previewUrl: Driver<URL>
let categoriesString: Driver<String>
let title: Driver<String>
let apiId: Driver<String>
let bookmarked: Driver<Bool>
// MARK: Private
fileprivate let manga: Variable<SearchedManga>
init(manga: SearchedManga) {
self.manga = Variable(manga)
previewUrl = self.manga
.asDriver()
.map { $0.image.url }
title = self.manga
.asDriver()
.map { $0.name }
apiId = self.manga
.asDriver()
.map { $0.apiId }
categoriesString = self.manga
.asDriver()
.map { $0.categories.joined(separator: ", ") }
// NOTE: Are we doing this on the main thread?
bookmarked = Driver.just(Database.exists(mangaId: self.manga.value.apiId))
}
func existsInDb() -> Bool {
return Database.exists(mangaId: manga.value.apiId)
}
}
| mit | 6287cca8a586b075551b1c117bbdf074 | 20.530612 | 78 | 0.650237 | 3.392283 | false | false | false | false |
UPetersen/LibreMonitor | LibreMonitor/Model/SensorData.swift | 1 | 6164 | //
// SensorData
// LibreMonitor
//
// Created by Uwe Petersen on 26.07.16.
// Copyright © 2016 Uwe Petersen. All rights reserved.
//
import Foundation
/// Structure for data from Freestyle Libre sensor
/// To be initialized with the bytes as read via nfc. Provides all derived data.
struct SensorData {
/// Number of bytes of sensor data to be used (read only), i.e. 344 bytes (24 for header, 296 for body and 24 for footer)
let numberOfBytes = 344 // Header and body and footer of Freestyle Libre data (i.e. 40 blocks of 8 bytes)
/// Array of 344 bytes as read via nfc
let bytes: [UInt8]
/// Subarray of 24 header bytes
let header: [UInt8]
/// Subarray of 296 body bytes
let body: [UInt8]
/// Subarray of 24 footer bytes
let footer: [UInt8]
/// Date when data was read from sensor
let date: Date
/// Minutes (approx) since start of sensor
let minutesSinceStart: Int
/// Index on the next block of trend data that the sensor will measure and store
let nextTrendBlock: Int
/// Index on the next block of history data that the sensor will create from trend data and store
let nextHistoryBlock: Int
/// true if the header crc, stored in the first two bytes, is equal to the calculated crc
var hasValidHeaderCRC: Bool {
return Crc.hasValidCrc16InFirstTwoBytes(header)
}
/// true if the body crc, stored in the first two bytes, is equal to the calculated crc
var hasValidBodyCRC: Bool {
return Crc.hasValidCrc16InFirstTwoBytes(body)
}
/// true if the footer crc, stored in the first two bytes, is equal to the calculated crc
var hasValidFooterCRC: Bool {
return Crc.hasValidCrc16InFirstTwoBytes(footer)
}
/// Sensor state (ready, failure, starting etc.)
var state: SensorState {
switch header[4] {
case 01:
return SensorState.notYetStarted
case 02:
return SensorState.starting
case 03:
return SensorState.ready
case 04:
return SensorState.expired
case 05:
return SensorState.shutdown
case 06:
return SensorState.failure
default:
return SensorState.unknown
}
}
init?(bytes: [UInt8], date: Date = Date()) {
guard bytes.count == numberOfBytes else {
return nil
}
self.bytes = bytes
self.date = date
let headerRange = 0..<24 // 24 bytes, i.e. 3 blocks a 8 bytes
let bodyRange = 24..<320 // 296 bytes, i.e. 37 blocks a 8 bytes
let footerRange = 320..<344 // 24 bytes, i.e. 3 blocks a 8 bytes
self.header = Array(bytes[headerRange])
self.body = Array(bytes[bodyRange])
self.footer = Array(bytes[footerRange])
self.nextTrendBlock = Int(body[2])
self.nextHistoryBlock = Int(body[3])
self.minutesSinceStart = Int(body[293]) << 8 + Int(body[292])
}
/// Get array of 16 trend glucose measurements.
/// Each array is sorted such that the most recent value is at index 0 and corresponds to the time when the sensor was read, i.e. self.date. The following measurements are each one more minute behind, i.e. -1 minute, -2 mintes, -3 minutes, ... -15 minutes.
///
/// - parameter offset: offset in mg/dl that is added
/// - parameter slope: slope in (mg/dl)/ raw
///
/// - returns: Array of Measurements
func trendMeasurements(_ offset: Double = 0.0, slope: Double = 0.1) -> [Measurement] {
var measurements = [Measurement]()
// Trend data is stored in body from byte 4 to byte 4+96=100 in units of 6 bytes. Index on data such that most recent block is first.
for blockIndex in 0...15 {
var index = 4 + (nextTrendBlock - 1 - blockIndex) * 6 // runs backwards
if index < 4 {
index = index + 96 // if end of ring buffer is reached shift to beginning of ring buffer
}
let range = index..<index+6
let measurementBytes = Array(body[range])
let measurementDate = date.addingTimeInterval(Double(-60 * blockIndex))
let measurement = Measurement(bytes: measurementBytes, slope: slope, offset: offset, date: measurementDate)
measurements.append(measurement)
}
return measurements
}
/// Get array of 32 history glucose measurements.
/// Each array is sorted such that the most recent value is at index 0. This most recent value corresponds to -(minutesSinceStart - 3) % 15 + 3. The following measurements are each 15 more minutes behind, i.e. -15 minutes behind, -30 minutes, -45 minutes, ... .
///
/// - parameter offset: offset in mg/dl that is added
/// - parameter slope: slope in (mg/dl)/ raw
///
/// - returns: Array of Measurements
func historyMeasurements(_ offset: Double = 0.0, slope: Double = 0.1) -> [Measurement] {
let mostRecentHistoryDate = date.addingTimeInterval( 60.0 * -Double( (minutesSinceStart - 3) % 15 + 3 ) )
var measurements = [Measurement]()
// History data is stored in body from byte 100 to byte 100+192-1=291 in units of 6 bytes. Index on data such that most recent block is first.
for blockIndex in 0..<32 {
var index = 100 + (nextHistoryBlock - 1 - blockIndex) * 6 // runs backwards
if index < 100 {
index = index + 192 // if end of ring buffer is reached shift to beginning of ring buffer
}
let range = index..<index+6
let measurementBytes = Array(body[range])
let measurementDate = mostRecentHistoryDate.addingTimeInterval(Double(-900 * blockIndex)) // 900 = 60 * 15
let measurement = Measurement(bytes: measurementBytes, slope: slope, offset: offset, date: measurementDate)
measurements.append(measurement)
}
return measurements
}
}
| apache-2.0 | 862523660b3700f9f35c76b8f3761611 | 39.281046 | 265 | 0.614473 | 4.380242 | false | false | false | false |
ONode/actor-platform | actor-apps/app-ios/ActorApp/Controllers/Settings/SettingsViewController.swift | 10 | 15820 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
import MobileCoreServices
class SettingsViewController: AATableViewController {
// MARK: -
// MARK: Private vars
private let UserInfoCellIdentifier = "UserInfoCellIdentifier"
private let TitledCellIdentifier = "TitledCellIdentifier"
private let TextCellIdentifier = "TextCellIdentifier"
private var tableData: UATableData!
private let uid: Int
private var user: ACUserVM?
private var binder = Binder()
private var phones: JavaUtilArrayList?
// MARK: -
// MARK: Constructors
init() {
uid = Int(Actor.myUid())
super.init(style: UITableViewStyle.Plain)
var title = "";
if (MainAppTheme.tab.showText) {
title = NSLocalizedString("TabSettings", comment: "Settings Title")
}
tabBarItem = UITabBarItem(title: title,
image: MainAppTheme.tab.createUnselectedIcon("ic_settings_outline"),
selectedImage: MainAppTheme.tab.createSelectedIcon("ic_settings_filled"))
if (!MainAppTheme.tab.showText) {
tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = MainAppTheme.list.bgColor
edgesForExtendedLayout = UIRectEdge.Top
automaticallyAdjustsScrollViewInsets = false
user = Actor.getUserWithUid(jint(uid))
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.backgroundColor = MainAppTheme.list.backyardColor
tableView.clipsToBounds = false
tableView.tableFooterView = UIView()
tableData = UATableData(tableView: tableView)
tableData.registerClass(UserPhotoCell.self, forCellReuseIdentifier: UserInfoCellIdentifier)
tableData.registerClass(TitledCell.self, forCellReuseIdentifier: TitledCellIdentifier)
tableData.registerClass(TextCell.self, forCellReuseIdentifier: TextCellIdentifier)
tableData.tableScrollClosure = { (tableView: UITableView) -> () in
self.applyScrollUi(tableView)
}
// Avatar
var profileInfoSection = tableData.addSection(autoSeparator: true)
.setFooterHeight(15)
profileInfoSection.addCustomCell { (tableView, indexPath) -> UITableViewCell in
var cell: UserPhotoCell = tableView.dequeueReusableCellWithIdentifier(self.UserInfoCellIdentifier, forIndexPath: indexPath) as! UserPhotoCell
cell.contentView.superview?.clipsToBounds = false
if self.user != nil {
cell.setUsername(self.user!.getNameModel().get())
}
self.applyScrollUi(tableView, cell: cell)
return cell
}.setHeight(avatarHeight)
// Nick
profileInfoSection
.addCustomCell { (tableView, indexPath) -> UITableViewCell in
var cell: TitledCell = tableView.dequeueReusableCellWithIdentifier(self.TitledCellIdentifier, forIndexPath: indexPath) as! TitledCell
cell.enableNavigationIcon()
if let nick = self.user!.getNickModel().get() {
cell.setTitle(localized("ProfileUsername"), content: "@\(nick)")
cell.setAction(false)
} else {
cell.setTitle(localized("ProfileUsername"), content: localized("SettingsUsernameNotSet"))
cell.setAction(true)
}
return cell
}
.setHeight(55)
.setAction { () -> () in
self.textInputAlert("SettingsUsernameTitle", content: self.user!.getNickModel().get(), action: "AlertSave", tapYes: { (nval) -> () in
var nNick: String? = nval.trim()
if nNick?.size == 0 {
nNick = nil
}
self.execute(Actor.editMyNickCommandWithNick(nNick))
})
}
var about = self.user!.getAboutModel().get()
if about == nil {
about = localized("SettingsAboutNotSet")
}
var aboutCell = profileInfoSection
.addTextCell(localized("ProfileAbout"), text: about)
.setEnableNavigation(true)
if self.user!.getAboutModel().get() == nil {
aboutCell.setIsAction(true)
}
aboutCell.setAction { () -> () in
var text = self.user!.getAboutModel().get()
if text == nil {
text = ""
}
var controller = EditTextController(title: localized("SettingsChangeAboutTitle"), actionTitle: localized("NavigationSave"), content: text, completition: { (newText) -> () in
var updatedText: String? = newText.trim()
if updatedText?.size == 0 {
updatedText = nil
}
self.execute(Actor.editMyAboutCommandWithNick(updatedText))
})
var navigation = AANavigationController(rootViewController: controller)
self.presentViewController(navigation, animated: true, completion: nil)
}
// Phones
profileInfoSection
.addCustomCells(55, countClosure: { () -> Int in
if (self.phones != nil) {
return Int(self.phones!.size())
}
return 0
}) { (tableView, index, indexPath) -> UITableViewCell in
var cell: TitledCell = tableView.dequeueReusableCellWithIdentifier(self.TitledCellIdentifier, forIndexPath: indexPath) as! TitledCell
if let phone = self.phones!.getWithInt(jint(index)) as? ACUserPhone {
cell.setTitle(phone.getTitle(), content: "+\(phone.getPhone())")
}
return cell
}.setAction { (index) -> () in
var phoneNumber = (self.phones?.getWithInt(jint(index)).getPhone())!
var hasPhone = UIApplication.sharedApplication().canOpenURL(NSURL(string: "tel://")!)
if (!hasPhone) {
UIPasteboard.generalPasteboard().string = "+\(phoneNumber)"
self.alertUser("NumberCopied")
} else {
self.showActionSheet(["CallNumber", "CopyNumber"],
cancelButton: "AlertCancel",
destructButton: nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if (index == 0) {
UIApplication.sharedApplication().openURL(NSURL(string: "tel://+\(phoneNumber)")!)
} else if index == 1 {
UIPasteboard.generalPasteboard().string = "+\(phoneNumber)"
self.alertUser("NumberCopied")
}
})
}
}
// Profile
var topSection = tableData.addSection(autoSeparator: true)
topSection.setHeaderHeight(15)
topSection.setFooterHeight(15)
// Profile: Set Photo
topSection.addActionCell("SettingsSetPhoto", actionClosure: { () -> () in
var hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
self.showActionSheet(hasCamera ? ["PhotoCamera", "PhotoLibrary"] : ["PhotoLibrary"],
cancelButton: "AlertCancel",
destructButton: self.user!.getAvatarModel().get() != nil ? "PhotoRemove" : nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if index == -2 {
self.confirmUser("PhotoRemoveGroupMessage",
action: "PhotoRemove",
cancel: "AlertCancel",
sourceView: self.view,
sourceRect: self.view.bounds,
tapYes: { () -> () in
Actor.removeMyAvatar()
})
} else if index >= 0 {
let takePhoto: Bool = (index == 0) && hasCamera
self.pickAvatar(takePhoto, closure: { (image) -> () in
Actor.changeOwnAvatar(image)
})
}
})
})
// Profile: Set Name
topSection.addActionCell("SettingsChangeName", actionClosure: { () -> () in
var alertView = UIAlertView(title: nil,
message: NSLocalizedString("SettingsEditHeader", comment: "Title"),
delegate: nil,
cancelButtonTitle: NSLocalizedString("AlertCancel", comment: "Cancel Title"))
alertView.addButtonWithTitle(NSLocalizedString("AlertSave", comment: "Save Title"))
alertView.alertViewStyle = UIAlertViewStyle.PlainTextInput
alertView.textFieldAtIndex(0)!.autocapitalizationType = UITextAutocapitalizationType.Words
alertView.textFieldAtIndex(0)!.text = self.user!.getNameModel().get()
alertView.textFieldAtIndex(0)?.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
alertView.tapBlock = { (alertView, buttonIndex) -> () in
if (buttonIndex == 1) {
let textField = alertView.textFieldAtIndex(0)!
if count(textField.text) > 0 {
self.execute(Actor.editMyNameCommandWithName(textField.text))
}
}
}
alertView.show()
})
// Settings
var actionsSection = tableData.addSection(autoSeparator: true)
.setHeaderHeight(15)
.setFooterHeight(15)
// Settings: Notifications
actionsSection.addNavigationCell("SettingsNotifications", actionClosure: { () -> () in
self.navigateNext(SettingsNotificationsViewController(), removeCurrent: false)
})
// Settings: Privacy
actionsSection.addNavigationCell("SettingsSecurity", actionClosure: { () -> () in
self.navigateNext(SettingsPrivacyViewController(), removeCurrent: false)
})
// Support
var supportSection = tableData.addSection(autoSeparator: true)
.setHeaderHeight(15)
.setFooterHeight(15)
// Support: Ask Question
supportSection.addNavigationCell("SettingsAskQuestion", actionClosure: { () -> () in
self.execute(Actor.findUsersCommandWithQuery("75551234567"), successBlock: { (val) -> Void in
var user:ACUserVM!
if let users = val as? IOSObjectArray {
if Int(users.length()) > 0 {
if let tempUser = users.objectAtIndex(0) as? ACUserVM {
user = tempUser
}
}
}
self.navigateDetail(ConversationViewController(peer: ACPeer.userWithInt(user.getId())))
}, failureBlock: { (val) -> Void in
// TODO: Implement
})
})
// Support: Ask Question
supportSection.addNavigationCell("SettingsAbout", actionClosure: { () -> () in
UIApplication.sharedApplication().openURL(NSURL(string: "https://actor.im")!)
})
// Support: App version
var version = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
supportSection.addCommonCell()
.setContent(NSLocalizedString("SettingsVersion", comment: "Version").stringByReplacingOccurrencesOfString("{version}", withString: version, options: NSStringCompareOptions.allZeros, range: nil))
.setStyle(.Hint)
// Bind
tableView.reloadData()
binder.bind(user!.getNameModel()!, closure: { (value: String?) -> () in
if value == nil {
return
}
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell {
cell.setUsername(value!)
}
})
binder.bind(user!.getAboutModel(), closure: { (value: String?) -> () in
var about = self.user!.getAboutModel().get()
if about == nil {
about = localized("SettingsAboutNotSet")
aboutCell.setIsAction(true)
} else {
aboutCell.setIsAction(false)
}
aboutCell.setContent(localized("ProfileAbout"), text: about)
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 2, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
})
binder.bind(user!.getNickModel(), closure: { (value: String?) -> () in
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 1, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
})
binder.bind(Actor.getOwnAvatarVM().getUploadState(), valueModel2: user!.getAvatarModel()) { (upload: ACAvatarUploadState?, avatar: ACAvatar?) -> () in
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell {
if (upload != nil && upload!.isUploading().boolValue) {
cell.userAvatarView.bind(self.user!.getNameModel().get(), id: jint(self.uid), fileName: upload?.getDescriptor())
cell.setProgress(true)
} else {
cell.userAvatarView.bind(self.user!.getNameModel().get(), id: jint(self.uid), avatar: avatar, clearPrev: false)
cell.setProgress(false)
}
}
}
binder.bind(user!.getPresenceModel(), closure: { (presence: ACUserPresence?) -> () in
var presenceText = Actor.getFormatter().formatPresence(presence, withSex: self.user!.getSex())
if presenceText != nil {
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell {
cell.setPresence(presenceText)
}
}
})
binder.bind(user!.getPhonesModel(), closure: { (phones: JavaUtilArrayList?) -> () in
if phones != nil {
self.phones = phones
self.tableView.reloadData()
}
})
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
Actor.onProfileOpenWithUid(jint(uid))
MainAppTheme.navigation.applyStatusBar()
navigationController?.navigationBar.shadowImage = UIImage()
applyScrollUi(tableView)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
Actor.onProfileClosedWithUid(jint(uid))
navigationController?.navigationBar.lt_reset()
}
}
| mit | 62340358916b326a36e1572ed2fdefcc | 42.224044 | 206 | 0.557585 | 5.543097 | false | false | false | false |
gottesmm/swift | stdlib/private/StdlibUnicodeUnittest/Collation.swift | 9 | 17743 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import StdlibUnittest
struct CollationTableEntry {
let scalars: [UnicodeScalar]
let collationElements: [UInt64]
let comment: String
init(
_ scalars: [UInt32],
_ collationElements: [UInt64],
_ comment: String
) {
self.scalars = scalars.map { UnicodeScalar($0)! }
self.collationElements = collationElements
self.comment = comment
}
}
/// An excerpt from the DUCET (Default Unicode Collation Element Table).
///
/// The data was extracted from
/// http://www.unicode.org/Public/UCA/9.0.0/allkeys.txt.
let ducetExtractData: [CollationTableEntry] = [
CollationTableEntry([0x00], [0x0000_0000_0000], "NULL"),
CollationTableEntry([0x01], [0x0000_0000_0000], "START OF HEADING"),
CollationTableEntry([0x02], [0x0000_0000_0000], "START OF TEXT"),
CollationTableEntry([0x03], [0x0000_0000_0000], "END OF TEXT"),
CollationTableEntry([0x04], [0x0000_0000_0000], "END OF TRANSMISSION"),
CollationTableEntry([0x05], [0x0000_0000_0000], "ENQUIRY"),
CollationTableEntry([0x06], [0x0000_0000_0000], "ACKNOWLEDGE"),
CollationTableEntry([0x07], [0x0000_0000_0000], "BELL"),
CollationTableEntry([0x08], [0x0000_0000_0000], "BACKSPACE"),
CollationTableEntry([0x09], [0x0201_0020_0002], "HORIZONTAL TABULATION"),
CollationTableEntry([0x0A], [0x0202_0020_0002], "LINE FEED"),
CollationTableEntry([0x0B], [0x0203_0020_0002], "VERTICAL TABULATION"),
CollationTableEntry([0x0C], [0x0204_0020_0002], "FORM FEED"),
CollationTableEntry([0x0D], [0x0205_0020_0002], "CARRIAGE RETURN"),
CollationTableEntry([0x0E], [0x0000_0000_0000], "SHIFT OUT"),
CollationTableEntry([0x0F], [0x0000_0000_0000], "SHIFT IN"),
CollationTableEntry([0x10], [0x0000_0000_0000], "DATA LINK ESCAPE"),
CollationTableEntry([0x11], [0x0000_0000_0000], "DEVICE CONTROL ONE"),
CollationTableEntry([0x12], [0x0000_0000_0000], "DEVICE CONTROL TWO"),
CollationTableEntry([0x13], [0x0000_0000_0000], "DEVICE CONTROL THREE"),
CollationTableEntry([0x14], [0x0000_0000_0000], "DEVICE CONTROL FOUR"),
CollationTableEntry([0x15], [0x0000_0000_0000], "NEGATIVE ACKNOWLEDGE"),
CollationTableEntry([0x16], [0x0000_0000_0000], "SYNCHRONOUS IDLE"),
CollationTableEntry([0x17], [0x0000_0000_0000], "END OF TRANSMISSION BLOCK"),
CollationTableEntry([0x18], [0x0000_0000_0000], "CANCEL"),
CollationTableEntry([0x19], [0x0000_0000_0000], "END OF MEDIUM"),
CollationTableEntry([0x1A], [0x0000_0000_0000], "SUBSTITUTE"),
CollationTableEntry([0x1B], [0x0000_0000_0000], "ESCAPE"),
CollationTableEntry([0x1C], [0x0000_0000_0000], "FILE SEPARATOR"),
CollationTableEntry([0x1D], [0x0000_0000_0000], "GROUP SEPARATOR"),
CollationTableEntry([0x1E], [0x0000_0000_0000], "RECORD SEPARATOR"),
CollationTableEntry([0x1F], [0x0000_0000_0000], "UNIT SEPARATOR"),
CollationTableEntry([0x20], [0x0209_0020_0002], "SPACE"),
CollationTableEntry([0x21], [0x0260_0020_0002], "EXCLAMATION MARK"),
CollationTableEntry([0x22], [0x030C_0020_0002], "QUOTATION MARK"),
CollationTableEntry([0x23], [0x0398_0020_0002], "NUMBER SIGN"),
CollationTableEntry([0x24], [0x1C12_0020_0002], "DOLLAR SIGN"),
CollationTableEntry([0x25], [0x0399_0020_0002], "PERCENT SIGN"),
CollationTableEntry([0x26], [0x0396_0020_0002], "AMPERSAND"),
CollationTableEntry([0x27], [0x0305_0020_0002], "APOSTROPHE"),
CollationTableEntry([0x28], [0x0317_0020_0002], "LEFT PARENTHESIS"),
CollationTableEntry([0x29], [0x0318_0020_0002], "RIGHT PARENTHESIS"),
CollationTableEntry([0x2A], [0x038F_0020_0002], "ASTERISK"),
CollationTableEntry([0x2B], [0x0616_0020_0002], "PLUS SIGN"),
CollationTableEntry([0x2C], [0x0222_0020_0002], "COMMA"),
CollationTableEntry([0x2D], [0x020D_0020_0002], "HYPHEN-MINUS"),
CollationTableEntry([0x2E], [0x0277_0020_0002], "FULL STOP"),
CollationTableEntry([0x2F], [0x0394_0020_0002], "SOLIDUS"),
CollationTableEntry([0x30], [0x1C3D_0020_0002], "DIGIT ZERO"),
CollationTableEntry([0x31], [0x1C3E_0020_0002], "DIGIT ONE"),
CollationTableEntry([0x32], [0x1C3F_0020_0002], "DIGIT TWO"),
CollationTableEntry([0x33], [0x1C40_0020_0002], "DIGIT THREE"),
CollationTableEntry([0x34], [0x1C41_0020_0002], "DIGIT FOUR"),
CollationTableEntry([0x35], [0x1C42_0020_0002], "DIGIT FIVE"),
CollationTableEntry([0x36], [0x1C43_0020_0002], "DIGIT SIX"),
CollationTableEntry([0x37], [0x1C44_0020_0002], "DIGIT SEVEN"),
CollationTableEntry([0x38], [0x1C45_0020_0002], "DIGIT EIGHT"),
CollationTableEntry([0x39], [0x1C46_0020_0002], "DIGIT NINE"),
CollationTableEntry([0x3A], [0x0239_0020_0002], "COLON"),
CollationTableEntry([0x3B], [0x0234_0020_0002], "SEMICOLON"),
CollationTableEntry([0x3C], [0x061A_0020_0002], "LESS-THAN SIGN"),
CollationTableEntry([0x3D], [0x061B_0020_0002], "EQUALS SIGN"),
CollationTableEntry([0x3E], [0x061C_0020_0002], "GREATER-THAN SIGN"),
CollationTableEntry([0x3F], [0x0266_0020_0002], "QUESTION MARK"),
CollationTableEntry([0x40], [0x038E_0020_0002], "COMMERCIAL AT"),
CollationTableEntry([0x41], [0x1C47_0020_0008], "LATIN CAPITAL LETTER A"),
CollationTableEntry([0x42], [0x1C60_0020_0008], "LATIN CAPITAL LETTER B"),
CollationTableEntry([0x43], [0x1C7A_0020_0008], "LATIN CAPITAL LETTER C"),
CollationTableEntry([0x44], [0x1C8F_0020_0008], "LATIN CAPITAL LETTER D"),
CollationTableEntry([0x45], [0x1CAA_0020_0008], "LATIN CAPITAL LETTER E"),
CollationTableEntry([0x46], [0x1CE5_0020_0008], "LATIN CAPITAL LETTER F"),
CollationTableEntry([0x47], [0x1CF4_0020_0008], "LATIN CAPITAL LETTER G"),
CollationTableEntry([0x48], [0x1D18_0020_0008], "LATIN CAPITAL LETTER H"),
CollationTableEntry([0x49], [0x1D32_0020_0008], "LATIN CAPITAL LETTER I"),
CollationTableEntry([0x4A], [0x1D4C_0020_0008], "LATIN CAPITAL LETTER J"),
CollationTableEntry([0x4B], [0x1D65_0020_0008], "LATIN CAPITAL LETTER K"),
CollationTableEntry([0x4C], [0x1D77_0020_0008], "LATIN CAPITAL LETTER L"),
CollationTableEntry([0x4D], [0x1DAA_0020_0008], "LATIN CAPITAL LETTER M"),
CollationTableEntry([0x4E], [0x1DB9_0020_0008], "LATIN CAPITAL LETTER N"),
CollationTableEntry([0x4F], [0x1DDD_0020_0008], "LATIN CAPITAL LETTER O"),
CollationTableEntry([0x50], [0x1E0C_0020_0008], "LATIN CAPITAL LETTER P"),
CollationTableEntry([0x51], [0x1E21_0020_0008], "LATIN CAPITAL LETTER Q"),
CollationTableEntry([0x52], [0x1E33_0020_0008], "LATIN CAPITAL LETTER R"),
CollationTableEntry([0x53], [0x1E71_0020_0008], "LATIN CAPITAL LETTER S"),
CollationTableEntry([0x54], [0x1E95_0020_0008], "LATIN CAPITAL LETTER T"),
CollationTableEntry([0x55], [0x1EB5_0020_0008], "LATIN CAPITAL LETTER U"),
CollationTableEntry([0x56], [0x1EE3_0020_0008], "LATIN CAPITAL LETTER V"),
CollationTableEntry([0x57], [0x1EF5_0020_0008], "LATIN CAPITAL LETTER W"),
CollationTableEntry([0x58], [0x1EFF_0020_0008], "LATIN CAPITAL LETTER X"),
CollationTableEntry([0x59], [0x1F0B_0020_0008], "LATIN CAPITAL LETTER Y"),
CollationTableEntry([0x5A], [0x1F21_0020_0008], "LATIN CAPITAL LETTER Z"),
CollationTableEntry([0x5B], [0x0319_0020_0002], "LEFT SQUARE BRACKET"),
CollationTableEntry([0x5C], [0x0395_0020_0002], "REVERSE SOLIDUS"),
CollationTableEntry([0x5D], [0x031A_0020_0002], "RIGHT SQUARE BRACKET"),
CollationTableEntry([0x5E], [0x0485_0020_0002], "CIRCUMFLEX ACCENT"),
CollationTableEntry([0x5F], [0x020B_0020_0002], "LOW LINE"),
CollationTableEntry([0x60], [0x0482_0020_0002], "GRAVE ACCENT"),
CollationTableEntry([0x61], [0x1C47_0020_0002], "LATIN SMALL LETTER A"),
CollationTableEntry([0x62], [0x1C60_0020_0002], "LATIN SMALL LETTER B"),
CollationTableEntry([0x63], [0x1C7A_0020_0002], "LATIN SMALL LETTER C"),
CollationTableEntry([0x64], [0x1C8F_0020_0002], "LATIN SMALL LETTER D"),
CollationTableEntry([0x65], [0x1CAA_0020_0002], "LATIN SMALL LETTER E"),
CollationTableEntry([0x66], [0x1CE5_0020_0002], "LATIN SMALL LETTER F"),
CollationTableEntry([0x67], [0x1CF4_0020_0002], "LATIN SMALL LETTER G"),
CollationTableEntry([0x68], [0x1D18_0020_0002], "LATIN SMALL LETTER H"),
CollationTableEntry([0x69], [0x1D32_0020_0002], "LATIN SMALL LETTER I"),
CollationTableEntry([0x6A], [0x1D4C_0020_0002], "LATIN SMALL LETTER J"),
CollationTableEntry([0x6B], [0x1D65_0020_0002], "LATIN SMALL LETTER K"),
CollationTableEntry([0x6C], [0x1D77_0020_0002], "LATIN SMALL LETTER L"),
CollationTableEntry([0x6D], [0x1DAA_0020_0002], "LATIN SMALL LETTER M"),
CollationTableEntry([0x6E], [0x1DB9_0020_0002], "LATIN SMALL LETTER N"),
CollationTableEntry([0x6F], [0x1DDD_0020_0002], "LATIN SMALL LETTER O"),
CollationTableEntry([0x70], [0x1E0C_0020_0002], "LATIN SMALL LETTER P"),
CollationTableEntry([0x71], [0x1E21_0020_0002], "LATIN SMALL LETTER Q"),
CollationTableEntry([0x72], [0x1E33_0020_0002], "LATIN SMALL LETTER R"),
CollationTableEntry([0x73], [0x1E71_0020_0002], "LATIN SMALL LETTER S"),
CollationTableEntry([0x74], [0x1E95_0020_0002], "LATIN SMALL LETTER T"),
CollationTableEntry([0x75], [0x1EB5_0020_0002], "LATIN SMALL LETTER U"),
CollationTableEntry([0x76], [0x1EE3_0020_0002], "LATIN SMALL LETTER V"),
CollationTableEntry([0x77], [0x1EF5_0020_0002], "LATIN SMALL LETTER W"),
CollationTableEntry([0x78], [0x1EFF_0020_0002], "LATIN SMALL LETTER X"),
CollationTableEntry([0x79], [0x1F0B_0020_0002], "LATIN SMALL LETTER Y"),
CollationTableEntry([0x7A], [0x1F21_0020_0002], "LATIN SMALL LETTER Z"),
CollationTableEntry([0x7B], [0x031B_0020_0002], "LEFT CURLY BRACKET"),
CollationTableEntry([0x7C], [0x061E_0020_0002], "VERTICAL LINE"),
CollationTableEntry([0x7D], [0x031C_0020_0002], "RIGHT CURLY BRACKET"),
CollationTableEntry([0x7E], [0x0620_0020_0002], "TILDE"),
CollationTableEntry([0x7F], [0x0000_0000_0000], "DELETE"),
// When String starts to use Latin-1 as one of its in-memory representations,
// this table should be extended to cover all scalars in U+0080 ... U+00FF.
CollationTableEntry([0x80], [0x0000_0000_0000], "<control>"),
CollationTableEntry([0xE1], [0x1C47_0020_0002, 0x0000_0024_0002], "LATIN SMALL LETTER A WITH ACUTE"),
CollationTableEntry([0xE2], [0x1C47_0020_0002, 0x0000_0027_0002], "LATIN SMALL LETTER A WITH CIRCUMFLEX"),
CollationTableEntry([0xFF], [0x1F0B_0020_0002, 0x0000_002B_0002], "LATIN SMALL LETTER Y WITH DIAERESIS"),
CollationTableEntry([0x3041], [0x3D5A_0020_000D], "HIRAGANA LETTER SMALL A"),
CollationTableEntry([0x3042], [0x3D5A_0020_000E], "HIRAGANA LETTER A"),
CollationTableEntry([0x30A1], [0x3D5A_0020_000F], "KATAKANA LETTER SMALL A"),
CollationTableEntry([0xFF67], [0x3D5A_0020_0010], "HALFWIDTH KATAKANA LETTER SMALL A"),
CollationTableEntry([0x30A2], [0x3D5A_0020_0011], "KATAKANA LETTER A"),
CollationTableEntry([0xFF71], [0x3D5A_0020_0012], "HALFWIDTH KATAKANA LETTER A"),
CollationTableEntry([0xFE00], [0x0000_0000_0000], "VARIATION SELECTOR-1"),
CollationTableEntry([0xFE01], [0x0000_0000_0000], "VARIATION SELECTOR-2"),
CollationTableEntry([0xE01EE], [0x0000_0000_0000], "VARIATION SELECTOR-255"),
CollationTableEntry([0xE01EF], [0x0000_0000_0000], "VARIATION SELECTOR-256"),
]
public struct HashableArray<Element : Hashable> : Hashable {
internal var _elements: [Element]
public init(_ elements: [Element]) {
_elements = elements
}
public var hashValue: Int {
// FIXME: this is a bad approach to combining hash values.
var result = 0
for x in _elements {
result ^= x.hashValue
result = result &* 997
}
return result
}
}
public func == <Element>(
lhs: HashableArray<Element>,
rhs: HashableArray<Element>
) -> Bool {
return lhs._elements.elementsEqual(rhs._elements)
}
extension HashableArray : ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Element...) {
self._elements = elements
}
}
let ducetExtract: [HashableArray<UnicodeScalar> : CollationTableEntry] = {
() in
var result: [HashableArray<UnicodeScalar> : CollationTableEntry] = [:]
for entry in ducetExtractData {
result[HashableArray(entry.scalars)] = entry
}
return result
}()
extension String {
/// Calculate collation elements for trivial cases.
///
/// Warning: this implementation does not conform to Unicode TR10!
/// It is a gross oversimplification that is only used to reduce the repetition
/// of test inputs in this file. Among other things, this algorithm does not
/// handle contractions in the collation table, does not perform string
/// normalization, does not synthesize derived collation weights etc.
internal var _collationElements: [UInt64] {
var result: [UInt64] = []
for us in self.unicodeScalars {
let scalars: HashableArray<UnicodeScalar> = [us]
let collationElements = ducetExtract[scalars]!.collationElements
if collationElements[0] != 0 {
result += collationElements
}
}
return result
}
}
public struct StringComparisonTest {
public let string: String
public let collationElements: [UInt64]
public let loc: SourceLoc
public var order: Int?
public init(
_ string: String,
inferCollationElements: Void,
file: String = #file, line: UInt = #line
) {
self.string = string
self.collationElements = string._collationElements
self.loc = SourceLoc(file, line, comment: "test data")
}
public init(
_ string: String,
_ collationElements: [UInt64],
sourceLocation: SourceLoc
) {
self.string = string
self.collationElements = collationElements
self.loc = sourceLocation
}
public init(
_ string: String,
_ collationElements: [UInt64],
file: String = #file, line: UInt = #line
) {
self.init(
string,
collationElements,
sourceLocation: SourceLoc(file, line, comment: "test data"))
}
public static let testsFromDUCET: [StringComparisonTest] = {
() in
var result: [StringComparisonTest] = []
for entry in ducetExtractData {
var s = ""
for c in entry.scalars {
s.append(Character(c))
}
if entry.collationElements[0] != 0 {
result.append(StringComparisonTest(s, entry.collationElements))
}
}
return result
}()
public static let hardcodedTests: [StringComparisonTest] = [
StringComparisonTest("", inferCollationElements: ()),
// Completely ignorable characters in ASCII strings.
StringComparisonTest("\u{00}\u{61}", inferCollationElements: ()),
StringComparisonTest("\u{61}\u{00}", inferCollationElements: ()),
StringComparisonTest("\u{00}\u{61}\u{00}", inferCollationElements: ()),
StringComparisonTest("\u{61}\u{00}\u{62}", inferCollationElements: ()),
// Completely ignorable characters in Latin-1 strings.
StringComparisonTest("\u{00}\u{E1}", inferCollationElements: ()),
StringComparisonTest("\u{E1}\u{00}", inferCollationElements: ()),
StringComparisonTest("\u{00}\u{E1}\u{00}", inferCollationElements: ()),
StringComparisonTest("\u{E1}\u{00}\u{E2}", inferCollationElements: ()),
// Completely ignorable characters in non-Latin-1 strings.
StringComparisonTest("\u{0000}\u{3041}", inferCollationElements: ()),
StringComparisonTest("\u{3041}\u{0000}", inferCollationElements: ()),
StringComparisonTest("\u{0000}\u{3041}\u{0000}", inferCollationElements: ()),
StringComparisonTest("\u{3041}\u{0000}\u{3042}", inferCollationElements: ()),
StringComparisonTest("\u{FE00}\u{3041}", inferCollationElements: ()),
StringComparisonTest("\u{3041}\u{FE00}", inferCollationElements: ()),
StringComparisonTest("\u{FE00}\u{3041}\u{FE00}", inferCollationElements: ()),
StringComparisonTest("\u{3041}\u{FE00}\u{3042}", inferCollationElements: ()),
StringComparisonTest("\u{E01EF}\u{3041}", inferCollationElements: ()),
StringComparisonTest("\u{03041}\u{E01EF}", inferCollationElements: ()),
StringComparisonTest("\u{E01EF}\u{03041}\u{E01EF}", inferCollationElements: ()),
StringComparisonTest("\u{03041}\u{E01EF}\u{03042}", inferCollationElements: ()),
// U+0061 LATIN SMALL LETTER A
// U+0301 COMBINING ACUTE ACCENT
// U+00E1 LATIN SMALL LETTER A WITH ACUTE
StringComparisonTest("\u{61}\u{301}", "\u{E1}"._collationElements),
]
public static let allTests: [StringComparisonTest] = {
() in
return testsFromDUCET + hardcodedTests
}()
}
public func sortKey(forCollationElements ces: [UInt64]) -> ([UInt16], [UInt16], [UInt16]) {
func L1(_ ce: UInt64) -> UInt16 {
return UInt16(truncatingBitPattern: ce >> 32)
}
func L2(_ ce: UInt64) -> UInt16 {
return UInt16(truncatingBitPattern: ce >> 16)
}
func L3(_ ce: UInt64) -> UInt16 {
return UInt16(truncatingBitPattern: ce)
}
var result1: [UInt16] = []
for ce in ces { result1.append(L1(ce)) }
var result2: [UInt16] = []
for ce in ces { result2.append(L2(ce)) }
var result3: [UInt16] = []
for ce in ces { result3.append(L3(ce)) }
return (result1, result2, result3)
}
public func collationElements(
_ lhs: [UInt64], areLessThan rhs: [UInt64]
) -> Bool {
let lhsKey = sortKey(forCollationElements: lhs)
let rhsKey = sortKey(forCollationElements: rhs)
if lhsKey.0 != rhsKey.0 {
return lhsKey.0.lexicographicallyPrecedes(rhsKey.0)
}
if lhsKey.1 != rhsKey.1 {
return lhsKey.1.lexicographicallyPrecedes(rhsKey.1)
}
return lhsKey.2.lexicographicallyPrecedes(rhsKey.2)
}
| apache-2.0 | 77637a7dfd94a7b6ee0a5740bf1bebb9 | 46.314667 | 108 | 0.699713 | 3.241323 | false | true | false | false |
BalestraPatrick/HomeKitty | Sources/App/Models/HomeKitApp.swift | 1 | 1391 | //
// Copyright © 2018 HomeKitty. All rights reserved.
//
import Foundation
import FluentPostgreSQL
import Vapor
struct HomeKitApp: PostgreSQLModel {
static var entity = "apps"
var id: Int?
let name: String
let subtitle: String?
let publisher: String
let websiteLink: String
let price: Double?
let appStoreLink: String
let appStoreIcon: String
let approved: Bool
let createdAt: Date
let updatedAt: Date
init(name: String,
subtitle: String?,
price: Double?,
appStoreLink: String,
appStoreIcon: String,
publisher: String,
websiteLink: String) {
self.name = name
self.subtitle = subtitle
self.publisher = publisher
self.websiteLink = websiteLink
self.price = price
self.appStoreLink = appStoreLink
self.appStoreIcon = appStoreIcon
self.approved = false
self.createdAt = Date()
self.updatedAt = Date()
}
enum CodingKeys: String, CodingKey {
case id
case name
case subtitle
case publisher
case websiteLink = "website_link"
case price
case appStoreLink = "app_store_link"
case appStoreIcon = "app_store_icon"
case approved
case createdAt
case updatedAt
}
}
extension HomeKitApp: PostgreSQLMigration { }
| mit | 29a4865c1a4cb93c159002e6989e9bad | 22.965517 | 52 | 0.618705 | 4.680135 | false | false | false | false |
evermeer/PassportScanner | Pod/PassportScannerController.swift | 1 | 20632 | //
// PassportScannerController.swift
//
// Created by Edwin Vermeer on 9/7/15.
// Copyright (c) 2015. All rights reserved.
//
import Foundation
import UIKit
import TesseractOCRSDKiOS
import EVGPUImage2
import GPUImage //Still using this for the rotate
import UIImage_Resize
import AVFoundation
// based to https://www.icao.int/publications/pages/publication.aspx?docnum=9303
@objc
public enum MRZType: Int {
case auto
case td1 // 3 lines - 30 chars per line
//case td2 // to be implemented
case td3 // 2 lines - 44 chars per line
}
@objc(PassportScannerController)
open class PassportScannerController: UIViewController, MGTesseractDelegate {
/// Set debug to true if you want to see what's happening
@objc public var debug = false
/// Set accuracy that is required for the scan. 1 = all checksums should be ok
@objc public var accuracy: Float = 1
/// If false then apply filters in post processing, otherwise instead of in camera preview
@objc public var showPostProcessingFilters = true
//last parsed image
@objc public var parsedImage: UIImage?
// The parsing to be applied
@objc public var mrzType: MRZType = MRZType.auto
// For if you want the data on a different location than standard
@objc public var tesseractTrainedDataAbsolutePath: String?
// Can be sat as a callback function
@objc public var scannerDidCompleteWith:((MRZParser?) -> ())?
// The size and location of the scan area so that you could create your own custom interface.
var ocrParsingRect: CGRect = CGRect(x: 350, y: 60, width: 350, height: 1800)
// We only wan to do the setup once.
@objc public var setupCompleted = false
/// When you create your own view, then make sure you have a GPUImageView that is linked to this
@IBOutlet var renderView: RenderView!
/// For capturing the video and passing it on to the filters.
var camera: Camera!
// Quick reference to the used filter configurations
var exposure: ExposureAdjustment!
var highlightShadow: HighlightsAndShadows!
var saturation: SaturationAdjustment!
var contrast: ContrastAdjustment!
var adaptiveThreshold: AdaptiveThreshold!
var averageColor: AverageColorExtractor!
var crop = Crop()
let defaultExposure: Float = 1.5
//Post processing filters
private var averageColorFilter: GPUImageAverageColor!
private var lastExposure: CGFloat = 1.5
private let enableAdaptativeExposure = true
let exposureFilter: GPUImageExposureFilter = GPUImageExposureFilter()
let highlightShadowFilter: GPUImageHighlightShadowFilter = GPUImageHighlightShadowFilter()
let saturationFilter: GPUImageSaturationFilter = GPUImageSaturationFilter()
let contrastFilter: GPUImageContrastFilter = GPUImageContrastFilter()
let adaptiveThresholdFilter: GPUImageAdaptiveThresholdFilter = GPUImageAdaptiveThresholdFilter()
var pictureOutput = PictureOutput()
/// The tesseract OCX engine
var tesseract: MGTesseract? = MGTesseract(language: "eng")
/**
Rotation is not needed.
:returns: Returns .portrait
*/
override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
get { return .portrait }
}
/**
Hide the status bar during scan
:returns: true to indicate the statusbar should be hidden
*/
override open var prefersStatusBarHidden: Bool {
get { return true }
}
/**
Initialize all graphic filters in the viewDidLoad
*/
open override func viewDidLoad() {
super.viewDidLoad()
if !self.setupCompleted {
self.setup()
}
}
@objc public func setup() {
if self.setupCompleted {
return
}
self.setupCompleted = true
self.view.backgroundColor = UIColor.white
if self.tesseractTrainedDataAbsolutePath != nil {
tesseract = MGTesseract(language: "eng", configDictionary: nil, configFileNames: nil, absoluteDataPath: self.tesseractTrainedDataAbsolutePath, engineMode: MGOCREngineMode.tesseractOnly)
}else{
tesseract = MGTesseract(language: "eng")
}
// Specify the crop region that will be used for the OCR
crop.cropSizeInPixels = Size(width: Float(ocrParsingRect.size.width), height: Float(ocrParsingRect.size.height))
crop.locationOfCropInPixels = Position(Float(ocrParsingRect.origin.x), Float(ocrParsingRect.origin.y), nil)
crop.overriddenOutputRotation = .rotateClockwise
if !showPostProcessingFilters {
exposureFilter.exposure = CGFloat(self.defaultExposure)
highlightShadowFilter.highlights = 0.8
saturationFilter.saturation = 0.6
contrastFilter.contrast = 2.0
adaptiveThresholdFilter.blurRadiusInPixels = 8.0
} else {
// Filter settings
exposure = ExposureAdjustment()
exposure.exposure = 0.7 // -10 - 10
highlightShadow = HighlightsAndShadows()
highlightShadow.highlights = 0.6 // 0 - 1
saturation = SaturationAdjustment();
saturation.saturation = 0.6 // 0 - 2
contrast = ContrastAdjustment();
contrast.contrast = 2.0 // 0 - 4
adaptiveThreshold = AdaptiveThreshold();
adaptiveThreshold.blurRadiusInPixels = 8.0
// Try to dynamically optimize the exposure based on the average color
averageColor = AverageColorExtractor();
averageColor.extractedColorCallback = { color in
let lighting = color.blueComponent + color.greenComponent + color.redComponent
let currentExposure = self.exposure.exposure
// The stable color is between 2.75 and 2.85. Otherwise change the exposure
if lighting < 2.75 {
self.exposure.exposure = currentExposure + (2.80 - lighting) * 2
}
if lighting > 2.85 {
self.exposure.exposure = currentExposure - (lighting - 2.80) * 2
}
if self.exposure.exposure > 2 {
self.exposure.exposure = self.defaultExposure
}
if self.exposure.exposure < -2 {
self.exposure.exposure = self.defaultExposure
}
}
}
// download trained data to tessdata folder for language from:
// https://code.google.com/p/tesseract-ocr/downloads/list
// optimisations created based on https://github.com/gali8/Tesseract-OCR-iOS/wiki/Tips-for-Improving-OCR-Results
// tesseract OCR settings
self.tesseract?.setVariableValue("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<", forKey: "tessedit_char_whitelist")
self.tesseract?.delegate = self
self.tesseract?.rect = CGRect(x: 0, y: 0, width: ocrParsingRect.size.height / 2, height: ocrParsingRect.size.width / 2)
// see http://www.sk-spell.sk.cx/tesseract-ocr-en-variables
self.tesseract?.setVariableValue("1", forKey: "tessedit_serial_unlv")
self.tesseract?.setVariableValue("FALSE", forKey: "x_ht_quality_check")
self.tesseract?.setVariableValue("FALSE", forKey: "load_system_dawg")
self.tesseract?.setVariableValue("FALSE", forKey: "load_freq_dawg")
self.tesseract?.setVariableValue("FALSE", forKey: "load_unambig_dawg")
self.tesseract?.setVariableValue("FALSE", forKey: "load_punc_dawg")
self.tesseract?.setVariableValue("FALSE", forKey: "load_number_dawg")
self.tesseract?.setVariableValue("FALSE", forKey: "load_fixed_length_dawgs")
self.tesseract?.setVariableValue("FALSE", forKey: "load_bigram_dawg")
self.tesseract?.setVariableValue("FALSE", forKey: "wordrec_enable_assoc")
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if camera == nil {
self.initCamera()
}
}
func initCamera(){
do {
// Initialize the camera
camera = try Camera(sessionPreset: AVCaptureSession.Preset.hd1920x1080)
camera.location = PhysicalCameraLocation.backFacing
if renderView==nil {
renderView = RenderView.init(frame: self.view.bounds)
self.view.addSubview(renderView)
}else{
renderView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
}
if !showPostProcessingFilters {
// Apply only the cropping
camera --> renderView
camera --> crop
} else {
// Chain the filter to the render view
camera --> exposure --> highlightShadow --> saturation --> contrast --> adaptiveThreshold --> renderView
// Use the same chained filters and forward these to 2 other filters
adaptiveThreshold --> crop --> averageColor
}
if debug{
let debugViewFrame : CGRect = self.getOcrParsingRectDebugView()
let scanAreaDebug = UIView (frame: CGRect(x:debugViewFrame.origin.x,
y:debugViewFrame.origin.y,
width:debugViewFrame.size.width,
height:debugViewFrame.size.height))
scanAreaDebug.backgroundColor = UIColor.red.withAlphaComponent(0.5)
renderView.addSubview(scanAreaDebug)
}
} catch {
fatalError("Could not initialize rendering pipeline: \(error)")
}
}
func evaluateExposure(image: UIImage){
if !self.enableAdaptativeExposure || self.averageColorFilter != nil {
return
}
DispatchQueue.global(qos: .background).async {
self.averageColorFilter = GPUImageAverageColor()
self.averageColorFilter.colorAverageProcessingFinishedBlock = {red, green, blue, alpha, time in
let lighting = blue + green + red
let currentExposure = self.lastExposure
// The stable color is between 2.75 and 2.85. Otherwise change the exposure
if lighting < 2.75 {
self.lastExposure = currentExposure + (2.80 - lighting) * 2
}
if lighting > 2.85 {
self.lastExposure = currentExposure - (lighting - 2.80) * 2
}
if self.lastExposure > 2 {
self.lastExposure = CGFloat(self.defaultExposure)
}
if self.lastExposure < -2 {
self.lastExposure = CGFloat(self.defaultExposure)
}
self.averageColorFilter = nil
}
self.averageColorFilter.image(byFilteringImage: image)
}
}
open func preprocessedImage(for tesseract: MGTesseract!, sourceImage: UIImage!) -> UIImage! {
// sourceImage is the same image you sent to Tesseract above.
// Processing is already done in dynamic filters
if showPostProcessingFilters { return sourceImage }
var filterImage: UIImage = sourceImage
exposureFilter.exposure = self.lastExposure
filterImage = exposureFilter.image(byFilteringImage: filterImage)
filterImage = highlightShadowFilter.image(byFilteringImage: filterImage)
filterImage = saturationFilter.image(byFilteringImage: filterImage)
filterImage = contrastFilter.image(byFilteringImage: filterImage)
filterImage = adaptiveThresholdFilter.image(byFilteringImage: filterImage)
self.evaluateExposure(image: filterImage)
return filterImage
}
/**
The frame of the ocr parsing. It is in locical pixel, relative to the vc's view.
The frame is used to show the area that will be scanned (if debug = true)
The real scan area is converted to a coordinate relative to the final image (fullhd frame)
*/
@objc public func setOcrParsingRect(frame: CGRect){
let videoFrameSize : CGSize = CGSize(width: 1080, height: 1920)
let scale : CGFloat = UIScreen.main.scale
let x : CGFloat = (frame.origin.x * scale * videoFrameSize.width) / (self.view.frame.size.width * scale)
let y : CGFloat = (frame.origin.y * scale * videoFrameSize.height) / (self.view.frame.size.height * scale)
let w : CGFloat = (frame.size.width * scale * videoFrameSize.width) / (self.view.frame.size.width * scale)
let h : CGFloat = (frame.size.height * scale * videoFrameSize.height) / (self.view.frame.size.height * scale)
self.ocrParsingRect = CGRect(x: x, y: y, width: w, height: h)
crop.cropSizeInPixels = Size(width: Float(ocrParsingRect.size.width), height: Float(ocrParsingRect.size.height))
crop.locationOfCropInPixels = Position(Float(ocrParsingRect.origin.x), Float(ocrParsingRect.origin.y), nil)
self.tesseract?.rect = CGRect(x: 0, y: 0, width: ocrParsingRect.size.height / 2, height: ocrParsingRect.size.width / 2)
}
func getOcrParsingRectDebugView() -> CGRect{
let videoFrameSize : CGSize = CGSize(width: 1080, height: 1920)
let h : CGFloat = (self.ocrParsingRect.size.height / videoFrameSize.height) * renderView.frame.size.height
let w : CGFloat = (self.ocrParsingRect.size.width / videoFrameSize.width) * renderView.frame.size.width
let x : CGFloat = ((self.ocrParsingRect.origin.x / videoFrameSize.width) * renderView.frame.size.width)
let y : CGFloat = ((self.ocrParsingRect.origin.y / videoFrameSize.height) * renderView.frame.size.height)
return CGRect(x: x, y: y, width: w, height: h)
}
@objc public func startScan() {
self.setup()
if camera == nil {
self.initCamera()
}
self.view.backgroundColor = UIColor.black
camera.startCapture()
scanning()
}
private func scanning() {
DispatchQueue.global().asyncAfter(deadline: .now() + 0.2) {
//print("Start OCR")
self.pictureOutput = PictureOutput()
self.pictureOutput.encodedImageFormat = .png
self.pictureOutput.onlyCaptureNextFrame = true
self.pictureOutput.imageAvailableCallback = { sourceImage in
DispatchQueue.global().async() {
if self.processImage(sourceImage: sourceImage) { return }
// Not successful, start another scan
self.scanning()
}
}
self.crop --> self.pictureOutput
}
}
@objc public func stopScan() {
self.view.backgroundColor = UIColor.white
camera.stopCapture()
tesseract = nil
abortScan()
}
/**
call this from your code to start a scan immediately or hook it to a button.
:param: sender The sender of this event
*/
@IBAction open func StartScan(sender: AnyObject) {
self.startScan()
}
/**
call this from your code to stop a scan or hook it to a button
:param: sender the sender of this event
*/
@IBAction open func StopScan(sender: AnyObject) {
self.stopScan()
}
open func imageFromView(myView: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(myView.bounds.size, myView.isOpaque, 0.0)
myView.drawHierarchy(in: myView.bounds, afterScreenUpdates: true)
let snapshotImageFromMyView = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//print(snapshotImageFromMyView)
return snapshotImageFromMyView!
}
/**
Processing the image
- parameter sourceImage: The image that needs to be processed
*/
open func processImage(sourceImage: UIImage) -> Bool {
// resize image. Smaller images are faster to process. When letters are too big the scan quality also goes down.
let croppedImage: UIImage = sourceImage.resizedImageToFit(in: CGSize(width: ocrParsingRect.size.width * 0.5, height: ocrParsingRect.size.height * 0.5), scaleIfSmaller: true)
// rotate image. tesseract needs the correct orientation.
// let image: UIImage = croppedImage.rotate(by: -90)!
// strange... this rotate will cause 1/2 the image to be skipped
// Rotate cropped image
let selectedFilter = GPUImageTransformFilter()
selectedFilter.setInputRotation(kGPUImageRotateLeft, at: 0)
let image: UIImage = selectedFilter.image(byFilteringImage: croppedImage)
// Perform the OCR scan
let result: String = self.doOCR(image: image)
// Create the MRZ object and validate if it's OK
var mrz: MRZParser
if mrzType == MRZType.auto {
mrz = MRZTD1(scan: result, debug: self.debug)
if mrz.isValid() < self.accuracy {
mrz = MRZTD3(scan: result, debug: self.debug)
}
} else if mrzType == MRZType.td1 {
mrz = MRZTD1(scan: result, debug: self.debug)
} else {
mrz = MRZTD3(scan: result, debug: self.debug)
}
if mrz.isValid() < self.accuracy {
print("Scan quality insufficient : \(mrz.isValid())")
DispatchQueue.main.async {
self.parsedImage = self.imageFromView(myView: self.renderView)
}
} else {
DispatchQueue.main.async {
let subviews = self.renderView.subviews
for view in subviews {
view.removeFromSuperview()
}
self.parsedImage = self.imageFromView(myView: self.renderView)
self.camera.stopCapture()
}
DispatchQueue.main.async {
self.successfulScan(mrz: mrz)
}
return true
}
return false
}
/**
Perform the tesseract OCR on an image.
- parameter image: The image to be scanned
- returns: The OCR result
*/
open func doOCR(image: UIImage) -> String {
// Start OCR
var result: String?
self.tesseract?.image = image
print("- Start recognize")
self.tesseract?.recognize()
result = self.tesseract?.recognizedText
//tesseract = nil
MGTesseract.clearCache()
print("Scan result : \(result ?? "")")
return result ?? ""
}
/**
Override this function in your own class for processing the result
:param: mrz The MRZ result
*/
open func successfulScan(mrz: MRZParser) {
if(self.scannerDidCompleteWith != nil){
self.scannerDidCompleteWith!(mrz)
}else{
assertionFailure("You should overwrite this function to handle the scan results")
}
}
/**
Override this function in your own class for processing a cancel
*/
open func abortScan() {
if(self.scannerDidCompleteWith != nil){
self.scannerDidCompleteWith!(nil)
}else{
assertionFailure("You should overwrite this function to handle an abort")
}
}
open override func viewWillDisappear(_ animated: Bool) {
tesseract = nil
super.viewWillDisappear(animated)
}
}
// Wanted to use this rotation function. Tesseract does not like the result image.
// Went back to GpuImage for the rotation.
// Will try again later so that we can remove the old GpuImage dependency
@available(iOS 10.0, *)
extension UIImage {
func rotate(by degrees: Double) -> UIImage? {
guard let cgImage = self.cgImage else { return nil }
let transform = CGAffineTransform(rotationAngle: CGFloat(degrees * .pi / 180.0))
var rect = CGRect(origin: .zero, size: self.size).applying(transform)
rect.origin = .zero
let renderer = UIGraphicsImageRenderer(size: rect.size)
return renderer.image { renderContext in
renderContext.cgContext.translateBy(x: rect.midX, y: rect.midY)
renderContext.cgContext.rotate(by: CGFloat(degrees * .pi / 180.0))
renderContext.cgContext.scaleBy(x: 1.0, y: -1.0)
let drawRect = CGRect(origin: CGPoint(x: -self.size.width/2, y: -self.size.height/2), size: self.size)
renderContext.cgContext.draw(cgImage, in: drawRect)
}
}
}
| bsd-3-clause | a1c4273f8d2fb19e77de82f416099d9f | 36.718464 | 197 | 0.630816 | 4.654185 | false | false | false | false |
AppTown/OpenWeather | OpenWeather/OpenWeather/JSONSerializable.swift | 1 | 1484 | //
// JSONSerializable.swift
// OpenWeather
//
// Created by Dario Banno on 29/05/2017.
// Copyright © 2017 AppTown. All rights reserved.
//
import Foundation
typealias JSONObject = [String: Any]
protocol JSONSerializable {
init?(json: JSONObject?)
}
extension JSONSerializable {
func toJSONObject() -> JSONObject {
var json = JSONObject()
for case let (label?, value) in Mirror(reflecting: self).children {
switch value {
case let value as JSONSerializable:
json[label] = value.toJSONObject()
case let value as NSObject:
json[label] = value
default:
Logger.print("Error: \(label) is unserializable for value \(value)")
}
}
return json
}
}
extension Array where Element: JSONSerializable {
/**
Initialize an array based on a json dictionary
- parameter jsonArray: The json array
*/
init?(jsonArray: [JSONObject]?) {
self.init()
guard let jsonArray = jsonArray else { return }
for json in jsonArray {
guard let element = Element(json: json) else {
// Fail initializer if an element cannot be serialised.
return nil
}
self += [element]
}
}
func toJSONArray() -> [JSONObject] {
return map { $0.toJSONObject() }
}
}
| bsd-3-clause | e57bfdb9f3aa5941781f57948d56f1d5 | 22.539683 | 84 | 0.548213 | 4.910596 | false | false | false | false |
bingoogolapple/SwiftNote-PartTwo | 画五角星/画五角星/MyRoateView.swift | 1 | 2383 | //
// MyRoateView.swift
// 画五角星
//
// Created by bingoogol on 14/10/9.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
class MyRoateView: UIView {
var points:[CGPoint] = [CGPoint]()
var hasPoint:Bool = false
override func drawRect(rect: CGRect) {
if !hasPoint {
// 计算五个点
println("计算五个点")
hasPoint = true
self.loadPoints()
}
// drawStar(UIGraphicsGetCurrentContext())
drawRandomStar(UIGraphicsGetCurrentContext(),count:20)
}
func loadPoints() {
var angle:CGFloat = 4 * CGFloat(M_PI) / 5
var radius:CGFloat = 100
points.append(CGPointMake(0, -radius))
for i in 1 ... 4 {
var newAngle:Float = Float(angle * CGFloat(i) - CGFloat(M_PI_2))
var x:CGFloat = CGFloat(cosf(newAngle)) * radius
var y:CGFloat = CGFloat(sinf(newAngle)) * radius
points.append(CGPointMake(x, y))
}
}
func drawRandomStar(context:CGContextRef,count:Int) {
for i in 1 ... count {
CGContextSaveGState(context)
var tx = CGFloat(arc4random()) % bounds.width
var ty = CGFloat(arc4random()) % bounds.height
CGContextTranslateCTM(context, tx, ty)
var angle = CGFloat(arc4random()) % 180 * CGFloat(M_PI) / 180
CGContextRotateCTM(context, angle)
var scale = CGFloat(arc4random_uniform(5)) / 10 + 0.3
CGContextScaleCTM(context, scale, scale)
drawStar(context)
CGContextRestoreGState(context)
}
}
func drawStar(context:CGContextRef) {
randomColor().set()
CGContextMoveToPoint(context, points[0].x, points[0].y)
for i in 1 ... 4 {
CGContextAddLineToPoint(context, points[i].x, points[i].y)
}
CGContextClosePath(context)
CGContextDrawPath(context, kCGPathFill)
}
func randomColor() -> UIColor {
/*
r g g 0 ~ 1
*/
var r = CGFloat(arc4random_uniform(255)) / 255
var g = CGFloat(arc4random_uniform(255)) / 255
var b = CGFloat(arc4random_uniform(255)) / 255
return UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
} | apache-2.0 | c52faaa53a0db26d7de625d25e932a7a | 29.179487 | 76 | 0.553336 | 4.179396 | false | false | false | false |
KaushalElsewhere/AllHandsOn | CleanSwiftTry2.3/CleanSwiftTry/AppDelegate.swift | 1 | 837 | //
// AppDelegate.swift
// CleanSwiftTry
//
// Created by Kaushal Elsewhere on 10/05/2017.
// Copyright © 2017 Elsewhere. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow? = UIWindow(frame: UIScreen.mainScreen().bounds)
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
let firstController = CreateOrderViewController()
let navController = UINavigationController(rootViewController: firstController)
//coordinator = AppCoordinator(nav: navController, rootController: firstController)
window?.rootViewController = navController
window?.makeKeyAndVisible()
return true
}
}
| mit | 3f1d5182c3c12af240602553419d19ed | 26.866667 | 128 | 0.704545 | 5.726027 | false | false | false | false |
nifti/CinchKit | CinchKit/Client/CNHSession.swift | 1 | 1764 | //
// CNHSession.swift
// CinchKit
//
// Created by Ryan Fitzgerald on 2/25/15.
// Copyright (c) 2015 cinch. All rights reserved.
//
import Foundation
public enum CNHSessionState {
// initial state indicating that no valid cached token was found
case Created
// state indicating user has logged in or a cached token is available
case Open
// session state indicating that the session was closed, but the users token
// remains cached on the device for later use
case Closed
}
public class CNHSession {
private let keychain = CNHKeychain()
// backing store for token data
private var _accessTokenData : CNHAccessTokenData?
public var accessTokenData : CNHAccessTokenData? {
get {
return _accessTokenData
}
set {
if let data = newValue {
keychain.save(data)
_accessTokenData = data
} else {
keychain.clear()
_accessTokenData = nil
}
}
}
public var sessionState : CNHSessionState {
var result = CNHSessionState.Created
if let tokenData = self.accessTokenData {
let now = NSDate()
if now.compare(tokenData.expires) == .OrderedAscending {
result = .Open
} else {
result = .Closed
}
}
return result
}
public var isOpen : Bool {
return self.sessionState == .Open
}
// close active session
public func close() {
keychain.clear()
_accessTokenData = nil
}
public init() {
_accessTokenData = keychain.load()
}
} | mit | 80093755fdf5df26f0c7471f16220b16 | 22.533333 | 80 | 0.552721 | 4.927374 | false | false | false | false |
batschz/minga-ios | Minga/Minga/StarRatingControl.swift | 1 | 3684 | //
// RatingControl.swift
// Minga
//
// Created by Carmen Probst on 05.06.17.
// Copyright © 2017 MingaApp. All rights reserved.
//
import UIKit
protocol StarRatingControlDelegate: class {
func didSelectRating(_ control: StarRatingControl, rating: Int)
}
class StarRatingControl: UIView {
@IBInspectable
var rating: Int = 0 {
didSet {
guard rating > 0 else {
rating = 0
return
}
guard rating <= maxRating else {
rating = maxRating
return
}
setNeedsLayout()
}
}
@IBInspectable
var maxRating: Int = 5 {
didSet {
setNeedsLayout()
}
}
@IBInspectable
var filledStarImage : UIImage? {
didSet {
setNeedsDisplay()
}
}
@IBInspectable
var emptyStarImage : UIImage? {
didSet {
setNeedsDisplay()
}
}
@IBInspectable
var spacing : Int = 5 {
didSet {
setNeedsDisplay()
}
}
weak var delegate: StarRatingControlDelegate?
fileprivate var ratingButtons = [UIButton]()
fileprivate var buttonSize : Int {
return Int(self.frame.height)
}
fileprivate var width : Int {
return (buttonSize + spacing) * maxRating
}
func initRate() {
if ratingButtons.count == 0 {
for _ in 0 ..< maxRating {
let button = UIButton()
button.setImage(emptyStarImage, for: UIControlState())
button.setImage(filledStarImage, for: .selected)
button.setImage(filledStarImage, for: [.highlighted, .selected])
button.isUserInteractionEnabled = false
button.adjustsImageWhenHighlighted = false
ratingButtons += [button]
addSubview(button)
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.initRate()
var buttonFrame = CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize)
for (index, button) in ratingButtons.enumerated() {
buttonFrame.origin.x = CGFloat(index * (buttonSize + spacing))
button.frame = buttonFrame
}
updateButtonSelectionStates()
}
override var intrinsicContentSize : CGSize {
return CGSize(width: width, height: buttonSize)
}
func updateButtonSelectionStates() {
for (index, button) in ratingButtons.enumerated() {
button.isSelected = index < rating
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
handleStarTouches(touches, withEvent: event)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
handleStarTouches(touches, withEvent: event)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
delegate?.didSelectRating(self, rating: self.rating)
}
func handleStarTouches(_ touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let position = touch.location(in: self)
if position.x > -50 && position.x < CGFloat(width + 50) {
ratingButtonSelected(position)
}
}
}
func ratingButtonSelected(_ position: CGPoint) {
for (index, button) in ratingButtons.enumerated() {
if position.x > button.frame.minX {
self.rating = index + 1
} else if position.x < 0 {
self.rating = 0
}
}
}
}
| mit | 21b65f7df18072e7c7ede73555ad37cc | 24.576389 | 83 | 0.562856 | 4.904128 | false | false | false | false |
emilstahl/swift | test/IRGen/class_bounded_generics.swift | 6 | 13645 | // RUN: %target-swift-frontend -emit-ir -primary-file %s -disable-objc-attr-requires-foundation-module | FileCheck %s
// REQUIRES: CPU=x86_64
// XFAIL: linux
protocol ClassBound : class {
func classBoundMethod()
}
protocol ClassBound2 : class {
func classBoundMethod2()
}
protocol ClassBoundBinary : class, ClassBound {
func classBoundBinaryMethod(x: Self)
}
@objc protocol ObjCClassBound {
func objCClassBoundMethod()
}
@objc protocol ObjCClassBound2 {
func objCClassBoundMethod2()
}
protocol NotClassBound {
func notClassBoundMethod()
func notClassBoundBinaryMethod(x: Self)
}
struct ClassGenericFieldStruct<T:ClassBound> {
var x : Int
var y : T
var z : Int
}
struct ClassProtocolFieldStruct {
var x : Int
var y : ClassBound
var z : Int
}
class ClassGenericFieldClass<T:ClassBound> {
final var x : Int = 0
final var y : T
final var z : Int = 0
init(t: T) {
y = t
}
}
class ClassProtocolFieldClass {
var x : Int = 0
var y : ClassBound
var z : Int = 0
init(classBound cb: ClassBound) {
y = cb
}
}
// CHECK: %C22class_bounded_generics22ClassGenericFieldClass = type <{ %swift.refcounted, %Si, %objc_object*, %Si }>
// CHECK: %V22class_bounded_generics24ClassProtocolFieldStruct = type <{ %Si, %P22class_bounded_generics10ClassBound_, %Si }>
// CHECK: %V22class_bounded_generics23ClassGenericFieldStruct = type <{ %Si, %objc_object*, %Si }>
// CHECK-LABEL: define hidden %objc_object* @_TF22class_bounded_generics23class_bounded_archetype{{.*}}(%objc_object*, %swift.type* %T, i8** %T.ClassBound)
func class_bounded_archetype<T : ClassBound>(x: T) -> T {
return x
}
class SomeClass {}
class SomeSubclass : SomeClass {}
// CHECK-LABEL: define hidden %C22class_bounded_generics9SomeClass* @_TF22class_bounded_generics28superclass_bounded_archetype{{.*}}(%C22class_bounded_generics9SomeClass*, %swift.type* %T)
func superclass_bounded_archetype<T : SomeClass>(x: T) -> T {
return x
}
// CHECK-LABEL: define hidden { %C22class_bounded_generics9SomeClass*, %C22class_bounded_generics12SomeSubclass* } @_TF22class_bounded_generics33superclass_bounded_archetype_call{{.*}}(%C22class_bounded_generics9SomeClass*, %C22class_bounded_generics12SomeSubclass*)
func superclass_bounded_archetype_call(x: SomeClass, y: SomeSubclass) -> (SomeClass, SomeSubclass) {
return (superclass_bounded_archetype(x),
superclass_bounded_archetype(y));
// CHECK: [[SOMECLASS_RESULT:%.*]] = call %C22class_bounded_generics9SomeClass* @_TF22class_bounded_generics28superclass_bounded_archetype{{.*}}(%C22class_bounded_generics9SomeClass* {{%.*}}, {{.*}})
// CHECK: [[SOMESUPERCLASS_IN:%.*]] = bitcast %C22class_bounded_generics12SomeSubclass* {{%.*}} to %C22class_bounded_generics9SomeClass*
// CHECK: [[SOMESUPERCLASS_RESULT:%.*]] = call %C22class_bounded_generics9SomeClass* @_TF22class_bounded_generics28superclass_bounded_archetype{{.*}}(%C22class_bounded_generics9SomeClass* [[SOMESUPERCLASS_IN]], {{.*}})
// CHECK: bitcast %C22class_bounded_generics9SomeClass* [[SOMESUPERCLASS_RESULT]] to %C22class_bounded_generics12SomeSubclass*
}
// CHECK-LABEL: define hidden void @_TF22class_bounded_generics30class_bounded_archetype_method{{.*}}(%objc_object*, %objc_object*, %swift.type* %T, i8** %T.ClassBoundBinary)
func class_bounded_archetype_method<T : ClassBoundBinary>(x: T, y: T) {
x.classBoundMethod()
// CHECK: [[INHERITED:%.*]] = load i8*, i8** %T.ClassBoundBinary, align 8
// CHECK: [[INHERITED_WTBL:%.*]] = bitcast i8* [[INHERITED]] to i8**
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[INHERITED_WTBL]], align 8
// CHECK: [[WITNESS_FUNC:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %swift.type*)
// CHECK: call void [[WITNESS_FUNC]](%objc_object* %0, %swift.type* {{.*}})
x.classBoundBinaryMethod(y)
// CHECK: [[WITNESS_ENTRY:%.*]] = getelementptr inbounds i8*, i8** %T.ClassBoundBinary, i32 1
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ENTRY]], align 8
// CHECK: call void bitcast (void (%swift.refcounted*)* @swift_unknownRetain to void (%objc_object*)*)(%objc_object* [[Y:%.*]])
// CHECK: [[WITNESS_FUNC:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %objc_object*, %swift.type*)
// CHECK: call void [[WITNESS_FUNC]](%objc_object* [[Y]], %objc_object* %0, %swift.type* {{.*}})
}
// CHECK-LABEL: define hidden { %objc_object*, %objc_object* } @_TF22class_bounded_generics29class_bounded_archetype_tuple{{.*}}(%objc_object*, %swift.type* %T, i8** %T.ClassBound)
func class_bounded_archetype_tuple<T : ClassBound>(x: T) -> (T, T) {
return (x, x)
}
class ConcreteClass : ClassBoundBinary, NotClassBound {
func classBoundMethod() {}
func classBoundBinaryMethod(x: ConcreteClass) {}
func notClassBoundMethod() {}
func notClassBoundBinaryMethod(x: ConcreteClass) {}
}
// CHECK-LABEL: define hidden %C22class_bounded_generics13ConcreteClass* @_TF22class_bounded_generics28call_class_bounded_archetype{{.*}}(%C22class_bounded_generics13ConcreteClass*) {{.*}} {
func call_class_bounded_archetype(x: ConcreteClass) -> ConcreteClass {
return class_bounded_archetype(x)
// CHECK: [[IN:%.*]] = bitcast %C22class_bounded_generics13ConcreteClass* {{%.*}} to %objc_object*
// CHECK: [[OUT_ORIG:%.*]] = call %objc_object* @_TF22class_bounded_generics23class_bounded_archetype{{.*}}(%objc_object* [[IN]], {{.*}})
// CHECK: [[OUT:%.*]] = bitcast %objc_object* [[OUT_ORIG]] to %C22class_bounded_generics13ConcreteClass*
// CHECK: ret %C22class_bounded_generics13ConcreteClass* [[OUT]]
}
// CHECK: define hidden void @_TF22class_bounded_generics27not_class_bounded_archetype{{.*}}(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.NotClassBound)
func not_class_bounded_archetype<T : NotClassBound>(x: T) -> T {
return x
}
// CHECK-LABEL: define hidden %objc_object* @_TF22class_bounded_generics44class_bounded_archetype_to_not_class_bounded{{.*}}(%objc_object*, %swift.type* %T, i8** %T.ClassBound, i8** %T.NotClassBound) {{.*}} {
func class_bounded_archetype_to_not_class_bounded
<T:protocol<ClassBound, NotClassBound>>(x:T) -> T {
// CHECK: alloca %objc_object*, align 8
return not_class_bounded_archetype(x)
}
/* TODO Abstraction remapping to non-class-bounded witnesses
func class_and_not_class_bounded_archetype_methods
<T:protocol<ClassBound, NotClassBound>>(x:T, y:T) {
x.classBoundMethod()
x.classBoundBinaryMethod(y)
x.notClassBoundMethod()
x.notClassBoundBinaryMethod(y)
}
*/
// CHECK-LABEL: define hidden { %objc_object*, i8** } @_TF22class_bounded_generics21class_bounded_erasure{{.*}}(%C22class_bounded_generics13ConcreteClass*) {{.*}} {
func class_bounded_erasure(x: ConcreteClass) -> ClassBound {
return x
// CHECK: [[INSTANCE_OPAQUE:%.*]] = bitcast %C22class_bounded_generics13ConcreteClass* [[INSTANCE:%.*]] to %objc_object*
// CHECK: [[T0:%.*]] = insertvalue { %objc_object*, i8** } undef, %objc_object* [[INSTANCE_OPAQUE]], 0
// CHECK: [[T1:%.*]] = insertvalue { %objc_object*, i8** } [[T0]], i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @_TWPC22class_bounded_generics13ConcreteClassS_10ClassBoundS_, i32 0, i32 0), 1
// CHECK: ret { %objc_object*, i8** } [[T1]]
}
// CHECK-LABEL: define hidden void @_TF22class_bounded_generics29class_bounded_protocol_method{{.*}}(%objc_object*, i8**) {{.*}} {
func class_bounded_protocol_method(x: ClassBound) {
x.classBoundMethod()
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_TABLE:%.*]], align 8
// CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %swift.type*)
// CHECK: call void [[WITNESS_FN]](%objc_object* %0, %swift.type* {{.*}})
}
// CHECK-LABEL: define hidden %C22class_bounded_generics13ConcreteClass* @_TF22class_bounded_generics28class_bounded_archetype_cast{{.*}}(%objc_object*, %swift.type* %T, i8** %T.ClassBound)
func class_bounded_archetype_cast<T : ClassBound>(x: T) -> ConcreteClass {
return x as! ConcreteClass
// CHECK: [[IN_PTR:%.*]] = bitcast %objc_object* {{%.*}} to i8*
// CHECK: [[T0:%.*]] = call %swift.type* @_TMaC22class_bounded_generics13ConcreteClass()
// CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to i8*
// CHECK: [[OUT_PTR:%.*]] = call i8* @swift_dynamicCastClassUnconditional(i8* [[IN_PTR]], i8* [[T1]])
// CHECK: [[OUT:%.*]] = bitcast i8* [[OUT_PTR]] to %C22class_bounded_generics13ConcreteClass*
// CHECK: ret %C22class_bounded_generics13ConcreteClass* [[OUT]]
}
// CHECK-LABEL: define hidden %C22class_bounded_generics13ConcreteClass* @_TF22class_bounded_generics27class_bounded_protocol_cast{{.*}}(%objc_object*, i8**)
func class_bounded_protocol_cast(x: ClassBound) -> ConcreteClass {
return x as! ConcreteClass
// CHECK: [[IN_PTR:%.*]] = bitcast %objc_object* {{%.*}} to i8*
// CHECK: [[T0:%.*]] = call %swift.type* @_TMaC22class_bounded_generics13ConcreteClass()
// CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to i8*
// CHECK: [[OUT_PTR:%.*]] = call i8* @swift_dynamicCastClassUnconditional(i8* [[IN_PTR]], i8* [[T1]])
// CHECK: [[OUT:%.*]] = bitcast i8* [[OUT_PTR]] to %C22class_bounded_generics13ConcreteClass*
// CHECK: ret %C22class_bounded_generics13ConcreteClass* [[OUT]]
}
// CHECK-LABEL: define hidden { %objc_object*, i8** } @_TF22class_bounded_generics35class_bounded_protocol_conversion{{.*}}(%objc_object*, i8**, i8**) {{.*}} {
func class_bounded_protocol_conversion_1(x: protocol<ClassBound, ClassBound2>)
-> ClassBound {
return x
}
// CHECK-LABEL: define hidden { %objc_object*, i8** } @_TF22class_bounded_generics35class_bounded_protocol_conversion{{.*}}(%objc_object*, i8**, i8**) {{.*}} {
func class_bounded_protocol_conversion_2(x: protocol<ClassBound, ClassBound2>)
-> ClassBound2 {
return x
}
// CHECK-LABEL: define hidden { %objc_object*, i8** } @_TF22class_bounded_generics40objc_class_bounded_protocol_conversion{{.*}}(%objc_object*, i8**) {{.*}} {
func objc_class_bounded_protocol_conversion_1
(x:protocol<ClassBound, ObjCClassBound>) -> ClassBound {
return x
}
// CHECK-LABEL: define hidden %objc_object* @_TF22class_bounded_generics40objc_class_bounded_protocol_conversion{{.*}}(%objc_object*, i8**) {{.*}} {
func objc_class_bounded_protocol_conversion_2
(x:protocol<ClassBound, ObjCClassBound>) -> ObjCClassBound {
return x
}
// CHECK-LABEL: define hidden %objc_object* @_TF22class_bounded_generics40objc_class_bounded_protocol_conversion{{.*}}(%objc_object*)
func objc_class_bounded_protocol_conversion_3
(x:protocol<ObjCClassBound, ObjCClassBound2>) -> ObjCClassBound {
return x
}
// CHECK-LABEL: define hidden %objc_object* @_TF22class_bounded_generics40objc_class_bounded_protocol_conversion{{.*}}(%objc_object*)
func objc_class_bounded_protocol_conversion_4
(x:protocol<ObjCClassBound, ObjCClassBound2>) -> ObjCClassBound2 {
return x
}
// CHECK-LABEL: define hidden { i64, %objc_object*, i64 } @_TF22class_bounded_generics33class_generic_field_struct_fields{{.*}}(i64, %objc_object*, i64, %swift.type* %T, i8** %T.ClassBound)
func class_generic_field_struct_fields<T : ClassBound>
(x:ClassGenericFieldStruct<T>) -> (Int, T, Int) {
return (x.x, x.y, x.z)
}
// CHECK-LABEL: define hidden void @_TF22class_bounded_generics34class_protocol_field_struct_fields{{.*}}(<{ %Si, %P22class_bounded_generics10ClassBound_, %Si }>* noalias nocapture sret, %V22class_bounded_generics24ClassProtocolFieldStruct* noalias nocapture dereferenceable({{.*}}))
func class_protocol_field_struct_fields
(x:ClassProtocolFieldStruct) -> (Int, ClassBound, Int) {
return (x.x, x.y, x.z)
}
// CHECK-LABEL: define hidden { i64, %objc_object*, i64 } @_TF22class_bounded_generics32class_generic_field_class_fields{{.*}}(%C22class_bounded_generics22ClassGenericFieldClass*)
func class_generic_field_class_fields<T : ClassBound>
(x:ClassGenericFieldClass<T>) -> (Int, T, Int) {
return (x.x, x.y, x.z)
// CHECK: getelementptr inbounds %C22class_bounded_generics22ClassGenericFieldClass, %C22class_bounded_generics22ClassGenericFieldClass* %0, i32 0, i32 1
// CHECK: getelementptr inbounds %C22class_bounded_generics22ClassGenericFieldClass, %C22class_bounded_generics22ClassGenericFieldClass* %0, i32 0, i32 2
// CHECK: getelementptr inbounds %C22class_bounded_generics22ClassGenericFieldClass, %C22class_bounded_generics22ClassGenericFieldClass* %0, i32 0, i32 3
}
// CHECK-LABEL: define hidden void @_TF22class_bounded_generics33class_protocol_field_class_fields{{.*}}(<{ %Si, %P22class_bounded_generics10ClassBound_, %Si }>* noalias nocapture sret, %C22class_bounded_generics23ClassProtocolFieldClass*)
func class_protocol_field_class_fields(x: ClassProtocolFieldClass)
-> (Int, ClassBound, Int) {
return (x.x, x.y, x.z)
// CHECK: = call i64 %{{[0-9]+}}
// CHECK: = call { %objc_object*, i8** } %{{[0-9]+}}
// CHECK: = call i64 %{{[0-9]+}}
}
class SomeSwiftClass {
class func foo() {}
}
// T must have a Swift layout, so we can load this metatype with a direct access.
// CHECK-LABEL: define hidden void @_TF22class_bounded_generics22class_bounded_metatype
// CHECK: [[T0:%.*]] = getelementptr inbounds %C22class_bounded_generics14SomeSwiftClass, %C22class_bounded_generics14SomeSwiftClass* {{%.*}}, i32 0, i32 0, i32 0
// CHECK-NEXT: [[T1:%.*]] = load %swift.type*, %swift.type** [[T0]], align 8
// CHECK-NEXT: [[T2:%.*]] = bitcast %swift.type* [[T1]] to void (%swift.type*)**
// CHECK-NEXT: [[T3:%.*]] = getelementptr inbounds void (%swift.type*)*, void (%swift.type*)** [[T2]], i64 10
// CHECK-NEXT: load void (%swift.type*)*, void (%swift.type*)** [[T3]], align 8
func class_bounded_metatype<T: SomeSwiftClass>(t : T) {
t.dynamicType.foo()
}
class WeakRef<T: AnyObject> {
weak var value: T?
}
| apache-2.0 | 47ea89236ef89a3240495b231683eca7 | 51.080153 | 283 | 0.697838 | 3.403592 | false | false | false | false |
luispadron/GradePoint | GradePoint/Controllers/Onboarding/Onboard3ViewController.swift | 1 | 6431 | //
// Onboard3ViewController.swift
// GradePoint
//
// Created by Luis Padron on 4/8/17.
// Copyright © 2017 Luis Padron. All rights reserved.
//
import UIKit
import RealmSwift
class Onboard3ViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var schoolTypeLabel: UILabel!
@IBOutlet weak var schoolTypeSegmentControl: UISegmentedControl!
@IBOutlet weak var gradingTypeLabel: UILabel!
@IBOutlet weak var gradingTypeSegementControl: UISegmentedControl!
@IBOutlet weak var swipeLabel: UILabel!
/// Reference to the parent controller
weak var pageController: OnboardPageViewController?
/// Determines whether we have previously animated the grading type segment and label, if so, don't animate again
var hasAnimatedGradingType = false
/// Determines whether we have started the animation for the swipe label, if so, dont start it again
var hasStartedSwipeAnimation = false
override func viewDidLoad() {
super.viewDidLoad()
// UI Set up, make all alphas 0, since I suck at animations and alpha animations are easy
titleLabel.alpha = 0.0
schoolTypeLabel.alpha = 0.0
schoolTypeSegmentControl.alpha = 0.0
gradingTypeLabel.alpha = 0.0
gradingTypeSegementControl.alpha = 0.0
swipeLabel.alpha = 0.0
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Animate the views
self.animateViews()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// Customize font size for segmented control
if previousTraitCollection?.horizontalSizeClass != traitCollection.horizontalSizeClass {
switch traitCollection.horizontalSizeClass {
case .compact:
schoolTypeSegmentControl.setTitleTextAttributes([NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue):
UIFont.systemFont(ofSize: 16)], for: .normal)
gradingTypeSegementControl.setTitleTextAttributes([NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue):
UIFont.systemFont(ofSize: 16)], for: .normal)
default:
schoolTypeSegmentControl.setTitleTextAttributes([NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue):
UIFont.systemFont(ofSize: 25)], for: .normal)
gradingTypeSegementControl.setTitleTextAttributes([NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue):
UIFont.systemFont(ofSize: 25)], for: .normal)
}
}
}
func animateViews() {
// First animate the title, school type label and segment control
// When user selects a school type, animate the grading type segment
UIView.animateKeyframes(withDuration: 1.5, delay: 0.0, options: [], animations: {
UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 1/3, animations: {
self.titleLabel.alpha = 1.0
})
UIView.addKeyframe(withRelativeStartTime: 1/3, relativeDuration: 1/3, animations: {
self.schoolTypeLabel.alpha = 1.0
})
UIView.addKeyframe(withRelativeStartTime: 2/3, relativeDuration: 1/3, animations: {
self.schoolTypeSegmentControl.alpha = 1.0
})
}, completion: nil)
}
// MARK: Actions
@IBAction func schoolTypeChanged(_ sender: UISegmentedControl) {
pageController?.dataSource = nil
pageController?.dataSource = pageController!
// If we haven't animated before, then animate the grading type label and control in now
if !hasAnimatedGradingType {
UIView.animateKeyframes(withDuration: 1.0, delay: 0.0, options: [], animations: {
UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 1/2, animations: {
self.gradingTypeLabel.alpha = 1.0
})
UIView.addKeyframe(withRelativeStartTime: 1/2, relativeDuration: 1/2, animations: {
self.gradingTypeSegementControl.alpha = 1.0
})
}, completion: nil)
}
// Update the user defaults key
let defaults = UserDefaults.standard
let type = sender.selectedSegmentIndex == 0 ? StudentType.college : StudentType.highSchool
defaults.set(type.rawValue, forKey: kUserDefaultStudentType)
}
@IBAction func gradingTypeChanged(_ sender: UISegmentedControl) {
pageController?.dataSource = nil
pageController?.dataSource = pageController!
// If we haven't animated the swipe label, do so now
if !hasStartedSwipeAnimation {
self.swipeLabel.alpha = 1.0
UIView.animateKeyframes(withDuration: 1.5, delay: 0.0, options: .repeat, animations: {
UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 1/2, animations: {
self.swipeLabel.alpha = 0.5
})
UIView.addKeyframe(withRelativeStartTime: 1/2, relativeDuration: 1/2, animations: {
self.swipeLabel.alpha = 1.0
})
}, completion: nil)
}
let type = sender.selectedSegmentIndex == 0 ? GPAScaleType.plusScale : GPAScaleType.nonPlusScale
// Create the grading scale and default grading rubric
GPAScale.createScale(with: type)
GradeRubric.createRubric(type: type)
}
// MARK: Helpers
/// Returns whether values are filled and can move on to next ViewController
var isReadyToTransition: Bool {
get {
let schoolReady = self.schoolTypeSegmentControl.selectedSegmentIndex >= 0
let gradeReady = self.gradingTypeSegementControl.selectedSegmentIndex >= 0
return schoolReady && gradeReady
}
}
}
| apache-2.0 | 07a65998d062bc0695d43e154c58cd09 | 42.741497 | 138 | 0.621773 | 5.331675 | false | false | false | false |
avito-tech/Paparazzo | Example/PaparazzoExample/Filters/AutoAdjustmentFilter.swift | 1 | 2092 | import Paparazzo
import ImageSource
import ImageIO
import CoreGraphics
import MobileCoreServices
final class AutoAdjustmentFilter: Filter {
let fallbackMessage: String? = "Failed to apply autocorrection".uppercased()
func apply(_ sourceImage: ImageSource, completion: @escaping ((_ resultImage: ImageSource) -> ())) {
let options = ImageRequestOptions(size: .fullResolution, deliveryMode: .best)
sourceImage.requestImage(options: options) { [weak self] (result: ImageRequestResult<UIImage>) in
guard let image = result.image else {
completion(sourceImage)
return
}
var ciImage = CIImage(image: image)
let adjustments = ciImage?.autoAdjustmentFilters()
adjustments?.forEach { filter in
filter.setValue(ciImage, forKey: kCIInputImageKey)
ciImage = filter.outputImage
}
let context = CIContext(options: nil)
if let output = ciImage, let cgImage = context.createCGImage(output, from: output.extent) {
if let image = self?.imageSource(with: cgImage) {
completion(image)
return
}
}
completion(sourceImage)
}
}
private func imageSource(with cgImage: CGImage) -> ImageSource? {
let path = (NSTemporaryDirectory() as NSString).appendingPathComponent("\(UUID().uuidString).jpg")
let url = URL(fileURLWithPath: path)
let destination = CGImageDestinationCreateWithURL(url as CFURL, kUTTypeJPEG, 1, nil)
if let destination = destination {
CGImageDestinationAddImage(destination, cgImage, nil)
if CGImageDestinationFinalize(destination) {
let imageSource = LocalImageSource(path: path, previewImage: cgImage)
return imageSource
}
}
return nil
}
}
| mit | 5669d3ecfa30a8a7d2b979b4ac086b03 | 35.068966 | 106 | 0.578872 | 6.011494 | false | false | false | false |
wesj/firefox-ios-1 | Storage/SQL/BookmarksSqlite.swift | 1 | 10292 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
class BookmarkTable<T> : GenericTable<BookmarkNode> {
private let favicons = FaviconsTable<Favicon>()
private let joinedFavicons = JoinedFaviconsHistoryTable<(Site, Favicon)>()
override var name: String { return "bookmarks" }
override var version: Int { return 2 }
override var rows: String { return "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"url TEXT, " +
"parent INTEGER, " +
"faviconId INTEGER, " +
"title TEXT" }
override func create(db: SQLiteDBConnection, version: Int) -> Bool {
return super.create(db, version: version) && favicons.create(db, version: version) && joinedFavicons.create(db, version: version)
}
override func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool {
return super.updateTable(db, from: from, to: to) && favicons.updateTable(db, from: from, to: to) && updateTable(db, from: from, to: to)
}
private func setupFavicon(db: SQLiteDBConnection, item: Type?) {
// If this has an icon attached, try to use it
if let favicon = item?.favicon {
if favicon.id == nil {
favicons.insertOrUpdate(db, obj: favicon)
}
} else {
// Otherwise, lets go look one up for this URL
if let bookmark = item as? BookmarkItem {
let options = QueryOptions(filter: bookmark.url, filterType: FilterType.ExactUrl)
let favicons = joinedFavicons.query(db, options: options)
if favicons.count > 0 {
if let (site, favicon) = favicons[0] as? (Site, Favicon) {
bookmark.favicon = favicon
}
}
}
}
}
override func insert(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int {
setupFavicon(db, item: item)
return super.insert(db, item: item, err: &err)
}
override func update(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int {
setupFavicon(db, item: item)
return super.update(db, item: item, err: &err)
}
override func getInsertAndArgs(inout item: BookmarkNode) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
args.append(item.guid)
if let bookmark = item as? BookmarkItem {
args.append(bookmark.url)
} else {
args.append(nil)
}
args.append(item.title)
args.append(item.favicon?.id)
return ("INSERT INTO \(name) (guid, url, title, faviconId) VALUES (?,?,?,?)", args)
}
override func getUpdateAndArgs(inout item: BookmarkNode) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
if let bookmark = item as? BookmarkItem {
args.append(bookmark.url)
} else {
args.append(nil)
}
args.append(item.title)
args.append(item.favicon?.id)
args.append(item.guid)
return ("UPDATE \(name) SET url = ?, title = ?, faviconId = ? WHERE guid = ?", args)
}
override func getDeleteAndArgs(inout item: BookmarkNode?) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
if let bookmark = item as? BookmarkItem {
if bookmark.guid != "" {
// If there's a guid, we'll delete entries with it
args.append(bookmark.guid)
return ("DELETE FROM \(name) WHERE guid = ?", args)
} else if bookmark.url != "" {
// If there's a url, we'll delete ALL entries with it
args.append(bookmark.url)
return ("DELETE FROM \(name) WHERE url = ?", args)
} else {
// If you passed us something with no url or guid, we'll just have to bail...
return nil
}
}
return ("DELETE FROM \(name)", args)
}
override var factory: ((row: SDRow) -> BookmarkNode)? {
return { row -> BookmarkNode in
let bookmark = BookmarkItem(guid: row["guid"] as String,
title: row["title"] as String,
url: row["bookmarkUrl"] as String)
bookmark.id = row["bookmarkId"] as? Int
if let faviconUrl = row["faviconUrl"] as? String {
let favicon = Favicon(url: faviconUrl,
date: NSDate(timeIntervalSince1970: row["faviconDate"] as Double),
type: IconType(rawValue: row["faviconType"] as Int)!)
bookmark.favicon = favicon
}
return bookmark
}
}
override func getQueryAndArgs(options: QueryOptions?) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
// XXX - This should support querying for a particular bookmark, querying by name/url, and querying
// for everything in a folder. Right now it doesn't do any of that :(
var sql = "SELECT \(name).id as bookmarkId, guid, \(name).url as bookmarkUrl, title, \(favicons.name).url as faviconUrl, date as faviconDate, type as faviconType FROM \(name)" +
" LEFT OUTER JOIN \(favicons.name) ON \(favicons.name).id = \(name).faviconId"
if let filter: AnyObject = options?.filter {
if let type = options?.filterType {
switch(type) {
case .ExactUrl:
args.append(filter)
return ("\(sql) WHERE bookmarkUrl = ?", args)
default:
break
}
}
// Default to search by guid (i.e. for a folder)
args.append(filter)
return ("\(sql) WHERE guid = ?", args)
}
return (sql, args)
}
}
class SqliteBookmarkFolder: BookmarkFolder {
private let cursor: Cursor
override var count: Int {
return cursor.count
}
override subscript(index: Int) -> BookmarkNode {
let bookmark = cursor[index]
if let item = bookmark as? BookmarkItem {
return item
}
return bookmark as SqliteBookmarkFolder
}
init(guid: String, title: String, children: Cursor) {
self.cursor = children
super.init(guid: guid, title: title)
}
}
public class BookmarksSqliteFactory : BookmarksModelFactory, ShareToDestination {
let db: BrowserDB
let table = BookmarkTable<BookmarkNode>()
public init(files: FileAccessor) {
db = BrowserDB(files: files)!
db.createOrUpdate(table)
}
private func getChildren(guid: String) -> Cursor {
var err: NSError? = nil
return db.query(&err, callback: { (connection, err) -> Cursor in
return self.table.query(connection, options: QueryOptions(filter: guid))
})
}
public func modelForFolder(folder: BookmarkFolder, success: (BookmarksModel) -> (), failure: (Any) -> ()) {
let children = getChildren(folder.guid)
if children.status == .Failure {
failure(children.statusMessage)
return
}
let f = SqliteBookmarkFolder(guid: folder.guid, title: folder.title, children: children)
success(BookmarksModel(modelFactory: self, root: f))
}
public func modelForFolder(guid: String, success: (BookmarksModel) -> (), failure: (Any) -> ()) {
var err: NSError? = nil
let children = db.query(&err, callback: { (connection, err) -> Cursor in
return self.table.query(connection, options: QueryOptions(filter: guid))
})
let folder = SqliteBookmarkFolder(guid: guid, title: "", children: children)
success(BookmarksModel(modelFactory: self, root: folder))
}
public func modelForRoot(success: (BookmarksModel) -> (), failure: (Any) -> ()) {
var err: NSError? = nil
let children = db.query(&err, callback: { (connection, err) -> Cursor in
return self.table.query(connection, options: QueryOptions(filter: nil))
})
let folder = SqliteBookmarkFolder(guid: BookmarkRoots.PLACES_FOLDER_GUID, title: "Root", children: children)
success(BookmarksModel(modelFactory: self, root: folder))
}
public var nullModel: BookmarksModel {
let children = Cursor(status: .Failure, msg: "Null model")
let folder = SqliteBookmarkFolder(guid: "Null", title: "Null", children: children)
return BookmarksModel(modelFactory: self, root: folder)
}
public func shareItem(item: ShareItem) {
var err: NSError? = nil
let inserted = db.insert(&err, callback: { (connection, err) -> Int in
var bookmark = BookmarkItem(guid: Bytes.generateGUID(), title: item.title ?? "", url: item.url)
bookmark.favicon = item.favicon
return self.table.insert(connection, item: bookmark, err: &err)
})
}
public func findForUrl(url: String, success: (Cursor) -> (), failure: (Any) -> ()) {
var err: NSError? = nil
let children = db.query(&err, callback: { (connection, err) -> Cursor in
let opts = QueryOptions(filter: url, filterType: FilterType.ExactUrl, sort: QuerySort.None)
return self.table.query(connection, options: opts)
})
if children.status == .Failure {
failure(children.statusMessage)
return
}
return success(children)
}
public func isBookmarked(url: String, success: (Bool) -> (), failure: (Any) -> ()) {
findForUrl(url, success: { children in
success(children.count > 0)
}, failure: failure)
}
public func remove(bookmark: BookmarkNode, success: (Bool) -> (), failure: (Any) -> ()) {
var err: NSError? = nil
let numDeleted = self.db.delete(&err) { (connection, err) -> Int in
return self.table.delete(connection, item: bookmark, err: &err)
}
if let err = err {
failure(err)
return
}
success(numDeleted > 0)
}
}
| mpl-2.0 | a8f0c7ed3248f5c04fc480d0e8028e7e | 37.837736 | 185 | 0.580839 | 4.402053 | false | false | false | false |
gobetti/Swift | MasterDetailiPad/MasterDetailiPad/AppDelegate.swift | 1 | 3366 | //
// AppDelegate.swift
// MasterDetailiPad
//
// Created by Carlos Butron on 07/12/14.
// Copyright (c) 2014 Carlos Butron.
//
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
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 | d2a6ac72c782e8f111cdfb76aefb972f | 54.180328 | 285 | 0.755199 | 6.279851 | false | false | false | false |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/WordStyle.swift | 1 | 1215 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/** WordStyle. */
public struct WordStyle: Codable {
public var level: Int?
public var names: [String]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case level = "level"
case names = "names"
}
/**
Initialize a `WordStyle` with member variables.
- parameter level:
- parameter names:
- returns: An initialized `WordStyle`.
*/
public init(level: Int? = nil, names: [String]? = nil) {
self.level = level
self.names = names
}
}
| mit | e35587aef572e09693790303ced5e4f0 | 26 | 82 | 0.672428 | 4.204152 | false | false | false | false |
evering7/iSpeak8 | Pods/FeedKit/Sources/FeedKit/Models/Namespaces/Media/MediaStatistics.swift | 2 | 2773 | //
// MediaStatistics.swift
//
// Copyright (c) 2017 Nuno Manuel Dias
//
// 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
/// This element specifies various statistics about a media object like the
/// view count and the favorite count. Valid attributes are views and favorites.
public class MediaStatistics {
/// The element's attributes.
public class Attributes {
/// The number of views.
public var views: Int?
/// The number fo favorites.
public var favorites: Int?
}
/// The element's attributes.
public var attributes: Attributes?
}
// MARK: - Initializers
extension MediaStatistics {
convenience init(attributes attributeDict: [String : String]) {
self.init()
self.attributes = MediaStatistics.Attributes(attributes: attributeDict)
}
}
extension MediaStatistics.Attributes {
convenience init?(attributes attributeDict: [String : String]) {
if attributeDict.isEmpty {
return nil
}
self.init()
self.views = Int(attributeDict["views"] ?? "")
self.favorites = Int(attributeDict["favorites"] ?? "")
}
}
// MARK: - Equatable
extension MediaStatistics: Equatable {
public static func ==(lhs: MediaStatistics, rhs: MediaStatistics) -> Bool {
return lhs.attributes == rhs.attributes
}
}
extension MediaStatistics.Attributes: Equatable {
public static func ==(lhs: MediaStatistics.Attributes, rhs: MediaStatistics.Attributes) -> Bool {
return
lhs.views == rhs.views &&
lhs.favorites == rhs.favorites
}
}
| mit | b6507244ad9a5937fdd84e8a644d81b0 | 28.5 | 101 | 0.669311 | 4.715986 | false | false | false | false |
honishi/Hakumai | Hakumai/Controllers/MainWindowController/MainViewController.swift | 1 | 58349 | //
// MainViewController.swift
// Hakumai
//
// Created by Hiroyuki Onishi on 11/9/14.
// Copyright (c) 2014 Hiroyuki Onishi. All rights reserved.
//
import Foundation
import AppKit
import Charts
import Kingfisher
import SnapKit
private let userWindowDefaultTopLeftPoint = NSPoint(x: 100, y: 100)
private let calculateActiveUserInterval: TimeInterval = 5
private let maximumFontSizeForNonMainColumn: CGFloat = 16
private let defaultMinimumRowHeight: CGFloat = 17
private let enableDebugButtons = false
private let defaultElapsedTimeValue = "--:--:--"
private let defaultLabelValue = "---"
private let defaultChartText = "-----"
private let defaultRankDateText = "--:--"
// swiftlint:disable file_length
protocol MainViewControllerDelegate: AnyObject {
func mainViewControllerDidPrepareLive(_ mainViewController: MainViewController, title: String, community: String)
func mainViewControllerDidDisconnect(_ mainViewController: MainViewController)
func mainViewControllerSpeechEnabledChanged(_ mainViewController: MainViewController, isEnabled: Bool)
func mainViewControllerDidDetectStoreComment(_ mainViewController: MainViewController)
func mainViewControllerDidDetectKusaComment(_ mainViewController: MainViewController)
func mainViewControllerDidReceiveGift(_ mainViewController: MainViewController)
}
final class MainViewController: NSViewController {
// MARK: Types
enum ConnectionStatus { case disconnected, connecting, connected }
// MARK: Properties
weak var delegate: MainViewControllerDelegate?
// MARK: Main Outlets
@IBOutlet private weak var grabUrlButton: NSButton!
@IBOutlet private weak var liveUrlTextField: NSTextField!
@IBOutlet private weak var debugReconnectButton: NSButton!
@IBOutlet private weak var debugExpireTokenButton: NSButton!
@IBOutlet private weak var connectButton: NSButton!
@IBOutlet private weak var liveThumbnailImageView: LiveThumbnailImageView!
@IBOutlet private weak var liveTitleLabel: NSTextField!
@IBOutlet private weak var communityTitleLabel: NSTextField!
@IBOutlet private weak var visitorsIconImageView: NSImageView!
@IBOutlet private weak var visitorsValueLabel: NSTextField!
@IBOutlet private weak var commentsIconImageView: NSImageView!
@IBOutlet private weak var commentsValueLabel: NSTextField!
@IBOutlet private weak var adPointsIconImageView: NSImageView!
@IBOutlet private weak var adPointsValueLabel: NSTextField!
@IBOutlet private weak var giftPointsIconImageView: NSImageView!
@IBOutlet private weak var giftPointsLabel: NSTextField!
@IBOutlet private weak var autoUrlButton: NSButton!
@IBOutlet private weak var speakButton: NSButton!
@IBOutlet private weak var liveTitleButton: PointingHandButton!
@IBOutlet private weak var communityTitleButton: PointingHandButton!
@IBOutlet private weak var adPointsButton: PointingHandButton!
@IBOutlet private weak var giftButton: PointingHandButton!
@IBOutlet private weak var scrollView: ButtonScrollView!
@IBOutlet private(set) weak var tableView: ClickTableView!
@IBOutlet private weak var commentTextField: NSTextField!
@IBOutlet private weak var commentAnonymouslyButton: NSButton!
@IBOutlet private weak var elapsedTimeIconImageView: NSImageView!
@IBOutlet private weak var elapsedTimeValueLabel: NSTextField!
@IBOutlet private weak var activeUserIconImageView: NSImageView!
@IBOutlet private weak var activeUserValueLabel: NSTextField!
@IBOutlet private weak var maxActiveUserValueLabel: NSTextField!
@IBOutlet private weak var activeUserChartView: LineChartView!
@IBOutlet private weak var rankingIconImageView: NSImageView!
@IBOutlet private weak var rankingValueLabel: NSTextField!
@IBOutlet private weak var rankingDateLabel: NSTextField!
@IBOutlet private weak var progressIndicator: NSProgressIndicator!
// MARK: Menu Delegate
// swiftlint:disable weak_delegate
@IBOutlet var menuDelegate: MenuDelegate!
// swiftlint:enable weak_delegate
// MARK: General Properties
private let nicoManager: NicoManagerType = NicoManager()
private let messageContainer = MessageContainer()
private let speechManager = SpeechManager()
private let liveThumbnailManager: LiveThumbnailManagerType = LiveThumbnailManager()
private let rankingManager: RankingManagerType = RankingManager.shared
private let notificationPresenter: NotificationPresenterProtocol = NotificationPresenter.default
private let kusaCommentDetector: KusaCommentDetectorType = KusaCommentDetector()
private let storeCommentDetector: StoreCommentDetectorType = StoreCommentDetector()
private(set) var live: Live?
private(set) var connectedToLive = false
private var liveStartedDate: Date?
// row-height cache
private var rowHeightCache = [Int: CGFloat]()
private var minimumRowHeight: CGFloat = defaultMinimumRowHeight
private var tableViewFontSize: CGFloat = CGFloat(kDefaultFontSize)
private var commentHistory = [String]()
private var commentHistoryIndex: Int = 0
private var elapsedTimeTimer: Timer?
private var activeUserTimer: Timer?
private var rankingTimer: Timer?
private var activeUserCount = 0
private var maxActiveUserCount = 0
private var activeUserHistory: [(Date, Int)] = []
private var cellViewFlashed: [String: Bool] = [:]
private var speechNameEnabled = false
private var speechGiftEnabled = false
private var speechAdEnabled = false
// AuthWindowController
private lazy var authWindowController: AuthWindowController = {
AuthWindowController.make(delegate: self)
}()
// UserWindowControllers
private var userWindowControllers = [UserWindowController]()
private var nextUserWindowTopLeftPoint: NSPoint = NSPoint.zero
deinit { log.debug("deinit") }
}
// MARK: - NSViewController Functions
extension MainViewController {
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureViews()
configureManagers()
configureMute()
configureFontSize()
configureAnonymouslyButton()
configureSpeech()
configureEmotionMessage()
configureDebugMessage()
DispatchQueue.main.async { self.focusLiveTextField() }
}
}
// MARK: - NSTableViewDataSource Functions
extension MainViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
messageContainer.count()
}
}
// MARK: - NSTableViewDelegate Functions
extension MainViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
let message = messageContainer[row]
if let cached = rowHeightCache[message.messageNo] {
return cached
}
guard let commentTableColumn = tableView.tableColumn(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: kCommentColumnIdentifier)) else { return 0 }
let rowHeight = calculateRowHeight(forMessage: message, width: commentTableColumn.width)
rowHeightCache[message.messageNo] = rowHeight
return rowHeight
}
private func calculateRowHeight(forMessage message: Message, width: CGFloat) -> CGFloat {
let iconHeight: CGFloat = {
switch message.content {
case .system, .debug:
return 0
case .chat(let chat):
return chat.hasUserIcon ? iconColumnWidth : 0
}
}()
let (content, attributes) = contentAndAttributes(forMessage: message)
let commentHeight = CommentTableCellView.calculateHeight(
text: content,
attributes: attributes,
hasGiftImage: message.isGift,
columnWidth: width
)
return [
iconHeight,
commentHeight,
minimumRowHeight
].max() ?? minimumRowHeight
}
private var iconColumnWidth: CGFloat {
let iconColumnId = NSUserInterfaceItemIdentifier(kIconColumnIdentifier)
return tableView.tableColumn(withIdentifier: iconColumnId)?.width ?? 0
}
private func calculateMinimumRowHeight(fontSize: CGFloat) -> CGFloat {
let placeholderContent = "." as NSString
let placeholderAttributes = UIHelper.commentAttributes(fontSize: fontSize)
let rect = placeholderContent.boundingRect(
with: CGSize(width: 1, height: 0),
options: .usesLineFragmentOrigin,
attributes: placeholderAttributes)
return rect.size.height
}
func tableViewColumnDidResize(_ aNotification: Notification) {
guard let column = (aNotification as NSNotification).userInfo?["NSTableColumn"] as? NSTableColumn else {
return
}
switch column.identifier.rawValue {
case kIconColumnIdentifier, kCommentColumnIdentifier:
rowHeightCache.removeAll(keepingCapacity: false)
tableView.reloadData()
default:
break
}
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
var view: NSTableCellView?
if let identifier = tableColumn?.identifier {
view = tableView.makeView(withIdentifier: identifier, owner: self) as? NSTableCellView
view?.textField?.stringValue = ""
}
let message = messageContainer[row]
guard let _view = view, let tableColumn = tableColumn else { return nil }
resetColorizeAndFlash(view: _view)
switch message.content {
case .system, .debug:
// No colorization and flash here.
configure(view: _view, forSystemAndDebug: message, withTableColumn: tableColumn)
case .chat:
configure(view: _view, forChat: message, withTableColumn: tableColumn)
colorizeOrFlashIfNeeded(view: _view, message: message, tableColumn: tableColumn)
}
return view
}
private func configure(view: NSTableCellView, forSystemAndDebug message: Message, withTableColumn tableColumn: NSTableColumn) {
switch tableColumn.identifier.rawValue {
case kRoomPositionColumnIdentifier:
let roomPositionView = view as? RoomPositionTableCellView
roomPositionView?.configure(message: message)
roomPositionView?.fontSize = nil
case kTimeColumnIdentifier:
let timeView = view as? TimeTableCellView
timeView?.configure(live: nil, message: message)
timeView?.fontSize = min(tableViewFontSize, maximumFontSizeForNonMainColumn)
case kIconColumnIdentifier:
let iconView = view as? IconTableCellView
iconView?.configure(iconType: .none)
case kCommentColumnIdentifier:
let commentView = view as? CommentTableCellView
let (content, attributes) = contentAndAttributes(forMessage: message)
let attributed = NSAttributedString(string: content, attributes: attributes)
commentView?.configure(attributedString: attributed)
case kUserIdColumnIdentifier:
let userIdView = view as? UserIdTableCellView
userIdView?.configure(info: nil)
userIdView?.fontSize = nil
case kPremiumColumnIdentifier:
let premiumView = view as? PremiumTableCellView
premiumView?.configure(premium: nil)
premiumView?.fontSize = nil
default:
break
}
}
private func configure(view: NSTableCellView, forChat message: Message, withTableColumn tableColumn: NSTableColumn) {
guard let live = live, case let .chat(chat) = message.content else { return }
switch tableColumn.identifier.rawValue {
case kRoomPositionColumnIdentifier:
let roomPositionView = view as? RoomPositionTableCellView
roomPositionView?.configure(message: message)
roomPositionView?.fontSize = min(tableViewFontSize, maximumFontSizeForNonMainColumn)
case kTimeColumnIdentifier:
let timeView = view as? TimeTableCellView
timeView?.configure(live: live, message: message)
timeView?.fontSize = min(tableViewFontSize, maximumFontSizeForNonMainColumn)
case kIconColumnIdentifier:
let iconView = view as? IconTableCellView
let iconType = { () -> IconType in
if chat.isSystem { return .none }
let iconUrl = nicoManager.userIconUrl(for: chat.userId)
return .user(iconUrl)
}()
iconView?.configure(iconType: iconType)
case kCommentColumnIdentifier:
let commentView = view as? CommentTableCellView
let (content, attributes) = contentAndAttributes(forMessage: message)
let attributed = NSAttributedString(string: content as String, attributes: attributes)
commentView?.configure(
attributedString: attributed,
giftImageUrl: message.giftImageUrl
)
case kUserIdColumnIdentifier:
let userIdView = view as? UserIdTableCellView
let handleName = HandleNameManager.shared.handleName(for: chat.userId, in: live.communityId)
userIdView?.configure(info: (
nicoManager: nicoManager,
handleName: handleName,
userId: chat.userId,
premium: chat.premium,
comment: chat.comment
))
userIdView?.fontSize = tableViewFontSize
case kPremiumColumnIdentifier:
let premiumView = view as? PremiumTableCellView
premiumView?.configure(premium: chat.premium)
premiumView?.fontSize = min(tableViewFontSize, maximumFontSizeForNonMainColumn)
default:
break
}
}
private func resetColorizeAndFlash(view: NSTableCellView) {
view.setBackgroundColor(nil)
view.cancelFlash()
}
private func colorizeOrFlashIfNeeded(view: NSTableCellView, message: Message, tableColumn: NSTableColumn) {
guard let live = live, case let .chat(chat) = message.content else { return }
let bgColor = HandleNameManager.shared.color(for: chat.userId, in: live.communityId)
view.setBackgroundColor(bgColor)
let messageNo = message.messageNo
let tableColumnId = tableColumn.identifier.rawValue
guard !isCellViewFlashed(messageNo: messageNo, tableColumnIdentifier: tableColumnId) else { return }
let flashColor: NSColor?
switch chat.slashCommand {
case .some(let slashCommand):
switch slashCommand {
case .gift:
flashColor = UIHelper.cellViewGiftFlashColor()
case .nicoad:
flashColor = UIHelper.cellViewAdFlashColor()
case .cruise, .emotion, .info, .quote, .spi, .vote, .unknown:
flashColor = nil
}
case .none:
flashColor = nil
}
if let flashColor = flashColor {
view.flash(flashColor, duration: 1.5)
setCellViewFlashedStatus(messageNo: messageNo, tableColumnIdentifier: tableColumnId, flashed: true)
}
}
// MARK: Utility
private func contentAndAttributes(forMessage message: Message) -> (String, [NSAttributedString.Key: Any]) {
let content: String
let attributes: [NSAttributedString.Key: Any]
switch message.content {
case .system(let system):
content = system.message
attributes = UIHelper.commentAttributes(fontSize: tableViewFontSize)
case .chat(let chat):
content = chat.comment
attributes = UIHelper.commentAttributes(
fontSize: tableViewFontSize,
isBold: chat.isFirst,
isRed: chat.isCasterComment)
case .debug(let debug):
content = debug.message
attributes = UIHelper.commentAttributes(fontSize: tableViewFontSize)
}
return (content, attributes)
}
}
private extension MainViewController {
func resetCellViewFlashedStatus() {
cellViewFlashed = [:]
}
func setCellViewFlashedStatus(messageNo: Int, tableColumnIdentifier: String, flashed: Bool) {
let key = _cellViewFlashedKey(messageNo, tableColumnIdentifier)
cellViewFlashed[key] = flashed
}
func isCellViewFlashed(messageNo: Int, tableColumnIdentifier: String) -> Bool {
let key = _cellViewFlashedKey(messageNo, tableColumnIdentifier)
return cellViewFlashed[key] == true
}
func _cellViewFlashedKey(_ messageNo: Int, _ tableColumnIdentifier: String) -> String {
return "\(messageNo):\(tableColumnIdentifier)"
}
}
// MARK: - NSControlTextEditingDelegate Functions
extension MainViewController: NSControlTextEditingDelegate {
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
let isMovedUp = commandSelector == #selector(NSResponder.moveUp(_:))
let isMovedDown = commandSelector == #selector(NSResponder.moveDown(_:))
if isMovedUp || isMovedDown {
if commentHistory.count == 0 {
// nop
} else {
handleCommentTextFieldKeyUpDown(isMovedUp: isMovedUp, isMovedDown: isMovedDown)
}
return true
}
return false
}
private func handleCommentTextFieldKeyUpDown(isMovedUp: Bool, isMovedDown: Bool) {
if isMovedUp && 0 <= commentHistoryIndex {
commentHistoryIndex -= 1
} else if isMovedDown && commentHistoryIndex <= (commentHistory.count - 1) {
commentHistoryIndex += 1
}
let inValidHistoryRange = (0 <= commentHistoryIndex && commentHistoryIndex <= (commentHistory.count - 1))
commentTextField.stringValue = (inValidHistoryRange ? commentHistory[commentHistoryIndex] : "")
// selectText() should be called in next run loop, http://stackoverflow.com/a/2196751
DispatchQueue.main.asyncAfter(deadline: .now()) {
self.commentTextField.selectText(self)
}
}
}
// MARK: - AuthWindowControllerDelegate Functions
extension MainViewController: AuthWindowControllerDelegate {
func authWindowControllerDidLogin(_ authWindowController: AuthWindowController) {
logSystemMessageToTable(L10n.loginCompleted)
}
}
// MARK: - NicoManagerDelegate Functions
extension MainViewController: NicoManagerDelegate {
func nicoManagerNeedsToken(_ nicoManager: NicoManagerType) {
showAuthWindowController()
}
func nicoManagerDidConfirmTokenExistence(_ nicoManager: NicoManagerType) {
// nop
}
func nicoManagerWillPrepareLive(_ nicoManager: NicoManagerType) {
updateMainControlViews(status: .connecting)
}
func nicoManagerDidPrepareLive(_ nicoManager: NicoManagerType, user: User, live: Live, connectContext: NicoConnectContext) {
self.live = live
delegate?.mainViewControllerDidPrepareLive(
self,
title: live.title,
community: live.community.title)
updateCommunityViews(for: live)
if live.isTimeShift {
liveThumbnailManager.start(for: live.liveProgramId, delegate: self)
resetCellViewFlashedStatus()
resetElapsedLabel()
resetActiveUser()
updateRankingLabel(rank: nil, date: nil)
logSystemMessageToTable(L10n.preparedLive(user.nickname))
return
}
startElapsedTimeAndActiveUserTimer()
switch connectContext {
case .normal:
liveThumbnailManager.start(for: live.liveProgramId, delegate: self)
kusaCommentDetector.start(delegate: self)
resetCellViewFlashedStatus()
resetActiveUser()
rankingManager.addDelegate(self, for: live.liveProgramId)
logSystemMessageToTable(L10n.preparedLive(user.nickname))
focusCommentTextField()
case .reconnect:
break
}
logDebugRankingManagerStatus()
}
func nicoManagerDidFailToPrepareLive(_ nicoManager: NicoManagerType, error: NicoError) {
logSystemMessageToTable(L10n.failedToPrepareLive(error.toMessage))
updateMainControlViews(status: .disconnected)
liveThumbnailManager.stop()
kusaCommentDetector.stop()
rankingManager.removeDelegate(self)
logDebugRankingManagerStatus()
}
func nicoManagerDidConnectToLive(_ nicoManager: NicoManagerType, roomPosition: RoomPosition, connectContext: NicoConnectContext) {
guard connectedToLive == false else { return }
connectedToLive = true
switch connectContext {
case .normal:
liveStartedDate = Date()
logSystemMessageToTable(L10n.connectedToLive)
showLiveOpenedNotification()
case .reconnect(let reason):
switch reason {
case .normal:
logSystemMessageToTable(L10n.reconnected)
case .noPong, .noTexts:
break
}
}
updateMainControlViews(status: .connected)
updateSpeechManagerState()
}
func nicoManagerDidReceiveChat(_ nicoManager: NicoManagerType, chat: Chat) {
// log.debug("\(chat.mail),\(chat.comment)")
guard let live = live else { return }
HandleNameManager.shared.extractAndUpdateHandleName(
from: chat.comment, for: chat.userId, in: live.communityId)
appendToTable(chat: chat)
for userWindowController in userWindowControllers where chat.userId == userWindowController.userId {
DispatchQueue.main.async {
userWindowController.reloadMessages()
}
}
if storeCommentDetector.isStoreComment(chat: chat) {
delegate?.mainViewControllerDidDetectStoreComment(self)
}
kusaCommentDetector.add(chat: chat)
if chat.isGift {
delegate?.mainViewControllerDidReceiveGift(self)
}
}
func nicoManagerWillReconnectToLive(_ nicoManager: NicoManagerType, reason: NicoReconnectReason) {
switch reason {
case .normal:
// logSystemMessageToTableView(L10n.reconnecting)
break
case .noPong, .noTexts:
break
}
logDebugReconnectReason(reason)
}
func nicoManagerReceivingTimeShiftChats(_ nicoManager: NicoManagerType, requestCount: Int, totalChatCount: Int) {
let shouldLog = requestCount % 5 == 0
guard shouldLog else { return }
logSystemMessageToTable(L10n.receivingComments(totalChatCount))
}
func nicoManagerDidReceiveTimeShiftChats(_ nicoManager: NicoManagerType, chats: [Chat]) {
logSystemMessageToTable(L10n.receivedComments(chats.count))
guard let live = live else { return }
chats.forEach {
HandleNameManager.shared.extractAndUpdateHandleName(
from: $0.comment, for: $0.userId, in: live.communityId)
}
bulkAppendToTable(chats: chats)
}
func nicoManagerDidDisconnect(_ nicoManager: NicoManagerType, disconnectContext: NicoDisconnectContext) {
switch disconnectContext {
case .normal:
logSystemMessageToTable(L10n.liveClosed)
showLiveClosedNotification()
case .reconnect(let reason):
switch reason {
case .normal:
logSystemMessageToTable(L10n.liveClosed)
case .noPong, .noTexts:
break
}
}
stopElapsedTimeAndActiveUserTimer()
connectedToLive = false
updateSpeechManagerState()
switch disconnectContext {
case .normal:
updateMainControlViews(status: .disconnected)
liveThumbnailManager.stop()
kusaCommentDetector.stop()
rankingManager.removeDelegate(self)
case .reconnect:
updateMainControlViews(status: .connecting)
}
logDebugRankingManagerStatus()
delegate?.mainViewControllerDidDisconnect(self)
}
func nicoManagerDidReceiveStatistics(_ nicoManager: NicoManagerType, stat: LiveStatistics) {
updateLiveStatistics(stat: stat)
}
func nicoManager(_ nicoManager: NicoManagerType, hasDebugMessgae message: String) {
logDebugMessageToTable(message)
}
}
extension MainViewController: LiveThumbnailManagerDelegate {
func liveThumbnailManager(_ liveThumbnailManager: LiveThumbnailManagerType, didGetThumbnailUrl thumbnailUrl: URL, forLiveProgramId liveProgramId: String) {
log.debug(thumbnailUrl)
liveThumbnailImageView.kf.setImage(
with: thumbnailUrl,
placeholder: liveThumbnailImageView.image
)
}
}
extension MainViewController: KusaCommentDetectorDelegate {
func kusaCommentDetectorDidDetectKusa(_ kusaCommentDetector: KusaCommentDetectorType) {
delegate?.mainViewControllerDidDetectKusaComment(self)
}
func kusaCommentDetector(_ kusaCommentDetector: KusaCommentDetectorType, hasDebugMessage message: String) {
logDebugMessageToTable(message)
}
}
extension MainViewController: RankingManagerDelegate {
func rankingManager(_ rankingManager: RankingManagerType, didUpdateRank rank: Int?, for liveId: String, at date: Date?) {
updateRankingLabel(rank: rank, date: date)
}
func rankingManager(_ rankingManager: RankingManagerType, hasDebugMessage message: String) {
logDebugMessageToTable(message)
}
}
// MARK: - UserWindowControllerDelegate Functions
extension MainViewController: UserWindowControllerDelegate {
func userWindowControllerWillClose(_ userWindowController: UserWindowController) {
log.debug("")
if let index = userWindowControllers.firstIndex(of: userWindowController) {
userWindowControllers.remove(at: index)
}
}
}
// MARK: - Public Functions
extension MainViewController {
func login() {
showAuthWindowController()
// login message will be displayed from `authWindowControllerDidLogin()` delegate method.
}
func logout() {
if connectedToLive {
nicoManager.disconnect()
}
nicoManager.logout()
authWindowController.logout()
logSystemMessageToTable(L10n.logoutCompleted)
}
var hasNeverBeenConnected: Bool { live == nil }
var commentInputInProgress: Bool { !commentTextField.stringValue.isEmpty }
var liveProgramIdInUrlTextField: String? {
liveUrlTextField.stringValue.extractLiveProgramId()
}
func connectToUrl(_ url: URL) {
liveUrlTextField.stringValue = url.absoluteString
connectLive(self)
}
func showHandleNameAddViewController(live: Live, chat: ChatMessage) {
let vc = StoryboardScene.MainWindowController.handleNameAddViewController.instantiate()
vc.handleName = (defaultHandleName(live: live, chat: chat) ?? "") as NSString
vc.completion = { [weak self, weak vc] (cancelled, handleName) in
guard let me = self, let vc = vc else { return }
if !cancelled, let handleName = handleName {
HandleNameManager.shared.setHandleName(
name: handleName, for: chat.userId, in: live.communityId)
me.reloadTableView()
}
me.dismiss(vc)
}
presentAsSheet(vc)
}
private func defaultHandleName(live: Live, chat: ChatMessage) -> String? {
var defaultHandleName: String?
if let handleName = HandleNameManager.shared.handleName(for: chat.userId, in: live.communityId) {
defaultHandleName = handleName
} else if let userName = nicoManager.cachedUserName(for: chat.userId) {
defaultHandleName = userName
}
return defaultHandleName
}
func reloadTableView() {
tableView.reloadData()
scrollView.flashScrollers()
}
// MARK: Hotkeys
func focusLiveTextField() {
liveUrlTextField.becomeFirstResponder()
}
func focusCommentTextField() {
commentTextField.becomeFirstResponder()
}
func toggleSpeech() {
speakButton.state = speakButton.isOn ? .off : .on // set "toggled" state
speakButtonStateChanged(self)
}
func toggleCommentAnonymouslyButtonState() {
commentAnonymouslyButton.state = commentAnonymouslyButton.isOn ? .off : .on // set "toggled" state
commentAnonymouslyButtonStateChanged(self)
}
func disconnect() {
guard connectedToLive else { return }
nicoManager.disconnect()
}
var clickedMessage: Message? {
guard tableView.clickedRow != -1 else { return nil }
return messageContainer[tableView.clickedRow]
}
func userPageUrl(for userId: String) -> URL? {
return nicoManager.userPageUrl(for: userId)
}
func setSpeechEnabled(_ isEnabled: Bool) {
speakButton.state = isEnabled ? .on : .off
updateSpeechManagerState()
}
func setSpeechNameEnabled(_ isEnabled: Bool) {
speechNameEnabled = isEnabled
}
func setSpeechGiftEnabled(_ isEnabled: Bool) {
speechGiftEnabled = isEnabled
}
func setSpeechAdEnabled(_ isEnabled: Bool) {
speechAdEnabled = isEnabled
}
func copyAllComments() {
guard let live = live else { return }
let copier: CommentCopierType = CommentCopier(
live: live,
messageContainer: messageContainer,
nicoManager: nicoManager,
handleNameManager: .shared
)
progressIndicator.startAnimation(self)
copier.copy { [weak self] in
DispatchQueue.main.async { self?.progressIndicator.stopAnimation(self) }
}
}
func setVoiceVolume(_ volume: Int) {
speechManager.setVoiceVolume(volume)
}
func setVoiceSpeaker(_ speaker: Int) {
speechManager.setVoiceSpeaker(speaker)
}
}
// MARK: Utility
extension MainViewController {
func changeFontSize(_ fontSize: Float) {
tableViewFontSize = CGFloat(fontSize)
minimumRowHeight = calculateMinimumRowHeight(fontSize: tableViewFontSize)
tableView.rowHeight = minimumRowHeight
rowHeightCache.removeAll(keepingCapacity: false)
tableView.reloadData()
}
func changeEnableMuteUserIds(_ enabled: Bool) {
messageContainer.enableMuteUserIds = enabled
log.debug("Changed enable mute user ids: \(enabled)")
rebuildFilteredMessages()
}
func changeMuteUserIds(_ muteUserIds: [[String: String]]) {
messageContainer.muteUserIds = muteUserIds
log.debug("Changed mute user ids: \(muteUserIds)")
rebuildFilteredMessages()
}
func changeEnableMuteWords(_ enabled: Bool) {
messageContainer.enableMuteWords = enabled
log.debug("Changed enable mute words: \(enabled)")
rebuildFilteredMessages()
}
func changeMuteWords(_ muteWords: [[String: String]]) {
messageContainer.muteWords = muteWords
log.debug("Changed mute words: \(muteWords)")
rebuildFilteredMessages()
}
func changeEnableEmotionMessage(_ enabled: Bool) {
messageContainer.enableEmotionMessage = enabled
log.debug("Changed enable emotion message: \(enabled)")
rebuildFilteredMessages()
}
func changeEnableDebugMessage(_ enabled: Bool) {
messageContainer.enableDebugMessage = enabled
log.debug("Changed enable debug message: \(enabled)")
rebuildFilteredMessages()
}
private func rebuildFilteredMessages() {
DispatchQueue.main.async {
self.progressIndicator.startAnimation(self)
let shouldScroll = self.scrollView.isReachedToBottom
self.messageContainer.rebuildFilteredMessages {
self.tableView.reloadData()
if shouldScroll {
self.scrollView.scrollToBottom()
}
self.scrollView.flashScrollers()
self.progressIndicator.stopAnimation(self)
}
}
}
}
// MARK: Chat Message Utility
private extension MainViewController {
func logSystemMessageToTable(_ message: String) {
appendToTable(systemMessage: message)
}
}
// MARK: Configure Views
private extension MainViewController {
// swiftlint:disable function_body_length
func configureViews() {
liveThumbnailImageView.addBorder()
[debugReconnectButton, debugExpireTokenButton].forEach {
$0?.isHidden = !enableDebugButtons
}
liveUrlTextField.placeholderString = L10n.liveUrlTextFieldPlaceholder
liveTitleLabel.stringValue = "[\(L10n.liveTitle)]"
communityTitleLabel.stringValue = "[\(L10n.communityName)]"
visitorsIconImageView.toolTip = L10n.visitorCount
visitorsValueLabel.toolTip = L10n.visitorCount
visitorsValueLabel.stringValue = defaultLabelValue
commentsIconImageView.toolTip = L10n.commentCount
commentsValueLabel.toolTip = L10n.commentCount
commentsValueLabel.stringValue = defaultLabelValue
adPointsIconImageView.toolTip = L10n.adPoints
adPointsValueLabel.toolTip = L10n.adPoints
adPointsValueLabel.stringValue = defaultLabelValue
giftPointsIconImageView.toolTip = L10n.giftPoints
giftPointsLabel.toolTip = L10n.giftPoints
giftPointsLabel.stringValue = defaultLabelValue
autoUrlButton.title = L10n.autoUrl
autoUrlButton.toolTip = L10n.autoUrlDescription
speakButton.title = L10n.speakComment
speakButton.toolTip = L10n.speakCommentDescription
if #available(macOS 10.14, *) {
speakButton.isHidden = false
} else {
speakButton.isHidden = true
}
commentTextField.placeholderString = L10n.commentTextFieldPlaceholder
elapsedTimeValueLabel.stringValue = defaultElapsedTimeValue
activeUserIconImageView.toolTip = L10n.activeUserDescription
activeUserValueLabel.toolTip = L10n.activeUserDescription
maxActiveUserValueLabel.toolTip = L10n.activeUserDescription
activeUserChartView.toolTip = L10n.activeUserHistoryDescription
rankingIconImageView.toolTip = L10n.rankingDescription
rankingValueLabel.toolTip = L10n.rankingDescription
rankingDateLabel.toolTip = L10n.rankingDescription
updateRankingLabel(rank: nil, date: nil)
scrollView.enableScrollButtons()
configureTableView()
registerNibs()
configureActiveUserChart()
resetActiveUser()
let appearanceMonitorView = AppearanceMonitorView.make { [weak self] in
self?.tableView.reloadData()
}
view.addSubview(appearanceMonitorView)
}
// swiftlint:enable function_body_length
func configureTableView() {
tableView.setClickAction(
clickHandler: nil,
doubleClickHandler: { [weak self] in self?.openUserWindow() }
)
}
func registerNibs() {
let nibs = [
(kNibNameRoomPositionTableCellView, kRoomPositionColumnIdentifier),
(kNibNameTimeTableCellView, kTimeColumnIdentifier),
(kNibNameIconTableCellView, kIconColumnIdentifier),
(kNibNameCommentTableCellView, kCommentColumnIdentifier),
(kNibNameUserIdTableCellView, kUserIdColumnIdentifier),
(kNibNamePremiumTableCellView, kPremiumColumnIdentifier)]
for (nibName, identifier) in nibs {
guard let nib = NSNib(nibNamed: nibName, bundle: Bundle.main) else { continue }
tableView.register(nib, forIdentifier: NSUserInterfaceItemIdentifier(rawValue: identifier))
}
}
func configureManagers() {
nicoManager.delegate = self
}
func configureMute() {
let enableMuteUserIds = UserDefaults.standard.bool(forKey: Parameters.enableMuteUserIds)
let muteUserIds = UserDefaults.standard.array(forKey: Parameters.muteUserIds) as? [[String: String]]
let enableMuteWords = UserDefaults.standard.bool(forKey: Parameters.enableMuteWords)
let muteWords = UserDefaults.standard.array(forKey: Parameters.muteWords) as? [[String: String]]
changeEnableMuteUserIds(enableMuteUserIds)
if let muteUserIds = muteUserIds { changeMuteUserIds(muteUserIds) }
changeEnableMuteWords(enableMuteWords)
if let muteWords = muteWords { changeMuteWords(muteWords) }
}
func configureFontSize() {
let fontSize = UserDefaults.standard.float(forKey: Parameters.fontSize)
changeFontSize(fontSize)
}
func configureAnonymouslyButton() {
let anonymous = UserDefaults.standard.bool(forKey: Parameters.commentAnonymously)
commentAnonymouslyButton.state = anonymous ? .on : .off
}
func configureSpeech() {
speechNameEnabled = UserDefaults.standard.bool(forKey: Parameters.commentSpeechEnableName)
speechGiftEnabled = UserDefaults.standard.bool(forKey: Parameters.commentSpeechEnableGift)
speechAdEnabled = UserDefaults.standard.bool(forKey: Parameters.commentSpeechEnableAd)
}
func configureEmotionMessage() {
let enabled = UserDefaults.standard.bool(forKey: Parameters.enableEmotionMessage)
changeEnableEmotionMessage(enabled)
}
func configureDebugMessage() {
let enabled = UserDefaults.standard.bool(forKey: Parameters.enableDebugMessage)
changeEnableDebugMessage(enabled)
}
func updateMainControlViews(status connectionStatus: ConnectionStatus) {
DispatchQueue.main.async { self._updateMainControlViews(status: connectionStatus) }
}
func _updateMainControlViews(status connectionStatus: ConnectionStatus) {
let controls: [NSControl] = [grabUrlButton, liveUrlTextField, connectButton]
switch connectionStatus {
case .disconnected:
controls.forEach { $0.isEnabled = true }
connectButton.image = Asset.playArrowBlack.image
progressIndicator.stopAnimation(self)
case .connecting:
controls.forEach { $0.isEnabled = false }
progressIndicator.startAnimation(self)
case .connected:
controls.forEach { $0.isEnabled = true }
connectButton.image = Asset.stopBlack.image
progressIndicator.stopAnimation(self)
}
}
func updateCommunityViews(for live: Live) {
DispatchQueue.main.async { self._updateCommunityViews(for: live) }
}
func _updateCommunityViews(for live: Live) {
liveTitleLabel.stringValue = live.title
communityTitleLabel.stringValue = live.community.title
}
}
// MARK: Chat Message Utility (Private)
private extension MainViewController {
func appendToTable(chat: Chat) {
DispatchQueue.main.async {
let result = self.messageContainer.append(chat: chat)
self._updateTable(appended: result.appended, messageCount: result.count)
guard result.appended, let message = result.message else { return }
self.handleSpeech(message: message)
}
}
func appendToTable(systemMessage: String) {
DispatchQueue.main.async {
let result = self.messageContainer.append(systemMessage: systemMessage)
self._updateTable(appended: result.appended, messageCount: result.count)
}
}
func appendToTable(debugMessage: String) {
DispatchQueue.main.async {
let result = self.messageContainer.append(debug: debugMessage)
self._updateTable(appended: result.appended, messageCount: result.count)
}
}
func _updateTable(appended: Bool, messageCount: Int) {
guard appended else { return }
let shouldScroll = scrollView.isReachedToBottom
let rowIndex = messageCount - 1
tableView.insertRows(at: IndexSet(integer: rowIndex), withAnimation: NSTableView.AnimationOptions())
if shouldScroll {
scrollView.scrollToBottom()
}
scrollView.flashScrollers()
}
func bulkAppendToTable(chats: [Chat]) {
DispatchQueue.main.async {
chats.forEach {
self.messageContainer.append(chat: $0)
}
self.tableView.reloadData()
self.scrollView.flashScrollers()
self.scrollView.updateButtonEnables()
}
}
}
// MARK: - Internal Functions
private extension MainViewController {
func initializeHandleNameManager() {
progressIndicator.startAnimation(self)
// force to invoke setup methods in HandleNameManager()
_ = HandleNameManager.shared
progressIndicator.stopAnimation(self)
}
// MARK: Live Info Updater
func updateLiveStatistics(stat: LiveStatistics) {
let visitors = String(stat.viewers).numberStringWithSeparatorComma()
let comments = String(stat.comments).numberStringWithSeparatorComma()
let adPoints = String(stat.adPoints ?? 0).numberStringWithSeparatorComma()
let giftPoints = String(stat.giftPoints ?? 0).numberStringWithSeparatorComma()
DispatchQueue.main.async {
self.visitorsValueLabel.stringValue = visitors
self.commentsValueLabel.stringValue = comments
self.adPointsValueLabel.stringValue = adPoints
self.giftPointsLabel.stringValue = giftPoints
}
}
}
// MARK: Control Handlers
extension MainViewController {
@IBAction func grabUrlFromBrowser(_ sender: AnyObject) {
let rawValue = UserDefaults.standard.integer(forKey: Parameters.browserInUse)
guard let browser = BrowserInUseType(rawValue: rawValue) else { return }
guard let url = BrowserHelper.extractUrl(fromBrowser: browser.toBrowserHelperBrowserType) else { return }
liveUrlTextField.stringValue = url
connectLive(self)
}
@IBAction func debugReconnectButtonPressed(_ sender: Any) {
let reason: NicoReconnectReason
reason = .normal
// reason = .noPong
// reason = .noTexts
nicoManager.reconnect(reason: reason)
}
@IBAction func debugExpireTokenButtonPressed(_ sender: Any) {
nicoManager.injectExpiredAccessToken()
logSystemMessageToTable("Injected expired access token.")
}
@IBAction func connectLive(_ sender: AnyObject) {
initializeHandleNameManager()
guard let liveProgramId = liveUrlTextField.stringValue.extractLiveProgramId() else { return }
clearAllChats()
liveThumbnailImageView.image = Asset.defaultLiveThumbnailImage.image
nicoManager.connect(liveProgramId: liveProgramId)
}
@IBAction func connectButtonPressed(_ sender: AnyObject) {
if connectedToLive {
nicoManager.disconnect()
} else {
connectLive(self)
}
}
@IBAction func openLivePage(_ sender: Any) {
guard let live = live,
let url = nicoManager.livePageUrl(for: live.liveProgramId) else { return }
NSWorkspace.shared.open(url)
}
@IBAction func openCommunityPage(_ sender: Any) {
guard let live = live,
let url = nicoManager.communityPageUrl(for: live.communityId) else { return }
NSWorkspace.shared.open(url)
}
@IBAction func openAdPage(_ sender: Any) {
guard let live = live,
let url = nicoManager.adPageUrl(for: live.liveProgramId) else { return }
NSWorkspace.shared.open(url)
}
@IBAction func openGiftPage(_ sender: Any) {
guard let live = live,
let url = nicoManager.giftPageUrl(for: live.liveProgramId) else { return }
NSWorkspace.shared.open(url)
}
@IBAction func comment(_ sender: AnyObject) {
let comment = commentTextField.stringValue.stringByRemovingControlCharacters
if comment.isEmpty {
scrollView.scrollToBottom()
scrollView.flashScrollers()
return
}
nicoManager.comment(comment, anonymously: commentAnonymouslyButton.isOn) { comment in
if comment == nil {
self.logSystemMessageToTable(L10n.failedToComment)
}
}
commentTextField.stringValue = ""
if commentHistory.count == 0 || commentHistory.last != comment {
commentHistory.append(comment)
commentHistoryIndex = commentHistory.count
}
}
@IBAction func speakButtonStateChanged(_ sender: Any) {
updateSpeechManagerState()
}
@IBAction func commentAnonymouslyButtonStateChanged(_ sender: Any) {
let isOn = commentAnonymouslyButton.state == .on
UserDefaults.standard.setValue(isOn, forKey: Parameters.commentAnonymously)
}
}
// MARK: User Window Functions
private extension MainViewController {
func openUserWindow() {
let clickedRow = tableView.clickedRow
guard clickedRow != -1 else { return }
let message = messageContainer[clickedRow]
guard case let .chat(chat) = message.content else { return }
var userWindowController: UserWindowController?
// check if user window exists?
for existing in userWindowControllers where chat.userId == existing.userId {
userWindowController = existing
log.debug("existing user-wc found, use it:\(userWindowController?.description ?? "")")
break
}
if userWindowController == nil, let live = live {
// not exist, so create and cache it
let handleName = HandleNameManager.shared.handleName(for: chat.userId, in: live.communityId)
userWindowController = UserWindowController.make(
delegate: self,
nicoManager: nicoManager,
live: live,
messageContainer: messageContainer,
userId: chat.userId,
handleName: handleName
)
guard let uwc = userWindowController else { fatalError("This is not going to be happened.") }
positionUserWindow(uwc.window)
log.debug("no existing user-wc found, create it:\(uwc.description)")
userWindowControllers.append(uwc)
}
userWindowController?.showWindow(self)
}
func positionUserWindow(_ userWindow: NSWindow?) {
guard let userWindow = userWindow else { return }
var topLeftPoint: NSPoint = nextUserWindowTopLeftPoint
if userWindowControllers.count == 0 {
topLeftPoint = userWindowDefaultTopLeftPoint
}
nextUserWindowTopLeftPoint = userWindow.cascadeTopLeft(from: topLeftPoint)
}
}
// MARK: Timer Functions
private extension MainViewController {
func startElapsedTimeAndActiveUserTimer() {
elapsedTimeTimer = Timer.scheduledTimer(
timeInterval: 1,
target: self,
selector: #selector(MainViewController.updateElapsedLabelValue),
userInfo: nil,
repeats: true)
activeUserTimer = Timer.scheduledTimer(
timeInterval: calculateActiveUserInterval,
target: self,
selector: #selector(MainViewController.calculateAndUpdateActiveUser),
userInfo: nil,
repeats: true)
}
func stopElapsedTimeAndActiveUserTimer() {
elapsedTimeTimer?.invalidate()
elapsedTimeTimer = nil
activeUserTimer?.invalidate()
activeUserTimer = nil
}
@objc func updateElapsedLabelValue() {
var display = defaultElapsedTimeValue
if let beginTime = nicoManager.live?.beginTime {
var prefix = ""
var elapsed = Date().timeIntervalSince(beginTime as Date)
if elapsed < 0 {
prefix = "-"
elapsed = abs(elapsed)
}
let hour = String(format: "%02d", Int(elapsed / 3600))
let minute = String(format: "%02d", Int((elapsed / 60).truncatingRemainder(dividingBy: 60)))
let second = String(format: "%02d", Int(elapsed.truncatingRemainder(dividingBy: 60)))
display = "\(prefix)\(hour):\(minute):\(second)"
}
DispatchQueue.main.async { self.elapsedTimeValueLabel.stringValue = display }
}
func resetElapsedLabel() {
DispatchQueue.main.async {
self.elapsedTimeValueLabel.stringValue = defaultElapsedTimeValue
}
}
@objc func calculateAndUpdateActiveUser() {
messageContainer.calculateActive { (active: Int?) -> Void in
guard let active = active else { return }
self.updateActiveUser(active: active)
DispatchQueue.main.async {
self.updateActiveUserLabels()
self.updateActiveUserChart()
}
}
}
}
// MARK: Active User
private extension MainViewController {
func updateActiveUser(active: Int) {
activeUserCount = active
maxActiveUserCount = max(maxActiveUserCount, active)
activeUserHistory.append((Date(), active))
activeUserHistory = activeUserHistory.filter { Date().timeIntervalSince($0.0) < chartDuration }
}
func resetActiveUser() {
activeUserCount = 0
maxActiveUserCount = 0
activeUserHistory.removeAll()
updateActiveUserLabels()
updateActiveUserChart()
}
func updateActiveUserLabels() {
if activeUserHistory.isEmpty {
activeUserValueLabel.stringValue = defaultLabelValue
maxActiveUserValueLabel.stringValue = defaultLabelValue
return
}
activeUserValueLabel.stringValue = String(activeUserCount)
maxActiveUserValueLabel.stringValue = String(maxActiveUserCount)
}
}
// MARK: Speech Handlers
private extension MainViewController {
func updateSpeechManagerState() {
guard #available(macOS 10.14, *) else { return }
if speakButton.isOn && connectedToLive && live?.isTimeShift == false {
speechManager.startManager()
} else {
speechManager.stopManager()
}
delegate?.mainViewControllerSpeechEnabledChanged(self, isEnabled: speakButton.isOn)
}
func handleSpeech(message: Message) {
guard #available(macOS 10.14, *) else { return }
guard speakButton.isOn else { return }
guard let live = live,
!live.isTimeShift else {
// log.debug("Skip enqueing since speech for time shift program is not supported.")
return
}
guard let started = liveStartedDate,
Date().timeIntervalSince(started) > 5 else {
// Skip enqueuing since there's possibility that we receive lots of
// messages for this time slot.
log.debug("Skip enqueuing early chats.")
return
}
switch message.content {
case .chat(let chat):
// 1. Is gift? ad?
let shouldSpeechGift = speechGiftEnabled && message.isGift
let shouldSpeechAd = speechAdEnabled && message.isAd
if shouldSpeechGift || shouldSpeechAd {
DispatchQueue.global(qos: .background).async {
self.speechManager.enqueue(
comment: chat.comment.stringByRemovingHeadingEmojiSpace,
skipIfDuplicated: false
)
}
return
}
// 2. Is user comment?
guard [.ippan, .premium, .ippanTransparent].contains(chat.premium) else { return }
// 3. Name enabled?
if speechNameEnabled {
resolveSpeechName(userId: chat.userId, communityId: live.communityId) { name in
DispatchQueue.global(qos: .background).async {
self.speechManager.enqueue(
comment: chat.comment,
name: name
)
}
}
return
}
// 4. Name not enabled.
DispatchQueue.global(qos: .background).async {
self.speechManager.enqueue(comment: chat.comment)
}
case .system, .debug:
break
}
}
func resolveSpeechName(userId: String, communityId: String, completion: @escaping (String?) -> Void) {
if let name = HandleNameManager.shared.handleName(for: userId, in: communityId) {
completion(name)
return
}
nicoManager.resolveUsername(for: userId) { completion($0) }
}
}
// MARK: Chart Functions
private extension MainViewController {
var chartDuration: TimeInterval { 20 * 60 } // 20 min
func configureActiveUserChart() {
// https://stackoverflow.com/a/41241795/13220031
activeUserChartView.minOffset = 0
activeUserChartView.noDataText = defaultChartText
activeUserChartView.toolTip = L10n.activeUserHistoryDescription
activeUserChartView.leftAxis.drawAxisLineEnabled = false
activeUserChartView.leftAxis.drawLabelsEnabled = false
activeUserChartView.rightAxis.enabled = false
activeUserChartView.xAxis.drawLabelsEnabled = false
activeUserChartView.xAxis.drawGridLinesEnabled = false
activeUserChartView.legend.enabled = false
}
func updateActiveUserChart() {
guard !activeUserHistory.isEmpty else {
activeUserChartView.clear()
return
}
let entries = activeUserHistory
.map { ($0.0.timeIntervalSince1970, Double($0.1))}
.map { ChartDataEntry(x: $0.0, y: $0.1) }
let data = LineChartData()
let ds = LineChartDataSet(entries: entries, label: "")
ds.colors = [NSColor.controlTextColor]
ds.drawCirclesEnabled = false
ds.drawValuesEnabled = false
ds.highlightEnabled = false
data.append(ds)
adjustChartLeftAxis(max: maxActiveUserCount)
activeUserChartView.xAxis.axisMinimum = Date().timeIntervalSince1970 - chartDuration
activeUserChartView.data = data
}
func adjustChartLeftAxis(max: Int) {
let _max = max == 0 ? 10 : max // `10` is temporary axis max value for no data case
let padding = Double(_max) * 0.05
activeUserChartView.leftAxis.axisMinimum = -1 * padding
activeUserChartView.leftAxis.axisMaximum = Double(_max) + padding
}
}
// MARK: Ranking Methods
private extension MainViewController {
func updateRankingLabel(rank: Int?, date: Date?) {
let _rank: String = {
guard let rank = rank else { return defaultLabelValue }
return "#\(rank)"
}()
let _date: String = {
guard let date = date else { return "[\(defaultRankDateText)]" }
let formatter = DateFormatter()
formatter.dateFormat = "H:mm"
return "[\(formatter.string(from: date))]"
}()
DispatchQueue.main.async {
self.rankingValueLabel.stringValue = _rank
self.rankingDateLabel.stringValue = _date
}
}
}
// MARK: Notification Methods
private extension MainViewController {
func showLiveOpenedNotification() {
_showNotification(title: L10n.connectedToLive)
}
func showLiveClosedNotification() {
_showNotification(title: L10n.liveClosed)
}
func _showNotification(title: String) {
let enabled = UserDefaults.standard.bool(forKey: Parameters.enableLiveNotification)
guard enabled, let live = live, !live.isTimeShift else { return }
notificationPresenter.show(
title: title,
body: "\(live.title)\n\(live.community.title)",
liveProgramId: live.liveProgramId,
jpegImageUrl: live.community.thumbnailUrl
)
}
}
// MARK: Misc Utility
private extension MainViewController {
func clearAllChats() {
messageContainer.removeAll()
rowHeightCache.removeAll(keepingCapacity: false)
tableView.reloadData()
}
func showAuthWindowController() {
authWindowController.startAuthorization()
authWindowController.showWindow(self)
}
}
// MARK: Debug Methods
private extension MainViewController {
func logDebugMessageToTable(_ message: String) {
log.debug(message)
appendToTable(debugMessage: message)
}
func logDebugReconnectReason(_ reason: NicoReconnectReason) {
let _reason: String = {
switch reason {
case .normal: return "normal"
case .noPong: return "no pong"
case .noTexts: return "no text"
}
}()
logDebugMessageToTable("Reconnecting... (\(_reason))")
}
func logDebugRankingManagerStatus() {
logDebugMessageToTable("RankingManager \(rankingManager.isRunning ? "started" : "stopped").")
}
}
private extension Chat {
var isGift: Bool { premium == .caster && comment.starts(with: "/gift ") }
}
private extension NicoError {
var toMessage: String {
switch self {
case .internal: return L10n.errorInternal
case .noLiveInfo: return L10n.errorNoLiveInfo
case .noMessageServerInfo: return L10n.errorNoMessageServerInfo
case .openMessageServerFailed: return L10n.errorFailedToOpenMessageServer
case .notStarted: return L10n.errorLiveNotStarted
}
}
}
private extension NSButton {
var isOn: Bool { self.state == .on }
}
private extension String {
var stringByRemovingControlCharacters: String {
stringByReplacingRegexp(pattern: "\\p{Cntrl}", with: "")
}
}
// swiftlint:enable file_length
| mit | 3b8bb236d7e4eb2a95679eacbf4dcd50 | 36.331414 | 161 | 0.66445 | 4.96165 | false | false | false | false |
astralbodies/CleanRooms | CleanRooms/Services/CoreDataStack.swift | 1 | 4674 | /*
* Copyright (c) 2015 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
import CoreData
class CoreDataStack {
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.razeware.CleanRooms" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("CleanRooms", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CleanRooms.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 39996e965fa8ada2b134ff6b0edf47a6 | 52.113636 | 287 | 0.756953 | 5.360092 | false | false | false | false |
li13418801337/DouyuTV | DouyuZB/DouyuZB/Classes/Home/Controller/GameViewController.swift | 1 | 4526 | //
// GameViewController.swift
// DouyuZB
//
// Created by work on 16/11/9.
// Copyright © 2016年 xiaosi. All rights reserved.
//
import UIKit
private let kEdgeMargin : CGFloat = 10
private let kItemW : CGFloat = (kScreenW - 2 * kEdgeMargin) / 3
private let kItemH : CGFloat = kItemW * 6 / 5
private let kGameCellID = "kGameCellID"
private let kGameHeaderViewID = "kGameCellID"
private let kHeaderViewH : CGFloat = 50
private let kGameViewH : CGFloat = 90
class GameViewController: UIViewController {
//MARK:懒加载属性
fileprivate lazy var gameVM : GameViewModel = GameViewModel()
fileprivate lazy var collectionView : UICollectionView = {[unowned self]in
//1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin)
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
collectionView.backgroundColor = UIColor.white
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil),forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kGameHeaderViewID)
collectionView.autoresizingMask = [.flexibleHeight]
collectionView.dataSource = self
return collectionView
}()
fileprivate lazy var topHeaderView : CollectionHeaderView = {
let headerView = CollectionHeaderView.collectionHeaderView()
headerView.frame = CGRect(x: 0, y: -(kHeaderViewH+kGameViewH), width: kScreenW, height: kHeaderViewH )
headerView.moreBtn.isHidden = true
headerView.titleLabel.text = "常见"
headerView.headImage.image = UIImage(named: "Img_orange")
return headerView
}()
fileprivate lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
//MARK: 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
//MARK: 设置UI界面
extension GameViewController{
fileprivate func setupUI(){
view.addSubview(collectionView)
//添加顶部的view
collectionView.addSubview(topHeaderView)
collectionView.addSubview(gameView)
collectionView.contentInset = UIEdgeInsets(top: kHeaderViewH+kGameViewH, left: 0, bottom: 0, right: 0)
}
}
//MARK: 请求数据
extension GameViewController{
fileprivate func loadData(){
gameVM.loadALLGameData {
//展示全部游戏
self.collectionView.reloadData()
//展示常用游戏
self.gameView.groups = Array(self.gameVM.games[0..<10])
}
}
}
//MARK: 遵守数据源和代理
extension GameViewController : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gameVM.games.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell
cell.baseGame = gameVM.games[indexPath.item]
return cell
}
//设置header
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//取出headerview
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kGameHeaderViewID, for: indexPath) as! CollectionHeaderView
//设置属性
headerView.titleLabel.text = "全部"
headerView.headImage.image = UIImage(named: "Img_orange")
headerView.moreBtn.isHidden = true
return headerView
}
}
| mit | 752eeeead9502958edc1e7e0e208e34a | 32.641221 | 189 | 0.679147 | 5.42734 | false | false | false | false |
kenwilcox/Petitions | Petitions/MasterViewController.swift | 1 | 3687 | //
// MasterViewController.swift
// Petitions
//
// Created by Kenneth Wilcox on 11/11/15.
// Copyright © 2015 Kenneth Wilcox. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [[String: String]]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let urlString: String
if navigationController?.tabBarItem.tag == 0 {
urlString = "https://api.whitehouse.gov/v1/petitions.json?limit=100"
} else {
urlString = "https://api.whitehouse.gov/v1/petitions.json?signatureCountFloor=10000&limit=100"
}
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { [unowned self] in
if let url = NSURL(string: urlString) {
if let data = try? NSData(contentsOfURL: url, options: []) {
let json = JSON(data: data)
if json["metadata"]["responseInfo"]["status"].intValue == 200 {
self.parseJSON(json)
} else {
self.showError()
}
} else {
self.showError()
}
} else {
self.showError()
}
}
}
func parseJSON(json: JSON) {
for result in json["results"].arrayValue {
let title = result["title"].stringValue
let body = result["body"].stringValue
let sigs = result["signatureCount"].stringValue
let obj = ["title": title, "body": body, "sigs": sigs]
objects.append(obj)
}
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
self.tableView.reloadData()
}
}
func showError() {
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
let ac = UIAlertController(title: "Loading error", message: "There was a problem loading the feed; please check your connection and try again.", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(ac, animated: true, completion: nil)
}
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row]
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = objects[indexPath.row]
cell.textLabel!.text = object["title"]
cell.detailTextLabel!.text = object["body"]
return cell
}
}
| mit | fbf122677452b0125595eed00af5f46f | 31.910714 | 174 | 0.672002 | 4.762274 | false | false | false | false |
MyHZ/DouYuZB | DYZB/DYZB/Classes/Main/View/CollectionViewBaseCell.swift | 1 | 1313 | //
// CollectionViewBaseCell.swift
// DYZB
//
// Created by DM on 2016/11/23.
// Copyright © 2016年 DM. All rights reserved.
//
import UIKit
import Kingfisher
class CollectionViewBaseCell: UICollectionViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var onlineButton: UIButton!
@IBOutlet weak var nickNameLabel: UILabel!
var anchor:AnchorModel?{
didSet{
//0.校验模型是否有值
guard let anchor = anchor else {
return
}
//1.取出在线人数显示文字
var onlineStr :String = ""
if anchor.online > 10000{
onlineStr = "\(Int(anchor.online / 10000))万在线"
}
else
{
onlineStr = "\(anchor.online)在线"
}
// onlineButton.setTitle(onlineStr, for: .normal)
//2.昵称的显示
// nickNameLabel.text = anchor.nickname
//3.设置封面图片
let iconUrl = URL(string: anchor.vertical_src)!
iconImageView.kf.setImage(with: iconUrl)
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| mit | 16509b878aacaa9800798ad94637939e | 23.352941 | 62 | 0.524155 | 4.813953 | false | false | false | false |
dcunited001/SpectraNu | Spectra/Node/Modelable.swift | 1 | 3156 | //
// Modelable.swift
// Pods
//
// Created by David Conner on 10/9/15.
//
//
import Foundation
import simd
public protocol Modelable: class {
var modelScale:float4 { get set }
var modelPosition:float4 { get set }
var modelRotation:float4 { get set }
var modelMatrix:float4x4 { get set }
func setModelableDefaults()
func calcModelMatrix() -> float4x4
func updateModelMatrix()
func setModelUniformsFrom(model: Modelable)
}
extension Modelable {
public func setModelableDefaults() {
modelPosition = float4(1.0, 1.0, 1.0, 1.0)
modelScale = float4(1.0, 1.0, 1.0, 1.0)
modelRotation = float4(1.0, 1.0, 1.0, 90.0)
}
public func calcModelMatrix() -> float4x4 {
// scale, then rotate, then translate!!
// - but it looks cooler identity * translate, rotate, scale
return Transform3D.translate(modelPosition) *
Transform3D.rotate(modelRotation) *
Transform3D.scale(modelScale) // <== N.B. this scales first!!
}
public func updateModelMatrix() {
modelMatrix = calcModelMatrix()
}
public func setModelUniformsFrom(model: Modelable) {
modelPosition = model.modelPosition
modelRotation = model.modelRotation
modelScale = model.modelScale
updateModelMatrix()
}
}
// TODO: use Self class for blocks in rotatable/translatable/scalable?
public protocol Rotatable: Modelable {
var rotationRate: Float { get set }
func rotateForTime(t: CFTimeInterval, block: (Rotatable -> Float)?)
var updateRotationalVectorRate: Float { get set }
func updateRotationalVectorForTime(t: CFTimeInterval, block: (Rotatable -> float4)?)
}
extension Rotatable {
public func rotateForTime(t: CFTimeInterval, block: (Rotatable -> Float)?) {
// TODO: clean this up. add applyRotation? as default extension to protocol?
// - or set up 3D transforms as a protocol?
let rotation = (rotationRate * Float(t)) * (block?(self) ?? 1)
self.modelRotation.w += rotation
}
public func updateRotationalVectorForTime(t: CFTimeInterval, block: (Rotatable -> float4)?) {
let rVector = (rotationRate * Float(t)) * (block?(self) ?? float4(1.0, 1.0, 1.0, 0.0))
self.modelRotation += rVector
}
}
public protocol Translatable: Modelable {
var translationRate: Float { get set }
func translateForTime(t: CFTimeInterval, block: (Translatable -> float4)?)
}
extension Translatable {
public func translateForTime(t: CFTimeInterval, block: (Translatable -> float4)?) {
let translation = (translationRate * Float(t)) * (block?(self) ?? float4(0.0, 0.0, 0.0, 0.0))
self.modelPosition += translation
}
}
public protocol Scalable: Modelable {
var scaleRate: Float { get set }
func scaleForTime(t: CFTimeInterval, block: (Scalable -> float4)?)
}
extension Scalable {
public func scaleForTime(t: CFTimeInterval, block: (Scalable -> float4)?) {
let scaleAmount = (scaleRate * Float(t)) * (block?(self) ?? float4(0.0, 0.0, 0.0, 0.0))
self.modelScale += scaleAmount
}
}
| mit | 05348140ff759523e5246933a99c1770 | 31.204082 | 101 | 0.653042 | 3.76611 | false | false | false | false |
mnmaraes/ReactiveSearcher | ReactiveSearcher/ReactiveCocoa+Extensions.swift | 1 | 1688 | //
// ReactiveCocoa+Extensions.swift
// ReactiveSearcher
//
// Created by Murillo Nicacio de Maraes on 6/16/15.
// Copyright (c) 2015 SuperUnreasonable. All rights reserved.
//
import Foundation
import ReactiveCocoa
import Result
import Box
/// Useful for Transforming Error Events into Next Events.
func mapResult<T, U, E: ErrorType>(transform: Result<T, E> -> U)(signal: Signal<T, E>) -> Signal<U, NoError> {
return signal
|> materialize
|> map { (event: Event<T, E>) -> Event<U, NoError> in
switch event {
case .Next(let box):
return .Next(box.map { transform(Result(value: $0)) })
case .Error(let box):
return .Next(box.map { transform(Result(error: $0)) })
case .Completed:
return .Completed
case .Interrupted:
return .Interrupted
}
}
|> dematerialize
}
/// Zips Signals together but only sends updates when `signal` does
func combineSampled<T, U, E: ErrorType>(signal: Signal<T, E>)(original: Signal<U, E>) -> Signal<(U, T), E> {
return Signal { sink in
let property = MutableProperty<T?>(nil)
let signalDisposable = property <~ signal |> mapResult { $0.value } |> ignoreNil
let originalDisposable = original
|> map { ($0, property.value) }
|> filter { $1 != nil }
|> map { ($0, $1!) }
|> observe(sink)
let composite = CompositeDisposable([signalDisposable])
if let originalDisposable = originalDisposable {
composite.addDisposable(originalDisposable)
}
return composite
}
} | mit | 22e93bedd7db15dbeae430a64e67cfd2 | 30.277778 | 110 | 0.582938 | 4.273418 | false | false | false | false |
KenHeglund/Mustang | MustangApp/Mustang/ViewController.swift | 1 | 6525 | /*===========================================================================
ViewController.swift
Mustang
Copyright (c) 2016 OrderedBytes. All rights reserved.
===========================================================================*/
import Cocoa
/*==========================================================================*/
class ViewController: NSViewController {
// MARK: - Private
@IBOutlet private var usagePageArrayController: NSArrayController!
@IBOutlet private var usageArrayController: NSArrayController!
@IBOutlet private var usagePageTableView: NSTableView!
@IBOutlet private var usageTableView: NSTableView!
private static let nameColumnIdentifier = NSUserInterfaceItemIdentifier(rawValue: "name")
var managedObjectContext: NSManagedObjectContext? {
self.representedObject as? NSManagedObjectContext
}
/*==========================================================================*/
@IBAction private func doAddUsagePage(_ sender: AnyObject?) {
guard let managedObjectContext = self.managedObjectContext else {
fatalError("Failed to obtain managed object context")
}
guard let nextUsagePageID = self.nextUsagePageID() else {
return
}
var newObject: NSManagedObject?
managedObjectContext.performAndWait {
newObject = NSEntityDescription.insertNewObject(forEntityName: Entity.UsagePage.entityName, into: managedObjectContext)
newObject?.setValue(nextUsagePageID, forKey: Entity.UsagePage.usagePageKey)
newObject?.setValue("New Usage Page \(nextUsagePageID)", forKey: Entity.UsagePage.nameKey)
}
guard let newUsagePage = newObject else {
fatalError("Failed to create new Usage Page entity")
}
self.usagePageArrayController.addObject(newUsagePage)
self.usagePageTableView.window?.makeFirstResponder(self.usagePageTableView)
let selectedRow = self.usagePageArrayController.selectionIndex
self.usagePageTableView.scrollRowToVisible(selectedRow)
let columnIndex = self.usagePageTableView.column(withIdentifier: ViewController.nameColumnIdentifier)
self.usagePageTableView.editColumn(columnIndex, row: selectedRow, with: nil, select: true)
}
/*==========================================================================*/
@IBAction private func doAddUsage(_ sender: AnyObject?) {
guard let managedObjectContext = self.managedObjectContext else {
fatalError("Failed to obtain managed object context")
}
guard let nextUsageID = self.nextUsageID() else {
return
}
var newObject: NSManagedObject?
managedObjectContext.performAndWait {
newObject = NSEntityDescription.insertNewObject(forEntityName: Entity.Usage.entityName, into: managedObjectContext)
newObject?.setValue(nextUsageID, forKey: Entity.Usage.usageKey)
newObject?.setValue("New Usage \(nextUsageID)", forKey: Entity.Usage.nameKey)
}
guard let newUsage = newObject else {
fatalError("Failed to create new Usage entity")
}
self.usageArrayController.addObject(newUsage)
self.usageTableView.window?.makeFirstResponder(self.usageTableView)
let selectedRow = self.usageArrayController.selectionIndex
self.usageTableView.scrollRowToVisible(selectedRow)
let columnIndex = self.usageTableView.column(withIdentifier: ViewController.nameColumnIdentifier)
self.usageTableView.editColumn(columnIndex, row: selectedRow, with: nil, select: true)
}
/*==========================================================================*/
@IBAction private func doAddUsagePageOrUsage(_ sender: AnyObject?) {
guard let firstResponder = self.view.window?.firstResponder else {
return
}
if firstResponder === self.usagePageTableView {
self.doAddUsagePage(sender)
}
else if firstResponder === self.usageTableView {
self.doAddUsage(sender)
}
}
// MARK: - MustangDocument internal
/*==========================================================================*/
private func nextUsagePageID() -> Int? {
guard let managedObjectContext = self.managedObjectContext else {
fatalError("Failed to obtain managed object context")
}
var nextUsagePageID = 1
var localError: NSError?
managedObjectContext.performAndWait {
let sortDescriptor = NSSortDescriptor(key: Entity.UsagePage.usagePageKey, ascending: false)
let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
fetchRequest.entity = NSEntityDescription.entity(forEntityName: Entity.UsagePage.entityName, in: managedObjectContext)
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.fetchLimit = 1
do {
let fetchResults = try managedObjectContext.fetch(fetchRequest)
let lastUsagePageID = (fetchResults.last as AnyObject).value(forKey: Entity.UsagePage.usagePageKey) as? Int ?? 0
nextUsagePageID = (lastUsagePageID + 1)
}
catch {
localError = error as NSError?
}
}
if let error = localError {
Swift.print(error)
return nil
}
return nextUsagePageID
}
/*==========================================================================*/
private func nextUsageID() -> Int? {
guard let managedObjectContext = self.managedObjectContext else {
fatalError("Failed to obtain managed object context")
}
guard let selectedObjects = self.usagePageArrayController.selectedObjects else {
return nil
}
guard selectedObjects.count == 1 else {
return nil
}
var nextUsageID = 1
var localError: NSError?
let selectedUsagePage = selectedObjects.last
guard let usagePage = (selectedUsagePage as AnyObject).value(forKey: Entity.UsagePage.usagePageKey) as? Int else {
return nextUsageID
}
let predicate = NSPredicate(format: "usagePage.usagePage == %ld", usagePage)
let sortDescriptor = NSSortDescriptor(key: Entity.Usage.usageKey, ascending: false)
managedObjectContext.performAndWait {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
fetchRequest.entity = NSEntityDescription.entity(forEntityName: Entity.Usage.entityName, in: managedObjectContext)
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.fetchLimit = 1
do {
let fetchResult = try managedObjectContext.fetch(fetchRequest)
let lastUsageID = (fetchResult.last as AnyObject).value(forKey: Entity.Usage.usageKey) as? Int ?? 0
nextUsageID = (lastUsageID + 1)
}
catch {
localError = error as NSError
}
}
if let error = localError {
Swift.print(error)
return nil
}
return nextUsageID
}
}
| mit | 2f679c8ae8089ce612075d13c835f314 | 31.462687 | 122 | 0.682146 | 4.62438 | false | false | false | false |
kellanburket/Passenger | Example/Passenger/Twitter/Status.swift | 1 | 1645 | //
// Status.swift
// Passenger
//
// Created by Kellan Cummings on 7/7/15.
// Copyright (c) 2015 CocoaPods. All rights reserved.
//
import Foundation
import Passenger
class Status: Model {
var screenName: String?
var text: String?
var entities = StatusEntity()
var coordinates: String?
var favorited = Bool()
var truncated = Bool()
var createdAt: NSDate?
var indices = [Int]()
var user = User()
var retweetCount = Int()
var favoriteCount = Int()
var inReplyToStatusId = Int()
var inReplyToStatusIdStr = String()
var inReplyToUserId = Int()
var inReplyToUserIdStr = String()
var inReplyToUserScreenName = String()
class func user(params: [String: AnyObject], onComplete: [Status]? -> Void) {
self.search(params) { obj in
if let tweets = obj as? [Status] {
onComplete(tweets)
} else {
onComplete(nil)
}
}
}
class func home(params: [String: AnyObject], onComplete: [Status]? -> Void) {
self.doAction("home", params: params) { (obj: [Model]?) in
if let tweets = obj as? [Status] {
onComplete(tweets)
} else {
onComplete(nil)
}
}
}
class func mentions(params: [String: AnyObject], onComplete: [Status]? -> Void) {
self.doAction("mentions", params: params) { (obj: [Model]?) in
if let tweets = obj as? [Status] {
onComplete(tweets)
} else {
onComplete(nil)
}
}
}
} | mit | ac0688bac612a65c44bb47c5147bc1d1 | 23.205882 | 85 | 0.538602 | 4.351852 | false | false | false | false |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Models/Search/Response/SearchResponse/Auxiliary/RenderingContent/FacetOrder/FacetOrdering.swift | 1 | 1145 | //
// FacetOrdering.swift
//
//
// Created by Vladislav Fitc on 15/06/2021.
//
import Foundation
/// Facets and facets values ordering rules container
public struct FacetOrdering {
/// The ordering of facets.
public let facets: FacetsOrder
/// The ordering of facet values, within an individual list.
public let values: [Attribute: FacetValuesOrder]
/**
- parameters:
- facets: The ordering of facets.
- values: The ordering of facet values, within an individual list.
*/
public init(facets: FacetsOrder = .init(),
values: [Attribute: FacetValuesOrder] = [:]) {
self.facets = facets
self.values = values
}
}
extension FacetOrdering: Codable {
enum CodingKeys: String, CodingKey {
case facets
case values
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.facets = try container.decodeIfPresent(forKey: .facets) ?? FacetsOrder()
let rawValues = try container.decodeIfPresent([String: FacetValuesOrder].self, forKey: .values) ?? [:]
self.values = rawValues.mapKeys(Attribute.init)
}
}
| mit | 234b4a52129ad9402894319b99aa3268 | 23.891304 | 106 | 0.686463 | 3.921233 | false | false | false | false |
Prosumma/Prosumma | Prosumma/RangeExtensions.swift | 1 | 1030 | //
// RangeExtensions.swift
// Prosumma
//
// Created by Gregory Higley on 10/2/15.
// Copyright © 2015 Prosumma LLC. All rights reserved.
//
import Foundation
public func +<E: IntegerArithmeticType>(lhs: Range<E>, rhs: Range<E>) -> Range<E> {
let lhsDistance = lhs.startIndex.distanceTo(lhs.endIndex)
let rhsDistance = rhs.startIndex.distanceTo(rhs.endIndex)
let distance = lhsDistance + rhsDistance
let startIndex = lhs.startIndex + rhs.startIndex
let endIndex = startIndex.advancedBy(distance - 1)
return startIndex..<endIndex
}
extension NSRange {
public init<I: Indexable where I.Index.Distance == Int>(_ indexable: I, range: Range<I.Index>) {
location = indexable.startIndex.distanceTo(range.startIndex)
length = range.startIndex.distanceTo(range.endIndex)
}
public init(_ string: String, range: Range<String.Index>) {
location = string.startIndex.distanceTo(range.startIndex)
length = range.startIndex.distanceTo(range.endIndex)
}
} | mit | 2edd8e9dc1fbf1bebba190d473855a52 | 31.1875 | 100 | 0.697765 | 3.957692 | false | false | false | false |
Chaosspeeder/YourGoals | YourGoals/UI/Views/NibLoadingView.swift | 1 | 1651 | //
// NibLoadingView.swift
// YourGoals
//
// Created by André Claaßen on 30.10.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
import UIKit
// Usage: Subclass your UIView from NibLoadView to automatically load a xib with the same name as your class
@IBDesignable
/// this base class makes Custom Controlls based on XIB files work.
/// to make you happy, do the following things
///
/// 1. Create a XIB-File
/// 2. Create a swift UIView class file with the same name as the xib
/// 3. The class file should be dependend of NibLoadingFiew
/// 4. in the xib the files owner placeholder (only) should set
/// to the swift class
/// 5. Now you can make other outlets for your controls
class NibLoadingView: UIView {
@IBOutlet weak var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
nibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
nibSetup()
}
private func nibSetup() {
backgroundColor = .clear
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.translatesAutoresizingMaskIntoConstraints = true
addSubview(view)
awakeFromNib()
}
private func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView
return nibView
}
}
| lgpl-3.0 | 2300b02ffc273174bd96edaa06638fa1 | 26.898305 | 108 | 0.650668 | 4.424731 | false | false | false | false |
apple/swift-async-algorithms | Sources/AsyncAlgorithms/Merge/AsyncMerge2Sequence.swift | 1 | 3060 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
@_implementationOnly import DequeModule
/// Creates an asynchronous sequence of elements from two underlying asynchronous sequences
public func merge<Base1: AsyncSequence, Base2: AsyncSequence>(_ base1: Base1, _ base2: Base2) -> AsyncMerge2Sequence<Base1, Base2>
where
Base1.Element == Base2.Element,
Base1: Sendable, Base2: Sendable,
Base1.Element: Sendable
{
return AsyncMerge2Sequence(base1, base2)
}
/// An ``Swift/AsyncSequence`` that takes two upstream ``Swift/AsyncSequence``s and combines their elements.
public struct AsyncMerge2Sequence<
Base1: AsyncSequence,
Base2: AsyncSequence
>: Sendable where
Base1.Element == Base2.Element,
Base1: Sendable, Base2: Sendable,
Base1.Element: Sendable
{
public typealias Element = Base1.Element
private let base1: Base1
private let base2: Base2
/// Initializes a new ``AsyncMerge2Sequence``.
///
/// - Parameters:
/// - base1: The first upstream ``Swift/AsyncSequence``.
/// - base2: The second upstream ``Swift/AsyncSequence``.
public init(
_ base1: Base1,
_ base2: Base2
) {
self.base1 = base1
self.base2 = base2
}
}
extension AsyncMerge2Sequence: AsyncSequence {
public func makeAsyncIterator() -> AsyncIterator {
let storage = MergeStorage<Base1, Base2, Base1>(
base1: base1,
base2: base2,
base3: nil
)
return AsyncIterator(storage: storage)
}
}
extension AsyncMerge2Sequence {
public struct AsyncIterator: AsyncIteratorProtocol {
/// This class is needed to hook the deinit to observe once all references to the ``AsyncIterator`` are dropped.
///
/// If we get move-only types we should be able to drop this class and use the `deinit` of the ``AsyncIterator`` struct itself.
final class InternalClass: Sendable {
private let storage: MergeStorage<Base1, Base2, Base1>
fileprivate init(storage: MergeStorage<Base1, Base2, Base1>) {
self.storage = storage
}
deinit {
self.storage.iteratorDeinitialized()
}
func next() async rethrows -> Element? {
try await storage.next()
}
}
let internalClass: InternalClass
fileprivate init(storage: MergeStorage<Base1, Base2, Base1>) {
internalClass = InternalClass(storage: storage)
}
public mutating func next() async rethrows -> Element? {
try await internalClass.next()
}
}
}
| apache-2.0 | 56d6e1fd5dfaa602adaa35821fd3dff1 | 31.553191 | 135 | 0.610131 | 4.643399 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKit/search/TKGeocoderHelper.swift | 1 | 8671 | //
// TKGeocoderHelper.swift
// TripKit
//
// Created by Adrian Schoenig on 27/11/2015.
// Copyright © 2015 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import MapKit
extension TKGeocoding {
@available(*, renamed: "geocode(_:near:)")
public func geocode(_ object: TKGeocodable, near region: MKMapRect, completion: @escaping (Result<Void, Error>) -> Void) {
Task {
do {
try await geocode(object, near: region)
completion(.success(()))
} catch {
completion(.failure(error))
}
}
}
public func geocode(_ object: TKGeocodable, near region: MKMapRect) async throws {
try await TKGeocoderHelper.geocode(object, using: self, near: region)
}
}
public class TKGeocoderHelper: NSObject {
public static var preferredGeocoder: TKGeocoding = {
return TKAppleGeocoder()
}()
private override init() {
super.init()
}
public enum GeocodingError: Error {
case missingAddress
case serverFoundNoMatch(String)
case unknownServerError(String)
case outdatedResult
}
@objc(errorForNoLocationFoundForInput:)
public static func errorForNoLocationFound(forInput input: String) -> Error {
let format = NSLocalizedString("'%@' not found.", tableName: "Shared", bundle: .tripKit, comment: "Error when location search for %input was not successful. (old key: RequestErrorFormat)")
let message = String(format: format, input)
return NSError(code: 64720, message: message)
}
@available(*, renamed: "geocode(_:using:near:)")
public class func geocode(_ object: TKGeocodable, using geocoder: TKGeocoding, near region: MKMapRect, completion: @escaping (Result<Void, Error>) -> Void) {
guard let address = object.addressForGeocoding, !address.isEmpty else {
completion(.failure(GeocodingError.missingAddress))
return
}
return geocoder.geocode(address, near: region) { result in
DispatchQueue.main.async {
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let results):
guard let best = TKGeocoderHelper.pickBest(from: results) else {
completion(.failure(GeocodingError.serverFoundNoMatch(address)))
return
}
// The objects stored in the objectsToBeGeocoded dictionary do
// not have coordinate values assigned (e.g., a location from
// contact), therefore, we need to manually set them afterwards.
// Also, as part of the method call, another reverse geocoding
// operation is performed on an Apple geocoder. This is because
// the coordinate from the "bestMatch" object may not match the
// address originally stored in the "geocodableObject", hence,
// the reverse geocoding returns the updated address matching
// the coordinate.
object.assign(best.coordinate, forAddress: address)
completion(.success(()))
}
}
}
}
public class func geocode(_ object: TKGeocodable, using geocoder: TKGeocoding, near region: MKMapRect) async throws {
return try await withCheckedThrowingContinuation { continuation in
geocode(object, using: geocoder, near: region) { result in
continuation.resume(with: result)
}
}
}
@objc(pickBestFromResults:)
public class func pickBest(from results: [MKAnnotation]) -> MKAnnotation? {
if results.count == 0 {
return nil
} else if results.count == 1, let first = results.first {
return first
} else {
return results
.compactMap { $0 as? TKSortableAnnotation }
.sorted { return $0.sortScore > $1.sortScore }
.first
?? results.first // if not sortable, pick first
}
}
}
// MARK: - Merging and pruning
extension TKGeocoderHelper {
@objc public class func mergedAndPruned(_ input:[TKNamedCoordinate], withMaximum max: Int) -> [TKNamedCoordinate] {
return input.deduplicated().pruned(maximum: max)
}
public class func pruned(_ input:[TKAutocompletionResult], withMaximum max: Int) -> [TKAutocompletionResult] {
return input.pruned(maximum: max) { $0.score }
}
}
extension TKNamedCoordinate {
fileprivate func merge(_ other: TKNamedCoordinate) {
sortScore = sortScore + min(10, other.sortScore)
var providers = Set<String>()
dataSources = (dataSources + other.dataSources).filter { providers.insert($0.provider.name).inserted }
}
}
extension MKCoordinateRegion {
static func region(latitude: CLLocationDegrees, longitude: CLLocationDegrees) -> MKCoordinateRegion {
let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let span = MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1)
return MKCoordinateRegion(center: coordinate, span: span)
}
}
extension Array {
fileprivate func pruned(maximum max: Int, scoreForElement handler: (Element) -> Int) -> [Element] {
if self.count < max {
return self
}
let sorted = self.sorted { handler($0) >= handler($1) }
return Array(sorted.prefix(max))
}
}
extension Array where Element : TKNamedCoordinate {
fileprivate func deduplicated() -> [Element] {
return reduce([]) { $0.mergeWithPreferences([$1]) }
}
fileprivate func pruned(maximum max: Int) -> [Element] {
return pruned(maximum: max) { $0.sortScore }
}
/// Merges the provided array into `self` removing duplicates and keeping
/// the preferred elements.
///
/// - SeeAlso: `shouldMerge` and `preferred`
public func mergeWithPreferences(_ other: [Element]) -> [Element] {
if other.isEmpty {
return self
}
var toRemove: [Element] = []
var toAdd: [Element] = []
for new in other {
// default do adding the new one
toAdd.append(new)
// check if we should merge with an existing one
for existing in self where shouldMerge(existing, second: new) {
if preferred(existing, second: new) == new {
// replace existing with new
new.merge(existing)
toRemove.append(existing)
} else {
// don't add new
existing.merge(new)
toAdd.removeLast()
}
break // merged
}
}
return filter { !toRemove.contains($0) } + toAdd
}
/// Determines if two coordinates should be merged and only one should be kept.
private func shouldMerge(_ first: Element, second: Element) -> Bool {
guard
let firstTitle = first.title, let secondTitle = second.title,
firstTitle.contains(secondTitle) || secondTitle.contains(firstTitle)
else {
return false
}
// Only merge same title if they are within a certain distance from
// each other.
let firstLocation = CLLocation(latitude: first.coordinate.latitude, longitude: first.coordinate.longitude)
let secondLocation = CLLocation(latitude: second.coordinate.latitude, longitude: second.coordinate.longitude)
return firstLocation.distance(from: secondLocation) < 50
}
/// Picks which of the two provided named coordinates is the preferred one. The order
/// of preference is:
///
/// 1. transit stops
/// 2. coordinates with attribution, e.g., a link to the Foursquare app
/// 3. higher score
/// 4. low score
/// 5. unverified
///
/// - Warning:
/// Make sure to call `shouldMerge` first.
fileprivate func preferred(_ first: Element, second: Element) -> Element {
if let _ = first as? TKStopCoordinate {
return first
} else if let _ = second as? TKStopCoordinate {
return second
} else if
let firstIsVerified = first.attributionIsVerified?.boolValue,
let secondIsVerified = second.attributionIsVerified?.boolValue,
firstIsVerified != secondIsVerified {
if firstIsVerified {
return first
} else {
return second
}
} else if
let firstIsVerified = first.attributionIsVerified?.boolValue,
!firstIsVerified,
second.attributionIsVerified == nil {
return second
} else if
let secondIsVerified = second.attributionIsVerified?.boolValue,
!secondIsVerified,
first.attributionIsVerified == nil {
return first
} else if !first.dataSources.isEmpty, second.dataSources.isEmpty {
return first
} else if first.dataSources.isEmpty, !second.dataSources.isEmpty {
return second
} else if first.sortScore >= second.sortScore {
return first
} else {
return second
}
}
}
| apache-2.0 | 7cabb216f65e9153fc1465e09ac9ec31 | 30.758242 | 192 | 0.655133 | 4.441598 | false | false | false | false |
montionugera/yellow | yellow-ios/yellow/Model/FeedViewModel.swift | 1 | 5499 | //
// FeedViewModel.swift
// FirebaseIntroduction
//
// Created by Ekachai Limpisoot on 8/30/17.
// Copyright © 2017 Ekachai Limpisoot. All rights reserved.
//
import UIKit
import FirebaseDatabase
protocol FeedViewModelDelegate : class {
func didAppendData(indexPath : IndexPath , feedContent: FeedContent)
func didFinishLoadDataOnInitilization()
func didRemoveData(indexPath : IndexPath)
func didFinishUpdate(indexPath : IndexPath , feedContent : FeedContent )
}
class FeedViewModel: NSObject {
var firebaseAPI : FirebaseAPI!
var feedContents : [FeedContent] = [FeedContent]()
weak var delegate : FeedViewModelDelegate?
fileprivate var initialDataHasBeenLoaded : Bool = false
override init() {
super.init()
}
func initilization() {
firebaseAPI = FirebaseAPI()
self.feedContents.removeAll()
firebaseAPI.storageRef.observeSingleEvent(of: .value, with: {[weak self] (snapshot) in
guard let the = self else {
return
}
for item in snapshot.children {
//let (data,value) = FBSnapShotToDictForClassMapping(any: item)
let feedContent = FeedContent(snapshot:item as! DataSnapshot)
if(self?.timeAgo24Hr( Date(timeIntervalSince1970: TimeInterval(feedContent.postDttmInt)) , currentDate: Date()) == false){
the.feedContents.append(feedContent)
}
// print(item)
}
// sort date time
the.feedContents.sort { $0.postDttmInt > $1.postDttmInt }
the.initialDataHasBeenLoaded = true
the.delegate?.didFinishLoadDataOnInitilization()
})
firebaseAPI.storageRef.observe(.childChanged, with: {[weak self] (snapshot) in
guard let the = self else {
return
}
if the.initialDataHasBeenLoaded {
guard let index = the.feedContents.index(where: { (f) -> Bool in
f.key == snapshot.key
}) else {
return
}
let value = snapshot.value as! Dictionary<String, AnyObject> // 2
// print("Edit\(value)")
let feedContent = FeedContent(snapshot:snapshot)
// update main variable
if let i = the.feedContents.index(where: { $0.key == feedContent.key }) {
the.feedContents[i] = feedContent
}
the.delegate?.didFinishUpdate(indexPath: IndexPath(item: index, section: 0), feedContent: feedContent)
}
}, withCancel: nil)
self.observingOnStorageAdd()
}
func observingOnStorageAdd() {
firebaseAPI.storageRef.observe(.childAdded, with: {[weak self] (snapshot) in
guard let the = self else {
return
}
if the.initialDataHasBeenLoaded {
let feedContent = FeedContent(snapshot:snapshot)
let repeatedModel = the.feedContents.filter({ (f) -> Bool in
f.key == feedContent.key
})
if repeatedModel.count == 0
&&
(self?.timeAgo24Hr( Date(timeIntervalSince1970: TimeInterval(feedContent.postDttmInt)) , currentDate: Date()) == false)
{
the.feedContents.append(feedContent)
// sort date time
// the.feedContents.sort { $0.postDttmInt > $1.postDttmInt }
the.delegate?.didAppendData(indexPath: IndexPath(item: the.feedContents.count - 1 , section: 0) , feedContent: feedContent)
}
}
})
}
deinit {
print("deinit In ViewModel")
}
func timeAgo24Hr(_ date:Date,currentDate:Date) -> Bool {
let calendar = Calendar.current
let now = currentDate
let earliest = (now as NSDate).earlierDate(date)
let latest = (earliest == now) ? date : now
let components:DateComponents = (calendar as NSCalendar).components([NSCalendar.Unit.minute , NSCalendar.Unit.hour , NSCalendar.Unit.day , NSCalendar.Unit.weekOfYear , NSCalendar.Unit.month , NSCalendar.Unit.year , NSCalendar.Unit.second], from: earliest, to: latest, options: NSCalendar.Options())
if (components.year! >= 2) {
return true
} else if (components.year! >= 1){
return true
} else if (components.month! >= 2) {
return true
} else if (components.month! >= 1){
return true
} else if (components.weekOfYear! >= 2) {
return true
} else if (components.weekOfYear! >= 1){
return true
} else if (components.day! >= 2) {
return true
} else if (components.day! >= 1){
return false
} else if (components.hour! >= 2) {
return false
} else if (components.hour! >= 1){
return false
} else if (components.minute! >= 2) {
return false
} else if (components.minute! >= 1){
return false
} else if (components.second! >= 3) {
return false
} else {
return false
}
}
}
| mit | 640690d98f773380c8bdbcd6589fffbe | 39.725926 | 306 | 0.54729 | 4.715266 | false | false | false | false |
yagiz/Bagel | mac/Bagel/Components/Packets/Cells/StatusPacketTableCellView.swift | 1 | 1344 | //
// StatusPacketTableCellView.swift
// Bagel
//
// Created by Yagiz Gurgul on 1.10.2018.
// Copyright © 2018 Yagiz Lab. All rights reserved.
//
import Cocoa
import macOSThemeKit
class StatusPacketTableCellView: NSTableCellView {
@IBOutlet weak var titleTextField: NSTextField!
var packet: BagelPacket!
{
didSet
{
self.refresh()
}
}
func refresh() {
var titleTextColor = NSColor.black
if let statusCodeInt = self.packet.requestInfo?.statusCode {
if let statusCodeInt = Int(statusCodeInt) {
if statusCodeInt >= 200 && statusCodeInt < 300 {
titleTextColor = ThemeColor.statusGreenColor
}else if statusCodeInt >= 300 && statusCodeInt < 400 {
titleTextColor = ThemeColor.statusOrangeColor
}else if statusCodeInt >= 400 {
titleTextColor = ThemeColor.statusRedColor
}
}
}
self.titleTextField.textColor = titleTextColor
self.titleTextField.stringValue = self.packet.requestInfo?.statusCode ?? ""
}
}
| apache-2.0 | 866c6184e6a7708fd96e945b523022ba | 24.826923 | 83 | 0.51452 | 5.864629 | false | false | false | false |
superk589/DereGuide | DereGuide/Model/CGSSGameResource.swift | 2 | 36897 | //
// CGSSGameResource.swift
// DereGuide
//
// Created by zzk on 2016/9/13.
// Copyright © 2016 zzk. All rights reserved.
//
import UIKit
import FMDB
import SwiftyJSON
typealias FMDBCallBackClosure<T> = (T) -> Void
typealias FMDBWrapperClosure = (FMDatabase) throws -> Void
extension FMDatabaseQueue {
func execute(_ task: @escaping FMDBWrapperClosure, completion:
(() -> Void)? = nil) {
inDatabase { (db) in
defer {
db.close()
}
do {
if db.open(withFlags: SQLITE_OPEN_READONLY) {
try task(db)
}
} catch {
print(db.lastErrorMessage())
}
completion?()
}
}
}
class MusicScoreDBQueue: FMDatabaseQueue {
func getBeatmaps(callback: @escaping FMDBCallBackClosure<[CGSSBeatmap]>) {
var beatmaps = [CGSSBeatmap]()
execute({ (db) in
let selectSql = "select * from blobs order by name asc"
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
if let data = set.data(forColumn: "data"),
let name = set.string(forColumn: "name"),
let number = name.match(pattern: "_([0-9]+).csv", index: 1).first,
let rawDifficulty = Int(number),
let beatmap = CGSSBeatmap.init(data: data, rawDifficulty: rawDifficulty) {
beatmaps.append(beatmap)
}
}
}) {
callback(beatmaps)
}
}
func getBeatmapCount(callback: @escaping FMDBCallBackClosure<Int>) {
var result = 0
execute({ (db) in
let selectSql = "select * from blobs order by name asc"
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
if let name = set.string(forColumn: "name"),
let _ = name.match(pattern: "_([0-9]+).csv", index: 1).first {
result += 1
}
}
}) {
callback(result)
}
}
func validateBeatmapCount(_ beatmapCount: Int, callback: @escaping FMDBCallBackClosure<Bool>) {
getBeatmapCount { (count) in
callback(beatmapCount == count)
}
}
}
class Master: FMDatabaseQueue {
func getEventAvailableList(callback: @escaping FMDBCallBackClosure<[Int]>) {
var list = [Int]()
execute({ (db) in
let selectSql = "select reward_id from event_available"
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
let rewardId = set.int(forColumnIndex: 0)
list.append(Int(rewardId))
}
// snow wings 两张活动卡数据库中遗失 做特殊处理
list.append(200129)
list.append(300135)
// trust me 卡片问题
list.append(300593)
list.append(300595)
list.removeAll { $0 == 300583 }
list.removeAll { $0 == 300585 }
// LIVE Carnival rewards are not in event_available table,
// needs special handling
var name = ""
let liveSQL = """
select b.name
from (
select *, rank() over (order by sort) as rank
from live_data
where event_type = 7
) a
left join music_data b on a.music_data_id = b.id
where rank in (
select rank
from (
select *, rank() over (order by event_start) as rank
from event_data where type = 7
)
)
"""
let subSet3 = try db.executeQuery(liveSQL, values: nil)
while subSet3.next() {
name = String(subSet3.string(forColumn: "name") ?? "")
break
}
if name != "" {
let rewardSql = """
select id as reward_id
from card_data
where name like '%\(name)%' and rarity = 5
"""
let subSet4 = try db.executeQuery(rewardSql, values: nil)
while subSet4.next() {
list.append(Int(subSet4.int(forColumn: "reward_id")))
}
}
}) {
callback(list)
}
}
func getGachaAvailableList(callback: @escaping FMDBCallBackClosure<[Int]>) {
var list = [Int]()
execute({ (db) in
let selectSql = "select reward_id from gacha_data a, gacha_available b where a.id = b.gacha_id and a.dicription not like '%限定%' UNION select card_id reward_id from gacha_data a, gacha_available_2 b where a.id = b.gacha_id and a.dicription not like '%限定%'"
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
let rewardId = set.int(forColumnIndex: 0)
list.append(Int(rewardId))
}
}) {
callback(list)
}
}
func getTimeLimitAvailableList(callback: @escaping FMDBCallBackClosure<[Int]>) {
var list = [Int]()
execute({ (db) in
let selectSql = "select reward_id from gacha_data a, gacha_available b where a.id = b.gacha_id and a.dicription like '%期間限定%' and recommend_order > 0 UNION select card_id reward_id from gacha_data a, gacha_available_2 b where a.id = b.gacha_id and a.dicription like '%期間限定%' and recommend_order > 0"
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
let rewardId = set.int(forColumnIndex: 0)
list.append(Int(rewardId))
}
}) {
callback(list)
}
}
func getFesAvailableList(callback: @escaping FMDBCallBackClosure<[Int]>) {
var list = [Int]()
execute({ (db) in
let selectSql = "select reward_id from gacha_data a, gacha_available b where a.id = b.gacha_id and a.dicription like '%フェス限定%' and recommend_order > 0 UNION select card_id reward_id from gacha_data a, gacha_available_2 b where a.id = b.gacha_id and a.dicription like '%フェス限定%' and recommend_order > 0"
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
let rewardId = set.int(forColumnIndex: 0)
list.append(Int(rewardId))
}
}) {
callback(list)
}
}
func getValidGacha(callback: @escaping FMDBCallBackClosure<[CGSSGacha]>) {
var list = [CGSSGacha]()
execute({ (db) in
let selectSql = "select a.id, a.name, a.dicription, a.start_date, a.end_date, b.rare_ratio, b.sr_ratio, b.ssr_ratio from gacha_data a, gacha_rate b where a.id = b.id and ( a.id like '3%' or a.id like '6%' ) order by end_date DESC"
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
let endDate = set.string(forColumn: "end_date")
let id = Int(set.int(forColumn: "id"))
let name = set.string(forColumn: "name")
let dicription = set.string(forColumn: "dicription")
let startDate = set.string(forColumn: "start_date")
if let startDate = startDate?.toDate(), id >= 60000, startDate > Date() {
continue
}
let rareRatio = Int(set.int(forColumn: "rare_ratio"))
let srRatio = Int(set.int(forColumn: "sr_ratio"))
let ssrRatio = Int(set.int(forColumn: "ssr_ratio"))
let rewardSql = "select reward_id, recommend_order from gacha_available where gacha_id = \(id) UNION select card_id reward_id, recommend_order from gacha_available_2 where gacha_id = \(id)"
var rewards = [Reward]()
let subSet = try db.executeQuery(rewardSql, values: nil)
while subSet.next() {
let rewardId = Int(subSet.int(forColumn: "reward_id"))
let recommendOrder = Int(subSet.int(forColumn: "recommend_order"))
rewards.append(Reward(cardId: rewardId, recommandOrder: recommendOrder, relativeOdds: 0, relativeSROdds: 0))
}
let gachaPool = CGSSGacha(id: id, name: name!, dicription: dicription!, startDate: startDate!, endDate: endDate!, rareRatio: rareRatio, srRatio: srRatio, ssrRatio: ssrRatio, rewards: rewards)
list.append(gachaPool)
}
}) {
callback(list)
}
}
func getChara(charaId: Int? = nil, callback: @escaping FMDBCallBackClosure<[CGSSChar]>) {
var result = [CGSSChar]()
execute({ (db) in
let selectSql = "select * from chara_data\(charaId == nil ? "" : " where chara_id = \(charaId!)")"
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
if let data = try? JSONSerialization.data(withJSONObject: set.resultDictionary ?? [], options: []) {
let chara = CGSSChar.init(fromJson: JSON(data))
result.append(chara)
}
}
}) {
callback(result)
}
}
func getTextBy(category: Int, index: Int, callback: @escaping FMDBCallBackClosure<String>) {
var result = ""
execute({ (db) in
let selectSql = "select * from text_data where category = \(category) and \"index\" = \(index)"
let set = try db.executeQuery(selectSql, values: nil)
if set.next() {
result = set.string(forColumn: "text") ?? ""
}
}) {
callback(result)
}
}
func getEvents(callback: @escaping FMDBCallBackClosure<[CGSSEvent]>) {
var list = [CGSSEvent]()
execute({ (db) in
let selectSql = "select * from event_data order by event_start asc"
var count = 0
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
count += 1
let sortId = count > 16 ? count + 2 : count + 1
let id = Int(set.int(forColumn: "id"))
let type = Int(set.int(forColumn: "type"))
let name = set.string(forColumn: "name")
let startDate = set.string(forColumn: "event_start")
let endDate = set.string(forColumn: "event_end")
let secondHalfStartDate = set.string(forColumn: "second_half_start")
var rewards = [Reward]()
if type != 7 {
// Get cards that are available as event rewards only
// i.e. remove N cards from event rewards list
let rewardSql = """
select a.*
from event_available a
left join card_data b on a.reward_id = b.id
where b.rarity >= 5 and a.event_id = \(id)
"""
let subSet = try db.executeQuery(rewardSql, values: nil)
while subSet.next() {
var rewardId = Int(subSet.int(forColumn: "reward_id"))
if rewardId == 300583 {
rewardId = 300593
}
if rewardId == 300585 {
rewardId = 300595
}
let recommendOrder = Int(subSet.int(forColumn: "recommend_order"))
let reward = Reward.init(cardId: rewardId, recommandOrder: recommendOrder, relativeOdds: 0, relativeSROdds: 0)
rewards.append(reward)
}
} else {
var name = ""
let liveSQL = """
select b.name
from (
select *, rank() over (order by sort) as rank
from live_data
where event_type = 7
) a
left join music_data b on a.music_data_id = b.id
where rank in (
select rank
from (
select *, rank() over (order by event_start) as rank
from event_data where type = 7
)
where id = \(id)
)
order by a.id asc
limit 1;
"""
let subSet3 = try db.executeQuery(liveSQL, values: nil)
while subSet3.next() {
name = String(subSet3.string(forColumn: "name") ?? "")
break
}
if name != "" {
let rewardSql = """
select id as reward_id, rank() over (order by disp_order asc) as recommend_order
from card_data
where name like '%\(name)%' and rarity = 5
"""
let subSet4 = try db.executeQuery(rewardSql, values: nil)
while subSet4.next() {
let rewardId = Int(subSet4.int(forColumn: "reward_id"))
let recommendOrder = Int(subSet4.int(forColumn: "recommend_order"))
let reward = Reward.init(cardId: rewardId, recommandOrder: recommendOrder, relativeOdds: 0, relativeSROdds: 0)
rewards.append(reward)
}
}
}
var liveId: Int = 0
let liveSql = """
select *
from (
select *, rank() over (order by sort) as rank
from live_data
where event_type = \(type)
)
where rank in (
select rank
from (
select *, rank() over (order by event_start) as rank
from event_data where type = \(type)
)
where id = \(id)
)
order by id asc
limit 1;
"""
let subSet2 = try db.executeQuery(liveSql, values: nil)
while subSet2.next() {
liveId = Int(subSet2.int(forColumn: "id"))
break
}
var ptBorders = [Int]()
if type == 1 {
let sql = "select rank_min from atapon_point_rank_disp where event_id = \(id) limit 6"
let set = try db.executeQuery(sql, values: nil)
while set.next() {
ptBorders.append(Int(set.int(forColumn: "rank_min")))
}
} else if type == 3 {
let sql = "select rank_min from medley_point_rank_disp where event_id = \(id) limit 6"
let set = try db.executeQuery(sql, values: nil)
while set.next() {
ptBorders.append(Int(set.int(forColumn: "rank_min")))
}
}
var scoreBorders = [Int]()
scoreBorders.append(1)
if type == 1 {
let sql = "select rank_max from atapon_score_rank_disp where event_id = \(id)"
let set = try db.executeQuery(sql, values: nil)
while set.next() {
scoreBorders.append(Int(set.int(forColumn: "rank_max")) + 1)
}
} else if type == 3 {
let sql = "select rank_max from medley_score_rank_disp where event_id = \(id)"
let set = try db.executeQuery(sql, values: nil)
while set.next() {
scoreBorders.append(Int(set.int(forColumn: "rank_max")) + 1)
}
} else if type == 5 {
let sql = "select rank_max from tour_score_rank_disp where event_id = \(id)"
let set = try db.executeQuery(sql, values: nil)
while set.next() {
scoreBorders.append(Int(set.int(forColumn: "rank_max")) + 1)
}
}
let event = CGSSEvent(sortId: sortId, id: id, type: type, startDate: startDate!, endDate: endDate!, name: name!, secondHalfStartDate: secondHalfStartDate!, reward: rewards, liveId: liveId, ptBorders: ptBorders, scoreBorders: scoreBorders)
list.append(event)
}
}) {
callback(list)
}
}
func getMusicInfo(musicDataID: Int? = nil, callback: @escaping FMDBCallBackClosure<[CGSSSong]>) {
var list = [CGSSSong]()
execute({ (db) in
let selectSql = """
SELECT
b.id,
max( a.id ) live_id,
min( a.id ) normal_live_id,
max( a.type ) type,
max( a.event_type ) event_type,
min( a.start_date ) start_date,
d.discription,
b.bpm,
b.name,
b.composer,
b.lyricist,
b.name_sort,
c.chara_position_1,
c.chara_position_2,
c.chara_position_3,
c.chara_position_4,
c.chara_position_5,
c.position_num
FROM
live_data a,
music_data b,
music_info d
LEFT OUTER JOIN live_data_position c ON a.id = c.live_data_id
WHERE
a.music_data_id = b.id
AND b.id = d.id
\(musicDataID == nil ? "" : "AND a.music_data_id = \(musicDataID!)")
GROUP BY
b.id
"""
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
let json = JSON(set.resultDictionary ?? [AnyHashable: Any]())
guard let song = CGSSSong(fromJson: json) else { continue }
// 去掉一些无效数据
if song.detail == "?" { continue }
if [1901, 1902, 90001].contains(song.musicID) { continue }
// some of the event songs have a start date at the end of the event, so add 30 days
if song.startDate > Date().addingTimeInterval(30 * 24 * 3600) && musicDataID == nil { continue }
list.append(song)
}
}) {
callback(list)
}
}
func getMusicInfo(charaID: Int, callback: @escaping FMDBCallBackClosure<[CGSSSong]>) {
var list = [CGSSSong]()
execute({ (db) in
let selectSql = """
SELECT
b.id,
max( a.id ) live_id,
min( a.id ) normal_live_id,
max( a.type ) type,
max( a.event_type ) event_type,
min( a.start_date ) start_date,
d.discription,
b.bpm,
b.name,
b.composer,
b.lyricist,
b.name_sort,
c.chara_position_1,
c.chara_position_2,
c.chara_position_3,
c.chara_position_4,
c.chara_position_5,
c.position_num
FROM
live_data a,
music_data b,
music_info d
LEFT OUTER JOIN live_data_position c ON a.id = c.live_data_id
WHERE
a.music_data_id = b.id
AND b.id = d.id
AND (c.chara_position_1 == \(charaID)
OR c.chara_position_2 == \(charaID)
OR c.chara_position_3 == \(charaID)
OR c.chara_position_4 == \(charaID)
OR c.chara_position_5 == \(charaID))
GROUP BY
b.id
"""
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
let json = JSON(set.resultDictionary ?? [AnyHashable: Any]())
guard let song = CGSSSong(fromJson: json) else { continue }
// 去掉一些无效数据
if song.detail == "?" { continue }
if [1901, 1902, 90001].contains(song.musicID) { continue }
list.append(song)
}
}) {
callback(list)
}
}
func getLiveTrend(eventId: Int, callback: @escaping FMDBCallBackClosure<[EventTrend]>) {
var list = [EventTrend]()
execute({ (db) in
let selectSql = "select * from tour_trend_live where event_id = \(eventId)"
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
let json = JSON(set.resultDictionary ?? [AnyHashable: Any]())
let trend = EventTrend.init(fromJson: json)
list.append(trend)
}
}) {
callback(list)
}
}
func getLives(liveId: Int? = nil, callback: @escaping FMDBCallBackClosure<[CGSSLive]>) {
var list = [CGSSLive]()
execute({ (db) in
let selectSql = """
SELECT
a.id,
a.event_type,
a.music_data_id,
a.start_date,
a.type,
b.bpm,
b.name_kana,
b.name
FROM
live_data a,
music_data b
WHERE
a.music_data_id = b.id
\(liveId == nil ? "" : "AND a.id = \(liveId!)")
"""
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
let json = JSON(set.resultDictionary ?? [AnyHashable: Any]())
guard let live = CGSSLive(fromJson: json) else { continue }
// not valid if count == 0
if live.beatmapCount == 0 { continue }
// 去掉一些无效数据
// 1901 - 2016-4-1 special live
// 1902 - 2017-4-1 special live
// 1903 - 2018-4-1 special live
// 90001 - DJ Pinya live
if (1900..<2000) ~= live.musicDataId || (90000..<100000) ~= live.musicDataId { continue }
let selectSql = """
SELECT
a.id,
a.live_data_id,
a.difficulty_type,
a.level_vocal stars_number,
b.notes_number,
a.rank_s_condition
FROM
live_detail a
LEFT OUTER JOIN live_notes_number b ON a.live_data_id = b.live_id
AND b.difficulty = a.difficulty_type
WHERE
a.live_data_id = \(live.id)
ORDER BY
a.difficulty_type ASC
"""
var details = [CGSSLiveDetail]()
let subSet = try db.executeQuery(selectSql, values: nil)
var count = 0
while subSet.next() && count < live.beatmapCount {
count += 1
let json = JSON(subSet.resultDictionary ?? [AnyHashable: Any]())
guard let detail = CGSSLiveDetail(fromJson: json) else { continue }
if detail.difficulty == .masterPlus { count -= 1 }
details.append(detail)
}
if details.count == 0 { continue }
live.details = details
if let anotherLive = list.first(where: { $0.musicDataId == live.musicDataId }) {
anotherLive.merge(anotherLive: live)
} else {
list.append(live)
}
}
}) {
callback(list)
}
}
// func getLiveDetails(liveID: Int, callback: @escaping FMDBCallBackClosure<[CGSSLiveDetail]>) {
// var list = [CGSSLiveDetail]()
// execute({ (db) in
// let selectSql = """
// SELECT
// a.live_data_id,
// a.difficulty_type,
// a.level_vocal stars_number,
// b.notes_number
// FROM
// live_detail a,
// live_notes_number b
// WHERE
// a.live_data_id = \(liveID)
// AND b.difficulty = a.difficulty_type
// AND b.live_id = a.live_data_id
// """
//
// let set = try db.executeQuery(selectSql, values: nil)
// while set.next() {
// let json = JSON(set.resultDictionary ?? [AnyHashable: Any]())
//
// guard let detail = CGSSLiveDetail(fromJson: json) else { continue }
//
// list.append(detail)
// }
// }) {
// callback(list)
// }
// }
func getVocalistsBy(musicDataId: Int, callback: @escaping FMDBCallBackClosure<[Int]>) {
var list = [Int]()
execute({ (db) in
let selectSql = "select chara_id from music_vocalist where a.id = \(musicDataId)"
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
let vocalist = Int(set.int(forColumn: "chara_id"))
list.append(vocalist)
}
}) {
callback(list)
}
}
func getGuaranteedCardIds(gacha: CGSSGacha, callback: @escaping FMDBCallBackClosure<[Int]>) {
var list = [Int]()
execute({ (db) in
let selectSql = "select reward_id from gacha_l_e_list a, gacha_l_group b where a.g_id = b.id and b.start_date <= '\(gacha.startDate)' and b.end_date >= '\(gacha.endDate)'"
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
let id = Int(set.int(forColumn: "reward_id"))
list.append(id)
}
}) {
callback(list)
}
}
func getCardsAvailableDate(callback: @escaping FMDBCallBackClosure<[Int: String]>) {
var dict = [Int: String]()
execute({ (db) in
let selectSql = """
SELECT
a.id,
min(c.start_date) gacha_date,
min(e.event_start) event_date
FROM
card_data a
LEFT JOIN (
SELECT
reward_id,
gacha_id
FROM
gacha_available
UNION
SELECT
card_id reward_id,
gacha_id
FROM
gacha_available_2) b ON a.id = b.reward_id
LEFT JOIN gacha_data c ON b.gacha_id = c.id
LEFT JOIN event_available d ON a.id = d.reward_id
LEFT JOIN event_data e ON d.event_id = e.id
GROUP BY
a.id
"""
let set = try db.executeQuery(selectSql, values: nil)
while set.next() {
let id = Int(set.int(forColumn: "id"))
if let dateString = set.string(forColumn: "event_date") ?? set.string(forColumn: "gacha_date") {
dict[id] = dateString
}
}
}) {
callback(dict)
}
}
}
class Manifest: FMDatabase {
func selectByName(_ string: String) -> [String] {
let selectSql = "select * from manifests where name = \"\(string)\""
var hashTable = [String]()
do {
let set = try self.executeQuery(selectSql, values: nil)
while set.next() {
hashTable.append(set.string(forColumn: "hash") ?? "")
}
} catch {
print(self.lastErrorMessage())
}
return hashTable
}
func getMusicScores() -> [String: String] {
let selectSql = "select * from manifests where name like \"musicscores_m%.bdb\""
var hashTable = [String: String]()
do {
let set = try self.executeQuery(selectSql, values: nil)
while set.next() {
if let name = set.string(forColumn: "name")?.match(pattern: "m([0-9]*)\\.", index: 1).first {
let hash = set.string(forColumn: "hash") ?? ""
// 去除一些无效数据
if ["901", "000"].contains(name) { continue }
hashTable[name] = hash
}
}
}
catch {
print(self.lastErrorMessage())
}
return hashTable
}
}
class CGSSGameResource: NSObject {
static let shared = CGSSGameResource()
static let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! + "/GameResource"
static let masterPath = path + "/master.db"
static let manifestPath = path + "/manifest.db"
lazy var master: Master = {
let dbQueue = Master(path: CGSSGameResource.masterPath)!
return dbQueue
}()
lazy var manifest: Manifest = {
let db = Manifest(path: CGSSGameResource.manifestPath)
return db
}()
fileprivate override init() {
super.init()
self.prepareFileDirectory()
self.prepareGachaList(callback: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func prepareFileDirectory() {
if !FileManager.default.fileExists(atPath: CGSSGameResource.path) {
do {
try FileManager.default.createDirectory(atPath: CGSSGameResource.path, withIntermediateDirectories: true, attributes: nil)
} catch {
// print(error)
}
}
}
func saveManifest(_ data: Data) {
prepareFileDirectory()
try? data.write(to: URL(fileURLWithPath: CGSSGameResource.manifestPath), options: [.atomic])
}
func saveMaster(_ data: Data) {
prepareFileDirectory()
try? data.write(to: URL(fileURLWithPath: CGSSGameResource.masterPath), options: [.atomic])
}
func checkMasterExistence() -> Bool {
let fm = FileManager.default
return fm.fileExists(atPath: CGSSGameResource.masterPath) && (NSData.init(contentsOfFile: CGSSGameResource.masterPath)?.length ?? 0) > 0
}
func checkManifestExistence() -> Bool {
let fm = FileManager.default
return fm.fileExists(atPath: CGSSGameResource.manifestPath) && (NSData.init(contentsOfFile: CGSSGameResource.manifestPath)?.length ?? 0) > 0
}
func getMasterHash() -> String? {
guard manifest.open(withFlags: SQLITE_OPEN_READONLY) else {
return nil
}
defer {
manifest.close()
}
return manifest.selectByName("master.mdb").first
}
func getScoreHash() -> [String: String] {
guard manifest.open(withFlags: SQLITE_OPEN_READONLY) else {
return [String: String]()
}
defer {
manifest.close()
}
return manifest.getMusicScores()
}
func getBeatmaps(liveId: Int) -> [CGSSBeatmap]? {
let path = String.init(format: DataPath.beatmap, liveId)
let fm = FileManager.default
var result: [CGSSBeatmap]?
let semaphore = DispatchSemaphore.init(value: 0)
if fm.fileExists(atPath: path), let dbQueue = MusicScoreDBQueue(path: path) {
dbQueue.getBeatmaps(callback: { (beatmaps) in
result = beatmaps
semaphore.signal()
})
} else {
semaphore.signal()
}
semaphore.wait()
return result
}
func getBeatmapCount(liveId: Int) -> Int {
let semaphore = DispatchSemaphore.init(value: 0)
var result = 0
let path = String.init(format: DataPath.beatmap, liveId)
let fm = FileManager.default
if fm.fileExists(atPath: path), let dbQueue = MusicScoreDBQueue(path: path) {
dbQueue.getBeatmapCount(callback: { (count) in
result = count
semaphore.signal()
})
} else {
semaphore.signal()
}
semaphore.wait()
return result
}
func checkExistenceOfBeatmap(liveId: Int) -> Bool {
let path = String.init(format: DataPath.beatmap, liveId)
let fm = FileManager.default
return fm.fileExists(atPath: path)
}
var isProcessing = false
func processDownloadedData(types: CGSSUpdateDataTypes, completion: (() -> ())?) {
let group = DispatchGroup()
isProcessing = true
if types.contains(.master) || types.contains(.card) {
group.enter()
prepareGachaList {
let list = CGSSDAO.shared.cardDict.allValues as! [CGSSCard]
for item in list {
if self.gachaAvailabelList.contains(item.seriesId) { item.availableType = .normal }
else if self.fesAvailabelList.contains(item.seriesId) { item.availableType = .fes }
else if self.timeLimitAvailableList.contains(item.seriesId) { item.availableType = .limit }
else if self.eventAvailabelList.contains(item.seriesId) { item.availableType = .event }
else { item.availableType = .free }
}
group.leave()
}
group.enter()
master.getCardsAvailableDate(callback: { (dict) in
for (id, value) in dict {
let card = CGSSDAO.shared.cardDict.object(forKey: String(id)) as? CGSSCard
card?.firstAvailableAt = value.toDate()
let evolutedCard = CGSSDAO.shared.cardDict.object(forKey: String(id + 1)) as? CGSSCard
evolutedCard?.firstAvailableAt = value.toDate()
}
group.leave()
})
}
group.notify(queue: .main, execute: {
completion?()
self.isProcessing = false
NotificationCenter.default.post(name: .gameResoureceProcessedEnd, object: nil)
})
}
// MARK: 卡池数据部分
var eventAvailabelList = [Int]()
var gachaAvailabelList = [Int]()
var timeLimitAvailableList = [Int]()
var fesAvailabelList = [Int]()
func prepareGachaList(callback: (() -> Void)?) {
let group = DispatchGroup.init()
group.enter()
master.getEventAvailableList { (result) in
self.eventAvailabelList = result
group.leave()
}
group.enter()
master.getGachaAvailableList { (result) in
self.gachaAvailabelList = result
group.leave()
}
group.enter()
master.getTimeLimitAvailableList { (result) in
self.timeLimitAvailableList = result
group.leave()
}
group.enter()
master.getFesAvailableList { (result) in
self.fesAvailabelList = result
group.leave()
}
group.notify(queue: DispatchQueue.global(qos: .userInitiated), work: DispatchWorkItem.init(block: {
callback?()
}))
}
}
| mit | 8692985241629a1f1f5156d7fd5ce101 | 38.159915 | 313 | 0.479228 | 4.539859 | false | false | false | false |
samodom/TestableMapKit | TestableMapKitTests/Tests/MutableMKRouteTests.swift | 1 | 2863 | //
// MutableMKRouteTests.swift
// TestableMapKit
//
// Created by Sam Odom on 12/26/14.
// Copyright (c) 2014 Swagger Soft. All rights reserved.
//
import MapKit
import XCTest
class MutableMKRouteTests: XCTestCase {
var route = MKRoute()
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testMutablePolyline() {
XCTAssertNil(route.polyline, "The polyline should be missing by default")
var coordinates =
[CLLocationCoordinate2D(latitude: 24.0, longitude: -24.0),
CLLocationCoordinate2D(latitude: 24.1, longitude: -24.1)]
let polyline = MKPolyline(coordinates: &coordinates, count: 2)
route.polyline = polyline
XCTAssertEqual(route.polyline, polyline, "The route should allow mutation of its polyline property")
}
func testMutableSteps() {
XCTAssertNil(route.steps, "The steps should be missing by default")
let steps = [MKRouteStep(), MKRouteStep(), MKRouteStep()]
route.steps = steps
XCTAssertEqual(route.steps as [MKRouteStep], steps, "The route should allow mutation of its steps property")
}
func testMutableName() {
XCTAssertNil(route.name, "The name should be missing by default")
route.name = "Sample Route"
XCTAssertEqual(route.name, "Sample Route", "The route should allow mutation of its name property")
}
func testMutableAdvisoryNotices() {
XCTAssertNil(route.advisoryNotices, "The advisory notices should be missing by default")
let notices = ["alpha", "bravo", "charlie"]
route.advisoryNotices = notices
XCTAssertEqual(route.advisoryNotices as [String], notices, "The route should allow mutation of its advisoryNotices property")
}
func testMutableDistance() {
XCTAssertEqual(route.distance, CLLocationDistance(0.0), "The distance should be zero by default")
route.distance = 14.42
XCTAssertEqual(route.distance, CLLocationDistance(14.42), "The route should allow mutation of its distance property")
}
func testMutableExpectedTravelTime() {
XCTAssertEqual(route.expectedTravelTime, NSTimeInterval(0.0), "The expected travel time should be zero by default")
route.expectedTravelTime = NSTimeInterval(14.42)
XCTAssertEqual(route.expectedTravelTime, NSTimeInterval(14.42), "The route should allow mutation of its expectedTravelTime property")
}
func testMutableTransportType() {
XCTAssertEqual(route.transportType, MKDirectionsTransportType.Automobile, "The transport type should be automobile by default")
route.transportType = .Walking
XCTAssertEqual(route.transportType, MKDirectionsTransportType.Walking, "The route should allow mutation of its transportType property")
}
}
| mit | 7d8a46aef1c744f67ca4247c1344882a | 38.763889 | 143 | 0.699616 | 4.632686 | false | true | false | false |
giangbvnbgit128/AnViet | AnViet/Class/Helpers/Extensions/NSUserDefaults.swift | 1 | 4415 | //
// NSUserDefaults.swift
// Koshien
//
// Created by HoaNV-iMac on 4/5/16.
// Copyright © 2016 Khoi Nguyen Nguyen. All rights reserved.
//
import Foundation
public let UserDefaults = Foundation.UserDefaults.standard
open class UserDefaultKeys {
fileprivate init() {}
}
open class Key<ValueType>: UserDefaultKeys {
open let name: String
public init(name: String) {
self.name = name
}
}
extension Foundation.UserDefaults {
class Result {
fileprivate let defaults: Foundation.UserDefaults
fileprivate let key: String
fileprivate init(defaults: Foundation.UserDefaults, key: String) {
self.defaults = defaults
self.key = key
}
// MARK: Getters
var object: AnyObject? { return defaults.object(forKey: key) as AnyObject? }
var string: String? { return defaults.string(forKey: key) }
var array: [AnyObject]? { return defaults.array(forKey: key) as [AnyObject]? }
var dictionary: [String : AnyObject]? { return defaults.dictionary(forKey: key) as [String : AnyObject]? }
var data: Data? { return defaults.data(forKey: key) }
var date: Date? { return object as? Date }
var integer: Int { return defaults.integer(forKey: key) }
var double: Double { return defaults.double(forKey: key) }
var bool: Bool { return defaults.bool(forKey: key) }
var float: Float { return defaults.float(forKey: key) }
}
@nonobjc subscript(key: String) -> Result {
return Result(defaults: self, key: key)
}
@nonobjc subscript(key: String) -> Any? {
get {
let result: Result = self[key]
return result
}
set {
switch newValue {
case let v as Int: set(v, forKey: key)
case let v as Double: set(v, forKey: key)
case let v as Bool: set(v, forKey: key)
case let v as Float: set(v, forKey: key)
case let v as URL: set(v, forKey: key)
case let v as NSObject: set(v, forKey: key)
case nil: removeObject(forKey: key)
default: assertionFailure("Invalid value type")
}
UserDefaults.synchronize()
}
}
public func setValue<T>(_ value: Any?, key: Key<T>) {
self[key.name] = value
}
public func hasKey<T>(_ key: Key<T>) -> Bool {
return object(forKey: key.name) != nil
}
public func removeValueForKey<T>(_ key: Key<T>) {
removeObject(forKey: key.name)
}
subscript(key: Key<String>) -> String? {
get {
return string(forKey: key.name)
}
set { setValue(newValue, key: key) }
}
subscript(key: Key<Bool>) -> Bool {
get { return bool(forKey: key.name) }
set { setValue(newValue, key: key) }
}
subscript(key: Key<Int>) -> Int {
get { return integer(forKey: key.name) }
set { setValue(newValue, key: key) }
}
subscript(key: Key<Double>) -> Double {
get { return double(forKey: key.name) }
set { setValue(newValue, key: key) }
}
subscript(key: Key<Float>) -> Float {
get { return float(forKey: key.name) }
set { setValue(newValue, key: key) }
}
subscript(key: Key<AnyObject>) -> AnyObject? {
get { return object(forKey: key.name) as AnyObject? }
set { setValue(newValue, key: key) }
}
subscript(key: Key<[String]>) -> [String]? {
get { return stringArray(forKey: key.name) }
set { setValue(newValue, key: key) }
}
subscript(key: Key<[AnyObject]>) -> [AnyObject]? {
get { return array(forKey: key.name) as [AnyObject]? }
set { setValue(newValue, key: key) }
}
subscript(key: Key<[String: AnyObject]>) -> [String: AnyObject]? {
get { return dictionary(forKey: key.name) as [String : AnyObject]? }
set { setValue(newValue, key: key) }
}
subscript(key: Key<Date>) -> Date? {
get { return object(forKey: key.name) as? Date }
set { setValue(newValue, key: key) }
}
subscript(key: Key<URL>) -> URL? {
get { return url(forKey: key.name) }
set { setValue(newValue, key: key) }
}
subscript(key: Key<Data>) -> Data? {
get { return data(forKey: key.name) }
set { setValue(newValue, key: key) }
}
}
| apache-2.0 | cfaf1698e5b2d0758200dbc9ee4b73e3 | 32.439394 | 114 | 0.574536 | 3.916593 | false | false | false | false |
sschiau/swift | stdlib/public/Darwin/Accelerate/vDSP_PolarRectangularConversion.swift | 8 | 8394 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension vDSP {
/// Rectangular to polar conversion, single-precision.
///
/// - Parameter rectangularCoordinates: Source vector, represented as consecutive x, y pairs.
/// - Returns: Polar coordinates, represented as consecutive rho, (radius) theta (angle in radians) pairs.
@inlinable
public static func rectangularToPolar<U>(_ rectangularCoordinates: U) -> [Float]
where
U: AccelerateBuffer,
U.Element == Float {
let result = Array<Float>(unsafeUninitializedCapacity: rectangularCoordinates.count) {
buffer, initializedCount in
convert(rectangularCoordinates: rectangularCoordinates,
toPolarCoordinates: &buffer)
initializedCount = rectangularCoordinates.count
}
return result
}
/// Rectangular to polar conversion, single-precision.
///
/// - Parameter rectangularCoordinates: Source vector, represented as consecutive x, y pairs.
/// - Parameter polarCoordinates: Destination vector, represented as consecutive rho, (radius) theta (angle in radians) pairs.
@inlinable
public static func convert<U, V>(rectangularCoordinates: U,
toPolarCoordinates polarCoordinates: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Float,
V.Element == Float {
let n = rectangularCoordinates.count
precondition(polarCoordinates.count == n)
polarCoordinates.withUnsafeMutableBufferPointer { dest in
rectangularCoordinates.withUnsafeBufferPointer { src in
vDSP_polar(src.baseAddress!, 2,
dest.baseAddress!, 2,
vDSP_Length(n / 2))
}
}
}
/// Rectangular to polar conversion, double-precision.
///
/// - Parameter rectangularCoordinates: Source vector, represented as consecutive x, y pairs.
/// - Returns: Polar coordinates, represented as consecutive rho, (radius) theta (angle in radians) pairs.
@inlinable
public static func rectangularToPolar<U>(_ rectangularCoordinates: U) -> [Double]
where
U: AccelerateBuffer,
U.Element == Double {
let result = Array<Double>(unsafeUninitializedCapacity: rectangularCoordinates.count) {
buffer, initializedCount in
convert(rectangularCoordinates: rectangularCoordinates,
toPolarCoordinates: &buffer)
initializedCount = rectangularCoordinates.count
}
return result
}
/// Rectangular to polar conversion, double-precision.
///
/// - Parameter rectangularCoordinates: Source vector, represented as consecutive x, y pairs.
/// - Parameter polarCoordinates: Destination vector, represented as consecutive rho, (radius) theta (angle in radians) pairs.
@inlinable
public static func convert<U, V>(rectangularCoordinates: U,
toPolarCoordinates polarCoordinates: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Double,
V.Element == Double {
let n = rectangularCoordinates.count
precondition(polarCoordinates.count == n)
polarCoordinates.withUnsafeMutableBufferPointer { dest in
rectangularCoordinates.withUnsafeBufferPointer { src in
vDSP_polarD(src.baseAddress!, 2,
dest.baseAddress!, 2,
vDSP_Length(n / 2))
}
}
}
/// Polar to rectangular conversion, single-precision.
///
/// - Parameter polarCoordinates: Source vector, represented as consecutive rho, (radius) theta (angle in radians) pairs.
/// - Returns: Rectangular coordinates, represented as consecutive x, y pairs.
@inlinable
public static func polarToRectangular<U>(_ polarCoordinates: U) -> [Float]
where
U: AccelerateBuffer,
U.Element == Float {
let result = Array<Float>(unsafeUninitializedCapacity: polarCoordinates.count) {
buffer, initializedCount in
convert(polarCoordinates: polarCoordinates,
toRectangularCoordinates: &buffer)
initializedCount = polarCoordinates.count
}
return result
}
/// Polar to rectangular conversion, single-precision.
///
/// - Parameter polarCoordinates: Source vector, represented as consecutive rho, (radius) theta (angle in radians) pairs.
/// - Parameter rectangularCoordinates: Destination vector, represented as consecutive x, y pairs.
@inlinable
public static func convert<U, V>(polarCoordinates: U,
toRectangularCoordinates rectangularCoordinates: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Float,
V.Element == Float {
let n = rectangularCoordinates.count
precondition(polarCoordinates.count == n)
rectangularCoordinates.withUnsafeMutableBufferPointer { dest in
polarCoordinates.withUnsafeBufferPointer { src in
vDSP_rect(src.baseAddress!, 2,
dest.baseAddress!, 2,
vDSP_Length(n / 2))
}
}
}
/// Polar to rectangular conversion, double-precision.
///
/// - Parameter polarCoordinates: Source vector, represented as consecutive rho, (radius) theta (angle in radians) pairs.
/// - Returns: Rectangular coordinates, represented as consecutive x, y pairs.
@inlinable
public static func polarToRectangular<U>(_ polarCoordinates: U) -> [Double]
where
U: AccelerateBuffer,
U.Element == Double {
let result = Array<Double>(unsafeUninitializedCapacity: polarCoordinates.count) {
buffer, initializedCount in
convert(polarCoordinates: polarCoordinates,
toRectangularCoordinates: &buffer)
initializedCount = polarCoordinates.count
}
return result
}
/// Polar to rectangular conversion, double-precision.
///
/// - Parameter polarCoordinates: Source vector, represented as consecutive rho, (radius) theta (angle in radians) pairs.
/// - Parameter rectangularCoordinates: Destination vector, represented as consecutive x, y pairs.
@inlinable
public static func convert<U, V>(polarCoordinates: U,
toRectangularCoordinates rectangularCoordinates: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Double,
V.Element == Double {
let n = rectangularCoordinates.count
precondition(polarCoordinates.count == n)
rectangularCoordinates.withUnsafeMutableBufferPointer { dest in
polarCoordinates.withUnsafeBufferPointer { src in
vDSP_rectD(src.baseAddress!, 2,
dest.baseAddress!, 2,
vDSP_Length(n / 2))
}
}
}
}
| apache-2.0 | 3a68df029e5ef1b3ed5d994acc1026ce | 40.349754 | 130 | 0.575768 | 5.894663 | false | false | false | false |
imitationgame/pokemonpassport | pokepass/Model/Settings/MSettings.swift | 1 | 1169 | import Foundation
class MSettings
{
enum Measures:Int16
{
case metric
case imperial
}
static let sharedInstance = MSettings()
private(set) var model:DObjectSettings?
private init()
{
}
//MARK: private
private func createModel()
{
DManager.sharedInstance.createManagedObject(
modelType:DObjectSettings.self)
{ (object:DObjectSettings) in
self.model = object
DManager.sharedInstance.save()
}
}
//MARK: public
func load()
{
if model == nil
{
DManager.sharedInstance.fetchManagedObjects(
modelType:DObjectSettings.self,
limit:1)
{ (objects:[DObjectSettings]?) in
guard
let object:DObjectSettings = objects?.first
else
{
self.createModel()
return
}
self.model = object
}
}
}
}
| mit | db5eda18250c71f428168307ee26cb0a | 19.508772 | 63 | 0.443969 | 5.702439 | false | false | false | false |
FutureKit/FutureKit | FutureKit/Future.swift | 1 | 65943 | //
// Future.swift
// FutureKit
//
// Created by Michael Gray on 4/21/15.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public struct GLOBAL_PARMS {
// WOULD LOVE TO TURN THESE INTO COMPILE TIME PROPERTIES
// MAYBE VIA an Objective C Header file?
static let ALWAYS_ASYNC_DISPATCH_DEFAULT_TASKS = false
static let WRAP_DEPENDENT_BLOCKS_WITH_OBJC_EXCEPTION_HANDLING = false
static let CANCELLATION_CHAINING = true
static let STACK_CHECKING_PROPERTY = "FutureKit.immediate.TaskDepth"
static let CURRENT_EXECUTOR_PROPERTY = "FutureKit.Executor.Current"
static let STACK_CHECKING_MAX_DEPTH:Int32 = 20
static var CONVERT_COMMON_NSERROR_VALUES_TO_CANCELLATIONS = true
public static var LOCKING_STRATEGY : SynchronizationType = .pThreadMutex
}
public enum FutureKitError : Error, Equatable {
case genericError(String)
case resultConversionError(String)
case completionConversionError(String)
case continueWithConversionError(String)
case errorForMultipleErrors(String,[Error])
case exceptionCaught(NSException,[AnyHashable: Any]?)
public init(genericError : String) {
self = .genericError(genericError)
}
public init(exception: NSException) {
var userInfo : [AnyHashable: Any]
if (exception.userInfo != nil) {
userInfo = exception.userInfo!
}
else {
userInfo = [AnyHashable: Any]()
}
userInfo["exception"] = NSException(name: exception.name, reason: exception.reason, userInfo: nil)
userInfo["callStackReturnAddresses"] = exception.callStackReturnAddresses
userInfo["callStackSymbols"] = exception.callStackSymbols
self = .exceptionCaught(exception,userInfo)
}
}
public func == (l: FutureKitError, r: FutureKitError) -> Bool {
switch l {
case let .genericError(lhs):
switch r {
case let .genericError(rhs):
return (lhs == rhs)
default:
return false
}
case let .resultConversionError(lhs):
switch r {
case let .resultConversionError(rhs):
return (lhs == rhs)
default:
return false
}
case let .completionConversionError(lhs):
switch r {
case let .completionConversionError(rhs):
return (lhs == rhs)
default:
return false
}
case let .continueWithConversionError(lhs):
switch r {
case let .continueWithConversionError(rhs):
return (lhs == rhs)
default:
return false
}
case let .errorForMultipleErrors(lhs,_):
switch r {
case let .errorForMultipleErrors(rhs,_):
return (lhs == rhs)
default:
return false
}
case let .exceptionCaught(lhs,_):
switch r {
case let .exceptionCaught(rhs,_):
return (lhs.isEqual(rhs))
default:
return false
}
}
}
internal class CancellationTokenSource {
// we are going to keep a weak copy of each token we give out.
// as long as there
internal typealias CancellationTokenPtr = Weak<CancellationToken>
fileprivate var tokens : [CancellationTokenPtr] = []
// once we have triggered cancellation, we can't do it again
fileprivate var canBeCancelled = true
// this is to flag that someone has made a non-forced cancel request, but we are ignoring it due to other valid tokens
// if those tokens disappear, we will honor the cancel request then.
fileprivate var pendingCancelRequestActive = false
fileprivate var handler : CancellationHandler?
fileprivate var forcedCancellationHandler : CancellationHandler
init(forcedCancellationHandler h: @escaping CancellationHandler) {
self.forcedCancellationHandler = h
}
fileprivate var cancellationIsSupported : Bool {
return (self.handler != nil)
}
// add blocks that will be called as soon as we initiate cancelation
internal func addHandler(_ h : @escaping CancellationHandler) {
if !self.canBeCancelled {
return
}
if let oldhandler = self.handler
{
self.handler = { (options) in
oldhandler(options)
h(options)
}
}
else {
self.handler = h
}
}
internal func clear() {
self.handler = nil
self.canBeCancelled = false
self.tokens.removeAll()
}
internal func getNewToken(_ synchObject : SynchronizationProtocol, lockWhenAddingToken : Bool) -> CancellationToken {
if !self.canBeCancelled {
return self._createUntrackedToken()
}
let token = self._createTrackedToken(synchObject)
if (lockWhenAddingToken) {
synchObject.lockAndModify { () -> Void in
if self.canBeCancelled {
self.tokens.append(CancellationTokenPtr(token))
}
}
}
else {
self.tokens.append(CancellationTokenPtr(token))
}
return token
}
fileprivate func _createUntrackedToken() -> CancellationToken {
return CancellationToken(
onCancel: { [weak self] (options, token) -> Void in
self?._performCancel(options)
},
onDeinit:nil)
}
fileprivate func _createTrackedToken(_ synchObject : SynchronizationProtocol) -> CancellationToken {
return CancellationToken(
onCancel: { [weak self] (options, token) -> Void in
self?._cancelRequested(token, options, synchObject)
},
onDeinit:{ [weak self] (token) -> Void in
self?._clearInitializedToken(token,synchObject)
})
}
fileprivate func _removeToken(_ cancelingToken:CancellationToken) {
// so remove tokens that no longer exist and the requested token
self.tokens = self.tokens.filter { (tokenPtr) -> Bool in
if let token = tokenPtr.value {
return (token !== cancelingToken)
}
else {
return false
}
}
}
fileprivate func _performCancel(_ options : CancellationOptions) {
if self.canBeCancelled {
if (!options.contains(.DoNotForwardCancelRequestIfThereAreOtherFuturesWaiting)) {
self.tokens.removeAll()
}
// there are no active tokens remaining, so allow the cancellation
if (self.tokens.count == 0) {
self.handler?(options)
self.canBeCancelled = false
self.handler = nil
}
else {
self.pendingCancelRequestActive = true
}
}
if options.contains(.ForceThisFutureToBeCancelledImmediately) {
self.forcedCancellationHandler(options)
}
}
fileprivate func _cancelRequested(_ cancelingToken:CancellationToken, _ options : CancellationOptions,_ synchObject : SynchronizationProtocol) {
synchObject.lockAndModify { () -> Void in
self._removeToken(cancelingToken)
}
self._performCancel(options)
}
fileprivate func _clearInitializedToken(_ token:CancellationToken,_ synchObject : SynchronizationProtocol) {
synchObject.lockAndModifySync { () -> Void in
self._removeToken(token)
if (self.pendingCancelRequestActive && self.tokens.count == 0) {
self.canBeCancelled = false
self.handler?([])
}
}
}
}
public struct CancellationOptions : OptionSet{
public let rawValue : Int
public init(rawValue:Int){ self.rawValue = rawValue}
@available(*, deprecated: 1.1, message: "depricated, cancellation forwards to all dependent futures by default use onSuccess",renamed: "DoNotForwardCancelRequestIfThereAreOtherFuturesWaiting")
public static let ForwardCancelRequestEvenIfThereAreOtherFuturesWaiting = CancellationOptions(rawValue:0)
/**
When the request is forwarded to another future, that future should cancel itself - even if there are other futures waiting for a result.
example:
let future: Future<NSData> = someFunction()
let firstChildofFuture = future.onComplete { (result) in
print("firstChildofFuture = \(result)")
}
let firstChildCancelToken = firstDependentFuture.getCancelToken()
let secondChildofFuture = future.onComplete { (result) in
print("secondChildofFuture result = \(result)")
}
firstChildCancelToken.cancel([.DoNotForwardCancelRequestIfThereAreOtherFuturesWaiting])
should result in `future` and `secondChildofFuture` not being cancelled.
otherwise future may ignore the firstChildCancelToken request to cancel, because it is still trying to satisify secondChildofFuture
*/
public static let DoNotForwardCancelRequestIfThereAreOtherFuturesWaiting = CancellationOptions(rawValue:1)
/**
If this future is dependent on the result of another future (via onComplete or .CompleteUsing(f))
than this cancellation request should NOT be forwarded to that future.
depending on the future's implementation, you may need include .ForceThisFutureToBeCancelledImmediately for cancellation to be successful
*/
public static let DoNotForwardRequest = CancellationOptions(rawValue:2)
/**
this is allows you to 'short circuit' a Future's internal cancellation request logic.
The Cancellation request is still forwarded (unless .DoNotForwardRequest is also sent), but an unfinished Future will be forced into the .Cancelled state early.
*/
public static let ForceThisFutureToBeCancelledImmediately = CancellationOptions(rawValue:4)
}
internal typealias CancellationHandler = ((_ options:CancellationOptions) -> Void)
open class CancellationToken {
final public func cancel(_ options : CancellationOptions = []) {
self.onCancel?(options,self)
self.onCancel = nil
}
open var cancelCanBeRequested : Bool {
return (self.onCancel != nil)
}
// private implementation details
deinit {
self.onDeinit?(self)
self.onDeinit = nil
}
internal typealias OnCancelHandler = ((_ options : CancellationOptions,_ token:CancellationToken) -> Void)
internal typealias OnDenitHandler = ((_ token:CancellationToken) -> Void)
fileprivate var onCancel : OnCancelHandler?
fileprivate var onDeinit : OnDenitHandler?
internal init(onCancel c:OnCancelHandler?, onDeinit d: OnDenitHandler?) {
self.onCancel = c
self.onDeinit = d
}
}
// Type Erased Future
public protocol AnyFuture {
var futureAny : Future<Any> { get }
func mapAs<S>() -> Future<S>
func mapAs() -> Future<Void>
}
/**
All Futures use the protocol FutureProtocol
*/
public protocol FutureProtocol : AnyFuture {
associatedtype T
var result : FutureResult<T>? { get }
var value : T? { get }
func onComplete<C: CompletionType>(_ executor : Executor,block: @escaping (_ result:FutureResult<T>) throws -> C) -> Future<C.T>
/**
convert this future of type `Future<T>` into another future type `Future<S>`
may fail to compile if T is not convertable into S using "`as!`"
works iff the following code works:
let t : T
let s = t as! S
example:
let f = Future<Int>(success:5)
let f2 : Future<Int32> = f.As()
assert(f2.result! == Int32(5))
you will need to formally declare the type of the new variable (ex: `f2`), in order for Swift to perform the correct conversion.
the following conversions should always work for any future
let fofany : Future<Any> = f.As()
let fofvoid: Future<Void> = f.As()
*/
func mapAs<S>() -> Future<S>
/**
convert Future<T> into another type Future<S?>.
WARNING: if 'T as! S' isn't legal, than all Success values may be converted to nil
example:
let f = Future<String>(success:"5")
let f2 : Future<[Int]?> = f.convertOptional()
assert(f2.result! == nil)
you will need to formally declare the type of the new variable (ex: `f2`), in order for Swift to perform the correct conversion.
*/
func mapAsOptional<S>() -> Future<S?>
func mapAs() -> Future<Void>
var description: String { get }
func getCancelToken() -> CancellationToken
}
public extension FutureProtocol {
var futureAny : Future<Any> {
return self.mapAs()
}
}
/**
`Future<T>`
A Future is a swift generic class that let's you represent an object that will be returned at somepoint in the future. Usually from some asynchronous operation that may be running in a different thread/dispatch_queue or represent data that must be retrieved from a remote server somewhere.
*/
open class Future<T> : FutureProtocol {
public typealias ReturnType = T
internal typealias CompletionErrorHandler = Promise<T>.CompletionErrorHandler
internal typealias completion_block_type = ((FutureResult<T>) -> Void)
internal typealias cancellation_handler_type = (()-> Void)
fileprivate final var __callbacks : [completion_block_type]?
/**
this is used as the internal storage for `var completion`
it is not thread-safe to read this directly. use `var synchObject`
*/
fileprivate final var __result : FutureResult<T>?
// private final let lock = NSObject()
// Warning - reusing this lock for other purposes is dangerous when using LOCKING_STRATEGY.NSLock
// don't read or write values Future
/**
used to synchronize access to both __completion and __callbacks
type of synchronization can be configured via GLOBAL_PARMS.LOCKING_STRATEGY
*/
internal final var synchObject : SynchronizationProtocol = GLOBAL_PARMS.LOCKING_STRATEGY.lockObject()
/**
is executed used `cancel()` has been requested.
*/
internal func addRequestHandler(_ h : @escaping CancellationHandler) {
self.synchObject.lockAndModify { () -> Void in
self.cancellationSource.addHandler(h)
}
}
lazy var cancellationSource: CancellationTokenSource = {
return CancellationTokenSource(forcedCancellationHandler: { [weak self] (options) -> Void in
assert(options.contains(.ForceThisFutureToBeCancelledImmediately), "the forced cancellation handler is only supposed to run when the .ForceThisFutureToBeCancelledImmediately option is on")
self?.completeWith(.cancelled)
})
}()
/**
returns: the current completion value of the Future
accessing this variable directly requires thread synchronization.
It is more efficient to examine completion values that are sent to an onComplete/onSuccess handler of a future than to examine it directly here.
type of synchronization used can be configured via GLOBAL_PARMS.LOCKING_STRATEGY
*/
public final var result : FutureResult<T>? {
get {
return self.synchObject.lockAndReadSync { () -> FutureResult<T>? in
return self.__result
}
}
}
/**
returns: the result of the Future iff the future has completed successfully. returns nil otherwise.
accessing this variable directly requires thread synchronization.
*/
open var value : T? {
get {
return self.result?.value
}
}
/**
returns: the error of the Future iff the future has completed with an Error. returns nil otherwise.
accessing this variable directly requires thread synchronization.
*/
open var error : Error? {
get {
return self.result?.error
}
}
/**
is true if the Future supports cancellation requests using `cancel()`
May return true, even if the Future has already been completed, and cancellation is no longer possible.
It only informs the user that this type of future can be cancelled.
*/
open var cancellationIsSupported : Bool {
return self.synchObject.lockAndReadSync { () -> Bool in
return (self.cancellationSource.cancellationIsSupported)
}
}
/**
returns: true if the Future has completed with any completion value.
is NOT threadsafe
*/
fileprivate final var __isCompleted : Bool {
return (self.__result != nil)
}
/**
returns: true if the Future has completed with any completion value.
accessing this variable directly requires thread synchronization.
*/
public final var isCompleted : Bool {
return self.synchObject.lockAndReadSync { () -> Bool in
return self.__isCompleted
}
}
/**
You can't instanciate an incomplete Future directly. You must use a Promsie, or use an Executor with a block.
*/
internal init() {
}
// internal init(cancellationSource s: CancellationTokenSource) {
// self.cancellationSource = s
// }
/**
creates a completed Future.
*/
// public init(result:FutureResult<T>) { // returns an completed Task
// self.__result = result
// }
/**
creates a completed Future with a completion == .Success(success)
*/
public required init(success:T) { // returns an completed Task with result T
self.__result = .success(success)
}
/**
creates a completed Future with a completion == .Error(failed)
*/
public required init(fail:Error) { // returns an completed Task that has Failed with this error
self.__result = .fail(fail)
}
/**
creates a completed Future with a completion == .Error(FutureNSError(failWithErrorMessage))
*/
public init(failWithErrorMessage errorMessage: String) {
self.__result = FutureResult<T>(failWithErrorMessage:errorMessage)
}
/**
creates a completed Future with a completion == .Error(FutureNSError(exception))
*/
public init(exception:NSException) { // returns an completed Task that has Failed with this error
self.__result = FutureResult<T>(exception:exception)
}
/**
creates a completed Future with a completion == .Cancelled(cancelled)
*/
public init(cancelled:()) { // returns an completed Task that has Failed with this error
self.__result = .cancelled
}
/**
creates a completed Future with a completion == .Cancelled(cancelled)
*/
public init(completeUsing f:Future<T>) { // returns an completed Task that has Failed with this error
self.completeWith(.completeUsing(f))
}
public convenience init<C:CompletionType>(delay:TimeInterval, completeWith: C) where C.T == T {
let executor: Executor = .primary
let p = Promise<T>()
p.automaticallyCancelOnRequestCancel()
executor.execute(afterDelay:delay) { () -> Void in
p.complete(completeWith)
}
self.init(completeUsing:p.future)
}
public convenience init(afterDelay delay:TimeInterval, success:T) { // emits a .Success after delay
let executor: Executor = .primary
let p = Promise<T>()
p.automaticallyCancelOnRequestCancel()
executor.execute(afterDelay:delay) {
p.completeWithSuccess(success)
}
self.init(completeUsing:p.future)
}
/**
Creates a future by executes block inside of an Executor, and when it's complete, sets the completion = .Success(block())
can only be used to a create a Future that should always succeed.
*/
public init(_ executor : Executor = .immediate , block: @escaping () throws -> T) {
let wrappedBlock = executor.callbackBlockFor { () -> Void in
do {
let r = try block()
self.completeWith(.success(r))
}
catch {
self.completeWith(.fail(error))
}
}
wrappedBlock()
}
/* public init(_ executor : Executor = .immediate, block: @autoclosure @escaping () -> T) {
let wrappedBlock = executor.callbackBlockFor { () -> Void in
self.completeWith(.success(block()))
}
wrappedBlock()
} */
/**
Creates a future by executes block inside of an Executor, and when it's complete, sets the completion = block()
can be used to create a Future that may succeed or fail.
the block can return a value of .CompleteUsing(Future<T>) if it wants this Future to complete with the results of another future.
*/
public init<C:CompletionType>(_ executor : Executor = .immediate, block: @escaping () throws -> C) where C.T == T {
executor.execute { () -> Void in
self.completeWithBlocks(completionBlock: {
return try block()
})
}
}
/* public init<C:CompletionType>(_ executor : Executor = .immediate, block: @autoclosure @escaping () -> C) where C.T == T {
executor.execute { () -> Void in
self.completeWith(block())
}
} */
/**
will complete the future and cause any registered callback blocks to be executed.
may execute asynchronously (depending on configured LOCKING_STRATEGY) and may return to the caller before it is finished executing.
type of synchronization used can be configured via GLOBAL_PARMS.LOCKING_STRATEGY
- parameter completion: the value to complete the Future with
*/
internal final func completeAndNotify<C:CompletionType>(_ completion : C) where C.T == T {
return self.completeWithBlocks(waitUntilDone: false,
completionBlock: { () -> C in
completion
})
}
/**
will complete the future and cause any registered callback blocks to be executed.
may execute asynchronously (depending on configured LOCKING_STRATEGY) and may return to the caller before it is finished executing.
if the Future has already been completed, the onCompletionError block will be executed. This block may be running in any queue (depending on the configure synchronization type).
type of synchronization used can be configured via GLOBAL_PARMS.LOCKING_STRATEGY
- parameter completion: the value to complete the Future with
- parameter onCompletionError: a block to execute if the Future has already been completed.
*/
internal final func completeAndNotify<C:CompletionType>(_ completion : C, onCompletionError : @escaping CompletionErrorHandler) where C.T == T {
self.completeWithBlocks(waitUntilDone: false, completionBlock: { () -> C in
return completion
}, onCompletionError: onCompletionError)
}
/**
will complete the future and cause any registered callback blocks to be executed.
may block the current thread (depending on configured LOCKING_STRATEGY)
type of synchronization used can be configured via GLOBAL_PARMS.LOCKING_STRATEGY
- parameter completion: the value to complete the Future with
- returns: true if Future was successfully completed. Returns false if the Future has already been completed.
*/
internal final func completeAndNotifySync<C:CompletionType>(_ completion : C) -> Bool where C.T == T {
var ret = true
self.completeWithBlocks(waitUntilDone: true, completionBlock: { () -> C in
return completion
}) { () -> Void in
ret = false
}
return ret
}
internal final func completeWithBlocks<C:CompletionType>(
waitUntilDone wait:Bool = false,
completionBlock : @escaping () throws -> C,
onCompletionError : @escaping () -> Void = {} ) where C.T == T {
typealias ModifyBlockReturnType = (callbacks:[completion_block_type]?,
result:FutureResult<T>?,
continueUsing:Future?)
self.synchObject.lockAndModify(waitUntilDone: wait, modifyBlock: { () -> ModifyBlockReturnType in
if let _ = self.__result {
// future was already complete!
return ModifyBlockReturnType(nil,nil,nil)
}
let c : Completion<T>
do {
c = try completionBlock().completion
}
catch {
c = .fail(error)
}
if (c.isCompleteUsing) {
return ModifyBlockReturnType(callbacks:nil,result:nil,continueUsing:c.completeUsingFuture)
}
else {
let callbacks = self.__callbacks
self.__callbacks = nil
self.cancellationSource.clear()
self.__result = c.result
return ModifyBlockReturnType(callbacks,self.__result,nil)
}
}, then:{ (modifyBlockReturned:ModifyBlockReturnType) -> Void in
if let callbacks = modifyBlockReturned.callbacks {
for callback in callbacks {
callback(modifyBlockReturned.result!)
}
}
if let f = modifyBlockReturned.continueUsing {
f.onComplete(.immediate) { (nextComp) -> Void in
self.completeWith(nextComp.completion)
}
.ignoreFailures()
let token = f.getCancelToken()
if token.cancelCanBeRequested {
self.addRequestHandler { (options : CancellationOptions) in
if !options.contains(.DoNotForwardRequest) {
token.cancel(options)
}
}
}
}
else if (modifyBlockReturned.result == nil) {
onCompletionError()
}
})
}
/**
if completion is of type .CompleteUsing(f), than this will register an appropriate callback on f to complete this future iff f completes.
otherwise it will complete the future and cause any registered callback blocks to be executed.
may execute asynchronously (depending on configured LOCKING_STRATEGY) and may return to the caller before it is finished executing.
if the Future has already been completed, this function will do nothing. No error is generated.
- parameter completion: the value to complete the Future with
*/
internal func completeWith(_ completion : Completion<T>) {
return self.completeAndNotify(completion)
}
internal func completeWith<C:CompletionType>(_ completion : C) where C.T == T {
return self.completeAndNotify(completion)
}
/**
if completion is of type .CompleteUsing(f), than this will register an appropriate callback on f to complete this future when f completes.
otherwise it will complete the future and cause any registered callback blocks to be executed.
may block the current thread
- parameter completion: the value to complete the Future with
- returns: true if Future was successfully completed. Returns false if the Future has already been completed.
*/
internal func completeWithSync<C:CompletionType>(_ completion : C) -> Bool where C.T == T {
return self.completeAndNotifySync(completion)
}
internal func completeWithSync(_ completion : Completion<T>) -> Bool {
return self.completeAndNotifySync(completion)
}
/**
if completion is of type .CompleteUsing(f), than this will register an appropriate callback on f to complete this future when f completes.
otherwise it will complete the future and cause any registered callback blocks to be executed.
will execute the block onCompletionError if the Future has already been completed. The onCompletionError block may execute inside any thread/queue, so care should be taken.
may execute asynchronously (depending on configured LOCKING_STRATEGY) and may return to the caller before it is finished executing.
- parameter completion: the value to complete the Future with
- parameter onCompletionError: a block to execute if the Future has already been completed.
*/
internal func completeWith<C:CompletionType>(_ completion : C, onCompletionError errorBlock: @escaping CompletionErrorHandler) where C.T == T {
return self.completeAndNotify(completion,onCompletionError: errorBlock)
}
/**
takes a user supplied block (usually from func onComplete()) and creates a Promise and a callback block that will complete the promise.
can add Objective-C Exception handling if GLOBAL_PARMS.WRAP_DEPENDENT_BLOCKS_WITH_OBJC_EXCEPTION_HANDLING is enabled.
- parameter forBlock: a user supplied block (via onComplete)
- returns: a tuple (promise,callbackblock) a new promise and a completion block that can be added to __callbacks
*/
internal final func createPromiseAndCallback<C:CompletionType>(_ forBlock: @escaping ((FutureResult<T>) throws -> C)) -> (promise : Promise<C.T> , completionCallback :completion_block_type) {
let promise = Promise<C.T>()
let completionCallback : completion_block_type = {(comp) -> Void in
do {
let c = try forBlock(comp)
promise.complete(c.completion)
}
catch {
promise.completeWithFail(error)
}
return
}
return (promise,completionCallback)
}
/**
takes a callback block and determines what to do with it based on the Future's current completion state.
If the Future has already been completed, than the callback block is executed.
If the Future is incomplete, it adds the callback block to the futures private var __callbacks
may execute asynchronously (depending on configured LOCKING_STRATEGY) and may return to the caller before it is finished executing.
- parameter callback: a callback block to be run if and when the future is complete
*/
fileprivate final func runThisCompletionBlockNowOrLater<S>(_ callback : @escaping completion_block_type,promise: Promise<S>) {
// lock my object, and either return the current completion value (if it's set)
// or add the block to the __callbacks if not.
self.synchObject.lockAndModifyAsync(modifyBlock: { () -> FutureResult<T>? in
// we are done! return the current completion value.
if let c = self.__result {
return c
}
else
{
// we only allocate an array after getting the first __callbacks.
// cause we are hyper sensitive about not allocating extra stuff for temporary transient Futures.
switch self.__callbacks {
case let .some(cb):
var newcb = cb
newcb.append(callback)
self.__callbacks = newcb
case .none:
self.__callbacks = [callback]
}
let t = self.cancellationSource.getNewToken(self.synchObject, lockWhenAddingToken: false)
promise.onRequestCancel(.immediate) { (options) -> CancelRequestResponse<S> in
if !options.contains(.DoNotForwardRequest) {
t.cancel(options)
}
return .continue
}
return nil
}
}, then: { (currentCompletionValue) -> Void in
// if we got a completion value, than we can execute the callback now.
if let c = currentCompletionValue {
callback(c)
}
})
}
/**
convert this future of type `Future<T>` into another future type `Future<__Type>`
WARNING: if `T as! __Type` isn't legal, than your code may generate an exception.
works iff the following code works:
let t : T
let s = t as! __Type
example:
let f = Future<Int>(success:5)
let f2 : Future<Int32> = f.As()
assert(f2.result! == Int32(5))
you will need to formally declare the type of the new variable in order for Swift to perform the correct conversion.
the following conversions should always work for any future
let fofany : Future<Any> = f.As()
let fofvoid: Future<Void> = f.As()
- returns: a new Future of with the result type of __Type
*/
@available(*, deprecated: 1.1, message: "renamed to mapAs()")
public final func As<__Type>() -> Future<__Type> {
return self.mapAs()
}
/**
convert this future of type `Future<T>` into another future type `Future<__Type>`
WARNING: if `T as! __Type` isn't legal, than your code may generate an exception.
works iff the following code works:
let t : T
let s = t as! __Type
example:
let f = Future<Int>(success:5)
let f2 : Future<Int32> = f.As()
assert(f2.result! == Int32(5))
you will need to formally declare the type of the new variable in order for Swift to perform the correct conversion.
the following conversions should always work for any future
let fofany : Future<Any> = f.As()
let fofvoid: Future<Void> = f.As()
- returns: a new Future of with the result type of __Type
*/
public final func mapAs<__Type>() -> Future<__Type> {
return self.map(.immediate) { (result) -> __Type in
return result as! __Type
}
}
public final func mapAs() -> Future<Void> {
return self.map(.immediate) { (result) -> Void in
return ()
}
}
/**
convert `Future<T>` into another type `Future<__Type?>`.
WARNING: if `T as! __Type` isn't legal, than all Success values may be converted to nil
example:
let f = Future<String>(success:"5")
let f2 : Future<[Int]?> = f.convertOptional()
assert(f2.result! == nil)
you will need to formally declare the type of the new variable (ex: `f2`), in order for Swift to perform the correct conversion.
- returns: a new Future of with the result type of __Type?
*/
@available(*, deprecated: 1.1, message: "renamed to mapAsOptional()")
public final func convertOptional<__Type>() -> Future<__Type?> {
return mapAsOptional()
}
/**
convert `Future<T>` into another type `Future<__Type?>`.
WARNING: if `T as! __Type` isn't legal, than all Success values may be converted to nil
example:
let f = Future<String>(success:"5")
let f2 : Future<[Int]?> = f.convertOptional()
assert(f2.result! == nil)
you will need to formally declare the type of the new variable (ex: `f2`), in order for Swift to perform the correct conversion.
- returns: a new Future of with the result type of __Type?
*/
public final func mapAsOptional<__Type>() -> Future<__Type?> {
return self.map(.immediate) { (result) -> __Type? in
return result as? __Type
}
}
/**
executes a block only if the Future has not completed. Will prevent the Future from completing until AFTER the block finishes.
Warning : do not cause the target to complete or call getCancelationToken() or call cancel() on an existing cancel token for this target inside this block. On some FutureKit implementations, this will cause a deadlock.
It may be better to safer and easier to just guarantee your onSuccess/onComplete logic run inside the same serial dispatch queue or Executor (eg .Main) and examine the var 'result' or 'isCompleted' inside the same context.
- returns: the value returned from the block if the block executed, or nil if the block didn't execute
*/
public final func IfNotCompleted<__Type>(_ block:@escaping () -> __Type) -> __Type? {
return self.synchObject.lockAndReadSync { () -> __Type? in
if !self.__isCompleted {
return block()
}
return nil
}
}
/**
executes a block and provides a 'thread safe' version of the current result.
In the case where the current result is nil, than the future will be prevented from completing until after this block is done executing.
Warning : do not cause the target to complete or call getCancelationToken() or call cancel() on an existing cancel token for this target inside this block. On some FutureKit implementations, this will cause a deadlock.
Instead use a returned value from the function to decide to complete or cancel the target.
It may be better to safer and easier to just guarantee your onSuccess/onComplete logic run inside the same serial dispatch queue or Executor (eg .Main) and examine the var 'result' or 'isCompleted' inside the same context.
- returns: the value returned from the block if the block executed
*/
public final func checkResult<__Type>(_ block:@escaping (FutureResult<T>?) -> __Type) -> __Type {
return self.synchObject.lockAndReadSync { () -> __Type in
return block(self.__result)
}
}
// ---------------------------------------------------------------------------------------------------
// Block Handlers
// ---------------------------------------------------------------------------------------------------
/**
executes a block using the supplied Executor if and when the target future is completed. Will execute immediately if the target is already completed.
This method will let you examine the completion state of target, and return a new future in any completion state, with the user defined type __Type.
The `completion` argument will be set to the Completion<T> value that completed the target. It will be one of 3 values (.Success, .Fail, or .Cancelled).
The block must return one of four enumeration values (.Success/.Fail/.Cancelled/.CompleteUsing).
Returning a future `f` using .CompleteUsing(f) causes the future returned from this method to be completed when `f` completes, using the completion value of `f`. (Leaving the Future in an incomplete state, until 'f' completes).
The new future returned from this function will be completed using the completion value returned from this block.
- parameter __Type: the type of the new Future that will be returned. When using XCode auto-complete, you will need to modify this into the swift Type you wish to return.
- parameter executor: an Executor to use to execute the block when it is ready to run.
- parameter block: a block that will execute when this future completes, and returns a new completion value for the new completion type. The block must return a Completion value (Completion<__Type>).
- returns: a new Future that returns results of type __Type (Future<__Type>)
*/
@discardableResult public final func onComplete<C: CompletionType>(_ executor : Executor,block:@escaping (_ result:FutureResult<T>) throws -> C) -> Future<C.T> {
let (promise, completionCallback) = self.createPromiseAndCallback(block)
let block = executor.callbackBlockFor(completionCallback)
self.runThisCompletionBlockNowOrLater(block,promise: promise)
return promise.future
}
/**
*/
public final func getCancelToken() -> CancellationToken {
return self.cancellationSource.getNewToken(self.synchObject, lockWhenAddingToken:true)
}
public final func delay(_ delay: TimeInterval) -> Future<T> {
let completion: Completion<T> = .completeUsing(self)
return Future(delay:delay, completeWith: completion)
}
}
extension FutureProtocol {
/**
if we try to convert a future from type T to type T, just ignore the request.
the compile should automatically figure out which version of As() execute
*/
public func As() -> Self {
return self
}
/**
if we try to convert a future from type T to type T, just ignore the request.
the swift compiler can automatically figure out which version of mapAs() execute
*/
public func mapAs() -> Self {
return self
}
public func withCancelToken() -> (Self,CancellationToken) {
return (self,self.getCancelToken())
}
@discardableResult public func onComplete<C: CompletionType>(_ block: @escaping (FutureResult<T>) throws -> C) -> Future<C.T> {
return self.onComplete(.primary,block:block)
}
/**
executes a block using the supplied Executor if and when the target future is completed. Will execute immediately if the target is already completed.
This method will let you examine the completion state of target, and return a new future that completes with a `.Success(result)`. The value returned from the block will be set as this Future's result.
- parameter __Type: the type of the new Future that will be returned. When using XCode auto-complete, you will need to modify this into the swift Type you wish to return.
- parameter executor: an Executor to use to execute the block when it is ready to run.
- parameter block: a block that will execute when this future completes, a `.Success(result)` using the return value of the block.
- returns: a new Future that returns results of type __Type
*/
@discardableResult public func onComplete<__Type>(_ executor: Executor = .primary, _ block:@escaping (_ result:FutureResult<T>) throws -> __Type) -> Future<__Type> {
return self.onComplete(executor) { (result) -> Completion<__Type> in
return .success(try block(result))
}
}
/**
takes a two block and executes one or the other. the didComplete() block will be executed if the target completes prior before the timeout.
it if and when this future is completed. The block will be executed using supplied Executor.
The new future returned from this function will be completed when the future returned from the block is completed.
This is the same as returning Completion<T>.CompleteUsing(f)
- parameter executor: an Executor to use to execute the block when it is ready to run.
- parameter didComplete: a block that will execute if this future completes. It will return a completion value that
- returns: a `Future<Void>` that completes after this block has executed.
*/
public func waitForComplete<C:CompletionType>(_ timeout: TimeInterval,
executor : Executor,
didComplete:@escaping (FutureResult<T>) throws -> C,
timedOut:@escaping () throws -> C
) -> Future<C.T> {
let p = Promise<C.T>()
p.automaticallyCancelOnRequestCancel()
self.onComplete(executor) { (c) -> Void in
p.completeWithBlock({ () -> C in
return try didComplete(c)
})
}
.ignoreFailures()
executor.execute(afterDelay:timeout) {
p.completeWithBlock { () -> C in
return try timedOut()
}
}
return p.future
}
public func waitForComplete<__Type>(_ timeout: TimeInterval,
executor : Executor,
didComplete:@escaping (FutureResult<T>) throws -> __Type,
timedOut:@escaping () throws -> __Type
) -> Future<__Type> {
return self.waitForComplete(timeout,
executor: executor,
didComplete: {
return Completion<__Type>.success(try didComplete($0))
},
timedOut: {
.success(try timedOut())
})
}
public func waitForSuccess<C:CompletionType>(_ timeout: TimeInterval,
executor : Executor,
didSucceed:@escaping (T) throws -> C.T,
timedOut:@escaping () throws -> C
) -> Future<C.T> {
let p = Promise<C.T>()
p.automaticallyCancelOnRequestCancel()
self.onSuccess { (result) -> Void in
p.completeWithSuccess(try didSucceed(result))
}.ignoreFailures()
executor.execute(afterDelay:timeout) {
p.completeWithBlock { () -> C in
return try timedOut()
}
}
return p.future
}
public func waitForSuccess<__Type>(_ timeout: TimeInterval,
executor : Executor,
didSucceed:(T) throws -> __Type,
timedOut:() throws -> __Type
) -> Future<__Type> {
return self.waitForSuccess(timeout,
executor: executor,
didSucceed: {
return try didSucceed($0)
},
timedOut: {
try timedOut()
})
}
/**
takes a block and executes it iff the target is completed with a .Success
If the target is completed with a .Success, then the block will be executed using the supplied Executor. The new future returned from this function will be completed using the completion value returned from this block.
If the target is completed with a .Fail, then the returned future will also complete with .Fail and this block will not be executed.
If the target is completed with a .Cancelled, then the returned future will also complete with .Cancelled and this block will not be executed.
*Warning* - as of swift 1.2, you can't use this method with a Future<Void> (it will give a compiler error). Instead use `onAnySuccess()`
- parameter __Type: the type of the new Future that will be returned. When using XCode auto-complete, you will need to modify this into the swift Type you wish to return.
- parameter executor: an Executor to use to execute the block when it is ready to run.
- parameter block: a block takes the .Success result of the target Future and returns the completion value of the returned Future.
- returns: a new Future of type Future<__Type>
*/
public func onSuccess<C: CompletionType>(_ executor : Executor = .primary,
block:@escaping (T) throws -> C) -> Future<C.T> {
return self.onComplete(executor) { (result) -> Completion<C.T> in
switch result {
case let .success(value):
return try block(value).completion
case let .fail(error):
return .fail(error)
case .cancelled:
return .cancelled
}
}
}
/**
takes a block and executes it iff the target is completed with a .Success
If the target is completed with a .Success, then the block will be executed using the supplied Executor.
The new future returned from this function will be completed with `.Success(result)` using the value returned from this block as the result.
If the target is completed with a .Fail, then the returned future will also complete with .Fail and this block will not be executed.
If the target is completed with a .Cancelled, then the returned future will also complete with .Cancelled and this block will not be executed.
*Warning* - as of swift 1.2/2.0, you can't use this method with a Future<Void> (it will give a compiler error). Instead use `onAnySuccess()`
- parameter __Type: the type of the new Future that will be returned. When using XCode auto-complete, you will need to modify this into the swift Type you wish to return.
- parameter executor: an Executor to use to execute the block when it is ready to run.
- parameter block: a block takes the .Success result of the target Future and returns a new result.
- returns: a new Future of type Future<__Type>
*/
public func onSuccess<__Type>(_ executor : Executor = .primary,
block:@escaping (T) throws -> __Type) -> Future<__Type> {
return self.onSuccess(executor) { (value : T) -> Completion<__Type> in
return .success(try block(value))
}
}
/**
takes a block and executes it iff the target is completed with a .Fail
If the target is completed with a .Fail, then the block will be executed using the supplied Executor.
This method returns a new Future. Which is identical to the depedent Future, with the added Failure handler, that will execute before the Future completes.
Failures are still forwarded. If you need to create side effects on errors, consider onComplete or mapError
- parameter executor: an Executor to use to execute the block when it is ready to run.
- parameter block: a block can process the error of a future.
*/
@discardableResult public func onFail(_ executor : Executor = .primary,
block:@escaping (_ error:Error)-> Void) -> Future<T>
{
return self.onComplete(executor) { (result) -> Completion<T> in
if (result.isFail) {
block(result.error)
}
return result.completion
}
}
/**
takes a block and executes it iff the target is completed with a .Fail
If the target is completed with a .Fail, then the block will be executed using the supplied Executor.
This method returns a new Future. Failures can be be remapped to different Completions. (Such as consumed or ignored or retried via returning .CompleteUsing()
- parameter executor: an Executor to use to execute the block when it is ready to run.
- parameter block: a block can process the error of a future.
*/
@discardableResult public func onFail<C:CompletionType>(_ executor : Executor = .primary,
block:@escaping (_ error:Error)-> C) -> Future<T> where C.T == T
{
return self.onComplete(executor) { (result) -> Completion<T> in
if (result.isFail) {
return block(result.error).completion
}
return result.completion
}
}
/**
takes a block and executes it iff the target is completed with a .Cancelled
If the target is completed with a .Cancelled, then the block will be executed using the supplied Executor.
This method returns a new Future. Cancellations
- parameter executor: an Executor to use to execute the block when it is ready to run.
- parameter block: a block takes the canceltoken returned by the target Future and returns the completion value of the returned Future.
*/
@discardableResult public func onCancel(_ executor : Executor = .primary, block:@escaping ()-> Void) -> Future<T>
{
return self.onComplete(executor) { (result) -> FutureResult<T> in
if (result.isCancelled) {
block()
}
return result
}
}
/**
takes a block and executes it iff the target is completed with a .Cancelled
If the target is completed with a .Cancelled, then the block will be executed using the supplied Executor.
This method returns a new Future. Cancellations
- parameter executor: an Executor to use to execute the block when it is ready to run.
- parameter block: a block takes the canceltoken returned by the target Future and returns the completion value of the returned Future.
*/
@discardableResult public func onCancel<C:CompletionType>(_ executor : Executor = .primary, block:@escaping ()-> C) -> Future<T> where C.T == T
{
return self.onComplete(executor) { (result) -> Completion<T> in
if (result.isCancelled) {
return block().completion
}
return result.completion
}
}
/*:
takes a block and executes it iff the target is completed with a .Fail or .Cancel
If the target is completed with a .Fail, then the block will be executed using the supplied Executor.
If the target is completed with a .Cancel, then the block will be executed using the supplied Executor.
This method returns a new Future. Which is identical to the depedent Future, with the added Fail/Cancel handler, that will execute after the dependent completes.
Cancelations and Failures are still forwarded.
- parameter executor: an Executor to use to execute the block when it is ready to run.
- parameter block: a block can process the error of a future. error will be nil when the Future was canceled
*/
@discardableResult public func onFailorCancel(_ executor : Executor = .primary,
block:@escaping (FutureResult<T>)-> Void) -> Future<T>
{
return self.onComplete(executor) { (result) -> FutureResult<T> in
switch result {
case .fail, .cancelled:
block(result)
case .success(_):
break
}
return result
}
}
/*:
takes a block and executes it iff the target is completed with a .Fail or .Cancel
If the target is completed with a .Fail, then the block will be executed using the supplied Executor.
If the target is completed with a .Cancel, then the block will be executed using the supplied Executor.
This method returns a new Future. Which is identical to the depedent Future, with the added Fail/Cancel handler, that will execute after the dependent completes.
Cancelations and Failures are still forwarded.
- parameter executor: an Executor to use to execute the block when it is ready to run.
- parameter block: a block can process the error of a future. error will be nil when the Future was canceled
*/
@discardableResult public func onFailorCancel<C:CompletionType>(_ executor : Executor = .primary,
block:@escaping (FutureResult<T>)-> C) -> Future<T> where C.T == T
{
return self.onComplete(executor) { (result) -> Completion<T> in
switch result {
case .fail, .cancelled:
return block(result).completion
case let .success(value):
return .success(value)
}
}
}
/*:
takes a block and executes it iff the target is completed with a .Fail or .Cancel
If the target is completed with a .Fail, then the block will be executed using the supplied Executor.
If the target is completed with a .Cancel, then the block will be executed using the supplied Executor.
This method returns a new Future. Which is identical to the depedent Future, with the added Fail/Cancel handler, that will execute after the dependent completes.
Cancelations and Failures are still forwarded.
- parameter executor: an Executor to use to execute the block when it is ready to run.
- parameter block: a block can process the error of a future. error will be nil when the Future was canceled
*/
public func onFailorCancel(_ executor : Executor = .primary,
block:@escaping (FutureResult<T>)-> Future<T>) -> Future<T>
{
return self.onComplete(executor) { (result) -> Completion<T> in
switch result {
case .fail, .cancelled:
return .completeUsing(block(result))
case let .success(value):
return .success(value)
}
}
}
/*:
this is basically a noOp method, but it removes the unused result compiler warning to add an error handler to your future.
Typically this method will be totally removed by the optimizer, and is really there so that developers will clearly document that they are ignoring errors returned from a Future
*/
@discardableResult public func ignoreFailures() -> Self
{
return self
}
/*:
this is basically a noOp method, but it removes the unused result compiler warning to add an error handler to your future.
Typically this method will be totally removed by the optimizer, and is really there so that developers will clearly document that they are ignoring errors returned from a Future
*/
@discardableResult public func assertOnFail() -> Self
{
self.onFail { error in
assertionFailure("Future failed unexpectantly")
}
.ignoreFailures()
return self
}
// rather use map? Sure!
public func map<__Type>(_ executor : Executor = .primary, block:@escaping (T) throws -> __Type) -> Future<__Type> {
return self.onSuccess(executor,block:block)
}
public func mapError(_ executor : Executor = .primary, block:@escaping (Error) throws -> Error) -> Future<T> {
return self.onComplete(executor) { (result) -> FutureResult<T> in
if case let .fail(error) = result {
return .fail(try block(error))
}
else {
return result
}
}
}
public func waitUntilCompleted() -> FutureResult<T> {
let s = SyncWaitHandler<T>(waitingOnFuture: self)
return s.waitUntilCompleted(doMainQWarning: true)
}
public func waitForResult() -> T? {
return self.waitUntilCompleted().value
}
public func _waitUntilCompletedOnMainQueue() -> FutureResult<T> {
let s = SyncWaitHandler<T>(waitingOnFuture: self)
return s.waitUntilCompleted(doMainQWarning: false)
}
}
extension Future {
final func then<C:CompletionType>(_ executor : Executor = .primary, block:@escaping (T) -> C) -> Future<C.T> {
return self.onSuccess(executor,block: block)
}
final func then<__Type>(_ executor : Executor = .primary,block:@escaping (T) -> __Type) -> Future<__Type> {
return self.onSuccess(executor,block: block)
}
}
extension Future : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return self.debugDescription
}
public var debugDescription: String {
let des = self.result?.description ?? "nil"
return "Future<\(String(describing: T.self))>{\(des)}"
}
public func debugQuickLookObject() -> AnyObject? {
return self.debugDescription as AnyObject?
}
}
public protocol OptionalProtocol {
associatedtype Wrapped
func isNil() -> Bool
func unwrap() -> Wrapped
func map<U>(_ f: (Wrapped) throws -> U) rethrows -> U?
func flatMap<U>(_ f: (Wrapped) throws -> U?) rethrows -> U?
init(_ some: Wrapped)
}
extension Optional : OptionalProtocol {
public func isNil() -> Bool {
switch self {
case .none:
return true
case .some:
return false
}
}
public func unwrap() -> Wrapped {
return self!
}
}
extension FutureProtocol where T : OptionalProtocol {
func As<OptionalS: OptionalProtocol>(_ type: OptionalS.Type) -> Future<OptionalS.Wrapped?> {
return self.map { (value) -> OptionalS.Wrapped? in
if (value.isNil()) {
return nil
}
return value.unwrap() as? OptionalS.Wrapped
}
}
}
extension FutureProtocol {
func AsOptional<OptionalS: OptionalProtocol>(_ type: OptionalS.Type) -> Future<OptionalS.Wrapped?> {
return self.map { (value) -> OptionalS.Wrapped? in
return value as? OptionalS.Wrapped
}
}
}
private var futureWithNoResult = Future<Any>()
class classWithMethodsThatReturnFutures {
func iReturnAnInt() -> Future<Int> {
return Future (.immediate) { () -> Int in
return 5
}
}
func iReturnFive() -> Int {
return 5
}
func iReturnFromBackgroundQueueUsingBlock() -> Future<Int> {
//
return Future(.default) {
self.iReturnFive()
}
}
func iWillUseAPromise() -> Future<Int> {
let p : Promise<Int> = Promise()
// let's do some async dispatching of things here:
DispatchQueue.main.async {
p.completeWithSuccess(5)
}
return p.future
}
func iMayFailRandomly() -> Future<[String:Int]> {
let p = Promise<[String:Int]>()
DispatchQueue.main.async {
let s = arc4random_uniform(3)
switch s {
case 0:
p.completeWithFail(FutureKitError.genericError("failed randomly"))
case 1:
p.completeWithCancel()
default:
p.completeWithSuccess(["Hi" : 5])
}
}
return p.future
}
func iMayFailRandomlyAlso() -> Future<[String:Int]> {
return Future(.main) { () -> Completion<[String:Int]> in
let s = arc4random_uniform(3)
switch s {
case 0:
return .fail(FutureKitError.genericError("Failed Also"))
case 1:
return .cancelled
default:
return .success(["Hi" : 5])
}
}
}
func iCopeWithWhatever() {
// ALL 3 OF THESE FUNCTIONS BEHAVE THE SAME
self.iMayFailRandomly().onComplete { (result) -> Completion<Void> in
switch result {
case let .success(value):
NSLog("\(value)")
return .success(())
case let .fail(e):
return .fail(e)
case .cancelled:
return .cancelled
}
}
.ignoreFailures()
self.iMayFailRandomly().onSuccess { (value) -> Completion<Int> in
return .success(5)
}.ignoreFailures()
self.iMayFailRandomly().onSuccess { (value) -> Void in
NSLog("")
}.ignoreFailures()
}
func iDontReturnValues() -> Future<()> {
let f = Future(.primary) { () -> Int in
return 5
}
let p = Promise<()>()
f.onSuccess { (value) -> Void in
DispatchQueue.main.async {
p.completeWithSuccess(())
}
}.ignoreFailures()
// let's do some async dispatching of things here:
return p.future
}
func imGonnaMapAVoidToAnInt() -> Future<Int> {
let x = self.iDontReturnValues()
.onSuccess { _ -> Void in
NSLog("do stuff")
}.onSuccess { _ -> Int in
return 5
}.onSuccess(.primary) { fffive in
Float(fffive + 10)
}
return x.onSuccess {
Int($0) + 5
}
}
func adding5To5Makes10() -> Future<Int> {
return self.imGonnaMapAVoidToAnInt().onSuccess { (value) in
return value + 5
}
}
func convertNumbersToString() -> Future<String> {
return self.imGonnaMapAVoidToAnInt().onSuccess {
return "\($0)"
}
}
func convertingAFuture() -> Future<NSString> {
let f = convertNumbersToString()
return f.mapAs()
}
func testing() {
_ = Future<Optional<Int>>(success: 5)
// let yx = convertOptionalFutures(x)
// let y : Future<Int64?> = convertOptionalFutures(x)
}
}
| mit | efc5a5124b424ed38cdb99fae3925e6b | 34.838587 | 294 | 0.617973 | 4.850533 | false | false | false | false |
CoderJChen/SWWB | CJWB/CJWB/AppDelegate.swift | 1 | 2744 | //
// AppDelegate.swift
// CJWB
//
// Created by 星驿ios on 2017/7/26.
// Copyright © 2017年 CJ. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var defaultVC : UIViewController? {
let isLogin = CJUserAccountViewModel.shareInstance.isLogin
return isLogin ? CJWelcomeVC() : UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UITabBar.appearance().tintColor = UIColor.orange
UINavigationBar.appearance().tintColor = UIColor.orange
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = defaultVC
window?.makeKeyAndVisible()
// window?.rootViewController = CJMainVC()
// Override point for customization after application launch.
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 invalidate graphics rendering callbacks. 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 active 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:.
}
}
| apache-2.0 | d88b7a835a3fb8962d4effd4740ebae6 | 44.616667 | 285 | 0.729266 | 5.643299 | false | false | false | false |
alblue/MerrySwiftmas | MerrySwiftmas/ChristmasTree.swift | 1 | 1835 | // Copyright (c) 2014 Alex Blewitt. All rights reserved.
// Licensed under the MIT License. See LICENSE for more details.
import SceneKit
let colors = [
UIColor.blueColor(),
UIColor.cyanColor(),
UIColor.magentaColor(),
UIColor.orangeColor(),
UIColor.purpleColor(),
UIColor.redColor(),
UIColor.whiteColor(),
UIColor.yellowColor(),
]
class ChristmasTree: SCNNode {
override init() {
super.init()
// create a cylinder to represent the tree trunk
let cylinder = SCNCylinder(radius:1, height:3)
// create a tree node to add to the scene
let tree = SCNNode(geometry: cylinder)
// and add it to the self node so it is seen
self.addChildNode(tree)
// set the cylinder's colour to brown
cylinder.firstMaterial?.diffuse.contents = UIColor.brownColor()
// adding three stacked cones
for i in 1...3 {
// adding a cone to represent the tree's leaves
let cone = SCNNode(geometry: SCNCone(topRadius:0, bottomRadius:3, height:3))
// position the cone up the Y axis at top of trunk
cone.position.y = 2 * Float(i) + 1
// give the tree trunk a green colour
cone.geometry?.firstMaterial?.diffuse.contents = UIColor.greenColor()
// and add the cone to the tree
tree.addChildNode(cone)
}
// adding presents
for i in 1...3 {
// presents are represented with a box
let present = SCNNode(geometry: SCNBox(width: 1, height: 1, length: 1, chamferRadius: 0))
// presents are coloured blue
present.geometry?.firstMaterial?.diffuse.contents = colors[random() % colors.count]
// position present at base of tree
present.position.x = Float(i % 2) * 2
present.position.z = Float(i / 2) * 2
present.position.y = -1
// and add to the tree
tree.addChildNode(present)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 8e67a6f65c1ce2523fe8b41c18a42045 | 27.671875 | 92 | 0.694823 | 3.449248 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/BlockchainNamespace/Sources/BlockchainNamespace/App/App+DeepLink.swift | 1 | 7384 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Foundation
extension App {
public class DeepLink {
private(set) unowned var app: AppProtocol
private var rules: CurrentValueSubject<[Rule], Never> = .init([])
private var bag: Set<AnyCancellable> = []
init(_ app: AppProtocol) {
self.app = app
}
func start() {
app.publisher(for: blockchain.app.configuration.deep_link.rules, as: [Rule?].self)
.compactMap(\.value)
.map { rules in Array(rules.compacted()) }
.removeDuplicates()
.assign(to: \.rules.value, on: self)
.store(in: &bag)
app.on(blockchain.app.process.deep_link)
.flatMap { [unowned self] event -> AnyPublisher<Session.Event, Never> in
self.app.publisher(for: blockchain.app.is.ready.for.deep_link, as: Bool.self)
.compactMap(\.value)
.filter { $0 }
.prefix(1)
.map { _ in event }
.eraseToAnyPublisher()
}
.flatMap { [unowned self] event -> AnyPublisher<(Session.Event, [Rule]), Never> in
self.rules
.map { rules in (event, rules) }
.eraseToAnyPublisher()
}
.sink { [weak self] event, rules in
self?.process(event: event, with: rules)
}
.store(in: &bag)
}
func process(event: Session.Event, with rules: [Rule]) {
do {
try process(
url: event.context.decode(blockchain.app.process.deep_link.url, as: URL.self),
with: rules
)
} catch {
app.post(error: error)
}
}
public func canProcess(url: URL) -> Bool {
(app.state.yes(if: blockchain.app.deep_link.dsl.is.enabled) && DSL.isDSL(url))
|| (app.state.yes(if: blockchain.app.is.ready.for.deep_link) && rules.value.match(for: url) != nil)
}
func process(url: URL, with rules: [Rule]) {
if app.state.yes(if: blockchain.app.deep_link.dsl.is.enabled), DSL.isDSL(url) {
do {
let dsl = try DSL(url, app: app)
app.state.transaction { state in
for (tag, value) in dsl.context {
state.set(tag.in(app), to: value)
}
}
for (ref, value) in dsl.context where ref.tag.is(blockchain.session.configuration.value) {
app.remoteConfiguration.override(ref.in(app), with: value)
}
if let event = dsl.event {
app.post(event: event, context: Tag.Context(dsl.context))
}
} catch {
app.post(error: error)
}
return
}
guard let match = rules.match(for: url) else {
return
}
app.post(event: match.rule.event, context: Tag.Context(match.parameters()))
}
}
}
extension App.DeepLink {
struct DSL: Equatable, Codable {
var event: Tag.Reference?
var context: [Tag.Reference: String] = [:]
}
}
extension App.DeepLink.DSL {
struct Error: Swift.Error {
let message: String
}
static func isDSL(_ url: URL) -> Bool {
url.path == "/app"
}
init(_ url: URL, app: AppProtocol) throws {
guard App.DeepLink.DSL.isDSL(url) else {
throw Error(message: "Not a \(Self.self): \(url)")
}
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
throw Error(message: "Failed to initialise a \(Self.self) from url \(url)")
}
event = try components.fragment.map { try Tag.Reference(id: $0, in: app.language) }
var context: [Tag.Reference: String] = [:]
for item in components.queryItems ?? [] {
try context[Tag.Reference(id: item.name.removingPercentEncoding ?? item.name, in: app.language)] = item.value?.removingPercentEncoding ?? item.value
}
self.context = context
}
}
extension App.DeepLink {
public struct Rule: Codable, Equatable {
public init(pattern: String, event: Tag.Reference, parameters: [App.DeepLink.Rule.Parameter]) {
self.pattern = pattern
self.event = event
self.parameters = parameters
}
public let pattern: String
public let event: Tag.Reference
public let parameters: [Parameter]
}
}
extension App.DeepLink.Rule {
public struct Parameter: Codable, Equatable {
public init(name: String, alias: Tag) {
self.name = name
self.alias = alias
}
public let name: String
public let alias: Tag
}
public struct Match {
public let url: URL
public let rule: App.DeepLink.Rule
public let result: NSTextCheckingResult
}
}
extension App.DeepLink.Rule.Match {
public func parameters() -> [Tag: String] {
let items = url.queryItems()
return rule.parameters
.reduce(into: [:]) { rules, parameter in
let range = result.range(withName: parameter.name)
rules[parameter.alias] = range.location == NSNotFound
? items[named: parameter.name]?.value
: NSString(string: url.absoluteString).substring(with: range)
}
}
}
extension URL {
func queryItems() -> [URLQueryItem] {
let components = URLComponents(url: self, resolvingAgainstBaseURL: false)
let queryItems = components?.queryItems ?? []
// since the web only uses URL fragments followed by query items,
// it seems to be the easiest way to get the query items back
// ie: https://login.blockchain.com/#/app/asset?code=BTC
let fragmentItems = URLComponents(string: components?.fragment ?? "")?
.queryItems ?? []
return queryItems + fragmentItems
}
}
extension Collection where Element == App.DeepLink.Rule {
public func match(for url: URL) -> App.DeepLink.Rule.Match? {
lazy.compactMap { rule -> App.DeepLink.Rule.Match? in
guard let pattern = try? NSRegularExpression(pattern: rule.pattern) else {
return nil
}
let string = url.absoluteString
guard let match = pattern.firstMatch(
in: string,
range: NSRange(string.startIndex..., in: string)
) else {
return nil
}
return App.DeepLink.Rule.Match(
url: url,
rule: rule,
result: match
)
}
.first
}
}
extension Collection where Element == URLQueryItem {
public subscript(named name: String) -> URLQueryItem? {
item(named: name)
}
public func item(named name: String) -> URLQueryItem? {
first(where: { $0.name == name })
}
}
| lgpl-3.0 | bb4d776494ec6c2b182c7a7de286f2f8 | 32.40724 | 160 | 0.529324 | 4.526671 | false | false | false | false |
CNKCQ/oschina | Pods/SnapKit/Source/ConstraintMakerExtendable.swift | 1 | 4878 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class ConstraintMakerExtendable: ConstraintMakerRelatable {
public var left: ConstraintMakerExtendable {
description.attributes += .left
return self
}
public var top: ConstraintMakerExtendable {
description.attributes += .top
return self
}
public var bottom: ConstraintMakerExtendable {
description.attributes += .bottom
return self
}
public var right: ConstraintMakerExtendable {
description.attributes += .right
return self
}
public var leading: ConstraintMakerExtendable {
description.attributes += .leading
return self
}
public var trailing: ConstraintMakerExtendable {
description.attributes += .trailing
return self
}
public var width: ConstraintMakerExtendable {
description.attributes += .width
return self
}
public var height: ConstraintMakerExtendable {
description.attributes += .height
return self
}
public var centerX: ConstraintMakerExtendable {
description.attributes += .centerX
return self
}
public var centerY: ConstraintMakerExtendable {
description.attributes += .centerY
return self
}
@available(*, deprecated: 3.0, message: "Use lastBaseline instead")
public var baseline: ConstraintMakerExtendable {
description.attributes += .lastBaseline
return self
}
public var lastBaseline: ConstraintMakerExtendable {
description.attributes += .lastBaseline
return self
}
@available(iOS 8.0, OSX 10.11, *)
public var firstBaseline: ConstraintMakerExtendable {
description.attributes += .firstBaseline
return self
}
@available(iOS 8.0, *)
public var leftMargin: ConstraintMakerExtendable {
description.attributes += .leftMargin
return self
}
@available(iOS 8.0, *)
public var rightMargin: ConstraintMakerExtendable {
description.attributes += .rightMargin
return self
}
@available(iOS 8.0, *)
public var topMargin: ConstraintMakerExtendable {
description.attributes += .topMargin
return self
}
@available(iOS 8.0, *)
public var bottomMargin: ConstraintMakerExtendable {
description.attributes += .bottomMargin
return self
}
@available(iOS 8.0, *)
public var leadingMargin: ConstraintMakerExtendable {
description.attributes += .leadingMargin
return self
}
@available(iOS 8.0, *)
public var trailingMargin: ConstraintMakerExtendable {
description.attributes += .trailingMargin
return self
}
@available(iOS 8.0, *)
public var centerXWithinMargins: ConstraintMakerExtendable {
description.attributes += .centerXWithinMargins
return self
}
@available(iOS 8.0, *)
public var centerYWithinMargins: ConstraintMakerExtendable {
description.attributes += .centerYWithinMargins
return self
}
public var edges: ConstraintMakerExtendable {
description.attributes += .edges
return self
}
public var size: ConstraintMakerExtendable {
description.attributes += .size
return self
}
@available(iOS 8.0, *)
public var margins: ConstraintMakerExtendable {
description.attributes += .margins
return self
}
@available(iOS 8.0, *)
public var centerWithinMargins: ConstraintMakerExtendable {
description.attributes += .centerWithinMargins
return self
}
}
| mit | c0c4c94616c853ff712c32520191b4a3 | 28.035714 | 81 | 0.676712 | 5.331148 | false | false | false | false |
chrisjmendez/swift-exercises | Basic/REST/HTTPRequests/Pods/SwiftHTTP/HTTPTask.swift | 1 | 22142 | //////////////////////////////////////////////////////////////////////////////////////////////////
//
// HTTPTask.swift
//
// Created by Dalton Cherry on 6/3/14.
// Copyright (c) 2014 Vluxe. All rights reserved.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
/// HTTP Verbs.
///
/// - GET: For GET requests.
/// - POST: For POST requests.
/// - PUT: For PUT requests.
/// - HEAD: For HEAD requests.
/// - DELETE: For DELETE requests.
/// - PATCH: For PATCH requests.
public enum HTTPMethod: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case HEAD = "HEAD"
case DELETE = "DELETE"
case PATCH = "PATCH"
}
/// Object representation of a HTTP Response.
public class HTTPResponse {
/// The header values in HTTP response.
public var headers: Dictionary<String,String>?
/// The mime type of the HTTP response.
public var mimeType: String?
/// The suggested filename for a downloaded file.
public var suggestedFilename: String?
/// The body or response data of the HTTP Response.
public var responseObject: AnyObject?
/// The status code of the HTTP Response.
public var statusCode: Int?
/// The URL of the HTTP Response.
public var URL: NSURL?
///Returns the response as a string
public var text: String? {
if let d = self.responseObject as? NSData {
return NSString(data: d, encoding: NSUTF8StringEncoding) as? String
} else if let val: AnyObject = self.responseObject {
return "\(val)"
}
return nil
}
//get the description of the response
public var description: String {
var buffer = ""
if let u = self.URL {
buffer += "URL:\n\(u)\n\n"
}
if let heads = self.headers {
buffer += "Headers:\n"
for (key, value) in heads {
buffer += "\(key): \(value)\n"
}
buffer += "\n"
}
if let s = self.text {
buffer += "Payload:\n\(s)\n"
}
return buffer
}
}
/// Holds the blocks of the background task.
class BackgroundBlocks {
// these 2 only get used for background download/upload since they have to be delegate methods
var success:((HTTPResponse) -> Void)?
var failure:((NSError, HTTPResponse?) -> Void)?
var progress:((Double) -> Void)?
/**
Initializes a new Background Block
:param: success The block that is run on a sucessful HTTP Request.
:param: failure The block that is run on a failed HTTP Request.
:param: progress The block that is run on the progress of a HTTP Upload or Download.
*/
init(_ success: ((HTTPResponse) -> Void)?, _ failure: ((NSError, HTTPResponse?) -> Void)?,_ progress: ((Double) -> Void)?) {
self.failure = failure
self.success = success
self.progress = progress
}
}
/// Subclass of NSOperation for handling and scheduling HTTPTask on a NSOperationQueue.
public class HTTPOperation : NSOperation {
private var task: NSURLSessionDataTask!
private var stopped = false
private var running = false
/// Controls if the task is finished or not.
public var done = false
//MARK: Subclassed NSOperation Methods
/// Returns if the task is asynchronous or not. This should always be false.
override public var asynchronous: Bool {
return false
}
/// Returns if the task has been cancelled or not.
override public var cancelled: Bool {
return stopped
}
/// Returns if the task is current running.
override public var executing: Bool {
return running
}
/// Returns if the task is finished.
override public var finished: Bool {
return done
}
/// Returns if the task is ready to be run or not.
override public var ready: Bool {
return !running
}
/// Starts the task.
override public func start() {
super.start()
stopped = false
running = true
done = false
task.resume()
}
/// Cancels the running task.
override public func cancel() {
super.cancel()
running = false
stopped = true
done = true
task.cancel()
}
/// Sets the task to finished.
public func finish() {
self.willChangeValueForKey("isExecuting")
self.willChangeValueForKey("isFinished")
running = false
done = true
self.didChangeValueForKey("isExecuting")
self.didChangeValueForKey("isFinished")
}
}
/// Configures NSURLSession Request for HTTPOperation. Also provides convenience methods for easily running HTTP Request.
public class HTTPTask : NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate {
var backgroundTaskMap = Dictionary<String,BackgroundBlocks>()
//var sess: NSURLSession?
public var baseURL: String?
public var requestSerializer = HTTPRequestSerializer()
public var responseSerializer: HTTPResponseSerializer?
//This gets called on auth challenges. If nil, default handling is use.
//Returning nil from this method will cause the request to be rejected and cancelled
public var auth:((NSURLAuthenticationChallenge) -> NSURLCredential?)?
//MARK: Public Methods
/// A newly minted HTTPTask for your enjoyment.
public override init() {
super.init()
}
/**
Creates a HTTPOperation that can be scheduled on a NSOperationQueue. Called by convenience HTTP verb methods below.
:param: url The url you would like to make a request to.
:param: method The HTTP method/verb for the request.
:param: parameters The parameters are HTTP parameters you would like to send.
:param: success The block that is run on a sucessful HTTP Request.
:param: failure The block that is run on a failed HTTP Request.
:returns: A freshly constructed HTTPOperation to add to your NSOperationQueue.
*/
public func create(url: String, method: HTTPMethod, parameters: Dictionary<String,AnyObject>!, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) -> HTTPOperation? {
let serialReq = createRequest(url, method: method, parameters: parameters)
if serialReq.error != nil {
if failure != nil {
failure(serialReq.error!, nil)
}
return nil
}
let opt = HTTPOperation()
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
let task = session.dataTaskWithRequest(serialReq.request,
completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
opt.finish()
if error != nil {
if failure != nil {
failure(error, nil)
}
return
}
if data != nil {
var responseObject: AnyObject = data
if self.responseSerializer != nil {
let resObj = self.responseSerializer!.responseObjectFromResponse(response, data: data)
if resObj.error != nil {
if failure != nil {
failure(resObj.error!, nil)
}
return
}
if resObj.object != nil {
responseObject = resObj.object!
}
}
var extraResponse = HTTPResponse()
if let hresponse = response as? NSHTTPURLResponse {
extraResponse.headers = hresponse.allHeaderFields as? Dictionary<String,String>
extraResponse.mimeType = hresponse.MIMEType
extraResponse.suggestedFilename = hresponse.suggestedFilename
extraResponse.statusCode = hresponse.statusCode
extraResponse.URL = hresponse.URL
}
extraResponse.responseObject = responseObject
if extraResponse.statusCode > 299 {
if failure != nil {
failure(self.createError(extraResponse.statusCode!), extraResponse)
}
} else if success != nil {
success(extraResponse)
}
} else if failure != nil {
failure(error, nil)
}
})
opt.task = task
return opt
}
/**
Creates a HTTPOperation as a HTTP GET request and starts it for you.
:param: url The url you would like to make a request to.
:param: parameters The parameters are HTTP parameters you would like to send.
:param: success The block that is run on a sucessful HTTP Request.
:param: failure The block that is run on a failed HTTP Request.
*/
public func GET(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) {
var opt = self.create(url, method:.GET, parameters: parameters,success: success,failure: failure)
if opt != nil {
opt!.start()
}
}
/**
Creates a HTTPOperation as a HTTP POST request and starts it for you.
:param: url The url you would like to make a request to.
:param: parameters The parameters are HTTP parameters you would like to send.
:param: success The block that is run on a sucessful HTTP Request.
:param: failure The block that is run on a failed HTTP Request.
*/
public func POST(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) {
var opt = self.create(url, method:.POST, parameters: parameters,success: success,failure: failure)
if opt != nil {
opt!.start()
}
}
/**
Creates a HTTPOperation as a HTTP PATCH request and starts it for you.
:param: url The url you would like to make a request to.
:param: parameters The parameters are HTTP parameters you would like to send.
:param: success The block that is run on a sucessful HTTP Request.
:param: failure The block that is run on a failed HTTP Request.
*/
public func PATCH(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) {
var opt = self.create(url, method:.PATCH, parameters: parameters,success: success,failure: failure)
if opt != nil {
opt!.start()
}
}
/**
Creates a HTTPOperation as a HTTP PUT request and starts it for you.
:param: url The url you would like to make a request to.
:param: parameters The parameters are HTTP parameters you would like to send.
:param: success The block that is run on a sucessful HTTP Request.
:param: failure The block that is run on a failed HTTP Request.
*/
public func PUT(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) {
var opt = self.create(url, method:.PUT, parameters: parameters,success: success,failure: failure)
if opt != nil {
opt!.start()
}
}
/**
Creates a HTTPOperation as a HTTP DELETE request and starts it for you.
:param: url The url you would like to make a request to.
:param: parameters The parameters are HTTP parameters you would like to send.
:param: success The block that is run on a sucessful HTTP Request.
:param: failure The block that is run on a failed HTTP Request.
*/
public func DELETE(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) {
var opt = self.create(url, method:.DELETE, parameters: parameters,success: success,failure: failure)
if opt != nil {
opt!.start()
}
}
/**
Creates a HTTPOperation as a HTTP HEAD request and starts it for you.
:param: url The url you would like to make a request to.
:param: parameters The parameters are HTTP parameters you would like to send.
:param: success The block that is run on a sucessful HTTP Request.
:param: failure The block that is run on a failed HTTP Request.
*/
public func HEAD(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) {
var opt = self.create(url, method:.HEAD, parameters: parameters,success: success,failure: failure)
if opt != nil {
opt!.start()
}
}
/**
Creates and starts a HTTPOperation to download a file in the background.
:param: url The url you would like to make a request to.
:param: parameters The parameters are HTTP parameters you would like to send.
:param: progress The progress returned in the progress block is between 0 and 1.
:param: success The block that is run on a sucessful HTTP Request. The HTTPResponse responseObject object will be a fileURL. You MUST copy the fileURL return in HTTPResponse.responseObject to a new location before using it (e.g. your documents directory).
:param: failure The block that is run on a failed HTTP Request.
*/
public func download(url: String, method: HTTPMethod = .GET, parameters: Dictionary<String,AnyObject>?,progress:((Double) -> Void)!, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) -> NSURLSessionDownloadTask? {
let serialReq = createRequest(url,method: method, parameters: parameters)
if serialReq.error != nil {
failure(serialReq.error!, nil)
return nil
}
let ident = createBackgroundIdent()
let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(ident)
let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
let task = session.downloadTaskWithRequest(serialReq.request)
self.backgroundTaskMap[ident] = BackgroundBlocks(success,failure,progress)
//this does not have to be queueable as Apple's background dameon *should* handle that.
task.resume()
return task
}
//TODO: not implemented yet.
/// not implemented yet.
public func uploadFile(url: String, parameters: Dictionary<String,AnyObject>?, progress:((Double) -> Void)!, success:((HTTPResponse) -> Void)!, failure:((NSError) -> Void)!) -> Void {
let serialReq = createRequest(url,method: .GET, parameters: parameters)
if serialReq.error != nil {
failure(serialReq.error!)
return
}
let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(createBackgroundIdent())
let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
//session.uploadTaskWithRequest(serialReq.request, fromData: nil)
}
//MARK: Private Helper Methods
/**
Creates and starts a HTTPOperation to download a file in the background.
:param: url The url you would like to make a request to.
:param: method The HTTP method/verb for the request.
:param: parameters The parameters are HTTP parameters you would like to send.
:returns: A NSURLRequest from configured requestSerializer.
*/
private func createRequest(url: String, method: HTTPMethod, parameters: Dictionary<String,AnyObject>!) -> (request: NSURLRequest, error: NSError?) {
var urlVal = url
//probably should change the 'http' to something more generic
if !url.hasPrefix("http") && self.baseURL != nil {
var split = url.hasPrefix("/") ? "" : "/"
urlVal = "\(self.baseURL!)\(split)\(url)"
}
if let u = NSURL(string: urlVal) {
return self.requestSerializer.createRequest(u, method: method, parameters: parameters)
}
return (NSURLRequest(),createError(-1001))
}
/**
Creates a random string to use for the identifier of the background download/upload requests.
:returns: Identifier String.
*/
private func createBackgroundIdent() -> String {
let letters = "abcdefghijklmnopqurstuvwxyz"
var str = ""
for var i = 0; i < 14; i++ {
let start = Int(arc4random() % 14)
str.append(letters[advance(letters.startIndex,start)])
}
return "com.vluxe.swifthttp.request.\(str)"
}
/**
Creates a random string to use for the identifier of the background download/upload requests.
:param: code Code for error.
:returns: An NSError.
*/
private func createError(code: Int) -> NSError {
var text = "An error occured"
if code == 404 {
text = "Page not found"
} else if code == 401 {
text = "Access denied"
} else if code == -1001 {
text = "Invalid URL"
}
return NSError(domain: "HTTPTask", code: code, userInfo: [NSLocalizedDescriptionKey: text])
}
/**
Creates a random string to use for the identifier of the background download/upload requests.
:param: identifier The identifier string.
:returns: An NSError.
*/
private func cleanupBackground(identifier: String) {
self.backgroundTaskMap.removeValueForKey(identifier)
}
//MARK: NSURLSession Delegate Methods
/// Method for authentication challenge.
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
if let a = auth {
let cred = a(challenge)
if let c = cred {
completionHandler(.UseCredential, c)
return
}
completionHandler(.RejectProtectionSpace, nil)
return
}
completionHandler(.PerformDefaultHandling, nil)
}
/// Called when the background task failed.
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let err = error {
let blocks = self.backgroundTaskMap[session.configuration.identifier]
if blocks?.failure != nil { //Swift bug. Can't use && with block (radar: 17469794)
blocks?.failure!(err, nil)
cleanupBackground(session.configuration.identifier)
}
}
}
/// The background download finished and reports the url the data was saved to.
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didFinishDownloadingToURL location: NSURL!) {
let blocks = self.backgroundTaskMap[session.configuration.identifier]
if blocks?.success != nil {
var resp = HTTPResponse()
if let hresponse = downloadTask.response as? NSHTTPURLResponse {
resp.headers = hresponse.allHeaderFields as? Dictionary<String,String>
resp.mimeType = hresponse.MIMEType
resp.suggestedFilename = hresponse.suggestedFilename
resp.statusCode = hresponse.statusCode
resp.URL = hresponse.URL
}
resp.responseObject = location
if resp.statusCode > 299 {
if blocks?.failure != nil {
blocks?.failure!(self.createError(resp.statusCode!), resp)
}
return
}
blocks?.success!(resp)
cleanupBackground(session.configuration.identifier)
}
}
/// Will report progress of background download
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let increment = 100.0/Double(totalBytesExpectedToWrite)
var current = (increment*Double(totalBytesWritten))*0.01
if current > 1 {
current = 1;
}
let blocks = self.backgroundTaskMap[session.configuration.identifier]
if blocks?.progress != nil {
blocks?.progress!(current)
}
}
/// The background download finished, don't have to really do anything.
public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
}
//TODO: not implemented yet.
/// not implemented yet. The background upload finished and reports the response data (if any).
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
//add upload finished logic
}
//TODO: not implemented yet.
/// not implemented yet.
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
//add progress block logic
}
//TODO: not implemented yet.
/// not implemented yet.
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
}
}
| mit | 949d9129c36d89de034cf876000c48bb | 40.542214 | 263 | 0.611598 | 5.127837 | false | false | false | false |
mitchtreece/Bulletin | Example/Pods/Espresso/Espresso/Classes/Core/UIKit/UITransition/Transitions/UIZoomTransition.swift | 1 | 3419 | //
// UIZoomTransition.swift
// Espresso
//
// Created by Mitch Treece on 5/10/19.
//
import UIKit
/**
A zooming view controller transition.
*/
public class UIZoomTransition: UITransition {
/// The transition's duration; _defaults to 0.6_.
public var duration: TimeInterval
/// The transition's zoom scale; _defaults to 0.8_.
public var scale: CGFloat
/// The corner radius to apply to the animating view controller; _defaults to 20_.
public var cornerRadius: CGFloat
/**
Initializes the transition with parameters.
- Parameter duration: The transition's animation duration; _defaults to 0.6_.
- Parameter scale: The transition's zoom scale; _defaults to 0.8_.
- Parameter cornerRadius: The corner radius to apply to the animating view controller; _defaults to 20_.
*/
public init(duration: TimeInterval = 0.6, scale: CGFloat = 0.8, cornerRadius: CGFloat = 20) {
self.duration = duration
self.scale = scale
self.cornerRadius = cornerRadius
}
override public func transitionController(for transitionType: TransitionType, info: Info) -> UITransitionController {
let isPresentation = (transitionType == .presentation)
let sourceVC = info.sourceViewController
let destinationVC = info.destinationViewController
let container = info.transitionContainerView
let context = info.context
return UITransitionController(setup: {
if isPresentation {
destinationVC.view.alpha = 0
destinationVC.view.frame = context.finalFrame(for: destinationVC)
destinationVC.view.transform = CGAffineTransform(scaleX: self.scale, y: self.scale)
destinationVC.view.layer.cornerRadius = self.cornerRadius
destinationVC.view.clipsToBounds = true
container.addSubview(destinationVC.view)
}
else {
destinationVC.view.frame = context.finalFrame(for: destinationVC)
container.insertSubview(destinationVC.view, belowSubview: sourceVC.view)
}
}, animations: {
UIAnimation(.spring(damping: 0.9, velocity: CGVector(dx: 0.25, dy: 0)), duration: self.duration, {
if isPresentation {
destinationVC.view.alpha = 1
destinationVC.view.layer.cornerRadius = 0
destinationVC.view.transform = .identity
}
else {
let scaleAddition = ((1 - self.scale) / 3)
let adjustedScale = (self.scale + scaleAddition)
sourceVC.view.alpha = 0
sourceVC.view.layer.cornerRadius = self.cornerRadius
sourceVC.view.transform = CGAffineTransform(scaleX: adjustedScale, y: adjustedScale)
}
})
}, completion: {
sourceVC.view.alpha = 1
context.completeTransition(!context.transitionWasCancelled)
})
}
}
| mit | 4dbb96713edc3230d019a3c53554f59f | 33.535354 | 121 | 0.555133 | 5.78511 | false | false | false | false |
renyufei8023/WeiBo | weibo/Classes/Home/Controller/QRCodeViewController.swift | 1 | 6465 | //
// QRCodeViewController.swift
// weibo
//
// Created by 任玉飞 on 16/4/27.
// Copyright © 2016年 任玉飞. All rights reserved.
//
import UIKit
import AVFoundation
class QRCodeViewController: UIViewController,UITabBarDelegate {
@IBOutlet weak var scanImageView: UIImageView!
@IBOutlet weak var scanLineCons: NSLayoutConstraint!
@IBOutlet weak var containerHeihhtCons: NSLayoutConstraint!
@IBOutlet weak var tabbar: UITabBar!
override func viewDidLoad() {
super.viewDidLoad()
tabbar.selectedItem = tabbar.items![0]
tabbar.delegate = self
statrtAnimation()
startScan()
}
//扫描动画
private func statrtAnimation() {
self.scanLineCons.constant = -self.containerHeihhtCons.constant
self.scanImageView.layoutIfNeeded()
UIView.animateWithDuration(2.0, animations: {
self.scanLineCons.constant = self.containerHeihhtCons.constant
UIView.setAnimationRepeatCount(MAXFLOAT)
self.scanImageView.layoutIfNeeded()
}, completion: nil)
}
private func startScan() {
// 1.判断是否能够将输入添加到会话中
if !session.canAddInput(avcapInput) {
return
}
// 2.判断是否能够将输出添加到会话中
if !session.canAddOutput(output) {
return
}
// 3.将输入和输出都添加到会话中
session.addInput(avcapInput)
print(output.availableMetadataObjectTypes)
session.addOutput(output)
print(output.availableMetadataObjectTypes)
// 4.设置输出能够解析的数据类型
// 注意: 设置能够解析的数据类型, 一定要在输出对象添加到会员之后设置, 否则会报错
output.metadataObjectTypes = output.availableMetadataObjectTypes
// 5.设置输出对象的代理, 只要解析成功就会通知代理
output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
// 添加预览图层
view.layer.insertSublayer(previewLayer, atIndex: 0)
// 添加绘制图层到预览层上面
previewLayer.addSublayer(drawlayer)
// 6.开始扫描
session.startRunning()
}
func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
if item.tag == 1 {
self.containerHeihhtCons.constant = 300
}else{
self.containerHeihhtCons.constant = 150
}
self.scanImageView.layer.removeAllAnimations()
statrtAnimation()
}
//会话
private lazy var session: AVCaptureSession = AVCaptureSession ()
//拿到输入设备,可能是空的所以是可选类型
private lazy var avcapInput: AVCaptureDeviceInput? = {
// 获取摄像头
let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
do{
// 创建输入对象
let input = try AVCaptureDeviceInput(device: device)
return input
}catch{
print(error)
return nil
}
}()
//拿到输出对象
private lazy var output: AVCaptureMetadataOutput = AVCaptureMetadataOutput()
//创建预览图层
private lazy var previewLayer: AVCaptureVideoPreviewLayer = {
let layer = AVCaptureVideoPreviewLayer(session: self.session)
layer.frame = UIScreen.mainScreen().bounds
return layer
}()
private lazy var drawlayer: CALayer = {
let layer = CALayer()
layer.frame = UIScreen.mainScreen().bounds
return layer
}()
@IBAction func close(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func myCardBtnClick(sender: AnyObject) {
navigationController?.pushViewController(QRCodeCardViewController(), animated: true)
}
}
extension QRCodeViewController: AVCaptureMetadataOutputObjectsDelegate
{
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!)
{
//0.清空图层
clearConers()
print(metadataObjects.last?.stringValue)
//1.获取扫描到二维码的位置
for object in metadataObjects {
//1.1判断当前获取到的数据,是否是机器可以识别的类型
if object is AVMetadataMachineReadableCodeObject {
//1.2将坐标转换界面可是别的坐标
let codeobject = previewLayer.transformedMetadataObjectForMetadataObject(object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
drawCorners(codeobject)
}
}
}
private func drawCorners(codeobject: AVMetadataMachineReadableCodeObject) {
if codeobject.corners.isEmpty {
return
}
//1.创建一个图层
let layer = CAShapeLayer()
layer.lineWidth = 2
layer.strokeColor = UIColor.greenColor().CGColor
layer.fillColor = UIColor.clearColor().CGColor
//2.创建一个路径
let path = UIBezierPath()
var point = CGPointZero
var index = 0
//2.1移动第一个点
CGPointMakeWithDictionaryRepresentation((codeobject.corners[index++] as! CFDictionaryRef), &point)
path.moveToPoint(point)
//2.2移动到其他的点
while index < codeobject.corners.count {
CGPointMakeWithDictionaryRepresentation((codeobject.corners[index++] as! CFDictionaryRef), &point)
path.addLineToPoint(point)
}
//2.3关闭路径
path.closePath()
//2.4绘制路径
layer.path = path.CGPath
//3.将绘制好的图层添加到drawLayer上
drawlayer.addSublayer(layer)
}
private func clearConers() {
// 1.判断drawLayer上是否有其它图层
if drawlayer.sublayers == nil || drawlayer.sublayers?.count == 0 {
return
}
//2.移除所有子图层
for subLayer in drawlayer.sublayers! {
subLayer.removeFromSuperlayer()
}
}
}
| mit | c02e4d06169b18c34533d7dac29ede75 | 28.467337 | 160 | 0.611357 | 5.037801 | false | false | false | false |
GraphQLSwift/GraphQL | Sources/GraphQL/Subscription/Subscribe.swift | 1 | 11523 | import NIO
import OrderedCollections
/**
* Implements the "Subscribe" algorithm described in the GraphQL specification.
*
* Returns a future which resolves to a SubscriptionResult containing either
* a SubscriptionObservable (if successful), or GraphQLErrors (error).
*
* If the client-provided arguments to this function do not result in a
* compliant subscription, the future will resolve to a
* SubscriptionResult containing `errors` and no `observable`.
*
* If the source stream could not be created due to faulty subscription
* resolver logic or underlying systems, the future will resolve to a
* SubscriptionResult containing `errors` and no `observable`.
*
* If the operation succeeded, the future will resolve to a SubscriptionResult,
* containing an `observable` which yields a stream of GraphQLResults
* representing the response stream.
*
* Accepts either an object with named arguments, or individual arguments.
*/
func subscribe(
queryStrategy: QueryFieldExecutionStrategy,
mutationStrategy: MutationFieldExecutionStrategy,
subscriptionStrategy: SubscriptionFieldExecutionStrategy,
instrumentation: Instrumentation,
schema: GraphQLSchema,
documentAST: Document,
rootValue: Any,
context: Any,
eventLoopGroup: EventLoopGroup,
variableValues: [String: Map] = [:],
operationName: String? = nil
) -> EventLoopFuture<SubscriptionResult> {
let sourceFuture = createSourceEventStream(
queryStrategy: queryStrategy,
mutationStrategy: mutationStrategy,
subscriptionStrategy: subscriptionStrategy,
instrumentation: instrumentation,
schema: schema,
documentAST: documentAST,
rootValue: rootValue,
context: context,
eventLoopGroup: eventLoopGroup,
variableValues: variableValues,
operationName: operationName
)
return sourceFuture.map { sourceResult -> SubscriptionResult in
if let sourceStream = sourceResult.stream {
let subscriptionStream = sourceStream.map { eventPayload -> Future<GraphQLResult> in
// For each payload yielded from a subscription, map it over the normal
// GraphQL `execute` function, with `payload` as the rootValue.
// This implements the "MapSourceToResponseEvent" algorithm described in
// the GraphQL specification. The `execute` function provides the
// "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the
// "ExecuteQuery" algorithm, for which `execute` is also used.
execute(
queryStrategy: queryStrategy,
mutationStrategy: mutationStrategy,
subscriptionStrategy: subscriptionStrategy,
instrumentation: instrumentation,
schema: schema,
documentAST: documentAST,
rootValue: eventPayload,
context: context,
eventLoopGroup: eventLoopGroup,
variableValues: variableValues,
operationName: operationName
)
}
return SubscriptionResult(stream: subscriptionStream, errors: sourceResult.errors)
} else {
return SubscriptionResult(errors: sourceResult.errors)
}
}
}
/**
* Implements the "CreateSourceEventStream" algorithm described in the
* GraphQL specification, resolving the subscription source event stream.
*
* Returns a Future which resolves to a SourceEventStreamResult, containing
* either an Observable (if successful) or GraphQLErrors (error).
*
* If the client-provided arguments to this function do not result in a
* compliant subscription, the future will resolve to a
* SourceEventStreamResult containing `errors` and no `observable`.
*
* If the source stream could not be created due to faulty subscription
* resolver logic or underlying systems, the future will resolve to a
* SourceEventStreamResult containing `errors` and no `observable`.
*
* If the operation succeeded, the future will resolve to a SubscriptionResult,
* containing an `observable` which yields a stream of event objects
* returned by the subscription resolver.
*
* A Source Event Stream represents a sequence of events, each of which triggers
* a GraphQL execution for that event.
*
* This may be useful when hosting the stateful subscription service in a
* different process or machine than the stateless GraphQL execution engine,
* or otherwise separating these two steps. For more on this, see the
* "Supporting Subscriptions at Scale" information in the GraphQL specification.
*/
func createSourceEventStream(
queryStrategy: QueryFieldExecutionStrategy,
mutationStrategy: MutationFieldExecutionStrategy,
subscriptionStrategy: SubscriptionFieldExecutionStrategy,
instrumentation: Instrumentation,
schema: GraphQLSchema,
documentAST: Document,
rootValue: Any,
context: Any,
eventLoopGroup: EventLoopGroup,
variableValues: [String: Map] = [:],
operationName: String? = nil
) -> EventLoopFuture<SourceEventStreamResult> {
let executeStarted = instrumentation.now
do {
// If a valid context cannot be created due to incorrect arguments,
// this will throw an error.
let exeContext = try buildExecutionContext(
queryStrategy: queryStrategy,
mutationStrategy: mutationStrategy,
subscriptionStrategy: subscriptionStrategy,
instrumentation: instrumentation,
schema: schema,
documentAST: documentAST,
rootValue: rootValue,
context: context,
eventLoopGroup: eventLoopGroup,
rawVariableValues: variableValues,
operationName: operationName
)
return try executeSubscription(context: exeContext, eventLoopGroup: eventLoopGroup)
} catch let error as GraphQLError {
instrumentation.operationExecution(
processId: processId(),
threadId: threadId(),
started: executeStarted,
finished: instrumentation.now,
schema: schema,
document: documentAST,
rootValue: rootValue,
eventLoopGroup: eventLoopGroup,
variableValues: variableValues,
operation: nil,
errors: [error],
result: nil
)
return eventLoopGroup.next().makeSucceededFuture(SourceEventStreamResult(errors: [error]))
} catch {
return eventLoopGroup.next()
.makeSucceededFuture(SourceEventStreamResult(errors: [GraphQLError(error)]))
}
}
func executeSubscription(
context: ExecutionContext,
eventLoopGroup: EventLoopGroup
) throws -> EventLoopFuture<SourceEventStreamResult> {
// Get the first node
let type = try getOperationRootType(schema: context.schema, operation: context.operation)
var inputFields: OrderedDictionary<String, [Field]> = [:]
var visitedFragmentNames: [String: Bool] = [:]
let fields = try collectFields(
exeContext: context,
runtimeType: type,
selectionSet: context.operation.selectionSet,
fields: &inputFields,
visitedFragmentNames: &visitedFragmentNames
)
// If query is valid, fields should have at least 1 member
guard
let responseName = fields.keys.first,
let fieldNodes = fields[responseName],
let fieldNode = fieldNodes.first
else {
throw GraphQLError(
message: "Subscription field resolution resulted in no field nodes."
)
}
guard let fieldDef = getFieldDef(schema: context.schema, parentType: type, fieldAST: fieldNode)
else {
throw GraphQLError(
message: "The subscription field '\(fieldNode.name.value)' is not defined.",
nodes: fieldNodes
)
}
// Implements the "ResolveFieldEventStream" algorithm from GraphQL specification.
// It differs from "ResolveFieldValue" due to providing a different `resolveFn`.
// Build a map of arguments from the field.arguments AST, using the
// variables scope to fulfill any variable references.
let args = try getArgumentValues(
argDefs: fieldDef.args,
argASTs: fieldNode.arguments,
variables: context.variableValues
)
// The resolve function's optional third argument is a context value that
// is provided to every resolve function within an execution. It is commonly
// used to represent an authenticated user, or request-specific caches.
let contextValue = context.context
// The resolve function's optional fourth argument is a collection of
// information about the current execution state.
let path = IndexPath().appending(fieldNode.name.value)
let info = GraphQLResolveInfo(
fieldName: fieldDef.name,
fieldASTs: fieldNodes,
returnType: fieldDef.type,
parentType: type,
path: path,
schema: context.schema,
fragments: context.fragments,
rootValue: context.rootValue,
operation: context.operation,
variableValues: context.variableValues
)
// Call the `subscribe()` resolver or the default resolver to produce an
// Observable yielding raw payloads.
let resolve = fieldDef.subscribe ?? defaultResolve
// Get the resolve func, regardless of if its result is normal
// or abrupt (error).
let resolvedFutureOrError = resolveOrError(
resolve: resolve,
source: context.rootValue,
args: args,
context: contextValue,
eventLoopGroup: eventLoopGroup,
info: info
)
let resolvedFuture: Future<Any?>
switch resolvedFutureOrError {
case let .failure(error):
if let graphQLError = error as? GraphQLError {
throw graphQLError
} else {
throw GraphQLError(error)
}
case let .success(success):
resolvedFuture = success
}
return resolvedFuture.map { resolved -> SourceEventStreamResult in
if !context.errors.isEmpty {
return SourceEventStreamResult(errors: context.errors)
} else if let error = resolved as? GraphQLError {
return SourceEventStreamResult(errors: [error])
} else if let stream = resolved as? EventStream<Any> {
return SourceEventStreamResult(stream: stream)
} else if resolved == nil {
return SourceEventStreamResult(errors: [
GraphQLError(message: "Resolved subscription was nil"),
])
} else {
let resolvedObj = resolved as AnyObject
return SourceEventStreamResult(errors: [
GraphQLError(
message: "Subscription field resolver must return EventStream<Any>. Received: '\(resolvedObj)'"
),
])
}
}
}
// Subscription resolvers MUST return observables that are declared as 'Any' due to Swift not having covariant generic support for type
// checking. Normal resolvers for subscription fields should handle type casting, same as resolvers for query fields.
struct SourceEventStreamResult {
public let stream: EventStream<Any>?
public let errors: [GraphQLError]
public init(stream: EventStream<Any>? = nil, errors: [GraphQLError] = []) {
self.stream = stream
self.errors = errors
}
}
| mit | 6671d27686c20834f7b858bb17e296b9 | 38.871972 | 135 | 0.677081 | 5.23297 | false | false | false | false |
MikeThomas1/RDICalculator | RDICalculator/Public/UnitsOfMeasure/Calculator/RDICalculator.swift | 1 | 3769 | //
// RDICalculator.swift
// RDICalculator
//
// Created by Michael Thomas on 8/30/17.
// Copyright © 2017 Vault-Tec. All rights reserved.
//
import Foundation
/**
This class handles calculating RDI (Recommended Daily Intake).
*/
public class RDICalculator {
/**
Gender, used to calculate RDI. Represents gender at birth.
*/
public enum Gender {
/**
The male gender. XY chromosomes.
*/
case male
/**
The female gender. XX chromosomes
*/
case female
internal func calories(kilogram: Kilogram, centimeter: Centimeter, age: Double, activity: ActivityLevel) -> Double {
switch self {
case .male:
let cals = (((66 + (13.7 * kilogram.value))) + (5 * centimeter.value)) - (6.8 * age)
return cals * activity.calRewardRate
case .female:
let cals = (((655 + (9.6 * kilogram.value))) + (1.8 * centimeter.value)) - (4.7 * age)
return cals * activity.calRewardRate
}
}
}
/**
The activity level of the person of which to calculate RDI for.
*/
public enum ActivityLevel {
/**
Little or no exercise, desk job
*/
case sedentary
/**
Light exercise/sports 1-3 days/wk
*/
case lightlyActive
/**
Moderate exercise/sports 3-5 days/wk
*/
case moderatelyActive
/**
Hard exercise/sports 6-7 days/wk
*/
case veryActive
/**
Hard daily exercise/sports & physical job
*/
case extremelyActive
internal var calRewardRate: Double {
switch self {
case .sedentary:
return 1.2
case .lightlyActive:
return 1.375
case .moderatelyActive:
return 1.55
case .veryActive:
return 1.725
case .extremelyActive:
return 1.9
}
}
}
/**
Calculates RDI (Recommended Daily Intake).
RDI (Recommended Daily Intake) calculated based on height, weight, gender, age, and activity.
- parameter height: The height of the person which to calculate RDI for. SeeAlso
- parameter weight: The weight of the person which to calculate RDI for. SeeAlso
- parameter gender: The gender of the person which to calculate RDI for. SeeAlso
- parameter age: The age of the person which to calculate RDI for.
- parameter activity: The activity level of the person which to calculate RDI for.
- returns: A RDI object containing calculated RDI.
*/
public static func calculate(height: Height, weight: Weight, gender: Gender, age: Int, activity: ActivityLevel) -> RDI {
let totalCalories = gender.calories(kilogram: weight.kilogram, centimeter: height.centimeter, age: Double(age), activity: activity)
let carbs: Carbohydrate = makeUnit(from: totalCalories)
let protein: Protein = makeUnit(from: totalCalories)
let fat: Fat = makeUnit(from: totalCalories)
return RDI(totalCalories: totalCalories, carbohydrate: carbs, protein: protein, fat: fat)
}
}
private extension RDICalculator {
static func makeUnit<T: RDIUnit>(of rdiUnitType: T, from totalCalories: Double) -> T {
let unit: T = makeUnit(from: totalCalories)
return unit
}
static func makeUnit<T: RDIUnit>(from totalCalories: Double) -> T {
let calories = totalCalories * T.percentage
return T(calories: calories)
}
}
| mit | ea783afbd801110e15aa1e34f6820a41 | 29.387097 | 139 | 0.572983 | 4.464455 | false | false | false | false |
bliker/ipython-osx | IPython/AppDelegate.swift | 1 | 1583 | //
// AppDelegate.swift
// IPython
//
// Created by Samuel Vasko on 17/12/14.
// Copyright (c) 2014 Samuel Vasko. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var shell: NSTask?
func applicationDidFinishLaunching(aNotification: NSNotification) {
var shell = NSTask()
shell.launchPath = "/usr/local/bin/ipython"
shell.arguments = ["notebook", "--no-browser"]
let pipe = NSPipe()
shell.standardOutput = pipe
pipe.fileHandleForReading.waitForDataInBackgroundAndNotify()
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: "receivedData:", name: NSFileHandleDataAvailableNotification, object: nil)
// You can also set a function to fire after the task terminates
shell.terminationHandler = {task -> Void in
// Handle the task ending here
}
// shell.launch()
}
func applicationWillTerminate(aNotification: NSNotification) {
println("closing")
}
// Take care of printing output of ipyton command
func receivedData(notif : NSNotification) {
let fh:NSFileHandle = notif.object as NSFileHandle
let data = fh.availableData
if data.length > 1 {
fh.waitForDataInBackgroundAndNotify()
let string = NSString(data: data, encoding: NSASCIIStringEncoding)
println(string!)
}
}
}
| mit | 2bb5095f2b4f00c56743cd04089eefea | 26.77193 | 129 | 0.63487 | 5.13961 | false | false | false | false |
fgengine/quickly | Quickly/Views/Pagebar/Default/QPagebarTitleCell.swift | 1 | 3060 | //
// Quickly
//
open class QPagebarTitleItem : QPagebarItem {
public var edgeInsets: UIEdgeInsets
public var title: QLabelStyleSheet
public var backgroundColor: UIColor?
public var selectedBackgroundColor: UIColor?
public init(
edgeInsets: UIEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4),
title: QLabelStyleSheet,
backgroundColor: UIColor? = nil,
selectedBackgroundColor: UIColor? = nil
) {
self.title = title
self.backgroundColor = backgroundColor
self.selectedBackgroundColor = selectedBackgroundColor
self.edgeInsets = edgeInsets
super.init(
canSelect: true,
canDeselect: true
)
}
}
open class QPagebarTitleCell< ItemType: QPagebarTitleItem > : QPagebarCell< ItemType > {
private lazy var _titleLabel: QLabel = {
let view = QLabel(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
private var _edgeInsets: UIEdgeInsets?
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.contentView.removeConstraints(self._constraints) }
didSet { self.contentView.addConstraints(self._constraints) }
}
open override class func size(
item: ItemType,
layout: UICollectionViewLayout,
section: IQCollectionSection,
spec: IQContainerSpec
) -> CGSize {
let availableWidth = spec.containerSize.width - (item.edgeInsets.left + item.edgeInsets.right)
let textSize = item.title.size(width: availableWidth)
return CGSize(
width: item.edgeInsets.left + textSize.width + item.edgeInsets.right,
height: spec.containerSize.height
)
}
open override func set(item: ItemType, spec: IQContainerSpec, animated: Bool) {
super.set(item: item, spec: spec, animated: animated)
if let backgroundColor = item.backgroundColor {
self.backgroundColor = backgroundColor
}
if let selectedBackgroundColor = item.selectedBackgroundColor {
let view = UIView(frame: self.bounds)
view.backgroundColor = selectedBackgroundColor
self.selectedBackgroundView = view
} else {
self.selectedBackgroundView = nil
}
if self._edgeInsets != item.edgeInsets {
self._edgeInsets = item.edgeInsets
self._constraints = [
self._titleLabel.topLayout == self.contentView.topLayout.offset(item.edgeInsets.top),
self._titleLabel.leadingLayout == self.contentView.leadingLayout.offset(item.edgeInsets.left),
self._titleLabel.trailingLayout == self.contentView.trailingLayout.offset(-item.edgeInsets.right),
self._titleLabel.bottomLayout == self.contentView.bottomLayout.offset(-item.edgeInsets.bottom)
]
}
self._titleLabel.apply(item.title)
}
}
| mit | 8af7184735c76e9e9c1f9596bd496235 | 34.581395 | 114 | 0.65 | 5.151515 | false | false | false | false |
ello/ello-ios | Sources/Controllers/ArtistInvites/Cells/ArtistInviteBubbleCell.swift | 1 | 12427 | ////
/// ArtistInviteBubbleCell.swift
//
import SnapKit
import SVGKit
import PINRemoteImage
class ArtistInviteBubbleCell: CollectionViewCell, ArtistInviteConfigurableCell {
static let reuseIdentifier = "ArtistInviteBubbleCell"
struct Size {
static let headerImageHeight: CGFloat = 230
static let infoTotalHeight: CGFloat = 86
static let logoImageSize = CGSize(width: 270, height: 152)
static let cornerRadius: CGFloat = 5
static let bubbleMargins = UIEdgeInsets(top: 0, left: 15, bottom: 15, right: 15)
static let infoMargins = UIEdgeInsets(top: 15, left: 15, bottom: 0, right: 15)
static let titleStatusSpacing: CGFloat = 21.5
static let dotYOffset: CGFloat = -1
static let dotStatusSpacing: CGFloat = 15
static let statusTypeDateSpacing: CGFloat = 10
static let descriptionMargins = UIEdgeInsets(top: 20, left: 15, bottom: 15, right: 15)
}
struct Config {
var title: String = ""
var inviteType: String = ""
var status: ArtistInvite.Status = .open
var shortDescription: String = ""
var longDescription: String = ""
var headerURL: URL?
var logoURL: URL?
var openedAt: Date?
var closedAt: Date?
var isInCountdown: Bool { return status == .open }
}
var config = Config() {
didSet {
updateConfig()
}
}
private let bg = UIView()
private let headerImage = PINAnimatedImageView()
private let headerOverlay = UIView()
private let logoImage = UIImageView()
private let titleLabel = StyledLabel(style: .artistInviteTitle)
private let statusImage = UIImageView()
private let statusLabel = StyledLabel()
private let inviteTypeLabel = StyledLabel(style: .gray)
private let dateLabel = StyledLabel(style: .gray)
private let descriptionWebView = ElloWebView()
static func calculateDynamicHeights(title: String, inviteType: String, cellWidth: CGFloat)
-> CGFloat
{
let textWidth = cellWidth - Size.bubbleMargins.sides - Size.infoMargins.sides
let height1 = NSAttributedString(
label: title,
style: .artistInviteTitle,
lineBreakMode: .byWordWrapping
).heightForWidth(textWidth)
let height2 = NSAttributedString(
label: inviteType,
style: .gray,
lineBreakMode: .byWordWrapping
).heightForWidth(textWidth)
return height1 + height2
}
override func style() {
bg.layer.cornerRadius = Size.cornerRadius
bg.clipsToBounds = true
bg.backgroundColor = .greyF2
headerImage.contentMode = .scaleAspectFill
headerImage.clipsToBounds = true
headerOverlay.backgroundColor = .black
headerOverlay.alpha = 0.3
logoImage.contentMode = .scaleAspectFit
logoImage.clipsToBounds = true
titleLabel.isMultiline = true
inviteTypeLabel.isMultiline = true
descriptionWebView.scrollView.isScrollEnabled = false
descriptionWebView.scrollView.scrollsToTop = false
descriptionWebView.isUserInteractionEnabled = false
}
override func bindActions() {
descriptionWebView.delegate = self
}
override func arrange() {
contentView.addSubview(bg)
bg.addSubview(headerImage)
bg.addSubview(headerOverlay)
bg.addSubview(logoImage)
bg.addSubview(titleLabel)
bg.addSubview(statusImage)
bg.addSubview(statusLabel)
bg.addSubview(inviteTypeLabel)
bg.addSubview(dateLabel)
bg.addSubview(descriptionWebView)
bg.snp.makeConstraints { make in
make.edges.equalTo(contentView).inset(Size.bubbleMargins)
}
headerImage.snp.makeConstraints { make in
make.top.leading.trailing.equalTo(bg)
make.height.equalTo(Size.headerImageHeight)
}
headerOverlay.snp.makeConstraints { make in
make.edges.equalTo(headerImage)
}
logoImage.snp.makeConstraints { make in
make.center.equalTo(headerImage)
make.size.equalTo(Size.logoImageSize).priority(Priority.medium)
make.width.lessThanOrEqualTo(bg).priority(Priority.required)
make.height.equalTo(logoImage.snp.width).multipliedBy(
Size.logoImageSize.height / Size.logoImageSize.width
).priority(Priority.required)
}
logoImage.setContentCompressionResistancePriority(
UILayoutPriority.defaultLow,
for: .vertical
)
logoImage.setContentCompressionResistancePriority(
UILayoutPriority.defaultLow,
for: .horizontal
)
titleLabel.snp.makeConstraints { make in
make.leading.trailing.equalTo(bg).inset(Size.infoMargins)
make.top.equalTo(headerImage.snp.bottom).offset(Size.infoMargins.top)
}
statusImage.snp.makeConstraints { make in
make.centerY.equalTo(statusLabel).offset(Size.dotYOffset)
make.leading.equalTo(titleLabel)
}
statusLabel.snp.makeConstraints { make in
make.leading.equalTo(statusImage.snp.trailing).offset(Size.dotStatusSpacing)
make.top.equalTo(titleLabel.snp.bottom).offset(Size.titleStatusSpacing)
}
inviteTypeLabel.snp.makeConstraints { make in
make.leading.trailing.equalTo(titleLabel)
make.top.equalTo(statusLabel.snp.bottom).offset(Size.statusTypeDateSpacing)
}
dateLabel.snp.makeConstraints { make in
make.top.equalTo(inviteTypeLabel.snp.bottom).offset(Size.statusTypeDateSpacing)
make.leading.trailing.equalTo(titleLabel)
}
descriptionWebView.snp.makeConstraints { make in
make.leading.trailing.bottom.equalTo(bg).inset(Size.descriptionMargins)
make.top.equalTo(dateLabel.snp.bottom).offset(Size.descriptionMargins.top)
}
}
override func prepareForReuse() {
super.prepareForReuse()
config = Config()
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
if superview != nil && config.isInCountdown {
startTimer()
}
else {
stopTimer()
}
}
private var timer: Timer?
private func startTimer() {
guard timer == nil else { return }
timer = Timer.scheduledTimer(
timeInterval: 0.25,
target: self,
selector: #selector(updateDateText),
userInfo: nil,
repeats: true
)
}
private func stopTimer() {
guard let timer = timer else { return }
timer.invalidate()
self.timer = nil
}
func updateConfig() {
titleLabel.text = config.title
inviteTypeLabel.text = config.inviteType
statusImage.image = config.status.image
statusLabel.text = config.status.text
statusLabel.style = config.status.labelStyle
updateDateText()
let images: [(URL?, UIImageView)] = [
(config.headerURL, headerImage),
(config.logoURL, logoImage),
]
for (url, imageView) in images {
if let url = url {
imageView.pin_setImage(from: url)
}
else {
imageView.pin_cancelImageDownload()
imageView.image = nil
}
}
let html = StreamTextCellHTML.artistInviteHTML(config.shortDescription)
descriptionWebView.loadHTMLString(html, baseURL: URL(string: "/"))
}
@objc
private func updateDateText() {
dateLabel.text = config.dateText()
}
}
extension ArtistInviteBubbleCell.Config {
static func fromArtistInvite(_ artistInvite: ArtistInvite) -> ArtistInviteBubbleCell.Config {
var config = ArtistInviteBubbleCell.Config()
config.title = artistInvite.title
config.shortDescription = artistInvite.shortDescription
config.longDescription = artistInvite.longDescription
config.inviteType = artistInvite.inviteType
config.status = artistInvite.status
config.openedAt = artistInvite.openedAt
config.closedAt = artistInvite.closedAt
config.headerURL = artistInvite.headerImage?.largeOrBest?.url
config.logoURL = artistInvite.logoImage?.optimized?.url
return config
}
}
extension ArtistInvite.Status {
var text: String {
switch self {
case .preview: return InterfaceString.ArtistInvites.PreviewStatus
case .upcoming: return InterfaceString.ArtistInvites.UpcomingStatus
case .open: return InterfaceString.ArtistInvites.OpenStatus
case .selecting: return InterfaceString.ArtistInvites.SelectingStatus
case .closed: return InterfaceString.ArtistInvites.ClosedStatus
}
}
var image: UIImage? {
switch self {
case .preview:
return SVGKImage(named: "artist_invite_status_preview.svg").uiImage.withRenderingMode(
.alwaysOriginal
)
case .upcoming:
return SVGKImage(named: "artist_invite_status_upcoming.svg").uiImage.withRenderingMode(
.alwaysOriginal
)
case .open:
return SVGKImage(named: "artist_invite_status_open.svg").uiImage.withRenderingMode(
.alwaysOriginal
)
case .selecting:
return SVGKImage(named: "artist_invite_status_selecting.svg").uiImage.withRenderingMode(
.alwaysOriginal
)
case .closed:
return SVGKImage(named: "artist_invite_status_closed.svg").uiImage.withRenderingMode(
.alwaysOriginal
)
}
}
var labelStyle: StyledLabel.Style {
switch self {
case .preview: return .artistInvitePreview
case .upcoming: return .artistInviteUpcoming
case .open: return .artistInviteOpen
case .selecting: return .artistInviteSelecting
case .closed: return .artistInviteClosed
}
}
}
extension StyledLabel.Style {
static let artistInviteTitle = StyledLabel.Style(
textColor: .black,
fontFamily: .artistInviteTitle
)
static let artistInvitePreview = StyledLabel.Style(
textColor: UIColor(hex: 0x0409FE)
)
static let artistInviteUpcoming = StyledLabel.Style(
textColor: UIColor(hex: 0xC000FF)
)
static let artistInviteOpen = StyledLabel.Style(
textColor: UIColor(hex: 0x00D100)
)
static let artistInviteSelecting = StyledLabel.Style(
textColor: UIColor(hex: 0xFDB02A)
)
static let artistInviteClosed = StyledLabel.Style(
textColor: UIColor(hex: 0xFE0404)
)
}
extension ArtistInviteBubbleCell.Config {
func dateText() -> String {
switch status {
case .preview, .upcoming:
return ""
case .selecting:
return InterfaceString.ArtistInvites.Selecting
case .closed:
guard let closedAt = closedAt else { return "" }
return InterfaceString.ArtistInvites.Ended(closedAt.monthDayYear())
default: break
}
if let closedAt = closedAt {
return dateTextRemaining(closedAt)
}
return ""
}
private func dateTextRemaining(_ closedAt: Date) -> String {
let now = Globals.now
let secondsRemaining = Int(closedAt.timeIntervalSince(now))
let daysRemaining = Int(secondsRemaining / 24 / 3600)
if daysRemaining > 1 {
return InterfaceString.ArtistInvites.DaysRemaining(daysRemaining)
}
return InterfaceString.ArtistInvites.Countdown(secondsRemaining)
}
}
extension ArtistInviteBubbleCell: UIWebViewDelegate {
func webView(
_ webView: UIWebView,
shouldStartLoadWith request: URLRequest,
navigationType: UIWebView.NavigationType
) -> Bool {
if let scheme = request.url?.scheme, scheme == "default" {
let responder: StreamCellResponder? = findResponder()
responder?.streamCellTapped(cell: self)
return false
}
else {
return ElloWebViewHelper.handle(request: request, origin: self)
}
}
}
| mit | 049e96fd5591ce7580dc47d916cdca50 | 32.677507 | 100 | 0.638288 | 4.964842 | false | true | false | false |
litecoin-association/LoafWallet | BreadWallet/BRWalletPlugin.swift | 2 | 10114 | //
// BRWalletPlugin.swift
// BreadWallet
//
// Created by Samuel Sutch on 2/18/16.
// Copyright (c) 2016 breadwallet LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// 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
@objc class BRWalletPlugin: NSObject, BRHTTPRouterPlugin, BRWebSocketClient {
var sockets = [String: BRWebSocket]()
var tempBitIDKeys = [String: BRKey]() // this should only ever be mutated from the main thread
let manager = BRWalletManager.sharedInstance()!
func announce(_ json: [String: Any]) {
if let jsonData = try? JSONSerialization.data(withJSONObject: json, options: []),
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue) {
for sock in sockets {
sock.1.send(String(jsonString))
}
} else {
print("[BRWalletPlugin] announce() could not encode payload: \(json)")
}
}
func hook(_ router: BRHTTPRouter) {
router.websocket("/_wallet/_socket", client: self)
let noteCenter = NotificationCenter.default
noteCenter.addObserver(forName: NSNotification.Name.BRPeerManagerSyncStarted,
object: nil, queue: nil) { (note) in
self.announce(["type": "sync_started"])
}
noteCenter.addObserver(forName: NSNotification.Name.BRPeerManagerSyncFailed,
object: nil, queue: nil) { (note) in
self.announce(["type": "sync_failed"])
}
noteCenter.addObserver(forName: NSNotification.Name.BRPeerManagerSyncFinished,
object: nil, queue: nil) { (note) in
self.announce(["type": "sync_finished"])
}
noteCenter.addObserver(forName: NSNotification.Name.BRPeerManagerTxStatus,
object: nil, queue: nil) { (note) in
self.announce(["type": "tx_status"])
}
noteCenter.addObserver(forName: NSNotification.Name.BRWalletManagerSeedChanged,
object: nil, queue: nil) { (note) in
if let wallet = self.manager.wallet {
self.announce(["type": "seed_changed", "balance": Int(wallet.balance)])
}
}
noteCenter.addObserver(forName: NSNotification.Name.BRWalletBalanceChanged,
object: nil, queue: nil) { (note) in
if let wallet = self.manager.wallet {
self.announce(["type": "balance_changed", "balance": Int(wallet.balance)])
}
}
router.get("/_wallet/info") { (request, match) -> BRHTTPResponse in
return try BRHTTPResponse(request: request, code: 200, json: self.walletInfo())
}
router.get("/_wallet/format") { (request, match) -> BRHTTPResponse in
if let amounts = request.query["amount"] , amounts.count > 0 {
let amount = amounts[0]
var intAmount: Int64 = 0
if amount.contains(".") { // assume full bitcoins
if let x = Float(amount) {
intAmount = Int64(x * 100000000.0)
}
} else {
if let x = Int64(amount) {
intAmount = x
}
}
return try BRHTTPResponse(request: request, code: 200, json: self.currencyFormat(intAmount))
} else {
return BRHTTPResponse(request: request, code: 400)
}
}
// POST /_wallet/sign_bitid
//
// Sign a message using the user's BitID private key. Calling this WILL trigger authentication
//
// Request body: application/json
// {
// "prompt_string": "Sign in to My Service", // shown to the user in the authentication prompt
// "string_to_sign": "https://bitid.org/bitid?x=2783408723", // the string to sign
// "bitid_url": "https://bitid.org/bitid", // the bitid url for deriving the private key
// "bitid_index": "0" // the bitid index as a string (just pass "0")
// }
//
// Response body: application/json
// {
// "signature": "oibwaeofbawoefb" // base64-encoded signature
// }
router.post("/_wallet/sign_bitid") { (request, match) -> BRHTTPResponse in
guard let cts = request.headers["content-type"] , cts.count == 1 && cts[0] == "application/json" else {
return BRHTTPResponse(request: request, code: 400)
}
guard let data = request.body(),
let j = try? JSONSerialization.jsonObject(with: data, options: []),
let json = j as? [String: String],
let stringToSign = json["string_to_sign"],
let bitidUrlString = json["bitid_url"],
let bitidUrl = URL(string: bitidUrlString),
let bii = json["bitid_index"],
let bitidIndex = Int(bii) else {
return BRHTTPResponse(request: request, code: 400)
}
let asyncResp = BRHTTPResponse(async: request)
var maybeSeed: Data?
DispatchQueue.main.sync {
CFRunLoopPerformBlock(RunLoop.main.getCFRunLoop(), CFRunLoopMode.commonModes.rawValue) {
let biuri = bitidUrl.host ?? bitidUrl.absoluteString
var key = self.tempBitIDKeys[biuri]
if key == nil {
maybeSeed = self.manager.seed(withPrompt: (bitidUrl.host ?? bitidUrl.description), forAmount: 0)
guard let seed = maybeSeed else {
request.queue.async {
asyncResp.provide(401)
}
return
}
let seq = BRBIP32Sequence()
guard let kd = seq.bitIdPrivateKey(UInt32(bitidIndex), forURI: biuri, fromSeed: seed),
let foundkey = BRKey(privateKey: kd) else {
request.queue.async {
asyncResp.provide(500)
}
return
}
// we got the key. hold on to it for 1 minute so the user doesn't have to provide authentication
// multiple times in a row
self.tempBitIDKeys[biuri] = foundkey
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(60)) {
self.tempBitIDKeys[biuri] = nil
}
key = foundkey
}
let sig = BRBitID.signMessage(stringToSign, usingKey: key!)
let ret: [String: Any] = [
"signature": sig,
"address": key!.address ?? ""
]
request.queue.async {
asyncResp.provide(200, json: ret)
}
}
}
return asyncResp
}
}
// MARK: - basic wallet functions
func walletInfo() -> [String: Any] {
let defs = UserDefaults.standard
var d = [String: Any]()
d["no_wallet"] = manager.noWallet
d["watch_only"] = manager.watchOnly
d["receive_address"] = manager.wallet?.receiveAddress
// the users btc,mbtc,bits setting
var mdigits = defs.integer(forKey: "SETTINGS_MAX_DIGITS")
if mdigits == 0 {
mdigits = 2
}
d["btc_denomination_digits"] = mdigits
return d
}
func currencyFormat(_ amount: Int64) -> [String: Any] {
var d = [String: Any]()
d["local_currency_amount"] = manager.localCurrencyString(forAmount: Int64(amount))
d["currency_amount"] = manager.string(forAmount: amount)
return d
}
// MARK: - socket handlers
func sendWalletInfo(_ socket: BRWebSocket) {
var d = self.walletInfo()
d["type"] = "wallet"
if let jdata = try? JSONSerialization.data(withJSONObject: d, options: []),
let jstring = NSString(data: jdata, encoding: String.Encoding.utf8.rawValue) {
socket.send(String(jstring))
}
}
func socketDidConnect(_ socket: BRWebSocket) {
print("WALLET CONNECT \(socket.id)")
sockets[socket.id] = socket
sendWalletInfo(socket)
}
func socketDidDisconnect(_ socket: BRWebSocket) {
print("WALLET DISCONNECT \(socket.id)")
sockets.removeValue(forKey: socket.id)
}
func socket(_ socket: BRWebSocket, didReceiveText text: String) {
print("WALLET RECV \(text)")
socket.send(text)
}
}
| mit | 36c24fa545d1026c31ea6c7621dcc617 | 43.555066 | 120 | 0.542515 | 4.69545 | false | false | false | false |
ccrama/Slide-iOS | Slide for Reddit/SettingsDonate.swift | 1 | 11178 | //
// SettingsDonate.swift
// Slide for Reddit
//
// Created by Carlos Crane on 2/17/19.
// Copyright © 2019 Haptic Apps. All rights reserved.
//
import Anchorage
import BiometricAuthentication
import LicensesViewController
import MessageUI
import RealmSwift
import RLBAlertsPickers
import SDWebImage
import UIKit
class SettingsDonate: UIViewController, MFMailComposeViewControllerDelegate {
static var changed = false
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
if ColorUtil.theme.isLight && SettingValues.reduceColor {
if #available(iOS 13, *) {
return .darkContent
} else {
return .default
}
} else {
return .lightContent
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupBaseBarColors()
navigationController?.setToolbarHidden(true, animated: false)
}
override func loadView() {
super.loadView()
}
var cellsDone = false
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if !cellsDone {
cellsDone = true
doCells()
}
}
var coffee = UILabel()
var bagel = UILabel()
var lunch = UILabel()
func doCells(_ reset: Bool = true) {
self.view.backgroundColor = ColorUtil.theme.backgroundColor
// set the title
self.title = "Tip jar"
let aboutArea = UIView()
let about = UILabel(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: 30))
about.font = UIFont.systemFont(ofSize: 15)
aboutArea.backgroundColor = ColorUtil.theme.foregroundColor
about.textColor = ColorUtil.theme.fontColor
about.text = "Thank you for being a Slide supporter! If you want to continue to support my work, feel free to leave me a tip 🍻\n\nPlease note, this does not enable Pro for your account and is purely a donation. If you have purchased pro and want to restore your purchase, or would like to go pro, exit this dialog and use the \"Support Slide, Go Pro!\" settings option!"
about.numberOfLines = 0
about.textAlignment = .center
about.lineBreakMode = .byClipping
about.sizeToFit()
bagel = UILabel(frame: CGRect.init(x: 0, y: 0, width: 100, height: 45))
bagel.text = "Tip me $2.99"
bagel.backgroundColor = GMColor.lightGreen300Color()
bagel.layer.cornerRadius = 22.5
bagel.clipsToBounds = true
bagel.numberOfLines = 0
bagel.lineBreakMode = .byWordWrapping
bagel.textColor = .white
bagel.font = UIFont.boldSystemFont(ofSize: 16)
bagel.textAlignment = .center
coffee = UILabel(frame: CGRect.init(x: 0, y: 0, width: 100, height: 45))
coffee.text = "Buy me a coffee! (tip $4.99)"
coffee.backgroundColor = GMColor.lightBlue300Color()
coffee.layer.cornerRadius = 22.5
coffee.clipsToBounds = true
coffee.textColor = .white
coffee.numberOfLines = 0
coffee.lineBreakMode = .byWordWrapping
coffee.font = UIFont.boldSystemFont(ofSize: 16)
coffee.textAlignment = .center
lunch = UILabel(frame: CGRect.init(x: 0, y: 0, width: 100, height: 45))
lunch.text = "Buy me lunch! (tip $9.99)"
lunch.backgroundColor = GMColor.red300Color()
lunch.layer.cornerRadius = 22.5
lunch.clipsToBounds = true
lunch.textColor = .white
lunch.numberOfLines = 0
lunch.lineBreakMode = .byWordWrapping
lunch.font = UIFont.boldSystemFont(ofSize: 16)
lunch.textAlignment = .center
bagel.addTapGestureRecognizer {
IAPHandlerTip.shared.purchaseMyProduct(index: 0)
self.alertController = UIAlertController(title: "Processing your tip!\n\n\n", message: nil, preferredStyle: .alert)
let spinnerIndicator = UIActivityIndicatorView(style: .whiteLarge)
spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5)
spinnerIndicator.color = ColorUtil.theme.fontColor
spinnerIndicator.startAnimating()
self.alertController?.view.addSubview(spinnerIndicator)
self.present(self.alertController!, animated: true, completion: nil)
}
coffee.addTapGestureRecognizer {
IAPHandlerTip.shared.purchaseMyProduct(index: 1)
self.alertController = UIAlertController(title: "Processing your tip!\n\n\n", message: nil, preferredStyle: .alert)
let spinnerIndicator = UIActivityIndicatorView(style: .whiteLarge)
spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5)
spinnerIndicator.color = ColorUtil.theme.fontColor
spinnerIndicator.startAnimating()
self.alertController?.view.addSubview(spinnerIndicator)
self.present(self.alertController!, animated: true, completion: nil)
}
lunch.addTapGestureRecognizer {
IAPHandlerTip.shared.purchaseMyProduct(index: 2)
self.alertController = UIAlertController(title: "Processing your tip!\n\n\n", message: nil, preferredStyle: .alert)
let spinnerIndicator = UIActivityIndicatorView(style: .whiteLarge)
spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5)
spinnerIndicator.color = ColorUtil.theme.fontColor
spinnerIndicator.startAnimating()
self.alertController?.view.addSubview(spinnerIndicator)
self.present(self.alertController!, animated: true, completion: nil)
}
aboutArea.addSubview(bagel)
aboutArea.addSubview(coffee)
aboutArea.addSubview(lunch)
aboutArea.addSubview(about)
bagel.horizontalAnchors == aboutArea.horizontalAnchors + 8
coffee.horizontalAnchors == aboutArea.horizontalAnchors + 8
lunch.horizontalAnchors == aboutArea.horizontalAnchors + 8
bagel.topAnchor == about.bottomAnchor + 16
coffee.topAnchor == bagel.bottomAnchor + 12
lunch.topAnchor == coffee.bottomAnchor + 12
bagel.heightAnchor == 45
coffee.heightAnchor == 45
lunch.heightAnchor == 45
about.horizontalAnchors == aboutArea.horizontalAnchors + 12
about.topAnchor == aboutArea.topAnchor + 12
let rect = about.textRect(forBounds: CGRect(x: 0, y: 0, width: self.view.frame.size.width - 24, height: CGFloat.greatestFiniteMagnitude), limitedToNumberOfLines: 0)
self.view.addSubview(aboutArea)
var total = CGFloat(45 * 3)
total += CGFloat(12 * 3)
total += CGFloat(16 + 16)
total += rect.height
self.preferredContentSize = CGSize(width: self.view.frame.size.width, height: total)
aboutArea.edgeAnchors == self.view.edgeAnchors
}
var alertController: UIAlertController?
override func viewDidLoad() {
super.viewDidLoad()
IAPHandlerTip.shared.fetchAvailableProducts()
IAPHandlerTip.shared.getItemsBlock = {(items) in
if items.isEmpty || items.count != 2 {
let alertView = UIAlertController(title: "Slide could not connect to Apple's servers", message: "Something went wrong connecting to Apple, please try again soon! Sorry for any inconvenience this may have caused", preferredStyle: .alert)
let action = UIAlertAction(title: "Close", style: .cancel, handler: { (_) in
})
alertView.addAction(action)
self.present(alertView, animated: true, completion: nil)
}
}
IAPHandlerTip.shared.purchaseStatusBlock = {[weak self] (type) in
guard let strongSelf = self else { return }
if type == .purchased {
strongSelf.alertController?.dismiss(animated: true, completion: nil)
let alertView = UIAlertController(title: "", message: "Thank you for supporting Slide development with your donation!", preferredStyle: .alert)
let action = UIAlertAction(title: "Close", style: .cancel, handler: { (_) in
self?.dismiss(animated: true, completion: nil)
})
alertView.addAction(action)
strongSelf.present(alertView, animated: true, completion: nil)
}
}
IAPHandlerTip.shared.errorBlock = {[weak self] (error) in
guard let strongSelf = self else { return }
strongSelf.alertController?.dismiss(animated: true, completion: nil)
if error != nil {
let alertView = UIAlertController(title: "Something went wrong!", message: "Your account has not been charged.\nError: \(error!)\n\nPlease send me an email if this issue persists!", preferredStyle: .alert)
let action = UIAlertAction(title: "Close", style: .cancel, handler: { (_) in
})
alertView.addAction(action)
alertView.addAction(UIAlertAction.init(title: "Email me", style: .default, handler: { (_) in
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = strongSelf
mail.setToRecipients(["[email protected]"])
mail.setSubject("Slide Pro Purchase")
mail.setMessageBody("<p>Apple ID: \nName:\n\n</p>", isHTML: true)
strongSelf.present(mail, animated: true)
}
}))
strongSelf.present(alertView, animated: true, completion: nil)
} else {
let alertView = UIAlertController(title: "Something went wrong!", message: "Your account has not been charged! \n\nPlease send me an email if this issue persists!", preferredStyle: .alert)
let action = UIAlertAction(title: "Close", style: .cancel, handler: { (_) in
})
alertView.addAction(action)
alertView.addAction(UIAlertAction.init(title: "Email me", style: .default, handler: { (_) in
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = strongSelf
mail.setToRecipients(["[email protected]"])
mail.setSubject("Slide Pro Purchase")
mail.setMessageBody("<p>Apple ID: \nName:\n\n</p>", isHTML: true)
strongSelf.present(mail, animated: true)
}
}))
strongSelf.present(alertView, animated: true, completion: nil)
}
}
}
}
| apache-2.0 | f24c4e8b843635e586bdbf982a4fec6d | 44.056452 | 378 | 0.612046 | 5.01526 | false | false | false | false |
Eflet/Charts | Charts/Classes/Data/Interfaces/ILineChartDataSet.swift | 2 | 3062 | //
// ILineChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
@objc
public protocol ILineChartDataSet: ILineRadarChartDataSet
{
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// The drawing mode for this line dataset
///
/// **default**: Linear
var mode: LineChartDataSet.Mode { get set }
/// Intensity for cubic lines (min = 0.05, max = 1)
///
/// **default**: 0.2
var cubicIntensity: CGFloat { get set }
@available(*, deprecated=1.0, message="Use `mode` instead.")
var drawCubicEnabled: Bool { get set }
@available(*, deprecated=1.0, message="Use `mode` instead.")
var isDrawCubicEnabled: Bool { get }
@available(*, deprecated=1.0, message="Use `mode` instead.")
var drawSteppedEnabled: Bool { get set }
@available(*, deprecated=1.0, message="Use `mode` instead.")
var isDrawSteppedEnabled: Bool { get }
/// The radius of the drawn circles.
var circleRadius: CGFloat { get set }
var circleColors: [NSUIColor] { get set }
/// - returns: the color at the given index of the DataSet's circle-color array.
/// Performs a IndexOutOfBounds check by modulus.
func getCircleColor(index: Int) -> NSUIColor?
/// Sets the one and ONLY color that should be used for this DataSet.
/// Internally, this recreates the colors array and adds the specified color.
func setCircleColor(color: NSUIColor)
/// Resets the circle-colors array and creates a new one
func resetCircleColors(index: Int)
/// If true, drawing circles is enabled
var drawCirclesEnabled: Bool { get set }
/// - returns: true if drawing circles for this DataSet is enabled, false if not
var isDrawCirclesEnabled: Bool { get }
/// The color of the inner circle (the circle-hole).
var circleHoleColor: NSUIColor { get set }
/// True if drawing circles for this DataSet is enabled, false if not
var drawCircleHoleEnabled: Bool { get set }
/// - returns: true if drawing the circle-holes is enabled, false if not.
var isDrawCircleHoleEnabled: Bool { get }
/// This is how much (in pixels) into the dash pattern are we starting from.
var lineDashPhase: CGFloat { get }
/// This is the actual dash pattern.
/// I.e. [2, 3] will paint [-- -- ]
/// [1, 3, 4, 2] will paint [- ---- - ---- ]
var lineDashLengths: [CGFloat]? { get set }
/// Line cap type, default is CGLineCap.Butt
var lineCapType: CGLineCap { get set }
/// Sets a custom FillFormatter to the chart that handles the position of the filled-line for each DataSet. Set this to null to use the default logic.
var fillFormatter: ChartFillFormatter? { get set }
}
| apache-2.0 | a7d169e8969dc76e1937fe2f77dec35d | 32.648352 | 154 | 0.648922 | 4.412104 | false | false | false | false |
ZWCoder/KMLive | KMLive/KMLive/KMFoundation/UIKit/KMNetworkAssitant.swift | 1 | 985 | //
// KMNetworkAssitant.swift
// KMLive
//
// Created by 联合创想 on 16/12/20.
// Copyright © 2016年 KMXC. All rights reserved.
//
import UIKit
import Alamofire
enum KMMethod {
case get
case post
}
class KMNetworkAssitant {
class func requestData(_ type: KMMethod,URLString:String,params:[String:Any]? = nil,finishedCallback:@escaping (_ result:Any) -> ()) {
// 1.获取类型
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
// 2.发送网络请求
Alamofire.request(URLString, method: method, parameters: params).responseJSON { (response) in
// 3.获取结果
guard let result = response.result.value else {
print(response.result.error ?? "")
return
}
// 4.将结果回调出去
finishedCallback(result)
}
}
}
| mit | eaf0c6975b93cd08b4ff10c54b127456 | 20.181818 | 138 | 0.524678 | 4.334884 | false | false | false | false |
zisko/swift | test/SILOptimizer/cast_folding_objc_no_foundation.swift | 1 | 2941 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -O -emit-sil %s | %FileCheck %s
// REQUIRES: objc_interop
// TODO: Update optimizer for id-as-Any changes.
// Note: no 'import Foundation'
struct PlainStruct {}
// CHECK-LABEL: sil shared [noinline] @$S31cast_folding_objc_no_foundation23testAnyObjectToArrayIntySbyXlFTf4g_n
// CHECK: bb0(%0 : $AnyObject):
// CHECK: [[SOURCE:%.*]] = alloc_stack $AnyObject
// CHECK: [[TARGET:%.*]] = alloc_stack $Array<Int>
// CHECK: checked_cast_addr_br take_always AnyObject in [[SOURCE]] : $*AnyObject to Array<Int> in [[TARGET]] : $*Array<Int>, bb1, bb2
@inline(never)
func testAnyObjectToArrayInt(_ a: AnyObject) -> Bool {
return a is [Int]
}
// CHECK-LABEL: sil shared [noinline] @$S31cast_folding_objc_no_foundation26testAnyObjectToArrayStringySbyXlFTf4g_n
// CHECK: bb0(%0 : $AnyObject):
// CHECK: [[SOURCE:%.*]] = alloc_stack $AnyObject
// CHECK: [[TARGET:%.*]] = alloc_stack $Array<String>
// CHECK: checked_cast_addr_br take_always AnyObject in [[SOURCE]] : $*AnyObject to Array<String> in [[TARGET]] : $*Array<String>, bb1, bb2
@inline(never)
func testAnyObjectToArrayString(_ a: AnyObject) -> Bool {
return a is [String]
}
// CHECK-LABEL: sil shared [noinline] @$S31cast_folding_objc_no_foundation30testAnyObjectToArrayNotBridged{{.*}}
// CHECK: bb0(%0 : $AnyObject):
// CHECK: [[SOURCE:%.*]] = alloc_stack $AnyObject
// CHECK: [[TARGET:%.*]] = alloc_stack $Array<PlainStruct>
// CHECK: checked_cast_addr_br take_always AnyObject in [[SOURCE]] : $*AnyObject to Array<PlainStruct> in [[TARGET]] : $*Array<PlainStruct>, bb1, bb2
@inline(never)
func testAnyObjectToArrayNotBridged(_ a: AnyObject) -> Bool {
return a is [PlainStruct]
}
// CHECK-LABEL: sil shared [noinline] @$S31cast_folding_objc_no_foundation25testAnyObjectToDictionaryySbyXlFTf4g_n
// CHECK: bb0(%0 : $AnyObject):
// CHECK: [[SOURCE:%.*]] = alloc_stack $AnyObject
// CHECK: [[TARGET:%.*]] = alloc_stack $Dictionary<Int, String>
// CHECK: checked_cast_addr_br take_always AnyObject in [[SOURCE]] : $*AnyObject to Dictionary<Int, String> in [[TARGET]] : $*Dictionary<Int, String>, bb1, bb2
@inline(never)
func testAnyObjectToDictionary(_ a: AnyObject) -> Bool {
return a is [Int: String]
}
// CHECK-LABEL: sil shared [noinline] @$S31cast_folding_objc_no_foundation21testAnyObjectToStringySbyXlFTf4g_n
// CHECK: bb0(%0 : $AnyObject):
// CHECK: [[SOURCE:%.*]] = alloc_stack $AnyObject
// CHECK: [[TARGET:%.*]] = alloc_stack $String
// CHECK: checked_cast_addr_br take_always AnyObject in [[SOURCE]] : $*AnyObject to String in [[TARGET]] : $*String, bb1, bb2
@inline(never)
func testAnyObjectToString(_ a: AnyObject) -> Bool {
return a is String
}
class SomeObject {}
print(testAnyObjectToArrayInt(SomeObject()))
print(testAnyObjectToArrayString(SomeObject()))
print(testAnyObjectToArrayNotBridged(SomeObject()))
print(testAnyObjectToDictionary(SomeObject()))
print(testAnyObjectToString(SomeObject()))
| apache-2.0 | f61439b29c2e874c9fa27995b5c6835e | 43.560606 | 159 | 0.709283 | 3.505364 | false | true | false | false |
boluomeng/Charts | ChartsRealm/Classes/Data/RealmLineRadarDataSet.swift | 1 | 2251 | //
// RealmLineRadarDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
import Charts
import Realm
import Realm.Dynamic
open class RealmLineRadarDataSet: RealmLineScatterCandleRadarDataSet, ILineRadarChartDataSet
{
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// The color that is used for filling the line surface area.
private var _fillColor = NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)
/// The color that is used for filling the line surface area.
open var fillColor: NSUIColor
{
get { return _fillColor }
set
{
_fillColor = newValue
fill = nil
}
}
/// The object that is used for filling the area below the line.
/// **default**: nil
open var fill: ChartFill?
/// The alpha value that is used for filling the line surface,
/// **default**: 0.33
open var fillAlpha = CGFloat(0.33)
private var _lineWidth = CGFloat(1.0)
/// line width of the chart (min = 0.2, max = 10)
///
/// **default**: 1
open var lineWidth: CGFloat
{
get
{
return _lineWidth
}
set
{
if (newValue < 0.2)
{
_lineWidth = 0.2
}
else if (newValue > 10.0)
{
_lineWidth = 10.0
}
else
{
_lineWidth = newValue
}
}
}
open var drawFilledEnabled = false
open var isDrawFilledEnabled: Bool
{
return drawFilledEnabled
}
// MARK: NSCopying
open override func copyWithZone(_ zone: NSZone?) -> Any
{
let copy = super.copyWithZone(zone) as! RealmLineRadarDataSet
copy.fillColor = fillColor
copy._lineWidth = _lineWidth
copy.drawFilledEnabled = drawFilledEnabled
return copy
}
}
| apache-2.0 | 697e85974522e300bbfeb232d4b2eb87 | 22.447917 | 107 | 0.563749 | 4.547475 | false | false | false | false |
Limon-O-O/Medusa | MED/ViewController.swift | 1 | 12825 | //
// ViewController.swift
// MED
//
// Created by Limon on 6/16/16.
// Copyright © 2016 MED. All rights reserved.
//
import UIKit
import AVFoundation
import AssetsLibrary
import Medusa
import Photos
//import Picasso
//import Lady
extension NSLayoutConstraint {
static func setMultiplier(_ multiplier: CGFloat, of constraint: inout NSLayoutConstraint) {
NSLayoutConstraint.deactivate([constraint])
let newConstraint = NSLayoutConstraint(item: constraint.firstItem!, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: constraint.secondItem!, attribute: constraint.secondAttribute, multiplier: multiplier, constant: 0.0)
newConstraint.priority = constraint.priority
newConstraint.shouldBeArchived = constraint.shouldBeArchived
newConstraint.identifier = constraint.identifier
NSLayoutConstraint.activate([newConstraint])
constraint = newConstraint
}
}
class ViewController: UIViewController {
fileprivate let maxTime: Float = 5.0
fileprivate var totalSeconds: Float = 0.0
// fileprivate var filter: HighPassSkinSmoothingFilter?
fileprivate var captureSessionCoordinator: CaptureSessionAssetWriterCoordinator?
@IBOutlet private weak var previewConstraintRatioHeight: NSLayoutConstraint!
@IBOutlet fileprivate weak var progressView: ProgressView!
@IBOutlet fileprivate weak var previewView: VideoPreviewView!
@IBOutlet fileprivate weak var ringControl: RingControl!
@IBOutlet fileprivate weak var rollbackButton: UIButton!
@IBOutlet fileprivate weak var saveButton: UIButton!
@IBOutlet weak var amountSlider: UISlider! {
didSet {
amountSlider.isHidden = true
// amountSlider.setThumbImage(UIImage(named: "slider_thumb"), for: UIControlState())
}
}
fileprivate var attributes: Attributes = {
let fileName = "video"
let mediaFormat = MediaFormat.mp4
let fileURL = FileManager.videoURLWithName(fileName, fileExtension: mediaFormat.filenameExtension)
let videoDimensions = CMVideoDimensions(width: 480, height: 480)
let numPixels = videoDimensions.width * videoDimensions.height
// 每像素比特
let bitsPerPixel: Int32 = 6
let bitsPerSecond = numPixels * bitsPerPixel
// AVVideoAverageBitRateKey: 可变码率
let codecSettings = [AVVideoAverageBitRateKey: bitsPerSecond, AVVideoMaxKeyFrameIntervalKey: 24]
let videoCompressionSettings: [String: Any] = [
AVVideoCodecKey: AVVideoCodecH264,
AVVideoCompressionPropertiesKey: codecSettings,
AVVideoScalingModeKey: AVVideoScalingModeResizeAspectFill
]
return Attributes(destinationURL: fileURL!, videoDimensions: videoDimensions, mediaFormat: mediaFormat, videoCompressionSettings: videoCompressionSettings)
}()
override func viewDidLoad() {
super.viewDidLoad()
let ratio = CGFloat(attributes.videoDimensions.height) / CGFloat(attributes.videoDimensions.width)
NSLayoutConstraint.setMultiplier(ratio, of: &previewConstraintRatioHeight)
previewView.backgroundColor = UIColor.red
AVCaptureDevice.requestAccess(for: AVMediaType.video) { granted in
let cameraPermission = granted
AVAudioSession.sharedInstance().requestRecordPermission { granted in
DispatchQueue.main.async {
print("cameraPermission \(cameraPermission) \(granted)")
guard cameraPermission && granted else { return }
self.cameraSetup()
}
}
}
NotificationCenter.default.addObserver(self, selector: #selector(deviceRotated), name: UIDevice.orientationDidChangeNotification, object: nil)
ringControl.toucheActions = { [weak self] status in
guard let strongSelf = self, let captureSessionCoordinator = strongSelf.captureSessionCoordinator else { return }
switch status {
case .began:
captureSessionCoordinator.startRecording(videoDimensions: strongSelf.attributes.videoDimensions, deviceOrientation: strongSelf.attributes.deviceOrientation)
case .end:
captureSessionCoordinator.pause()
case .press:
break
}
}
}
@objc private func deviceRotated() {
let action: (UIDeviceOrientation) -> Void = { [weak self] orientation in
guard let sSelf = self else { return }
let videoDimensions: CMVideoDimensions
let ratio: CGFloat
switch orientation {
case .landscapeRight, .landscapeLeft:
// 9比16,横屏拍摄的时候,保证写入的视频和预览的时候一致,同时调整 assetWriterInput.transform 保证横屏显示
videoDimensions = CMVideoDimensions(width: 360, height: 640)
ratio = CGFloat(sSelf.view.frame.height) / CGFloat(sSelf.view.frame.width)
default:
videoDimensions = CMVideoDimensions(width: 480, height: 480)
ratio = CGFloat(videoDimensions.height) / CGFloat(videoDimensions.width)
}
sSelf.attributes.videoDimensions = videoDimensions
sSelf.attributes.deviceOrientation = orientation
NSLayoutConstraint.setMultiplier(ratio, of: &sSelf.previewConstraintRatioHeight)
UIView.animate(withDuration: 0.2) { [weak sSelf] in
guard let ssSelf = sSelf else { return }
ssSelf.view.layoutIfNeeded()
}
}
switch UIDevice.current.orientation {
case .landscapeLeft:
guard attributes.deviceOrientation != .landscapeLeft else { return }
action(.landscapeLeft)
print("landscape Left \(self.previewView.frame)")
case .landscapeRight:
guard attributes.deviceOrientation != .landscapeRight else { return }
action(.landscapeRight)
print("landscape Right \(self.previewView.frame)")
default:
guard attributes.deviceOrientation != .portrait else { return }
action(.portrait)
print("other \(self.previewView.frame)")
}
print()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print(previewView.frame)
}
fileprivate func cameraSetup() {
do {
captureSessionCoordinator = try CaptureSessionAssetWriterCoordinator(sessionPreset: AVCaptureSession.Preset.vga640x480, attributes: attributes, position: .front)
captureSessionCoordinator?.delegate = self
} catch {
print("cameraSetup error: \(error.localizedDescription)")
}
guard let captureSessionCoordinator = captureSessionCoordinator else { return }
previewView.cameraDevice = captureSessionCoordinator.captureDevice
previewView.canvasContentMode = .scaleAspectFill
captureSessionCoordinator.startRunning()
print("startRunning success")
}
@IBAction func amountValueChanged(_ sender: UISlider) {
// filter?.inputAmount = sender.value
print("amountValue: \(sender.value)")
}
@IBAction fileprivate func skinSmooth(_ sender: UIButton) {
// filter = !sender.isSelected ? HighPassSkinSmoothingFilter() : nil
// amountSlider.value = amountSlider.value == 0.0 ? Float(filter?.inputAmount ?? 0.0) : amountSlider.value
// filter?.inputAmount = amountSlider.value
//
// amountSlider.isHidden = !amountSlider.isHidden
// sender.isSelected = !sender.isSelected
}
@IBAction fileprivate func swapCameraDevicePosition(_ sender: UIButton) {
try! captureSessionCoordinator?.swapCaptureDevicePosition()
}
@IBAction fileprivate func rollbackAction(_ sender: UIButton) {
if sender.isSelected {
let delta = progressView.rollback()
totalSeconds = max(totalSeconds - (maxTime * delta), 0.0)
print("totalSeconds \(totalSeconds) (maxTime * delta) \((maxTime * delta))")
if progressView.trackViews.isEmpty {
rollbackButton.isHidden = true
saveButton.isHidden = true
totalSeconds = 0.0
}
// delete the lastest video
captureSessionCoordinator?.removeLastSegment()
} else {
progressView.trackViews.last?.backgroundColor = UIColor.brown
}
sender.isSelected = !sender.isSelected
}
@IBAction fileprivate func saveAction(_ sender: UIButton) {
resetProgressView()
captureSessionCoordinator?.stopRecording(isCancel: false)
}
fileprivate func resetProgressView() {
progressView.status = .idle
totalSeconds = 0.0
}
}
// MARK: - CaptureSessionCoordinatorDelegate
extension ViewController: CaptureSessionCoordinatorDelegate {
func coordinatorVideoDataOutput(didOutputSampleBuffer sampleBuffer: CMSampleBuffer, completionHandler: ((CMSampleBuffer, CIImage?) -> Void)) {
guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
//
// var outputImage = CIImage(cvPixelBuffer: imageBuffer)
//
// if let filter = filter {
// filter.inputImage = outputImage
// if let newOutputImage = filter.outputImage {
// outputImage = newOutputImage
// }
// }
//
// DispatchQueue.main.sync(execute: {
// })
// let height = CGFloat(CVPixelBufferGetHeight(imageBuffer))
// let width = CGFloat(CVPixelBufferGetWidth(imageBuffer))
// print(width, height)
self.previewView.pixelBuffer = imageBuffer
completionHandler(sampleBuffer, nil)
}
func coordinatorWillBeginRecording(_ coordinator: CaptureSessionCoordinator) {}
func coordinatorDidRecording(_ coordinator: CaptureSessionCoordinator, seconds: Float) {
print("\(Int(seconds / 60)):\(seconds.truncatingRemainder(dividingBy: 60))")
let totalTimeBuffer = totalSeconds + seconds
if totalTimeBuffer > maxTime {
self.captureSessionCoordinator?.stopRecording(isCancel: false)
resetProgressView()
return
}
progressView.progress = totalTimeBuffer / maxTime
}
func coordinatorWillPauseRecording(_ coordinator: CaptureSessionCoordinator) {
progressView.pause()
rollbackButton.isHidden = false
saveButton.isHidden = false
}
func coordinatorDidPauseRecording(_ coordinator: CaptureSessionCoordinator, segments: [Segment]) {
let seconds = segments.last?.seconds ?? 0.0
totalSeconds += seconds
}
func coordinatorDidBeginRecording(_ coordinator: CaptureSessionCoordinator) {
switch progressView.status {
case .pause:
progressView.resume()
case .progressing, .idle:
break
}
rollbackButton.isHidden = true
saveButton.isHidden = true
rollbackButton.isSelected = false
progressView.trackViews.last?.backgroundColor = progressView.progressTintColor
}
func coordinator(_ coordinator: CaptureSessionCoordinator, didFinishRecordingToOutputFileURL outputFileURL: URL?, error: Error?) {
ringControl.touchStatus = .end
guard error == nil else {
print("\((#file as NSString).lastPathComponent)[\(#line)], \(#function): \(error?.localizedDescription ?? "")")
resetProgressView()
return
}
guard let outputFileURL = outputFileURL else { return }
let videoAsset = AVURLAsset(url: outputFileURL, options: nil)
let videoDuration = Int(CMTimeGetSeconds(videoAsset.duration) as Double)
print("didFinishRecording fileSize: \(fileSize(outputFileURL)) M, \(videoDuration) seconds")
saveVideoToPhotosAlbum(outputFileURL)
}
}
// MARK: - Private Methods
extension ViewController {
fileprivate func saveVideoToPhotosAlbum(_ fileURL: URL) {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: fileURL)
}, completionHandler: { (success, error) in
if success {
print("Saved to PhotosAlbum Successfully")
FileManager.removeVideoFileWithFileURL(fileURL)
} else {
print("Save error: \(String(describing: error?.localizedDescription))")
}
})
}
fileprivate func fileSize(_ fileURL: URL) -> Double {
return Double((try? Data(contentsOf: fileURL))?.count ?? 0)/(1024.00*1024.0)
}
}
| mit | 716c71dfb2b7f824fa1833aff4222eb7 | 34.372222 | 255 | 0.664206 | 5.382079 | false | false | false | false |
superpixelhq/AbairLeat-iOS | Abair Leat/Util/NSDate-Extenstions.swift | 1 | 2394 | //
// NSDate-Extenstions.swift
// Abair Leat
//
// Created by Aaron Signorelli on 30/11/2015.
// Copyright © 2015 Superpixel. All rights reserved.
//
import Foundation
extension NSDate {
struct Date {
static let formatter = NSDateFormatter()
}
static func fromIsoDate(isoDate: String) -> NSDate? {
Date.formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX"
Date.formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
Date.formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)!
Date.formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
return Date.formatter.dateFromString(isoDate)
}
func toIsoFormat() -> String {
Date.formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX"
Date.formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
Date.formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)!
Date.formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
return Date.formatter.stringFromDate(self)
}
func toShortDateStyle() -> String {
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.ShortStyle
formatter.timeStyle = NSDateFormatterStyle.NoStyle
return formatter.stringFromDate(self)
}
func toShortTimeStyle() -> String {
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.NoStyle
formatter.timeStyle = NSDateFormatterStyle.ShortStyle
return formatter.stringFromDate(self)
}
// returns true if the date happened today
func occuredToday() -> Bool {
return numberOfDaysUntilDateTime(NSDate()) < 1
}
func numberOfDaysUntilDateTime(toDateTime: NSDate, inTimeZone timeZone: NSTimeZone? = nil) -> Int {
let calendar = NSCalendar.currentCalendar()
if let timeZone = timeZone {
calendar.timeZone = timeZone
}
var fromDate: NSDate?, toDate: NSDate?
calendar.rangeOfUnit(.Day, startDate: &fromDate, interval: nil, forDate: self)
calendar.rangeOfUnit(.Day, startDate: &toDate, interval: nil, forDate: toDateTime)
let difference = calendar.components(.Day, fromDate: fromDate!, toDate: toDate!, options: [])
return difference.day
}
}
| apache-2.0 | d936d78b15df463d367e0a0146d6521f | 35.815385 | 103 | 0.671542 | 4.682975 | false | false | false | false |
mrchenhao/Queue | Queue/NSUserDefaultsSerializer.swift | 1 | 2067 | //
// NSUserDefaultsSerializer.swift
// Queue
//
// Created by ChenHao on 12/10/15.
// Copyright © 2015 HarriesChen. All rights reserved.
//
import Foundation
/// comfire the QueueSerializationProvider protocol to persistent the queue to the NSUserdefualts
open class NSUserDefaultsSerializer: QueueSerializationProvider {
public init() { }
open func serializeTask(_ task: QueueTask, queueName: String) {
if let serialized = task.toJSONString() {
let defaults = UserDefaults.standard
var stringArray: [String]
if let curStringArray = defaults.stringArray(forKey: queueName) {
stringArray = curStringArray
stringArray.append(serialized)
} else {
stringArray = [serialized]
}
defaults.setValue(stringArray, forKey: queueName)
defaults.synchronize()
print("序列化成功")
} else {
print("序列化失败")
}
}
open func deserialzeTasks(_ queue: Queue) -> [QueueTask] {
let defaults = UserDefaults.standard
if let queneName = queue.name,
let stringArray = defaults.stringArray(forKey: queneName) {
print(stringArray.count)
//.map { return QueueTask(json: $0, queue: queue)})
return stringArray
.map { return QueueTask(json: $0, queue: queue)}
.filter { return $0 != nil }
.map { return $0! }
}
return []
}
open func removeTask(_ taskID: String, queue: Queue) {
if let queueName = queue.name {
var curArray: [QueueTask] = deserialzeTasks(queue)
curArray = curArray.filter {return $0.taskID != taskID }
let stringArray = curArray
.map {return $0.toJSONString() }
.filter { return $0 != nil}
.map { return $0! }
UserDefaults.standard.setValue(stringArray, forKey: queueName)
}
}
}
| mit | 60a1f5486aba39d66e414338eadd5d6c | 32.540984 | 97 | 0.567449 | 4.703448 | false | false | false | false |
maxgoedjen/M3U8 | M3U8Tests/KeyItemSpec.swift | 1 | 2297 | //
// KeyItemSpec.swift
// M3U8
//
// Created by Max Goedjen on 8/10/15.
// Copyright © 2015 Max Goedjen. All rights reserved.
//
import M3U8
import Nimble
import Quick
class KeyItemSpec: QuickSpec {
override func spec() {
describe("KeyItem") {
it("should initialize with parameters") {
let item = KeyItem(method: "AES-128", uri: "http://test.key", iv: "D512BBF", keyFormat: "identity", keyFormatVersions: "1/3")
expect(item.method) == "AES-128"
expect(item.uri) == "http://test.key"
expect(item.iv) == "D512BBF"
expect(item.keyFormat) == "identity"
expect(item.keyFormatVersions) == "1/3"
expect(item.description) == "#EXT-X-KEY:METHOD=AES-128,URI=\"http://test.key\",IV=D512BBF,KEYFORMAT=\"identity\",KEYFORMATVERSIONS=\"1/3\""
}
it("should initialize with only partial parameters") {
let item = KeyItem(method: "AES-128", uri: "http://test.key")
expect(item.description) == "#EXT-X-KEY:METHOD=AES-128,URI=\"http://test.key\""
}
it("should initialize with only method") {
let item = KeyItem(method: "NONE")
expect(item.description) == "#EXT-X-KEY:METHOD=NONE"
}
it("should initialize with string") {
let string = "#EXT-X-KEY:METHOD=AES-128,URI=\"http://test.key\",IV=D512BBF,KEYFORMAT=\"identity\",KEYFORMATVERSIONS=\"1/3\""
let item = KeyItem(string: string)
expect(item).toNot(beNil())
expect(item?.method) == "AES-128"
expect(item?.uri) == "http://test.key"
expect(item?.iv) == "D512BBF"
expect(item?.keyFormat) == "identity"
expect(item?.keyFormatVersions) == "1/3"
}
it("shoudl fail to initialize from string without method") {
let string = "#EXT-X-KEY:URI=\"http://test.key\",IV=D512BBF,KEYFORMAT=\"identity\",KEYFORMATVERSIONS=\"1/3\""
let item = KeyItem(string: string)
expect(item).to(beNil())
}
}
}
} | mit | 5b1a5d452491c0778328e7d71d471242 | 37.283333 | 155 | 0.518293 | 3.858824 | false | true | false | false |
zalando/MapleBacon | MapleBacon/Extensions/DownsamplingImageTransformer.swift | 2 | 1235 | //
// Copyright © 2020 Schnaub. All rights reserved.
//
import UIKit
public final class DownsamplingImageTransformer: ImageTransforming {
public var identifier: String {
"com.schnaub.DownsamplingImageTransformer@\(targetSize)"
}
private let targetSize: CGSize
init(size: CGSize) {
targetSize = size * UIScreen.main.scale
}
public func transform(image: UIImage) -> UIImage? {
let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
guard let data = image.pngData(), let imageSource = CGImageSourceCreateWithData(data as CFData, imageSourceOptions) else {
return image
}
let maxDimensionInPixels = max(targetSize.width, targetSize.height)
let downsampleOptions = [kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels] as CFDictionary
guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else {
return image
}
return UIImage(cgImage: downsampledImage)
}
}
| mit | e961ef22e8a07c35b2a84d4953ab9434 | 32.351351 | 126 | 0.71718 | 5.228814 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.