repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
foozmeat/XCGLogger | XCGLogger/Library/XCGLogger/XCGLogger.swift | 1 | 34929 | //
// XCGLogger.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2014-06-06.
// Copyright (c) 2014 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
import Foundation
#if os(iOS)
import UIKit
#else
import AppKit
#endif
// MARK: - XCGLogDetails
// - Data structure to hold all info about a log message, passed to log destination classes
public struct XCGLogDetails {
public var logLevel: XCGLogger.LogLevel
public var date: NSDate
public var logMessage: String
public var functionName: String
public var fileName: String
public var lineNumber: Int
public init(logLevel: XCGLogger.LogLevel, date: NSDate, logMessage: String, functionName: String, fileName: String, lineNumber: Int) {
self.logLevel = logLevel
self.date = date
self.logMessage = logMessage
self.functionName = functionName
self.fileName = fileName
self.lineNumber = lineNumber
}
}
// MARK: - XCGLogDestinationProtocol
// - Protocol for output classes to conform to
public protocol XCGLogDestinationProtocol: DebugPrintable {
var owner: XCGLogger {get set}
var identifier: String {get set}
var outputLogLevel: XCGLogger.LogLevel {get set}
func processLogDetails(logDetails: XCGLogDetails)
func processInternalLogDetails(logDetails: XCGLogDetails) // Same as processLogDetails but should omit function/file/line info
func isEnabledForLogLevel(logLevel: XCGLogger.LogLevel) -> Bool
}
// MARK: - XCGBaseLogDestination
// - A base class log destination that doesn't actually output the log anywhere and is intented to be subclassed
public class XCGBaseLogDestination: XCGLogDestinationProtocol, DebugPrintable {
// MARK: - Properties
public var owner: XCGLogger
public var identifier: String
public var outputLogLevel: XCGLogger.LogLevel = .Debug
public var showFunctionName: Bool = true
public var showThreadName: Bool = false
public var showFileName: Bool = true
public var showLineNumber: Bool = true
public var showLogLevel: Bool = true
public var showDate: Bool = true
// MARK: - DebugPrintable
public var debugDescription: String {
get {
return "\(reflect(self.dynamicType).summary): \(identifier) - LogLevel: \(outputLogLevel.description()) showFunctionName: \(showFunctionName) showThreadName: \(showThreadName) showLogLevel: \(showLogLevel) showFileName: \(showFileName) showLineNumber: \(showLineNumber) showDate: \(showDate)"
}
}
// MARK: - Life Cycle
public init(owner: XCGLogger, identifier: String = "") {
self.owner = owner
self.identifier = identifier
}
// MARK: - Methods to Process Log Details
public func processLogDetails(logDetails: XCGLogDetails) {
var extendedDetails: String = ""
if showDate {
var formattedDate: String = logDetails.date.description
if let dateFormatter = owner.dateFormatter {
formattedDate = dateFormatter.stringFromDate(logDetails.date)
}
extendedDetails += "\(formattedDate) "
}
if showLogLevel {
extendedDetails += "[" + logDetails.logLevel.description() + "] "
}
if showThreadName {
extendedDetails += "[" + (NSThread.isMainThread() ? "main" : (NSThread.currentThread().name != "" ? NSThread.currentThread().name : String(format:"%p", NSThread.currentThread()))) + "] "
}
if showFileName {
extendedDetails += "[" + logDetails.fileName.lastPathComponent + (showLineNumber ? ":" + String(logDetails.lineNumber) : "") + "] "
}
else if showLineNumber {
extendedDetails += "[" + String(logDetails.lineNumber) + "] "
}
if showFunctionName {
extendedDetails += "\(logDetails.functionName) "
}
output(logDetails, text: "\(extendedDetails)> \(logDetails.logMessage)")
}
public func processInternalLogDetails(logDetails: XCGLogDetails) {
var extendedDetails: String = ""
if showDate {
var formattedDate: String = logDetails.date.description
if let dateFormatter = owner.dateFormatter {
formattedDate = dateFormatter.stringFromDate(logDetails.date)
}
extendedDetails += "\(formattedDate) "
}
if showLogLevel {
extendedDetails += "[" + logDetails.logLevel.description() + "] "
}
output(logDetails, text: "\(extendedDetails)> \(logDetails.logMessage)")
}
// MARK: - Misc methods
public func isEnabledForLogLevel (logLevel: XCGLogger.LogLevel) -> Bool {
return logLevel >= self.outputLogLevel
}
// MARK: - Methods that must be overriden in subclasses
public func output(logDetails: XCGLogDetails, text: String) {
// Do something with the text in an overridden version of this method
precondition(false, "Must override this")
}
}
// MARK: - XCGConsoleLogDestination
// - A standard log destination that outputs log details to the console
public class XCGConsoleLogDestination: XCGBaseLogDestination {
// MARK: - Properties
public var xcodeColors: [XCGLogger.LogLevel: XCGLogger.XcodeColor]? = nil
// MARK: - Misc Methods
public override func output(logDetails: XCGLogDetails, text: String) {
let adjustedText: String
if let xcodeColor = (xcodeColors ?? owner.xcodeColors)[logDetails.logLevel] where owner.xcodeColorsEnabled {
adjustedText = "\(xcodeColor.format())\(text)\(XCGLogger.XcodeColor.reset)"
}
else {
adjustedText = text
}
dispatch_async(XCGLogger.logQueue) {
print("\(adjustedText)\n")
}
}
}
// MARK: - XCGNSLogDestination
// - A standard log destination that outputs log details to the console using NSLog instead of println
public class XCGNSLogDestination: XCGBaseLogDestination {
// MARK: - Properties
public var xcodeColors: [XCGLogger.LogLevel: XCGLogger.XcodeColor]? = nil
public override var showDate: Bool {
get {
return false
}
set {
// ignored, NSLog adds the date, so we always want showDate to be false in this subclass
}
}
// MARK: - Misc Methods
public override func output(logDetails: XCGLogDetails, text: String) {
let adjustedText: String
if let xcodeColor = (xcodeColors ?? owner.xcodeColors)[logDetails.logLevel] where owner.xcodeColorsEnabled {
adjustedText = "\(xcodeColor.format())\(text)\(XCGLogger.XcodeColor.reset)"
}
else {
adjustedText = text
}
NSLog(adjustedText)
}
}
// MARK: - XCGFileLogDestination
// - A standard log destination that outputs log details to a file
public class XCGFileLogDestination: XCGBaseLogDestination {
// MARK: - Properties
private var writeToFileURL: NSURL? = nil {
didSet {
openFile()
}
}
private var logFileHandle: NSFileHandle? = nil
// MARK: - Life Cycle
public init(owner: XCGLogger, writeToFile: AnyObject, identifier: String = "") {
super.init(owner: owner, identifier: identifier)
if writeToFile is NSString {
writeToFileURL = NSURL.fileURLWithPath(writeToFile as! String)
}
else if writeToFile is NSURL {
writeToFileURL = writeToFile as? NSURL
}
else {
writeToFileURL = nil
}
openFile()
}
deinit {
// close file stream if open
closeFile()
}
// MARK: - File Handling Methods
private func openFile() {
if logFileHandle != nil {
closeFile()
}
if let writeToFileURL = writeToFileURL,
let path = writeToFileURL.path {
NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil)
var fileError: NSError? = nil
logFileHandle = NSFileHandle(forWritingToURL: writeToFileURL, error: &fileError)
if logFileHandle == nil {
owner._logln("Attempt to open log file for writing failed: \(fileError?.localizedDescription)", logLevel: .Error)
}
else {
owner.logAppDetails(selectedLogDestination: self)
let logDetails = XCGLogDetails(logLevel: .Info, date: NSDate(), logMessage: "XCGLogger writing to log to: \(writeToFileURL)", functionName: "", fileName: "", lineNumber: 0)
owner._logln(logDetails.logMessage, logLevel: logDetails.logLevel)
processInternalLogDetails(logDetails)
}
}
}
private func closeFile() {
logFileHandle?.closeFile()
logFileHandle = nil
}
// MARK: - Misc Methods
public override func output(logDetails: XCGLogDetails, text: String) {
if let encodedData = "\(text)\n".dataUsingEncoding(NSUTF8StringEncoding) {
logFileHandle?.writeData(encodedData)
}
}
}
// MARK: - XCGLogger
// - The main logging class
public class XCGLogger: DebugPrintable {
// MARK: - Constants
public struct constants {
public static let defaultInstanceIdentifier = "com.cerebralgardens.xcglogger.defaultInstance"
public static let baseConsoleLogDestinationIdentifier = "com.cerebralgardens.xcglogger.logdestination.console"
public static let nslogDestinationIdentifier = "com.cerebralgardens.xcglogger.logdestination.console.nslog"
public static let baseFileLogDestinationIdentifier = "com.cerebralgardens.xcglogger.logdestination.file"
public static let nsdataFormatterCacheIdentifier = "com.cerebralgardens.xcglogger.nsdataFormatterCache"
public static let logQueueIdentifier = "com.cerebralgardens.xcglogger.queue"
public static let versionString = "2.2"
}
// MARK: - Enums
public enum LogLevel: Int, Comparable {
case Verbose
case Debug
case Info
case Warning
case Error
case Severe
case None
public func description() -> String {
switch self {
case .Verbose:
return "Verbose"
case .Debug:
return "Debug"
case .Info:
return "Info"
case .Warning:
return "Warning"
case .Error:
return "Error"
case .Severe:
return "Severe"
case .None:
return "None"
}
}
}
public struct XcodeColor {
public static let escape = "\u{001b}["
public static let resetFg = "\u{001b}[fg;"
public static let resetBg = "\u{001b}[bg;"
public static let reset = "\u{001b}[;"
public var fg: (Int, Int, Int)? = nil
public var bg: (Int, Int, Int)? = nil
public func format() -> String {
var format: String = ""
if fg == nil && bg == nil {
// neither set, return reset value
return XcodeColor.reset
}
if let fg = fg {
format += "\(XcodeColor.escape)fg\(fg.0),\(fg.1),\(fg.2);"
}
else {
format += XcodeColor.resetFg
}
if let bg = bg {
format += "\(XcodeColor.escape)bg\(bg.0),\(bg.1),\(bg.2);"
}
else {
format += XcodeColor.resetBg
}
return format
}
public init(fg: (Int, Int, Int)? = nil, bg: (Int, Int, Int)? = nil) {
self.fg = fg
self.bg = bg
}
#if os(iOS)
public init(fg: UIColor, bg: UIColor? = nil) {
var redComponent: CGFloat = 0
var greenComponent: CGFloat = 0
var blueComponent: CGFloat = 0
var alphaComponent: CGFloat = 0
fg.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha:&alphaComponent)
self.fg = (Int(redComponent * 255), Int(greenComponent * 255), Int(blueComponent * 255))
if let bg = bg {
bg.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha:&alphaComponent)
self.bg = (Int(redComponent * 255), Int(greenComponent * 255), Int(blueComponent * 255))
}
else {
self.bg = nil
}
}
#else
public init(fg: NSColor, bg: NSColor? = nil) {
if let fgColorSpaceCorrected = fg.colorUsingColorSpaceName(NSCalibratedRGBColorSpace) {
self.fg = (Int(fgColorSpaceCorrected.redComponent * 255), Int(fgColorSpaceCorrected.greenComponent * 255), Int(fgColorSpaceCorrected.blueComponent * 255))
}
else {
self.fg = nil
}
if let bg = bg,
let bgColorSpaceCorrected = bg.colorUsingColorSpaceName(NSCalibratedRGBColorSpace) {
self.bg = (Int(bgColorSpaceCorrected.redComponent * 255), Int(bgColorSpaceCorrected.greenComponent * 255), Int(bgColorSpaceCorrected.blueComponent * 255))
}
else {
self.bg = nil
}
}
#endif
public static let red: XcodeColor = {
return XcodeColor(fg: (255, 0, 0))
}()
public static let green: XcodeColor = {
return XcodeColor(fg: (0, 255, 0))
}()
public static let blue: XcodeColor = {
return XcodeColor(fg: (0, 0, 255))
}()
public static let black: XcodeColor = {
return XcodeColor(fg: (0, 0, 0))
}()
public static let white: XcodeColor = {
return XcodeColor(fg: (255, 255, 255))
}()
public static let lightGrey: XcodeColor = {
return XcodeColor(fg: (211, 211, 211))
}()
public static let darkGrey: XcodeColor = {
return XcodeColor(fg: (169, 169, 169))
}()
public static let orange: XcodeColor = {
return XcodeColor(fg: (255, 165, 0))
}()
public static let whiteOnRed: XcodeColor = {
return XcodeColor(fg: (255, 255, 255), bg: (255, 0, 0))
}()
public static let darkGreen: XcodeColor = {
return XcodeColor(fg: (0, 128, 0))
}()
}
// MARK: - Properties (Options)
public var identifier: String = ""
public var outputLogLevel: LogLevel = .Debug {
didSet {
for index in 0 ..< logDestinations.count {
logDestinations[index].outputLogLevel = outputLogLevel
}
}
}
public var xcodeColorsEnabled: Bool = false
public var xcodeColors: [XCGLogger.LogLevel: XCGLogger.XcodeColor] = [
.Verbose: .lightGrey,
.Debug: .darkGrey,
.Info: .blue,
.Warning: .orange,
.Error: .red,
.Severe: .whiteOnRed
]
// MARK: - Properties
public class var logQueue: dispatch_queue_t {
struct Statics {
static var logQueue = dispatch_queue_create(XCGLogger.constants.logQueueIdentifier, nil)
}
return Statics.logQueue
}
private var _dateFormatter: NSDateFormatter? = nil
public var dateFormatter: NSDateFormatter? {
get {
if _dateFormatter != nil {
return _dateFormatter
}
let defaultDateFormatter = NSDateFormatter()
defaultDateFormatter.locale = NSLocale.currentLocale()
defaultDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
_dateFormatter = defaultDateFormatter
return _dateFormatter
}
set {
_dateFormatter = newValue
}
}
public var logDestinations: Array<XCGLogDestinationProtocol> = []
// MARK: - Life Cycle
public init() {
// Check if XcodeColors is installed and enabled
if let xcodeColors = NSProcessInfo.processInfo().environment["XcodeColors"] as? String {
xcodeColorsEnabled = xcodeColors == "YES"
}
// Setup a standard console log destination
addLogDestination(XCGConsoleLogDestination(owner: self, identifier: XCGLogger.constants.baseConsoleLogDestinationIdentifier))
}
// MARK: - Default instance
public class func defaultInstance() -> XCGLogger {
struct statics {
static let instance: XCGLogger = XCGLogger()
}
statics.instance.identifier = XCGLogger.constants.defaultInstanceIdentifier
return statics.instance
}
// MARK: - Setup methods
public class func setup(logLevel: LogLevel = .Debug, showFunctionName: Bool = true, showThreadName: Bool = false, showLogLevel: Bool = true, showFileNames: Bool = true, showLineNumbers: Bool = true, showDate: Bool = true, writeToFile: AnyObject? = nil, fileLogLevel: LogLevel? = nil) {
defaultInstance().setup(logLevel: logLevel, showFunctionName: showFunctionName, showThreadName: showThreadName, showLogLevel: showLogLevel, showFileNames: showFileNames, showLineNumbers: showLineNumbers, showDate: showDate, writeToFile: writeToFile)
}
public func setup(logLevel: LogLevel = .Debug, showFunctionName: Bool = true, showThreadName: Bool = false, showLogLevel: Bool = true, showFileNames: Bool = true, showLineNumbers: Bool = true, showDate: Bool = true, writeToFile: AnyObject? = nil, fileLogLevel: LogLevel? = nil) {
outputLogLevel = logLevel;
if let standardConsoleLogDestination = logDestination(XCGLogger.constants.baseConsoleLogDestinationIdentifier) as? XCGConsoleLogDestination {
standardConsoleLogDestination.showFunctionName = showFunctionName
standardConsoleLogDestination.showThreadName = showThreadName
standardConsoleLogDestination.showLogLevel = showLogLevel
standardConsoleLogDestination.showFileName = showFileNames
standardConsoleLogDestination.showLineNumber = showLineNumbers
standardConsoleLogDestination.showDate = showDate
standardConsoleLogDestination.outputLogLevel = logLevel
}
logAppDetails()
if let writeToFile: AnyObject = writeToFile {
// We've been passed a file to use for logging, set up a file logger
let standardFileLogDestination: XCGFileLogDestination = XCGFileLogDestination(owner: self, writeToFile: writeToFile, identifier: XCGLogger.constants.baseFileLogDestinationIdentifier)
standardFileLogDestination.showFunctionName = showFunctionName
standardFileLogDestination.showThreadName = showThreadName
standardFileLogDestination.showLogLevel = showLogLevel
standardFileLogDestination.showFileName = showFileNames
standardFileLogDestination.showLineNumber = showLineNumbers
standardFileLogDestination.showDate = showDate
standardFileLogDestination.outputLogLevel = fileLogLevel ?? logLevel
addLogDestination(standardFileLogDestination)
}
}
// MARK: - Logging methods
public class func logln(@autoclosure closure: () -> String?, logLevel: LogLevel = .Debug, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) {
self.defaultInstance().logln(logLevel: logLevel, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func logln(logLevel: LogLevel = .Debug, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__, @noescape closure: () -> String?) {
self.defaultInstance().logln(logLevel: logLevel, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func logln(@autoclosure closure: () -> String?, logLevel: LogLevel = .Debug, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) {
self.logln(logLevel: logLevel, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func logln(logLevel: LogLevel = .Debug, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__, @noescape closure: () -> String?) {
let date = NSDate()
var logDetails: XCGLogDetails? = nil
for logDestination in self.logDestinations {
if (logDestination.isEnabledForLogLevel(logLevel)) {
if logDetails == nil {
if let logMessage = closure() {
logDetails = XCGLogDetails(logLevel: logLevel, date: date, logMessage: logMessage, functionName: functionName, fileName: fileName, lineNumber: lineNumber)
}
else {
break
}
}
logDestination.processLogDetails(logDetails!)
}
}
}
public class func exec(logLevel: LogLevel = .Debug, closure: () -> () = {}) {
self.defaultInstance().exec(logLevel: logLevel, closure: closure)
}
public func exec(logLevel: LogLevel = .Debug, closure: () -> () = {}) {
if (!isEnabledForLogLevel(logLevel)) {
return
}
closure()
}
public func logAppDetails(selectedLogDestination: XCGLogDestinationProtocol? = nil) {
let date = NSDate()
var buildString = ""
if let infoDictionary = NSBundle.mainBundle().infoDictionary {
if let CFBundleShortVersionString = infoDictionary["CFBundleShortVersionString"] as? String {
buildString = "Version: \(CFBundleShortVersionString) "
}
if let CFBundleVersion = infoDictionary["CFBundleVersion"] as? String {
buildString += "Build: \(CFBundleVersion) "
}
}
let processInfo: NSProcessInfo = NSProcessInfo.processInfo()
let XCGLoggerVersionNumber = XCGLogger.constants.versionString
let logDetails: Array<XCGLogDetails> = [XCGLogDetails(logLevel: .Info, date: date, logMessage: "\(processInfo.processName) \(buildString)PID: \(processInfo.processIdentifier)", functionName: "", fileName: "", lineNumber: 0),
XCGLogDetails(logLevel: .Info, date: date, logMessage: "XCGLogger Version: \(XCGLoggerVersionNumber) - LogLevel: \(outputLogLevel.description())", functionName: "", fileName: "", lineNumber: 0)]
for logDestination in (selectedLogDestination != nil ? [selectedLogDestination!] : logDestinations) {
for logDetail in logDetails {
if !logDestination.isEnabledForLogLevel(.Info) {
continue;
}
logDestination.processInternalLogDetails(logDetail)
}
}
}
// MARK: - Convenience logging methods
// MARK: * Verbose
public class func verbose(@autoclosure closure: () -> String?, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) {
self.defaultInstance().logln(logLevel: .Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func verbose(functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__, @noescape closure: () -> String?) {
self.defaultInstance().logln(logLevel: .Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func verbose(@autoclosure closure: () -> String?, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) {
self.logln(logLevel: .Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func verbose(functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__, @noescape closure: () -> String?) {
self.logln(logLevel: .Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: * Debug
public class func debug(@autoclosure closure: () -> String?, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) {
self.defaultInstance().logln(logLevel: .Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func debug(functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__, @noescape closure: () -> String?) {
self.defaultInstance().logln(logLevel: .Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func debug(@autoclosure closure: () -> String?, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) {
self.logln(logLevel: .Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func debug(functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__, @noescape closure: () -> String?) {
self.logln(logLevel: .Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: * Info
public class func info(@autoclosure closure: () -> String?, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) {
self.defaultInstance().logln(logLevel: .Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func info(functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__, @noescape closure: () -> String?) {
self.defaultInstance().logln(logLevel: .Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func info(@autoclosure closure: () -> String?, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) {
self.logln(logLevel: .Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func info(functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__, @noescape closure: () -> String?) {
self.logln(logLevel: .Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: * Warning
public class func warning(@autoclosure closure: () -> String?, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) {
self.defaultInstance().logln(logLevel: .Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func warning(functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__, @noescape closure: () -> String?) {
self.defaultInstance().logln(logLevel: .Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func warning(@autoclosure closure: () -> String?, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) {
self.logln(logLevel: .Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func warning(functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__, @noescape closure: () -> String?) {
self.logln(logLevel: .Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: * Error
public class func error(@autoclosure closure: () -> String?, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) {
self.defaultInstance().logln(logLevel: .Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func error(functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__, @noescape closure: () -> String?) {
self.defaultInstance().logln(logLevel: .Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func error(@autoclosure closure: () -> String?, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) {
self.logln(logLevel: .Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func error(functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__, @noescape closure: () -> String?) {
self.logln(logLevel: .Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: * Severe
public class func severe(@autoclosure closure: () -> String?, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) {
self.defaultInstance().logln(logLevel: .Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func severe(functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__, @noescape closure: () -> String?) {
self.defaultInstance().logln(logLevel: .Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func severe(@autoclosure closure: () -> String?, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) {
self.logln(logLevel: .Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func severe(functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__, @noescape closure: () -> String?) {
self.logln(logLevel: .Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: - Exec Methods
// MARK: * Verbose
public class func verboseExec(closure: () -> () = {}) {
self.defaultInstance().exec(logLevel: XCGLogger.LogLevel.Verbose, closure: closure)
}
public func verboseExec(closure: () -> () = {}) {
self.exec(logLevel: XCGLogger.LogLevel.Verbose, closure: closure)
}
// MARK: * Debug
public class func debugExec(closure: () -> () = {}) {
self.defaultInstance().exec(logLevel: XCGLogger.LogLevel.Debug, closure: closure)
}
public func debugExec(closure: () -> () = {}) {
self.exec(logLevel: XCGLogger.LogLevel.Debug, closure: closure)
}
// MARK: * Info
public class func infoExec(closure: () -> () = {}) {
self.defaultInstance().exec(logLevel: XCGLogger.LogLevel.Info, closure: closure)
}
public func infoExec(closure: () -> () = {}) {
self.exec(logLevel: XCGLogger.LogLevel.Info, closure: closure)
}
// MARK: * Warning
public class func warningExec(closure: () -> () = {}) {
self.defaultInstance().exec(logLevel: XCGLogger.LogLevel.Warning, closure: closure)
}
public func warningExec(closure: () -> () = {}) {
self.exec(logLevel: XCGLogger.LogLevel.Warning, closure: closure)
}
// MARK: * Error
public class func errorExec(closure: () -> () = {}) {
self.defaultInstance().exec(logLevel: XCGLogger.LogLevel.Error, closure: closure)
}
public func errorExec(closure: () -> () = {}) {
self.exec(logLevel: XCGLogger.LogLevel.Error, closure: closure)
}
// MARK: * Severe
public class func severeExec(closure: () -> () = {}) {
self.defaultInstance().exec(logLevel: XCGLogger.LogLevel.Severe, closure: closure)
}
public func severeExec(closure: () -> () = {}) {
self.exec(logLevel: XCGLogger.LogLevel.Severe, closure: closure)
}
// MARK: - Misc methods
public func isEnabledForLogLevel (logLevel: XCGLogger.LogLevel) -> Bool {
return logLevel >= self.outputLogLevel
}
public func logDestination(identifier: String) -> XCGLogDestinationProtocol? {
for logDestination in logDestinations {
if logDestination.identifier == identifier {
return logDestination
}
}
return nil
}
public func addLogDestination(logDestination: XCGLogDestinationProtocol) -> Bool {
let existingLogDestination: XCGLogDestinationProtocol? = self.logDestination(logDestination.identifier)
if existingLogDestination != nil {
return false
}
logDestinations.append(logDestination)
return true
}
public func removeLogDestination(logDestination: XCGLogDestinationProtocol) {
removeLogDestination(logDestination.identifier)
}
public func removeLogDestination(identifier: String) {
logDestinations = logDestinations.filter({$0.identifier != identifier})
}
// MARK: - Private methods
private func _logln(logMessage: String, logLevel: LogLevel = .Debug) {
let date = NSDate()
var logDetails: XCGLogDetails? = nil
for logDestination in self.logDestinations {
if (logDestination.isEnabledForLogLevel(logLevel)) {
if logDetails == nil {
logDetails = XCGLogDetails(logLevel: logLevel, date: date, logMessage: logMessage, functionName: "", fileName: "", lineNumber: 0)
}
logDestination.processInternalLogDetails(logDetails!)
}
}
}
// MARK: - DebugPrintable
public var debugDescription: String {
get {
var description: String = "\(reflect(self.dynamicType).summary): \(identifier) - logDestinations: \r"
for logDestination in logDestinations {
description += "\t \(logDestination.debugDescription)\r"
}
return description
}
}
}
// Implement Comparable for XCGLogger.LogLevel
public func < (lhs:XCGLogger.LogLevel, rhs:XCGLogger.LogLevel) -> Bool {
return lhs.rawValue < rhs.rawValue
}
| mit | ebaadb25520b634f1563d8cada4c151a | 41.083133 | 304 | 0.630708 | 5.007742 | false | false | false | false |
tecgirl/firefox-ios | Extensions/ShareTo/SendToDevice.swift | 2 | 2016 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
class SendToDevice: ClientPickerViewControllerDelegate, InstructionsViewControllerDelegate {
var sharedItem: ShareItem?
weak var delegate: ShareControllerDelegate?
func initialViewController() -> UIViewController {
if !hasAccount() {
let instructionsViewController = InstructionsViewController()
instructionsViewController.delegate = self
return instructionsViewController
}
let clientPickerViewController = ClientPickerViewController()
clientPickerViewController.clientPickerDelegate = self
clientPickerViewController.profile = nil // This means the picker will open and close the default profile
return clientPickerViewController
}
func finish() {
delegate?.finish(afterDelay: 0)
}
func clientPickerViewController(_ clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) {
guard let item = sharedItem else {
return finish()
}
let profile = BrowserProfile(localName: "profile")
profile.sendItems([item], toClients: clients).uponQueue(.main) { result in
profile.shutdown()
self.finish()
addAppExtensionTelemetryEvent(forMethod: "send-to-device")
}
}
func clientPickerViewControllerDidCancel(_ clientPickerViewController: ClientPickerViewController) {
finish()
}
func instructionsViewControllerDidClose(_ instructionsViewController: InstructionsViewController) {
finish()
}
private func hasAccount() -> Bool {
let profile = BrowserProfile(localName: "profile")
defer {
profile.shutdown()
}
return profile.hasAccount()
}
}
| mpl-2.0 | 6796a4b04dcea93f01fe73f7ea844f22 | 33.169492 | 135 | 0.688988 | 6.054054 | false | false | false | false |
melke/CloudKitDictionarySyncer | CloudKitDictionarySyncer/ViewController.swift | 1 | 5823 | //
// ViewController.swift
// CloudKitDictionarySyncer
//
// Created by Mats Melke on 08/02/15.
// Copyright (c) 2015 Baresi. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var myTableView: UITableView!
var dict:NSMutableDictionary = NSMutableDictionary()
let syncer = CloudKitDictionarySyncer(dictname: "anexampledict", debug: true)
override func viewDidLoad() {
super.viewDidLoad()
self.syncer.loadDictionary(onComplete: {
loadResult in
switch loadResult {
case .Dict(let loadeddict):
self.dict = loadeddict
println("EXAMPLE: Dict loaded dict = \(loadeddict)")
if let rowlabels = self.dict["rowlabels"] as? [String] {
// Yes, we already got the rowlabel key, do nothing
} else {
// init rowlabel key with empty array
self.dict["rowlabels"] = [String]()
}
case .Conflict(let localdict, let clouddict, let latest):
// Handle conflict. In this example, we are merging all unique rowlabels from both dicts.
println("EXAMPLE: Conflict detected")
var localrows = localdict["rowlabels"] as? [String]
var cloudrows = clouddict["rowlabels"] as? [String]
if localrows != nil && cloudrows != nil {
println("Both dicts have rowlabels array, will merge cloud array into local array")
for label in cloudrows! {
if !contains(localrows!, label) {
localrows!.append(label)
}
}
self.dict = localdict
self.dict["rowlabels"] = localrows
// The dict has changed, thanks to the merge, so we need to resave it
self.syncer.saveDictionary(self.dict, onComplete: {
status in
println("Resaved merged dict. Save status = \(status)")
})
} else if let rows = localrows {
// We only have rows in localdict
self.dict = localdict
self.dict["rowlabels"] = localrows
} else if let rows = cloudrows {
// We only have rows in clouddict
self.dict = clouddict
self.dict["rowlabels"] = cloudrows
} else {
// we don't have any rows in any of the dicts
self.dict = localdict
// init rowlabel key with empty array
self.dict["rowlabels"] = [String]()
}
/*
// A simple alternative is to always use the latest saved dict (can be dangerous):
switch latest {
case .Plist:
self.dict = localdict
case .CloudKit:
self.dict = clouddict
}
*/
}
// reload table
dispatch_async(dispatch_get_main_queue(), {
self.myTableView.reloadData()
})
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("tapped row \(indexPath.row)")
let numrows = self.tableView(tableView, numberOfRowsInSection: 1)
if indexPath.row == numrows - 1 {
if var tablerows = self.dict["rowlabels"] as? [String] {
tablerows.append("Row \(indexPath.row+1)")
self.dict["rowlabels"] = tablerows
// Note that the saving is done in background, but your Dictionary is already
// updated, so there is no need to wait for the saving to complete before you reload the table
dispatch_async(dispatch_get_main_queue(), {
self.myTableView.reloadData()
})
self.syncer.saveDictionary(self.dict, onComplete: {
status in
println("Save status = \(status)")
})
}
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("exampleCell", forIndexPath: indexPath) as? UITableViewCell
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "exampleCell")
}
let numrows = self.tableView(tableView, numberOfRowsInSection: 1)
if indexPath.row == numrows - 1 {
cell?.textLabel?.text = "Tap here to add row"
} else {
if let tablerows = self.dict["rowlabels"] as? [String] {
println("\(tablerows[indexPath.row])")
cell?.textLabel?.text = tablerows[indexPath.row]
}
}
return cell!
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rowcount = 1 // One for the row with the "Add new row" button
if let tablerows = self.dict["rowlabels"] as? [String] {
rowcount += tablerows.count
}
return rowcount
}
}
| mit | a5abb813149e5e8562a86d23bd5cbe47 | 40.297872 | 122 | 0.518633 | 5.312956 | false | false | false | false |
haawa799/WaniKani-iOS | WaniKani/Utils/DataFetchManager.swift | 1 | 8298 | //
// DataFetchManager.swift
//
//
// Created by Andriy K. on 8/19/15.
//
//
import UIKit
import WaniKit
import RealmSwift
import Realm
import PermissionScope
var user: User? {
return realm.objects(User).first
}
class DataFetchManager: NSObject {
static let sharedInstance = DataFetchManager()
func makeInitialPreperations() {
performMigrationIfNeeded()
moveRealmToAppGroupIfNeeded()
initialUserCreation()
}
func moveRealmToAppGroupIfNeeded() {
guard let originalDefaultRealmPath = Realm.Configuration.defaultConfiguration.path else { return }
guard let realmPath = waniRealmConfiguration.path else { return }
let fileManager = NSFileManager.defaultManager()
//Moves the realm to the new location if it hasn't been done previously
if (fileManager.fileExistsAtPath(originalDefaultRealmPath) && !fileManager.fileExistsAtPath(realmPath)) {
do {
try fileManager.moveItemAtPath(originalDefaultRealmPath, toPath: realmPath)
} catch _ {
print("error moving realm")
}
}
}
func performMigrationIfNeeded() {
Realm.Configuration.defaultConfiguration = Realm.Configuration(
schemaVersion: 12,
migrationBlock: { migration, oldSchemaVersion in
})
}
func fetchAllData() {
fetchStudyQueue()
fetchLevelProgression()
}
func initialUserCreation() {
if user == nil {
var token: dispatch_once_t = 0
let usr = User()
dispatch_once(&token) {
let studyQ = StudyQueue()
let levelProgression = LevelProgression()
dispatch_sync(realmQueue) { () -> Void in
try! realm.write({ () -> Void in
realm.add(usr)
usr.studyQueue = studyQ
usr.levelProgression = levelProgression
})
}
}
}
}
func fetchStudyQueue(completionHandler: ((result: UIBackgroundFetchResult)->())? = nil) {
// Fetch data
appDelegate.waniApiManager?.fetchStudyQueue { result -> Void in
switch result {
case .Error(let _):
completionHandler?(result: UIBackgroundFetchResult.Failed)
case .Response(let response):
let resp = response()
// Make sure recieved data is OK
guard let userInfo = resp.userInfo, studyQInfo = resp.studyQInfo else {
completionHandler?(result: UIBackgroundFetchResult.Failed)
return
}
// Update user and study queue on realmQueue
dispatch_async(realmQueue) { () -> Void in
// Make sure that user exist
guard let user = realm.objects(User).first else { return }
// Update study queue, and user info
try! realm.write({ () -> Void in
if user.levels == nil {
user.levels = WaniKaniLevels()
}
self.checkIfUserLeveledUp(user.level, newLevel: userInfo.level)
user.studyQueue?.updateWith(studyQInfo)
user.updateUserWithUserInfo(userInfo)
})
realm.refresh()
// Do some stuff with data
dispatch_async(dispatch_get_main_queue(), { () -> Void in
realm.refresh()
let user = realm.objects(User).first
guard let studyQ = user?.studyQueue else { return }
let result: UIBackgroundFetchResult = self.schedulePushNotificationIfNeededFor(studyQ) ? .NewData : .NoData
appDelegate.notificationCenterManager.postNotification(.NewStudyQueueReceivedNotification, object: studyQ)
completionHandler?(result: result)
})
}
}
}
}
func fetchLevelKanji(levelIndex: Int, completion: (()->())? = nil) {
let apiManager: WaniApiManager = {
let level = user?.level
if level > 3 {
return appDelegate.waniApiManager
} else {
let manager = WaniApiManager()
// ❗️❗️❗️❗️
// For users with level 3 and lower apiManager.fetchKanjiList returns null
// therefore I use my API key to let them see all the kanji that they will learn in future.
// My API key is not commited to GithubFor obvious reasons
manager.setApiKey("c6ce4072cf1bd37b407f2c86d69137e3") // Insert your API key here or comment it out
return manager
}
}()
apiManager.fetchKanjiList(levelIndex) { (result) -> Void in
//
switch result {
case .Error(let error):
print(error())
break
case .Response(let response):
let resp = response()
guard let kanjiList = resp.kanji else {
return
}
dispatch_async(realmQueue) { () -> Void in
// Make sure that user exist
guard let user = realm.objects(User).first else { return }
// Update study queue, and user info
try! realm.write({ () -> Void in
user.levels?.updateKanjiListForLevel(levelIndex, newList: kanjiList)
})
realm.refresh()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
realm.refresh()
completion?()
let user = realm.objects(User).first
guard let _ = user?.levels?.levels else { return }
appDelegate.notificationCenterManager.postNotification(.UpdatedKanjiListNotification, object: levelIndex)
})
}
}
}
}
func schedulePushNotificationIfNeededFor(studyQueue: StudyQueue) -> Bool {
var newNotification = false
if PermissionScope().statusNotifications() != .Disabled {
newNotification = NotificationManager.sharedInstance.scheduleNextReviewNotification(studyQueue.nextReviewDate)
let additionalNotifications = SettingsSuit.sharedInstance.ignoreLessonsInIconCounter.setting.enabled ? 0 : studyQueue.lessonsAvaliable
let newAppIconCounter = studyQueue.reviewsAvaliable + additionalNotifications
let oldAppIconCounter = UIApplication.sharedApplication().applicationIconBadgeNumber
newNotification = newNotification || (oldAppIconCounter != newAppIconCounter)
UIApplication.sharedApplication().applicationIconBadgeNumber = newAppIconCounter
}
return newNotification
}
func fetchLevelProgression() {
// Fetch data
appDelegate.waniApiManager.fetchLevelProgression { result -> Void in
switch result {
case .Error(let _): break
case .Response(let response):
let resp = response()
// Make sure recieved data is OK
guard let userInfo = resp.userInfo, levelProgressionInfo = resp.levelProgression else {
return
}
dispatch_async(realmQueue) { () -> Void in
// Make sure that user exist
guard let user = realm.objects(User).first else { return }
// Update study queue, and user info
try! realm.write({ () -> Void in
self.checkIfUserLeveledUp(user.level, newLevel: userInfo.level)
user.levelProgression?.updateWith(levelProgressionInfo)
user.updateUserWithUserInfo(userInfo)
})
realm.refresh()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
realm.refresh()
let user = realm.objects(User).first
guard let levelProgression = user?.levelProgression else { return}
appDelegate.notificationCenterManager.postNotification(.NewLevelProgressionReceivedNotification, object: levelProgression)
})
}
}
}
}
func checkIfUserLeveledUp(oldLevel: Int, newLevel: Int?) {
guard let newLevel = newLevel else { return }
if newLevel != oldLevel {
fetchLevelKanji(newLevel, completion: { () -> () in
appDelegate.sendThisLevelKanjiData()
})
}
dispatch_async(dispatch_get_main_queue()) { () -> Void in
//User leveled up
delay(7, closure: { () -> () in
AwardsManager.sharedInstance.userLevelUp(oldLevel: oldLevel, newLevel: newLevel)
})
}
}
}
| gpl-3.0 | 1699e016ce8ad4fec10f6c3752229374 | 30.018727 | 140 | 0.610964 | 4.880377 | false | false | false | false |
devpunk/cartesian | cartesian/View/DrawProject/Size/VDrawProjectSizeBar.swift | 1 | 2976 | import UIKit
class VDrawProjectSizeBar:UIView
{
private(set) weak var labelTitle:UILabel!
private weak var controller:CDrawProject!
private let kLabelTitleLeft:CGFloat = 10
private let kLabelTitleWidth:CGFloat = 200
private let kButtonCloseWidth:CGFloat = 100
private let kBorderHeight:CGFloat = 1
init(controller:CDrawProject)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let border:VBorder = VBorder(color:UIColor(white:0, alpha:0.1))
let labelTitle:UILabel = UILabel()
labelTitle.isUserInteractionEnabled = false
labelTitle.translatesAutoresizingMaskIntoConstraints = false
labelTitle.backgroundColor = UIColor.clear
labelTitle.font = UIFont.medium(size:15)
labelTitle.textColor = UIColor.black
self.labelTitle = labelTitle
let buttonClose:UIButton = UIButton()
buttonClose.translatesAutoresizingMaskIntoConstraints = false
buttonClose.setTitleColor(
UIColor.cartesianBlue,
for:UIControlState.normal)
buttonClose.setTitleColor(
UIColor(white:0, alpha:0.2),
for:UIControlState.highlighted)
buttonClose.setTitle(
NSLocalizedString("VDrawProjectSizeBar_buttonClose", comment:""),
for:UIControlState.normal)
buttonClose.titleLabel!.font = UIFont.bolder(size:17)
buttonClose.addTarget(
self,
action:#selector(actionClose(sender:)),
for:UIControlEvents.touchUpInside)
addSubview(border)
addSubview(labelTitle)
addSubview(buttonClose)
NSLayoutConstraint.equalsVertical(
view:labelTitle,
toView:self)
NSLayoutConstraint.leftToLeft(
view:labelTitle,
toView:self,
constant:kLabelTitleLeft)
NSLayoutConstraint.width(
view:labelTitle,
constant:kLabelTitleWidth)
NSLayoutConstraint.bottomToBottom(
view:border,
toView:self)
NSLayoutConstraint.height(
view:border,
constant:kBorderHeight)
NSLayoutConstraint.equalsHorizontal(
view:border,
toView:self)
NSLayoutConstraint.equalsVertical(
view:buttonClose,
toView:self)
NSLayoutConstraint.rightToRight(
view:buttonClose,
toView:self)
NSLayoutConstraint.width(
view:buttonClose,
constant:kButtonCloseWidth)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: actions
func actionClose(sender button:UIButton)
{
controller.viewProject.viewSize?.animateClose()
}
}
| mit | 9b5e4594f8e3a9b1fbef7eb24a87d484 | 30.659574 | 77 | 0.626008 | 5.511111 | false | false | false | false |
SebastienFCT/FCTBubbleChat | FCTBubbleChat/FCTBubbleChat/FCTBubbleData.swift | 1 | 1495 | //
// FCTBubbleData.swift
// FCTBubbleChat
//
// Created by sebastien FOCK CHOW THO on 2016-04-08.
// Copyright © 2016 sebfct. All rights reserved.
//
import UIKit
public enum FCTBubbleDataType: Int {
case Mine
case Other
}
public enum FCTBubbleContentType: Int {
case Text
case Image
}
public class FCTBubbleData: NSObject {
var type: FCTBubbleDataType = .Mine
var contentType: FCTBubbleContentType = .Text
// Bubble infos
internal var userName: String?
internal var userPic: UIImage?
internal var date: NSDate!
// Bubble content
internal var stringContent: String?
internal var imageContent: UIImage?
public convenience init(userName: String?, userPic: UIImage?, date: NSDate, stringContent: String, type: FCTBubbleDataType, contentType: FCTBubbleContentType) {
self.init()
self.userName = userName
self.userPic = userPic
self.type = type
self.contentType = contentType
self.date = date
self.stringContent = stringContent
}
public convenience init(userName: String?, userPic: UIImage?, date: NSDate, imageContent: UIImage, type: FCTBubbleDataType, contentType: FCTBubbleContentType) {
self.init()
self.userName = userName
self.userPic = userPic
self.type = type
self.contentType = contentType
self.date = date
self.imageContent = imageContent
}
}
| mit | f99daa6b8f5a393480cf42f34c61d28b | 24.758621 | 164 | 0.653949 | 4.446429 | false | false | false | false |
AnthonyMDev/QueryGenie | QueryGenie/Realm/RealmQueryable.swift | 1 | 1885 | //
// RealmQueryable.swift
//
// Created by Anthony Miller on 12/28/16.
//
import Foundation
import RealmSwift
/// A query that can be executed to retrieve Realm `Objects`.
public protocol RealmQueryable: GenericQueryable {
associatedtype Element: Object
var realm: Realm? { get }
func setValue(_ value: Any?, forKey key: String)
}
// MARK: - Enumerable
extension RealmQueryable {
public final func count() -> Int {
return Int(objects().count)
}
public final func firstOrCreated(_ predicateClosure: (Self.Element.Type) -> NSComparisonPredicate) throws -> Self.Element {
let predicate = predicateClosure(Self.Element.self)
if let entity = self.filter(predicate).first() {
return entity
} else {
guard let realm = realm else { throw RealmError.noRealm }
let attributeName = predicate.leftExpression.keyPath
let value: Any = predicate.rightExpression.constantValue!
let entity = realm.create(Element.self, value: [attributeName: value], update: true)
return entity
}
}
private final func setValue<T>(_ value: T, for attribute: Attribute<T>) {
setValue(value, forKey: attribute.___name)
}
public final func setValue<T>(_ value: T, for attributeClosure: (Self.Element.Type) -> Attribute<T>) {
setValue(value, for: attributeClosure(Self.Element.self))
}
private final func setValue<T>(_ value: T?, for attribute: NullableAttribute<T>) {
setValue(value, forKey: attribute.___name)
}
public final func setValue<T>(_ value: T?, for attributeClosure: (Self.Element.Type) -> NullableAttribute<T>) {
setValue(value, for: attributeClosure(Self.Element.self))
}
}
| mit | e7f43a1b4d2e971be5b83a46d0c638ae | 28.453125 | 127 | 0.616976 | 4.53125 | false | false | false | false |
LoopKit/LoopKit | LoopKit/GlucoseKit/GlucoseStore.swift | 1 | 37031 | //
// GlucoseStore.swift
// Naterade
//
// Created by Nathan Racklyeft on 1/24/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
import CoreData
import HealthKit
import os.log
public protocol GlucoseStoreDelegate: AnyObject {
/**
Informs the delegate that the glucose store has updated glucose data.
- Parameter glucoseStore: The glucose store that has updated glucose data.
*/
func glucoseStoreHasUpdatedGlucoseData(_ glucoseStore: GlucoseStore)
}
/**
Manages storage, retrieval, and calculation of glucose data.
There are three tiers of storage:
* Persistant cache, stored in Core Data, used to ensure access if the app is suspended and re-launched while the Health database
* is protected and to provide data for upload to remote data services. Backfilled from HealthKit data up to observation interval.
```
0 [max(cacheLength, momentumDataInterval, observationInterval)]
|––––|
```
* HealthKit data, managed by the current application
```
0 [managedDataInterval?]
|––––––––––––|
```
* HealthKit data, managed by the manufacturer's application
```
[managedDataInterval?] [maxPurgeInterval]
|–––––––––--->
```
*/
public final class GlucoseStore: HealthKitSampleStore {
/// Notification posted when glucose samples were changed, either via direct add or from HealthKit
public static let glucoseSamplesDidChange = NSNotification.Name(rawValue: "com.loopkit.GlucoseStore.glucoseSamplesDidChange")
public weak var delegate: GlucoseStoreDelegate?
private let glucoseType = HKQuantityType.quantityType(forIdentifier: .bloodGlucose)!
/// The oldest interval to include when purging managed data
private let maxPurgeInterval: TimeInterval = TimeInterval(hours: 24) * 7
/// The interval before which glucose values should be purged from HealthKit. If nil, glucose values are not purged.
public var managedDataInterval: TimeInterval? {
get {
return lockedManagedDataInterval.value
}
set {
lockedManagedDataInterval.value = newValue
}
}
private let lockedManagedDataInterval = Locked<TimeInterval?>(nil)
/// The interval of glucose data to keep in cache
public let cacheLength: TimeInterval
/// The interval of glucose data to use for momentum calculation
public let momentumDataInterval: TimeInterval
/// The interval to observe HealthKit data to populate the cache
public let observationInterval: TimeInterval
private let queue = DispatchQueue(label: "com.loopkit.GlucoseStore.queue", qos: .utility)
private let log = OSLog(category: "GlucoseStore")
/// The most-recent glucose value.
public private(set) var latestGlucose: GlucoseSampleValue? {
get {
return lockedLatestGlucose.value
}
set {
lockedLatestGlucose.value = newValue
}
}
private let lockedLatestGlucose = Locked<GlucoseSampleValue?>(nil)
private let storeSamplesToHealthKit: Bool
private let cacheStore: PersistenceController
private let provenanceIdentifier: String
public var healthKitStorageDelay: TimeInterval = 0
// If HealthKit sharing is not authorized, `nil` will prevent later storage
var healthKitStorageDelayIfAllowed: TimeInterval? { storeSamplesToHealthKit && sharingAuthorized ? healthKitStorageDelay : nil }
static let healthKitQueryAnchorMetadataKey = "com.loopkit.GlucoseStore.hkQueryAnchor"
public init(
healthStore: HKHealthStore,
observeHealthKitSamplesFromOtherApps: Bool = true,
storeSamplesToHealthKit: Bool = true,
cacheStore: PersistenceController,
observationEnabled: Bool = true,
cacheLength: TimeInterval = 60 /* minutes */ * 60 /* seconds */,
momentumDataInterval: TimeInterval = 15 /* minutes */ * 60 /* seconds */,
observationInterval: TimeInterval? = nil,
provenanceIdentifier: String
) {
let cacheLength = max(cacheLength, momentumDataInterval, observationInterval ?? 0)
self.cacheStore = cacheStore
self.momentumDataInterval = momentumDataInterval
self.storeSamplesToHealthKit = storeSamplesToHealthKit
self.cacheLength = cacheLength
self.observationInterval = observationInterval ?? cacheLength
self.provenanceIdentifier = provenanceIdentifier
super.init(healthStore: healthStore,
observeHealthKitSamplesFromCurrentApp: true,
observeHealthKitSamplesFromOtherApps: observeHealthKitSamplesFromOtherApps,
type: glucoseType,
observationStart: Date(timeIntervalSinceNow: -self.observationInterval),
observationEnabled: observationEnabled)
let semaphore = DispatchSemaphore(value: 0)
cacheStore.onReady { (error) in
guard error == nil else {
semaphore.signal()
return
}
cacheStore.fetchAnchor(key: GlucoseStore.healthKitQueryAnchorMetadataKey) { (anchor) in
self.queue.async {
self.queryAnchor = anchor
if !self.authorizationRequired {
self.createQuery()
}
self.updateLatestGlucose()
semaphore.signal()
}
}
}
semaphore.wait()
}
// MARK: - HealthKitSampleStore
override func queryAnchorDidChange() {
cacheStore.storeAnchor(queryAnchor, key: GlucoseStore.healthKitQueryAnchorMetadataKey)
}
override func processResults(from query: HKAnchoredObjectQuery, added: [HKSample], deleted: [HKDeletedObject], anchor: HKQueryAnchor, completion: @escaping (Bool) -> Void) {
queue.async {
guard anchor != self.queryAnchor else {
self.log.default("Skipping processing results from anchored object query, as anchor was already processed")
completion(true)
return
}
var changed = false
var error: Error?
self.cacheStore.managedObjectContext.performAndWait {
do {
// Add new samples
if let samples = added as? [HKQuantitySample] {
for sample in samples {
if try self.addGlucoseSample(for: sample) {
self.log.debug("Saved sample %@ into cache from HKAnchoredObjectQuery", sample.uuid.uuidString)
changed = true
} else {
self.log.default("Sample %@ from HKAnchoredObjectQuery already present in cache", sample.uuid.uuidString)
}
}
}
// Delete deleted samples
let count = try self.deleteGlucoseSamples(withUUIDs: deleted.map { $0.uuid })
if count > 0 {
self.log.debug("Deleted %d samples from cache from HKAnchoredObjectQuery", count)
changed = true
}
guard changed else {
return
}
error = self.cacheStore.save()
} catch let coreDataError {
error = coreDataError
}
}
guard error == nil else {
completion(false)
return
}
if !changed {
completion(true)
return
}
// Purge expired managed data from HealthKit
if let newestStartDate = added.map({ $0.startDate }).max() {
self.purgeExpiredManagedDataFromHealthKit(before: newestStartDate)
}
self.handleUpdatedGlucoseData()
completion(true)
}
}
}
// MARK: - Fetching
extension GlucoseStore {
/// Retrieves glucose samples within the specified date range.
///
/// - Parameters:
/// - start: The earliest date of glucose samples to retrieve, if provided.
/// - end: The latest date of glucose samples to retrieve, if provided.
/// - completion: A closure called once the glucose samples have been retrieved.
/// - result: An array of glucose samples, in chronological order by startDate, or error.
public func getGlucoseSamples(start: Date? = nil, end: Date? = nil, completion: @escaping (_ result: Result<[StoredGlucoseSample], Error>) -> Void) {
queue.async {
completion(self.getGlucoseSamples(start: start, end: end))
}
}
private func getGlucoseSamples(start: Date? = nil, end: Date? = nil) -> Result<[StoredGlucoseSample], Error> {
dispatchPrecondition(condition: .onQueue(queue))
var samples: [StoredGlucoseSample] = []
var error: Error?
cacheStore.managedObjectContext.performAndWait {
do {
samples = try self.getCachedGlucoseObjects(start: start, end: end).map { StoredGlucoseSample(managedObject: $0) }
} catch let coreDataError {
error = coreDataError
}
}
if let error = error {
return .failure(error)
}
return .success(samples)
}
private func getCachedGlucoseObjects(start: Date? = nil, end: Date? = nil) throws -> [CachedGlucoseObject] {
dispatchPrecondition(condition: .onQueue(queue))
var predicates: [NSPredicate] = []
if let start = start {
predicates.append(NSPredicate(format: "startDate >= %@", start as NSDate))
}
if let end = end {
predicates.append(NSPredicate(format: "startDate < %@", end as NSDate))
}
let request: NSFetchRequest<CachedGlucoseObject> = CachedGlucoseObject.fetchRequest()
request.predicate = (predicates.count > 1) ? NSCompoundPredicate(andPredicateWithSubpredicates: predicates) : predicates.first
request.sortDescriptors = [NSSortDescriptor(key: "startDate", ascending: true)]
return try self.cacheStore.managedObjectContext.fetch(request)
}
private func updateLatestGlucose() {
dispatchPrecondition(condition: .onQueue(queue))
cacheStore.managedObjectContext.performAndWait {
var latestGlucose: StoredGlucoseSample?
do {
let request: NSFetchRequest<CachedGlucoseObject> = CachedGlucoseObject.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(key: "startDate", ascending: false)]
request.fetchLimit = 1
let objects = try self.cacheStore.managedObjectContext.fetch(request)
latestGlucose = objects.first.map { StoredGlucoseSample(managedObject: $0) }
} catch let error {
self.log.error("Unable to fetch latest glucose object: %@", String(describing: error))
}
self.latestGlucose = latestGlucose
}
}
}
// MARK: - Modification
extension GlucoseStore {
/// Add glucose samples to store.
///
/// - Parameters:
/// - samples: The new glucose samples to add to the store.
/// - completion: A closure called once the glucose samples have been stored.
/// - result: An array of glucose samples that were stored, or error.
public func addGlucoseSamples(_ samples: [NewGlucoseSample], completion: @escaping (_ result: Result<[StoredGlucoseSample], Error>) -> Void) {
guard !samples.isEmpty else {
completion(.success([]))
return
}
queue.async {
var storedSamples: [StoredGlucoseSample] = []
var error: Error?
self.cacheStore.managedObjectContext.performAndWait {
do {
// Filter samples to ensure no duplicate sync identifiers nor existing sample with matching sync identifier for our provenance identifier
var syncIdentifiers = Set<String>()
let samples: [NewGlucoseSample] = try samples.compactMap { sample in
guard syncIdentifiers.insert(sample.syncIdentifier).inserted else {
self.log.default("Skipping adding glucose sample due to duplicate sync identifier: %{public}@", sample.syncIdentifier)
return nil
}
let request: NSFetchRequest<CachedGlucoseObject> = CachedGlucoseObject.fetchRequest()
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [NSPredicate(format: "provenanceIdentifier == %@", self.provenanceIdentifier),
NSPredicate(format: "syncIdentifier == %@", sample.syncIdentifier)])
request.fetchLimit = 1
guard try self.cacheStore.managedObjectContext.count(for: request) == 0 else {
self.log.default("Skipping adding glucose sample due to existing cached sync identifier: %{public}@", sample.syncIdentifier)
return nil
}
return sample
}
guard !samples.isEmpty else {
return
}
let objects: [CachedGlucoseObject] = samples.map { sample in
let object = CachedGlucoseObject(context: self.cacheStore.managedObjectContext)
object.create(from: sample,
provenanceIdentifier: self.provenanceIdentifier,
healthKitStorageDelay: self.healthKitStorageDelayIfAllowed)
return object
}
error = self.cacheStore.save()
guard error == nil else {
return
}
storedSamples = objects.map { StoredGlucoseSample(managedObject: $0) }
} catch let coreDataError {
error = coreDataError
}
}
if let error = error {
completion(.failure(error))
return
}
self.handleUpdatedGlucoseData()
completion(.success(storedSamples))
}
}
private func saveSamplesToHealthKit() {
dispatchPrecondition(condition: .onQueue(queue))
var error: Error?
guard storeSamplesToHealthKit else {
return
}
cacheStore.managedObjectContext.performAndWait {
do {
let request: NSFetchRequest<CachedGlucoseObject> = CachedGlucoseObject.fetchRequest()
request.predicate = NSPredicate(format: "healthKitEligibleDate <= %@", Date() as NSDate)
request.sortDescriptors = [NSSortDescriptor(key: "modificationCounter", ascending: true)] // Maintains modificationCounter order
let objects = try self.cacheStore.managedObjectContext.fetch(request)
guard !objects.isEmpty else {
return
}
if objects.contains(where: { $0.uuid != nil }) {
self.log.error("Found CachedGlucoseObjects with non-nil uuid. Should never happen, but HealthKit should be able to resolve it.")
// Note: UUIDs will be overwritten below, but since the syncIdentifiers will match then HealthKit can resolve correctly via replacement
}
let quantitySamples = objects.map { $0.quantitySample }
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
self.healthStore.save(quantitySamples) { (_, healthKitError) in
error = healthKitError
dispatchGroup.leave()
}
dispatchGroup.wait()
// If there is an error writing to HealthKit, then do not persist uuids and retry later
guard error == nil else {
return
}
for (object, quantitySample) in zip(objects, quantitySamples) {
object.uuid = quantitySample.uuid
object.healthKitEligibleDate = nil
object.updateModificationCounter() // Maintains modificationCounter order
}
error = self.cacheStore.save()
guard error == nil else {
return
}
self.log.default("Stored %d eligible glucose samples to HealthKit", objects.count)
} catch let coreDataError {
error = coreDataError
}
}
if let error = error {
self.log.error("Error saving samples to HealthKit: %{public}@", String(describing: error))
}
}
private func addGlucoseSample(for sample: HKQuantitySample) throws -> Bool {
dispatchPrecondition(condition: .onQueue(queue))
// Are there any objects matching the UUID?
let request: NSFetchRequest<CachedGlucoseObject> = CachedGlucoseObject.fetchRequest()
request.predicate = NSPredicate(format: "uuid == %@", sample.uuid as NSUUID)
request.fetchLimit = 1
let count = try cacheStore.managedObjectContext.count(for: request)
guard count == 0 else {
return false
}
// Add an object for this UUID
let object = CachedGlucoseObject(context: cacheStore.managedObjectContext)
object.create(from: sample)
return true
}
private func deleteGlucoseSamples(withUUIDs uuids: [UUID], batchSize: Int = 500) throws -> Int {
dispatchPrecondition(condition: .onQueue(queue))
var count = 0
for batch in uuids.chunked(into: batchSize) {
let predicate = NSPredicate(format: "uuid IN %@", batch.map { $0 as NSUUID })
count += try cacheStore.managedObjectContext.purgeObjects(of: CachedGlucoseObject.self, matching: predicate)
}
return count
}
///
/// - Parameters:
/// - since: Only consider glucose valid after or at this date
/// - Returns: The latest CGM glucose, if available in the time period specified
public func getLatestCGMGlucose(since: Date, completion: @escaping (_ result: Result<StoredGlucoseSample?, Error>) -> Void) {
queue.async {
self.cacheStore.managedObjectContext.performAndWait {
let request: NSFetchRequest<CachedGlucoseObject> = CachedGlucoseObject.fetchRequest()
request.predicate = NSPredicate(format: "startDate >= %@ AND wasUserEntered == NO", since as NSDate)
request.sortDescriptors = [NSSortDescriptor(key: "startDate", ascending: false)]
request.fetchLimit = 1
do {
let objects = try self.cacheStore.managedObjectContext.fetch(request)
let samples = objects.map { StoredGlucoseSample(managedObject: $0) }
completion(.success(samples.first))
} catch let error {
self.log.error("Error in getLatestCGMGlucose: %@", String(describing: error))
completion(.failure(error))
}
}
}
}
}
// MARK: - Watch Synchronization
extension GlucoseStore {
/// Get glucose samples in main app to deliver to Watch extension
public func getSyncGlucoseSamples(start: Date? = nil, end: Date? = nil, completion: @escaping (_ result: Result<[StoredGlucoseSample], Error>) -> Void) {
queue.async {
var samples: [StoredGlucoseSample] = []
var error: Error?
self.cacheStore.managedObjectContext.performAndWait {
do {
samples = try self.getCachedGlucoseObjects(start: start, end: end).map { StoredGlucoseSample(managedObject: $0) }
} catch let coreDataError {
error = coreDataError
}
}
if let error = error {
completion(.failure(error))
return
}
completion(.success(samples))
}
}
/// Store glucose samples in Watch extension
public func setSyncGlucoseSamples(_ objects: [StoredGlucoseSample], completion: @escaping (Error?) -> Void) {
queue.async {
var error: Error?
self.cacheStore.managedObjectContext.performAndWait {
guard !objects.isEmpty else {
return
}
objects.forEach {
let object = CachedGlucoseObject(context: self.cacheStore.managedObjectContext)
object.update(from: $0)
}
error = self.cacheStore.save()
}
if let error = error {
completion(error)
return
}
self.handleUpdatedGlucoseData()
completion(nil)
}
}
}
// MARK: - Cache Management
extension GlucoseStore {
public var earliestCacheDate: Date {
return Date(timeIntervalSinceNow: -cacheLength)
}
/// Purge all glucose samples from the glucose store and HealthKit (matching the specified device predicate).
///
/// - Parameters:
/// - healthKitPredicate: The predicate to use in matching HealthKit glucose objects.
/// - completion: The completion handler returning any error.
public func purgeAllGlucoseSamples(healthKitPredicate: NSPredicate, completion: @escaping (Error?) -> Void) {
queue.async {
let storeError = self.purgeCachedGlucoseObjects()
self.healthStore.deleteObjects(of: self.glucoseType, predicate: healthKitPredicate) { _, _, healthKitError in
self.queue.async {
if let error = storeError ?? healthKitError {
completion(error)
return
}
self.handleUpdatedGlucoseData()
completion(nil)
}
}
}
}
private func purgeExpiredCachedGlucoseObjects() {
purgeCachedGlucoseObjects(before: earliestCacheDate)
}
/// Purge cached glucose objects from the glucose store.
///
/// - Parameters:
/// - date: Purge cached glucose objects with start date before this date.
/// - completion: The completion handler returning any error.
public func purgeCachedGlucoseObjects(before date: Date? = nil, completion: @escaping (Error?) -> Void) {
queue.async {
if let error = self.purgeCachedGlucoseObjects(before: date) {
completion(error)
return
}
self.handleUpdatedGlucoseData()
completion(nil)
}
}
@discardableResult
private func purgeCachedGlucoseObjects(before date: Date? = nil) -> Error? {
dispatchPrecondition(condition: .onQueue(queue))
var error: Error?
cacheStore.managedObjectContext.performAndWait {
do {
var predicate: NSPredicate?
if let date = date {
predicate = NSPredicate(format: "startDate < %@", date as NSDate)
}
let count = try cacheStore.managedObjectContext.purgeObjects(of: CachedGlucoseObject.self, matching: predicate)
self.log.default("Purged %d CachedGlucoseObjects", count)
} catch let coreDataError {
self.log.error("Unable to purge CachedGlucoseObjects: %{public}@", String(describing: error))
error = coreDataError
}
}
return error
}
private func purgeExpiredManagedDataFromHealthKit(before date: Date) {
dispatchPrecondition(condition: .onQueue(queue))
guard let managedDataInterval = managedDataInterval else {
return
}
let end = min(Date(timeIntervalSinceNow: -managedDataInterval), date)
let predicate = HKQuery.predicateForSamples(withStart: Date(timeIntervalSinceNow: -maxPurgeInterval), end: end)
healthStore.deleteObjects(of: glucoseType, predicate: predicate) { (success, count, error) -> Void in
// error is expected and ignored if protected data is unavailable
if success {
self.log.debug("Successfully purged %d HealthKit objects older than %{public}@", count, String(describing: end))
}
}
}
private func handleUpdatedGlucoseData() {
dispatchPrecondition(condition: .onQueue(queue))
self.purgeExpiredCachedGlucoseObjects()
self.updateLatestGlucose()
self.saveSamplesToHealthKit()
NotificationCenter.default.post(name: GlucoseStore.glucoseSamplesDidChange, object: self)
delegate?.glucoseStoreHasUpdatedGlucoseData(self)
}
}
// MARK: - Math
extension GlucoseStore {
/// Calculates the momentum effect for recent glucose values.
///
/// The duration of effect data returned is determined by the `momentumDataInterval`, and the delta between data points is 5 minutes.
///
/// This operation is performed asynchronously and the completion will be executed on an arbitrary background queue.
///
/// - Parameters:
/// - completion: A closure called once the calculation has completed.
/// - result: The calculated effect values, or an empty array if the glucose data isn't suitable for momentum calculation, or error.
public func getRecentMomentumEffect(_ completion: @escaping (_ result: Result<[GlucoseEffect], Error>) -> Void) {
getGlucoseSamples(start: Date(timeIntervalSinceNow: -momentumDataInterval)) { (result) in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let samples):
let effects = samples.linearMomentumEffect(
duration: self.momentumDataInterval,
delta: TimeInterval(minutes: 5)
)
completion(.success(effects))
}
}
}
/// Calculates a timeline of effect velocity (glucose/time) observed in glucose that counteract the specified effects.
///
/// - Parameters:
/// - start: The earliest date of glucose samples to include.
/// - end: The latest date of glucose samples to include, if provided.
/// - effects: Glucose effects to be countered, in chronological order, and counteraction effects calculated.
/// - completion: A closure called once the glucose samples have been retrieved and counteraction effects calculated.
/// - result: An array of glucose effect velocities describing the change in glucose samples compared to the specified glucose effects, or error.
public func getCounteractionEffects(start: Date, end: Date? = nil, to effects: [GlucoseEffect], _ completion: @escaping (_ result: Result<[GlucoseEffectVelocity], Error>) -> Void) {
getGlucoseSamples(start: start, end: end) { (result) in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let samples):
completion(.success(self.counteractionEffects(for: samples, to: effects)))
}
}
}
/// Calculates a timeline of effect velocity (glucose/time) observed in glucose that counteract the specified effects.
///
/// - Parameter:
/// - samples: The observed timeline of samples.
/// - effects: An array of velocities describing the change in glucose samples compared to the specified effects
public func counteractionEffects<Sample: GlucoseSampleValue>(for samples: [Sample], to effects: [GlucoseEffect]) -> [GlucoseEffectVelocity] {
samples.counteractionEffects(to: effects)
}
}
// MARK: - Remote Data Service Query
extension GlucoseStore {
public struct QueryAnchor: Equatable, RawRepresentable {
public typealias RawValue = [String: Any]
internal var modificationCounter: Int64
public init() {
self.modificationCounter = 0
}
public init?(rawValue: RawValue) {
guard let modificationCounter = rawValue["modificationCounter"] as? Int64 else {
return nil
}
self.modificationCounter = modificationCounter
}
public var rawValue: RawValue {
var rawValue: RawValue = [:]
rawValue["modificationCounter"] = modificationCounter
return rawValue
}
}
public enum GlucoseQueryResult {
case success(QueryAnchor, [StoredGlucoseSample])
case failure(Error)
}
public func executeGlucoseQuery(fromQueryAnchor queryAnchor: QueryAnchor?, limit: Int, completion: @escaping (GlucoseQueryResult) -> Void) {
queue.async {
var queryAnchor = queryAnchor ?? QueryAnchor()
var queryResult = [StoredGlucoseSample]()
var queryError: Error?
guard limit > 0 else {
completion(.success(queryAnchor, []))
return
}
self.cacheStore.managedObjectContext.performAndWait {
let storedRequest: NSFetchRequest<CachedGlucoseObject> = CachedGlucoseObject.fetchRequest()
storedRequest.predicate = NSPredicate(format: "modificationCounter > %d", queryAnchor.modificationCounter)
storedRequest.sortDescriptors = [NSSortDescriptor(key: "modificationCounter", ascending: true)]
storedRequest.fetchLimit = limit
do {
let stored = try self.cacheStore.managedObjectContext.fetch(storedRequest)
if let modificationCounter = stored.max(by: { $0.modificationCounter < $1.modificationCounter })?.modificationCounter {
queryAnchor.modificationCounter = modificationCounter
}
queryResult.append(contentsOf: stored.compactMap { StoredGlucoseSample(managedObject: $0) })
} catch let error {
queryError = error
return
}
}
if let queryError = queryError {
completion(.failure(queryError))
return
}
completion(.success(queryAnchor, queryResult))
}
}
}
// MARK: - Critical Event Log Export
extension GlucoseStore: CriticalEventLog {
private var exportProgressUnitCountPerObject: Int64 { 1 }
private var exportFetchLimit: Int { Int(criticalEventLogExportProgressUnitCountPerFetch / exportProgressUnitCountPerObject) }
public var exportName: String { "Glucose.json" }
public func exportProgressTotalUnitCount(startDate: Date, endDate: Date? = nil) -> Result<Int64, Error> {
var result: Result<Int64, Error>?
self.cacheStore.managedObjectContext.performAndWait {
do {
let request: NSFetchRequest<CachedGlucoseObject> = CachedGlucoseObject.fetchRequest()
request.predicate = self.exportDatePredicate(startDate: startDate, endDate: endDate)
let objectCount = try self.cacheStore.managedObjectContext.count(for: request)
result = .success(Int64(objectCount) * exportProgressUnitCountPerObject)
} catch let error {
result = .failure(error)
}
}
return result!
}
public func export(startDate: Date, endDate: Date, to stream: OutputStream, progress: Progress) -> Error? {
let encoder = JSONStreamEncoder(stream: stream)
var modificationCounter: Int64 = 0
var fetching = true
var error: Error?
while fetching && error == nil {
self.cacheStore.managedObjectContext.performAndWait {
do {
guard !progress.isCancelled else {
throw CriticalEventLogError.cancelled
}
let request: NSFetchRequest<CachedGlucoseObject> = CachedGlucoseObject.fetchRequest()
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [NSPredicate(format: "modificationCounter > %d", modificationCounter),
self.exportDatePredicate(startDate: startDate, endDate: endDate)])
request.sortDescriptors = [NSSortDescriptor(key: "modificationCounter", ascending: true)]
request.fetchLimit = self.exportFetchLimit
let objects = try self.cacheStore.managedObjectContext.fetch(request)
if objects.isEmpty {
fetching = false
return
}
try encoder.encode(objects)
modificationCounter = objects.last!.modificationCounter
progress.completedUnitCount += Int64(objects.count) * exportProgressUnitCountPerObject
} catch let fetchError {
error = fetchError
}
}
}
if let closeError = encoder.close(), error == nil {
error = closeError
}
return error
}
private func exportDatePredicate(startDate: Date, endDate: Date? = nil) -> NSPredicate {
var predicate = NSPredicate(format: "startDate >= %@", startDate as NSDate)
if let endDate = endDate {
predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, NSPredicate(format: "startDate < %@", endDate as NSDate)])
}
return predicate
}
}
// MARK: - Core Data (Bulk) - TEST ONLY
extension GlucoseStore {
public func addNewGlucoseSamples(samples: [NewGlucoseSample], completion: @escaping (Error?) -> Void) {
guard !samples.isEmpty else {
completion(nil)
return
}
queue.async {
var error: Error?
self.cacheStore.managedObjectContext.performAndWait {
for sample in samples {
let object = CachedGlucoseObject(context: self.cacheStore.managedObjectContext)
object.create(from: sample, provenanceIdentifier: self.provenanceIdentifier, healthKitStorageDelay: self.healthKitStorageDelayIfAllowed)
}
error = self.cacheStore.save()
}
guard error == nil else {
completion(error)
return
}
self.log.info("Added %d CachedGlucoseObjects", samples.count)
self.delegate?.glucoseStoreHasUpdatedGlucoseData(self)
completion(nil)
}
}
}
// MARK: - Issue Report
extension GlucoseStore {
/// Generates a diagnostic report about the current state.
///
/// This operation is performed asynchronously and the completion will be executed on an arbitrary background queue.
///
/// - parameter completionHandler: A closure called once the report has been generated. The closure takes a single argument of the report string.
public func generateDiagnosticReport(_ completionHandler: @escaping (_ report: String) -> Void) {
queue.async {
var report: [String] = [
"## GlucoseStore",
"",
"* latestGlucoseValue: \(String(reflecting: self.latestGlucose))",
"* managedDataInterval: \(self.managedDataInterval ?? 0)",
"* cacheLength: \(self.cacheLength)",
"* momentumDataInterval: \(self.momentumDataInterval)",
"* observationInterval: \(self.observationInterval)",
super.debugDescription,
"",
"### cachedGlucoseSamples",
]
switch self.getGlucoseSamples(start: Date(timeIntervalSinceNow: -.hours(24))) {
case .failure(let error):
report.append("Error: \(error)")
case .success(let samples):
for sample in samples {
report.append(String(describing: sample))
}
}
report.append("")
completionHandler(report.joined(separator: "\n"))
}
}
}
| mit | bc0abe9eccdfe3d6fe7cab6307d6ba50 | 38.892125 | 185 | 0.599513 | 5.461527 | false | false | false | false |
airspeedswift/swift-compiler-crashes | crashes-fuzzing/00424-no-stacktrace.random.swift | 12 | 2432 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
return d<A"\()
import CoreData
return "
case b in x in a {
typealias B<I : B? = {
self] in
let g = compose(g: c> [B) -> ("""
}
case b {
let c: NSObject {
protocol a {
import Foundation
return $0
protocol A : Array) {
self.E == .c> U.dynamicType)
return nil
}
return b
}
}
return d
return true
return [B
let t: P {
func f("")-> Int = { x }
typealias R
}
import Foundation
}
extension NSSet {
}
static let h = [T>: NSManagedObject {
}
let g = { c>()
typealias h> {
convenience init() -> T
var c>Bool)
}
func g(t: C {
var e: String = {
init()
}
}
class d: NSObject {
}
}
self.B
func b<T>(t: T]((t: NSObject {
self] {
protocol c = {
func a(object1: P {
typealias R
convenience init("\() {
class C<T
var e)
}
var e: AnyObject.R
extension NSSet {
let c: Array) -> [B<T] {
import CoreData
var e: A.d.Type) {
class C) -> {
}
protocol P {
println(object2: T
}
}
class C
}
}
typealias e : Int -> : d where T) -> {
let a {
struct D : A {
}
}
import Foundation
let d<H : A? = nil
self.B? {
private let d<T, f: NSManagedObject {
class func f: B<C> : C> Self {
typealias F>(n: NSObject {
}
protocol P {
class A : e, f: AnyObject, AnyObject) -> Int = A"\(n: d = { c) {
typealias F = compose()(f)
class C<f : Int -> {
import Foundation
}
}
class A : A: T>>(false)
}
let g = D>)
import Foundation
struct D : Int -> T>())
import Foundation
let c(AnyObject, b = .init()
println(t: A {
f = b: U.E == {
if true {
}
case b = e: P {
private class A {
return nil
func g<T) {
convenience init()
if c == f<T! {
return self.b = ""
if c = b<T where A: e, object1, f<T] in
override init(n: P {
}
func f(t: A((c: A : A> Int = b> {
}
}
d: Int
}
return d.Type) {
struct S {
[T>()
}
import Foundation
}
class A : T>? {
var b {
self.E
struct B
}
protocol c {
typealias e = 0
func b
struct c {
convenience init(x)
import Foundation
}
typealias R = b
typealias e : B<A? = 0
}
class C) ->) -> Int {
}
return { x }
}
typealias R
}
protocol P {
let c: B("A.e where A.c()(f<T where T>(g<T! {
var b<H : P> {
let f = {
e : T] in
}
}
class A {
}
}
class func b.e == { c(x: e: Int
let v: P {
}
}
class func a(self)
let d<T>) {
}
println(c: B? = B<c> Self {
let c = {
}
self.R
}
class A {
struct c == e: A>>()
let c(n: Array) -> T -> {
}
return $0
}
private class A : U : (x: P> T where H) {
if true {
let c
| mit | b71d755993fcfde10c4cb54a6ad8b57a | 12.740113 | 87 | 0.594984 | 2.49692 | false | false | false | false |
DopamineLabs/DopamineKit-iOS | BoundlessKit/Classes/Integration/HttpClients/Data/Models/BoundlessConfiguration.swift | 1 | 6559 | //
// BoundlessConfiguration.swift
// BoundlessKit
//
// Created by Akash Desai on 3/10/18.
//
import Foundation
internal struct BoundlessConfiguration {
let configID: String?
let integrationMethod: String
let reinforcementEnabled: Bool
let reportBatchSize: Int
let triggerEnabled: Bool
let trackingEnabled: Bool
let trackBatchSize: Int
let locationObservations: Bool
let applicationState: Bool
let applicationViews: Bool
let consoleLoggingEnabled: Bool
init(configID: String? = nil,
integrationMethod: String = "manual",
reinforcementEnabled: Bool = true,
reportBatchSize: Int = 10,
triggerEnabled: Bool = false,
trackingEnabled: Bool = true,
trackBatchSize: Int = 10,
locationObservations: Bool = false,
applicationState: Bool = false,
applicationViews: Bool = false,
consoleLoggingEnabled: Bool = true
) {
self.configID = configID
self.integrationMethod = integrationMethod
self.reinforcementEnabled = reinforcementEnabled
self.reportBatchSize = reportBatchSize
self.triggerEnabled = triggerEnabled
self.trackingEnabled = trackingEnabled
self.trackBatchSize = trackBatchSize
self.locationObservations = locationObservations
self.applicationState = applicationState
self.applicationViews = applicationViews
self.consoleLoggingEnabled = consoleLoggingEnabled
}
}
extension BoundlessConfiguration {
func encode() -> Data {
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
archiver.encode(configID, forKey: "configID")
archiver.encode(integrationMethod, forKey: "integrationMethod")
archiver.encode(reinforcementEnabled, forKey: "reinforcementEnabled")
archiver.encode(reportBatchSize, forKey: "reportBatchSize")
archiver.encode(triggerEnabled, forKey: "triggerEnabled")
archiver.encode(trackingEnabled, forKey: "trackingEnabled")
archiver.encode(trackBatchSize, forKey: "trackBatchSize")
archiver.encode(locationObservations, forKey: "locationObservations")
archiver.encode(applicationState, forKey: "applicationState")
archiver.encode(applicationViews, forKey: "applicationViews")
archiver.encode(consoleLoggingEnabled, forKey: "consoleLoggingEnabled")
archiver.finishEncoding()
return data as Data
}
init?(data: Data) {
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
defer {
unarchiver.finishDecoding()
}
guard let configID = unarchiver.decodeObject(forKey: "configID") as? String else { return nil }
guard let integrationMethod = unarchiver.decodeObject(forKey: "integrationMethod") as? String else { return nil }
self.init(configID: configID,
integrationMethod: integrationMethod,
reinforcementEnabled: unarchiver.decodeBool(forKey: "reinforcementEnabled"),
reportBatchSize: unarchiver.decodeInteger(forKey: "reportBatchSize"),
triggerEnabled: unarchiver.decodeBool(forKey: "triggerEnabled"),
trackingEnabled: unarchiver.decodeBool(forKey: "trackingEnabled"),
trackBatchSize: unarchiver.decodeInteger(forKey: "trackBatchSize"),
locationObservations: unarchiver.decodeBool(forKey: "locationObservations"),
applicationState: unarchiver.decodeBool(forKey: "applicationState"),
applicationViews: unarchiver.decodeBool(forKey: "applicationViews"),
consoleLoggingEnabled: unarchiver.decodeBool(forKey: "consoleLoggingEnabled")
)
}
}
extension BoundlessConfiguration {
static func convert(from dict: [String: Any]) -> BoundlessConfiguration? {
guard let configID = dict["configID"] as? String? else { BKLog.debug(error: "Bad parameter"); return nil }
guard let reinforcementEnabled = dict["reinforcementEnabled"] as? Bool else { BKLog.debug(error: "Bad parameter"); return nil }
guard let triggerEnabled = dict["triggerEnabled"] as? Bool else { BKLog.debug(error: "Bad parameter"); return nil }
guard let trackingEnabled = dict["trackingEnabled"] as? Bool else { BKLog.debug(error: "Bad parameter"); return nil }
guard let trackingCapabilities = dict["trackingCapabilities"] as? [String: Any] else { BKLog.debug(error: "Bad parameter"); return nil }
guard let applicationState = trackingCapabilities["applicationState"] as? Bool else { BKLog.debug(error: "Bad parameter"); return nil }
guard let applicationViews = trackingCapabilities["applicationViews"] as? Bool else { BKLog.debug(error: "Bad parameter"); return nil }
guard let locationObservations = trackingCapabilities["locationObservations"] as? Bool else { BKLog.debug(error: "Bad parameter"); return nil }
guard let batchSize = dict["batchSize"] as? [String: Any] else { BKLog.debug(error: "Bad parameter"); return nil }
guard let trackBatchSize = batchSize["track"] as? Int else { BKLog.debug(error: "Bad parameter"); return nil }
guard let reportBatchSize = batchSize["report"] as? Int else { BKLog.debug(error: "Bad parameter"); return nil }
guard let integrationMethod = dict["integrationMethod"] as? String else { BKLog.debug(error: "Bad parameter"); return nil }
guard let consoleLoggingEnabled = dict["consoleLoggingEnabled"] as? Bool else { BKLog.debug(error: "Bad parameter"); return nil }
return BoundlessConfiguration.init(configID: configID,
integrationMethod: integrationMethod,
reinforcementEnabled: reinforcementEnabled,
reportBatchSize: reportBatchSize,
triggerEnabled: triggerEnabled,
trackingEnabled: trackingEnabled,
trackBatchSize: trackBatchSize,
locationObservations: locationObservations,
applicationState: applicationState,
applicationViews: applicationViews,
consoleLoggingEnabled: consoleLoggingEnabled
)
}
}
| mit | b27b09c30d5fade875906cfe5c7830a7 | 52.325203 | 151 | 0.655283 | 5.349918 | false | true | false | false |
kean/Nuke | Tests/NukeTests/ImagePipelineTests/ImagePipelineConfigurationTests.swift | 1 | 2731 | // The MIT License (MIT)
//
// Copyright (c) 2015-2022 Alexander Grebenyuk (github.com/kean).
import XCTest
@testable import Nuke
class ImagePipelineConfigurationTests: XCTestCase {
func testImageIsLoadedWithRateLimiterDisabled() {
// Given
let dataLoader = MockDataLoader()
let pipeline = ImagePipeline {
$0.dataLoader = dataLoader
$0.imageCache = nil
$0.isRateLimiterEnabled = false
}
// When/Then
expect(pipeline).toLoadImage(with: Test.request)
wait()
}
// MARK: DataCache
func testWithDataCache() {
let pipeline = ImagePipeline(configuration: .withDataCache)
XCTAssertNotNil(pipeline.configuration.dataCache)
}
// MARK: Changing Callback Queue
func testChangingCallbackQueueLoadImage() {
// Given
let queue = DispatchQueue(label: "testChangingCallbackQueue")
let queueKey = DispatchSpecificKey<Void>()
queue.setSpecific(key: queueKey, value: ())
let dataLoader = MockDataLoader()
let pipeline = ImagePipeline {
$0.dataLoader = dataLoader
$0.imageCache = nil
$0.callbackQueue = queue
}
// When/Then
let expectation = self.expectation(description: "Image Loaded")
pipeline.loadImage(with: Test.url, progress: { _, _, _ in
XCTAssertNotNil(DispatchQueue.getSpecific(key: queueKey))
}, completion: { _ in
XCTAssertNotNil(DispatchQueue.getSpecific(key: queueKey))
expectation.fulfill()
})
wait()
}
func testChangingCallbackQueueLoadData() {
// Given
let queue = DispatchQueue(label: "testChangingCallbackQueue")
let queueKey = DispatchSpecificKey<Void>()
queue.setSpecific(key: queueKey, value: ())
let dataLoader = MockDataLoader()
let pipeline = ImagePipeline {
$0.dataLoader = dataLoader
$0.imageCache = nil
$0.callbackQueue = queue
}
// When/Then
let expectation = self.expectation(description: "Image data Loaded")
pipeline.loadData(with: Test.request, progress: { _, _ in
XCTAssertNotNil(DispatchQueue.getSpecific(key: queueKey))
}, completion: { _ in
XCTAssertNotNil(DispatchQueue.getSpecific(key: queueKey))
expectation.fulfill()
})
wait()
}
func testEnablingSignposts() {
ImagePipeline.Configuration.isSignpostLoggingEnabled = false // Just padding
ImagePipeline.Configuration.isSignpostLoggingEnabled = true
ImagePipeline.Configuration.isSignpostLoggingEnabled = false
}
}
| mit | 8a1d9cced736622e638e778d411a75fd | 29.685393 | 84 | 0.62468 | 5.114232 | false | true | false | false |
KittenYang/A-GUIDE-TO-iOS-ANIMATION | Swift Version/KYCuteView-Swift/KYCuteView-Swift/CuteView.swift | 1 | 9733 | //
// CuteView.swift
// CuteView-Swift
//
// Created by Kitten Yang on 1/19/16.
// Copyright © 2016 Kitten Yang. All rights reserved.
//
import UIKit
struct BubbleOptions {
var text: String = ""
var bubbleWidth: CGFloat = 0.0
var viscosity: CGFloat = 0.0
var bubbleColor: UIColor = UIColor.whiteColor()
}
class CuteView: UIView {
var frontView: UIView?
var bubbleOptions: BubbleOptions!{
didSet{
bubbleLabel.text = bubbleOptions.text
}
}
private var bubbleLabel: UILabel!
private var containerView: UIView!
private var cutePath: UIBezierPath!
private var fillColorForCute: UIColor!
private var animator: UIDynamicAnimator!
private var snap: UISnapBehavior!
private var backView: UIView!
private var shapeLayer: CAShapeLayer!
private var r1: CGFloat = 0.0
private var r2: CGFloat = 0.0
private var x1: CGFloat = 0.0
private var y1: CGFloat = 0.0
private var x2: CGFloat = 0.0
private var y2: CGFloat = 0.0
private var centerDistance: CGFloat = 0.0
private var cosDigree: CGFloat = 0.0
private var sinDigree: CGFloat = 0.0
private var pointA = CGPointZero
private var pointB = CGPointZero
private var pointC = CGPointZero
private var pointD = CGPointZero
private var pointO = CGPointZero
private var pointP = CGPointZero
private var initialPoint: CGPoint = CGPointZero
private var oldBackViewFrame: CGRect = CGRectZero
private var oldBackViewCenter: CGPoint = CGPointZero
init(point: CGPoint, superView: UIView, options: BubbleOptions) {
super.init(frame: CGRectMake(point.x, point.y, options.bubbleWidth, options.bubbleWidth))
bubbleOptions = options
initialPoint = point
containerView = superView
containerView.addSubview(self)
setUp()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func drawRect() {
guard let frontView = frontView else{
return
}
x1 = backView.center.x
y1 = backView.center.y
x2 = frontView.center.x
y2 = frontView.center.y
let xtimesx = (x2-x1)*(x2-x1)
centerDistance = sqrt(xtimesx + (y2-y1)*(y2-y1))
if centerDistance == 0 {
cosDigree = 1
sinDigree = 0
}else{
cosDigree = (y2-y1)/centerDistance
sinDigree = (x2-x1)/centerDistance
}
r1 = oldBackViewFrame.size.width / 2 - centerDistance/bubbleOptions.viscosity
pointA = CGPointMake(x1-r1*cosDigree, y1+r1*sinDigree) // A
pointB = CGPointMake(x1+r1*cosDigree, y1-r1*sinDigree) // B
pointD = CGPointMake(x2-r2*cosDigree, y2+r2*sinDigree) // D
pointC = CGPointMake(x2+r2*cosDigree, y2-r2*sinDigree) // C
pointO = CGPointMake(pointA.x + (centerDistance / 2)*sinDigree, pointA.y + (centerDistance / 2)*cosDigree)
pointP = CGPointMake(pointB.x + (centerDistance / 2)*sinDigree, pointB.y + (centerDistance / 2)*cosDigree)
backView.center = oldBackViewCenter;
backView.bounds = CGRectMake(0, 0, r1*2, r1*2);
backView.layer.cornerRadius = r1;
cutePath = UIBezierPath()
cutePath.moveToPoint(pointA)
cutePath.addQuadCurveToPoint(pointD, controlPoint: pointO)
cutePath.addLineToPoint(pointC)
cutePath.addQuadCurveToPoint(pointB, controlPoint: pointP)
cutePath.moveToPoint(pointA)
if backView.hidden == false {
shapeLayer.path = cutePath.CGPath
shapeLayer.fillColor = fillColorForCute.CGColor
containerView.layer.insertSublayer(shapeLayer, below: frontView.layer)
}
}
private func setUp() {
shapeLayer = CAShapeLayer()
backgroundColor = UIColor.clearColor()
frontView = UIView(frame: CGRect(x: initialPoint.x, y: initialPoint.y, width: bubbleOptions.bubbleWidth, height: bubbleOptions.bubbleWidth))
guard let frontView = frontView else {
print("frontView is nil")
return
}
r2 = frontView.bounds.size.width / 2.0
frontView.layer.cornerRadius = r2
frontView.backgroundColor = bubbleOptions.bubbleColor
backView = UIView(frame: frontView.frame)
r1 = backView.bounds.size.width / 2
backView.layer.cornerRadius = r1
backView.backgroundColor = bubbleOptions.bubbleColor
bubbleLabel = UILabel()
bubbleLabel.frame = CGRect(x: 0, y: 0, width: frontView.bounds.width, height: frontView.bounds.height)
bubbleLabel.textColor = UIColor.whiteColor()
bubbleLabel.textAlignment = .Center
bubbleLabel.text = bubbleOptions.text
frontView.insertSubview(bubbleLabel, atIndex: 0)
containerView.addSubview(backView)
containerView.addSubview(frontView)
x1 = backView.center.x
y1 = backView.center.y
x2 = frontView.center.x
y2 = frontView.center.y
pointA = CGPointMake(x1-r1,y1); // A
pointB = CGPointMake(x1+r1, y1); // B
pointD = CGPointMake(x2-r2, y2); // D
pointC = CGPointMake(x2+r2, y2); // C
pointO = CGPointMake(x1-r1,y1); // O
pointP = CGPointMake(x2+r2, y2); // P
oldBackViewFrame = backView.frame
oldBackViewCenter = backView.center
backView.hidden = true //为了看到frontView的气泡晃动效果,需要暂时隐藏backView
addAniamtionLikeGameCenterBubble()
let panGesture = UIPanGestureRecognizer(target: self, action: "handleDragGesture:")
frontView.addGestureRecognizer(panGesture)
}
@objc private func handleDragGesture(ges: UIPanGestureRecognizer) {
let dragPoint = ges.locationInView(containerView)
if ges.state == .Began {
// 不给r1赋初始值的话,如果第一次拖动使得r1少于6,第二次拖动就直接隐藏绘制路径了
r1 = oldBackViewFrame.width / 2
backView.hidden = false
fillColorForCute = bubbleOptions.bubbleColor
removeAniamtionLikeGameCenterBubble()
} else if ges.state == .Changed {
frontView?.center = dragPoint
if r1 <= 6 {
fillColorForCute = UIColor.clearColor()
backView.hidden = true
shapeLayer.removeFromSuperlayer()
}
drawRect()
} else if ges.state == .Ended || ges.state == .Cancelled || ges.state == .Failed {
backView.hidden = true
fillColorForCute = UIColor.clearColor()
shapeLayer.removeFromSuperlayer()
UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: .CurveEaseInOut, animations: { [weak self] () -> Void in
if let strongsSelf = self {
strongsSelf.frontView?.center = strongsSelf.oldBackViewCenter
}
}, completion: { [weak self] (finished) -> Void in
if let strongsSelf = self {
strongsSelf.addAniamtionLikeGameCenterBubble()
}
})
}
}
}
// MARK : GameCenter Bubble Animation
extension CuteView {
private func addAniamtionLikeGameCenterBubble() {
let pathAnimation = CAKeyframeAnimation(keyPath: "position")
pathAnimation.calculationMode = kCAAnimationPaced
pathAnimation.fillMode = kCAFillModeForwards
pathAnimation.removedOnCompletion = false
pathAnimation.repeatCount = Float.infinity
pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
pathAnimation.duration = 5.0
let curvedPath = CGPathCreateMutable()
guard let frontView = frontView else {
print("frontView is nil!")
return
}
let circleContainer = CGRectInset(frontView.frame, frontView.bounds.width / 2 - 3, frontView.bounds.size.width / 2 - 3)
CGPathAddEllipseInRect(curvedPath, nil, circleContainer)
pathAnimation.path = curvedPath
frontView.layer.addAnimation(pathAnimation, forKey: "circleAnimation")
let scaleX = CAKeyframeAnimation(keyPath: "transform.scale.x")
scaleX.duration = 1.0
scaleX.values = [NSNumber(double: 1.0),NSNumber(double: 1.1),NSNumber(double: 1.0)]
scaleX.keyTimes = [NSNumber(double: 0.0), NSNumber(double: 0.5), NSNumber(double: 1.0)]
scaleX.repeatCount = Float.infinity
scaleX.autoreverses = true
scaleX.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
frontView.layer.addAnimation(scaleX, forKey: "scaleXAnimation")
let scaleY = CAKeyframeAnimation(keyPath: "transform.scale.y")
scaleY.duration = 1.5
scaleY.values = [NSNumber(double: 1.0),NSNumber(double: 1.1),NSNumber(double: 1.0)]
scaleY.keyTimes = [NSNumber(double: 0.0), NSNumber(double: 0.5), NSNumber(double: 1.0)]
scaleY.repeatCount = Float.infinity
scaleY.autoreverses = true
scaleY.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
frontView.layer.addAnimation(scaleY, forKey: "scaleYAnimation")
}
private func removeAniamtionLikeGameCenterBubble() {
if let frontView = frontView {
frontView.layer.removeAllAnimations()
}
}
} | gpl-2.0 | e3f66148b5789e78bd66f8fde8a2b6e6 | 37.346614 | 178 | 0.633832 | 4.406593 | false | false | false | false |
infobip/mobile-messaging-sdk-ios | Classes/Vendor/Alamofire/Request.swift | 1 | 24301 | //
// Request.swift
//
// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary.
protocol RequestAdapter {
/// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result.
///
/// - parameter urlRequest: The URL request to adapt.
///
/// - throws: An `Error` if the adaptation encounters an error.
///
/// - returns: The adapted `URLRequest`.
func adapt(_ urlRequest: URLRequest) throws -> URLRequest
}
// MARK: -
/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not.
typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void
/// A type that determines whether a request should be retried after being executed by the specified session manager
/// and encountering an error.
protocol RequestRetrier {
/// Determines whether the `Request` should be retried by calling the `completion` closure.
///
/// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs
/// to be retried. The one requirement is that the completion closure is called to ensure the request is properly
/// cleaned up after.
///
/// - parameter manager: The session manager the request was executed on.
/// - parameter request: The request that failed due to the encountered error.
/// - parameter error: The error encountered when executing the request.
/// - parameter completion: The completion closure to be executed when retry decision has been determined.
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion)
}
// MARK: -
protocol TaskConvertible {
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask
}
/// A dictionary of headers to apply to a `URLRequest`.
typealias HTTPHeaders = [String: String]
// MARK: -
/// Responsible for sending a request and receiving the response and associated data from the server, as well as
/// managing its underlying `URLSessionTask`.
class Request {
// MARK: Helper Types
/// A closure executed when monitoring upload or download progress of a request.
typealias ProgressHandler = (Progress) -> Void
enum RequestTask {
case data(TaskConvertible?, URLSessionTask?)
case download(TaskConvertible?, URLSessionTask?)
case upload(TaskConvertible?, URLSessionTask?)
case stream(TaskConvertible?, URLSessionTask?)
}
// MARK: Properties
/// The delegate for the underlying task.
var delegate: TaskDelegate {
get {
taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
return taskDelegate
}
set {
taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
taskDelegate = newValue
}
}
/// The underlying task.
var task: URLSessionTask? { return delegate.task }
/// The session belonging to the underlying task.
let session: URLSession
/// The request sent or to be sent to the server.
var request: URLRequest? { return task?.originalRequest }
/// The response received from the server, if any.
var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse }
/// The number of times the request has been retried.
var retryCount: UInt = 0
let originalTask: TaskConvertible?
var startTime: CFAbsoluteTime?
var endTime: CFAbsoluteTime?
var validations: [() -> Void] = []
private var taskDelegate: TaskDelegate
private var taskDelegateLock = NSLock()
// MARK: Lifecycle
init(session: URLSession, requestTask: RequestTask, error: Error? = nil) {
self.session = session
switch requestTask {
case .data(let originalTask, let task):
taskDelegate = DataTaskDelegate(task: task)
self.originalTask = originalTask
case .download(let originalTask, let task):
taskDelegate = DownloadTaskDelegate(task: task)
self.originalTask = originalTask
case .upload(let originalTask, let task):
taskDelegate = UploadTaskDelegate(task: task)
self.originalTask = originalTask
case .stream(let originalTask, let task):
taskDelegate = TaskDelegate(task: task)
self.originalTask = originalTask
}
delegate.error = error
delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() }
}
// MARK: Authentication
/// Associates an HTTP Basic credential with the request.
///
/// - parameter user: The user.
/// - parameter password: The password.
/// - parameter persistence: The URL credential persistence. `.ForSession` by default.
///
/// - returns: The request.
@discardableResult
func authenticate(
user: String,
password: String,
persistence: URLCredential.Persistence = .forSession)
-> Self
{
let credential = URLCredential(user: user, password: password, persistence: persistence)
return authenticate(usingCredential: credential)
}
/// Associates a specified credential with the request.
///
/// - parameter credential: The credential.
///
/// - returns: The request.
@discardableResult
func authenticate(usingCredential credential: URLCredential) -> Self {
delegate.credential = credential
return self
}
/// Returns a base64 encoded basic authentication credential as an authorization header tuple.
///
/// - parameter user: The user.
/// - parameter password: The password.
///
/// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise.
class func authorizationHeader(user: String, password: String) -> (key: String, value: String)? {
guard let data = "\(user):\(password)".data(using: .utf8) else { return nil }
let credential = data.base64EncodedString(options: [])
return (key: "Authorization", value: "Basic \(credential)")
}
// MARK: State
/// Resumes the request.
func resume() {
guard let task = task else { delegate.queue.isSuspended = false ; return }
if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
task.resume()
NotificationCenter.default.post(
name: Notification.Name.Task.DidResume,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
/// Suspends the request.
func suspend() {
guard let task = task else { return }
task.suspend()
NotificationCenter.default.post(
name: Notification.Name.Task.DidSuspend,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
/// Cancels the request.
func cancel() {
guard let task = task else { return }
task.cancel()
NotificationCenter.default.post(
name: Notification.Name.Task.DidCancel,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
}
// MARK: - CustomStringConvertible
extension Request: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes the HTTP method and URL, as
/// well as the response status code if a response has been received.
var description: String {
var components: [String] = []
if let HTTPMethod = request?.httpMethod {
components.append(HTTPMethod)
}
if let urlString = request?.url?.absoluteString {
components.append(urlString)
}
if let response = response {
components.append("(\(response.statusCode))")
}
return components.joined(separator: " ")
}
}
// MARK: - CustomDebugStringConvertible
extension Request: CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, in the form of a cURL command.
var debugDescription: String {
return cURLRepresentation()
}
func cURLRepresentation() -> String {
var components = ["$ curl -v"]
guard let request = self.request,
let url = request.url,
let host = url.host
else {
return "$ curl command could not be created"
}
if let httpMethod = request.httpMethod, httpMethod != "GET" {
components.append("-X \(httpMethod)")
}
if let credentialStorage = self.session.configuration.urlCredentialStorage {
let protectionSpace = URLProtectionSpace(
host: host,
port: url.port ?? 0,
protocol: url.scheme,
realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
)
if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
for credential in credentials {
guard let user = credential.user, let password = credential.password else { continue }
components.append("-u \(user):\(password)")
}
} else {
if let credential = delegate.credential, let user = credential.user, let password = credential.password {
components.append("-u \(user):\(password)")
}
}
}
if session.configuration.httpShouldSetCookies {
if
let cookieStorage = session.configuration.httpCookieStorage,
let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
{
let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" }
#if swift(>=3.2)
components.append("-b \"\(string[..<string.index(before: string.endIndex)])\"")
#else
components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"")
#endif
}
}
var headers: [AnyHashable: Any] = [:]
session.configuration.httpAdditionalHeaders?.filter { $0.0 != AnyHashable("Cookie") }
.forEach { headers[$0.0] = $0.1 }
request.allHTTPHeaderFields?.filter { $0.0 != "Cookie" }
.forEach { headers[$0.0] = $0.1 }
components += headers.map {
let escapedValue = String(describing: $0.value).replacingOccurrences(of: "\"", with: "\\\"")
return "-H \"\($0.key): \(escapedValue)\""
}
if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-d \"\(escapedBody)\"")
}
components.append("\"\(url.absoluteString)\"")
return components.joined(separator: " \\\n\t")
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionDataTask`.
class DataRequest: Request {
// MARK: Helper Types
struct Requestable: TaskConvertible {
let urlRequest: URLRequest
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let urlRequest = try self.urlRequest.adapt(using: adapter)
return queue.sync { session.dataTask(with: urlRequest) }
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
override var request: URLRequest? {
if let request = super.request { return request }
if let requestable = originalTask as? Requestable { return requestable.urlRequest }
return nil
}
/// The progress of fetching the response data from the server for the request.
var progress: Progress { return dataDelegate.progress }
var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate }
// MARK: Stream
/// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
///
/// This closure returns the bytes most recently received from the server, not including data from previous calls.
/// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
/// also important to note that the server data in any `Response` object will be `nil`.
///
/// - parameter closure: The code to be executed periodically during the lifecycle of the request.
///
/// - returns: The request.
@discardableResult
func stream(closure: ((Data) -> Void)? = nil) -> Self {
dataDelegate.dataStream = closure
return self
}
// MARK: Progress
/// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is read from the server.
///
/// - returns: The request.
@discardableResult
func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
dataDelegate.progressHandler = (closure, queue)
return self
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`.
class DownloadRequest: Request {
// MARK: Helper Types
/// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
/// destination URL.
struct DownloadOptions: OptionSet {
/// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
let rawValue: UInt
/// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0)
/// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
static let removePreviousFile = DownloadOptions(rawValue: 1 << 1)
/// Creates a `DownloadFileDestinationOptions` instance with the specified raw value.
///
/// - parameter rawValue: The raw bitmask value for the option.
///
/// - returns: A new log level instance.
init(rawValue: UInt) {
self.rawValue = rawValue
}
}
/// A closure executed once a download request has successfully completed in order to determine where to move the
/// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
/// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
/// the options defining how the file should be moved.
typealias DownloadFileDestination = (
_ temporaryURL: URL,
_ response: HTTPURLResponse)
-> (destinationURL: URL, options: DownloadOptions)
enum Downloadable: TaskConvertible {
case request(URLRequest)
case resumeData(Data)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let task: URLSessionTask
switch self {
case let .request(urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.downloadTask(with: urlRequest) }
case let .resumeData(resumeData):
task = queue.sync { session.downloadTask(withResumeData: resumeData) }
}
return task
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
override var request: URLRequest? {
if let request = super.request { return request }
if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable {
return urlRequest
}
return nil
}
/// The resume data of the underlying download task if available after a failure.
var resumeData: Data? { return downloadDelegate.resumeData }
/// The progress of downloading the response data from the server for the request.
var progress: Progress { return downloadDelegate.progress }
var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate }
// MARK: State
/// Cancels the request.
override open func cancel() {
cancel(createResumeData: true)
}
/// Cancels the request.
///
/// - parameter createResumeData: Determines whether resume data is created via the underlying download task or not.
func cancel(createResumeData: Bool) {
if createResumeData {
downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 }
} else {
downloadDelegate.downloadTask.cancel()
}
NotificationCenter.default.post(
name: Notification.Name.Task.DidCancel,
object: self,
userInfo: [Notification.Key.Task: task as Any]
)
}
// MARK: Progress
/// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is read from the server.
///
/// - returns: The request.
@discardableResult
func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
downloadDelegate.progressHandler = (closure, queue)
return self
}
// MARK: Destination
/// Creates a download file destination closure which uses the default file manager to move the temporary file to a
/// file URL in the first available directory with the specified search path directory and search path domain mask.
///
/// - parameter directory: The search path directory. `.DocumentDirectory` by default.
/// - parameter domain: The search path domain mask. `.UserDomainMask` by default.
///
/// - returns: A download file destination closure.
class func suggestedDownloadDestination(
for directory: FileManager.SearchPathDirectory = .documentDirectory,
in domain: FileManager.SearchPathDomainMask = .userDomainMask)
-> DownloadFileDestination
{
return { temporaryURL, response in
let directoryURLs = FileManager.default.urls(for: directory, in: domain)
if !directoryURLs.isEmpty {
return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), [])
}
return (temporaryURL, [])
}
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`.
class UploadRequest: DataRequest {
// MARK: Helper Types
enum Uploadable: TaskConvertible {
case data(Data, URLRequest)
case file(URL, URLRequest)
case stream(InputStream, URLRequest)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let task: URLSessionTask
switch self {
case let .data(data, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(with: urlRequest, from: data) }
case let .file(url, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) }
case let .stream(_, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) }
}
return task
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
override var request: URLRequest? {
if let request = super.request { return request }
guard let uploadable = originalTask as? Uploadable else { return nil }
switch uploadable {
case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest):
return urlRequest
}
}
/// The progress of uploading the payload to the server for the upload request.
var uploadProgress: Progress { return uploadDelegate.uploadProgress }
var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate }
// MARK: Upload Progress
/// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to
/// the server.
///
/// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress
/// of data being read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is sent to the server.
///
/// - returns: The request.
@discardableResult
func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
uploadDelegate.uploadProgressHandler = (closure, queue)
return self
}
}
// MARK: -
#if !os(watchOS)
/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`.
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
class StreamRequest: Request {
enum Streamable: TaskConvertible {
case stream(hostName: String, port: Int)
case netService(NetService)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
let task: URLSessionTask
switch self {
case let .stream(hostName, port):
task = queue.sync { session.streamTask(withHostName: hostName, port: port) }
case let .netService(netService):
task = queue.sync { session.streamTask(with: netService) }
}
return task
}
}
}
#endif
| apache-2.0 | 29e6f9a91fe962e32de69ad3a967b236 | 35.819697 | 131 | 0.63841 | 5.12247 | false | false | false | false |
yeti/emojikeyboard | EmojiKeyboard/Classes/EKB.swift | 1 | 8137 | //
// EmojiKeyboard.swift
// GottaGo
//
// Created by Lee McDole on 1/30/16.
// Copyright © 2016 Yeti LLC. All rights reserved.
//
import Foundation
public protocol EKBDelegate {
func ekbButtonPressed(string: String)
}
public class EKB: NSObject, NSXMLParserDelegate, EKBInputViewDelegate {
// Views
public var ekbInputView: EKBInputView?
// Emojis
var emojiGroups: [EKBEmojiGroup]
var currentEmojiGroup: EKBEmojiGroup?
var modifiers = [String]()
private let screenSize:CGRect = UIScreen.mainScreen().bounds
public var ekbDelegate: EKBDelegate?
///////////////////////////
// Initialization functions
///////////////////////////
public override init() {
emojiGroups = [EKBEmojiGroup]()
currentEmojiGroup = nil
super.init()
processEmojiFile()
// Setup Emoji Keyboard
ekbInputView = UINib(nibName: "EKBInputView", bundle: EKBUtils.resourceBundle()).instantiateWithOwner(nil, options: nil)[0] as? EKBInputView
ekbInputView!.ekbInputViewDelegate = self
// Set our height
ekbInputView?.autoresizingMask = .None
ekbInputView?.frame = CGRectMake(0, 0, 0, 260)
}
private func processEmojiFile() {
let filename = "EmojiList"
var parser: NSXMLParser?
if let bundle = EKBUtils.resourceBundle() {
let path = bundle.pathForResource(filename, ofType: "xml")
if let path = path {
parser = NSXMLParser(contentsOfURL: NSURL(fileURLWithPath: path))
}
} else {
print("Failed to find emoji list file")
}
if let parser = parser {
// Let's parse that xml!
parser.delegate = self
if !parser.parse() {
let parseError = parser.parserError!
print("Error parsing emoji list: \(parseError)")
}
if currentEmojiGroup != nil {
print("XML appeared malformed, an unclosed EmojiGroup was found")
}
}
}
func printEmojiListInfo() {
var emojiCount = 0
for group in emojiGroups {
emojiCount += group.emojis.count
}
print("Finished parsing EmojiList. Found \(emojiGroups.count) groups containing \(emojiCount) emojis")
print("Group Name Emoji Count")
var modifiableCount = 0
for group in emojiGroups {
print("\(group.name) \(group.emojis.count)")
for emoji in group.emojis {
if emoji.modifiers != nil {
modifiableCount++
}
}
}
print("Total with modifiers: \(modifiableCount)")
}
/////////////////////////////////////////
// NSXMLParserDelegate protocol functions
/////////////////////////////////////////
@objc public func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?,
qualifiedName qName: String?, attributes attributeDict: [String : String])
{
if elementName == "EmojiModifier" {
loadEmojiModifier(elementName, attributeDict: attributeDict)
} else if elementName == "EmojiGroup" {
if currentEmojiGroup != nil {
print("Unexpected new EmojiGroup found while parsing EmojiGroup")
}
currentEmojiGroup = EKBEmojiGroup(name: attributeDict["name"]!)
} else if elementName == "Emoji" {
loadEmoji(elementName, attributeDict: attributeDict)
}
}
@objc public func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?,
qualifiedName qName: String?)
{
if elementName == "EmojiGroup" {
if currentEmojiGroup == nil {
print("Unexpected end of EmojiGroup found")
}
emojiGroups.append(currentEmojiGroup!)
currentEmojiGroup = nil
}
}
///////////////////////////////
// XML Parsing Helper Functions
///////////////////////////////
private func loadEmojiModifier(elementName: String, attributeDict: [String : String]) {
let unicode = attributeDict["unicode"]
let emoji = attributeDict["emoji"]
verifyUnicodeEmojiMatch(unicode!, emoji: emoji!)
let newEmojiModifier = String(emoji!)
modifiers.append(newEmojiModifier)
}
private func loadEmoji(elementName: String, attributeDict: [String : String]) {
let unicode = attributeDict["unicode"]
let emoji = attributeDict["emoji"]
// Check if this emoji is even supported
let minVersion = attributeDict["minversion"] ?? ""
if !versionCheck(minVersion) {
return
}
verifyUnicodeEmojiMatch(unicode!, emoji: emoji!)
// Check if modifications are supported
var modifiable = false
let modifiableVersion = attributeDict["modifiableversion"] ?? "false"
if modifiableVersion != "false" {
// Might be modifiable. Check version
if versionCheck(modifiableVersion) {
modifiable = true
}
}
let newEmoji = EKBEmoji(character: emoji!, modifiers: (modifiable) ? modifiers : nil)
currentEmojiGroup!.appendEmoji(newEmoji)
}
private func versionCheck(minVersion: String) -> Bool {
var versionReqs: [Int] = minVersion.characters.split{$0 == "."}.map(String.init).map{Int($0)!} // Clean this up?
while versionReqs.count < 3 {
// Turn "8" and "8.0" into "8.0.0", for example
versionReqs.append(0)
}
let os = NSProcessInfo().operatingSystemVersion
// TODO: Maybe a more functional approach to solving this problem:
// Check major version
if versionReqs[0] < os.majorVersion {
return true
} else if versionReqs[0] > os.majorVersion {
return false
}
// Major version == requirement, must dig deeper
// Check minor version
if versionReqs[1] < os.minorVersion {
return true
} else if versionReqs[1] > os.minorVersion {
return false
}
// Minor version == requirement, must dig deeper
// Check patch version
if versionReqs[2] < os.patchVersion {
return true
} else if versionReqs[2] > os.patchVersion {
return false
}
// Major, Minor, and Patch version == requirement. We're good!
return true
}
private func verifyUnicodeEmojiMatch(unicode: String, emoji: String) -> Bool {
// Verify that the displayed emoji and the unicode value match
let unicodeStrings = unicode.characters.split{$0 == " "}.map(String.init)
var unicodeCharacters = [Character]()
for string in unicodeStrings {
// Convert unicodeStrings -> Ints -> UnicodeScalars -> Characters
let unicodeInt = Int(string, radix: 16)
unicodeCharacters.append(Character(UnicodeScalar(unicodeInt!)))
}
let unicodeEmoji = String(unicodeCharacters)
if unicodeEmoji != emoji {
print("Mismatched unicode and emoji values: \(unicode) \(emoji)")
return false
}
return true
}
//////////////////////////////////////////
// EKBInputViewDelegate protocol functions
//////////////////////////////////////////
// Action handler for whenever a button is pressed. Probably want to send a character to the UIResponder
public func buttonPressed(groupIndex: Int, index: Int) {
let emoji: String = emojiGroups[groupIndex].emojis[index].getModifiedString()
ekbDelegate?.ekbButtonPressed(emoji)
}
// Return the number of groups in this keyboard
public func getGroupCount() -> Int {
return emojiGroups.count
}
// Return the name of the specified group
public func getGroupName(groupIndex: Int) -> String {
if groupIndex >= 0 && groupIndex < emojiGroups.count {
return emojiGroups[groupIndex].name
}
return ""
}
// Return the number of items within this group
public func getItemCount(groupIndex: Int) -> Int {
if groupIndex >= 0 && groupIndex < emojiGroups.count {
return emojiGroups[groupIndex].emojis.count
}
return 0
}
// Get the emoji for a specified group and index
public func getEmojiAt(groupIndex: Int, index: Int) -> EKBEmoji? {
if groupIndex >= 0 && groupIndex < emojiGroups.count {
if index >= 0 && index < emojiGroups[groupIndex].emojis.count {
return emojiGroups[groupIndex].emojis[index]
}
}
return nil
}
}
| mit | f51d655cbfef9e852f1083e8c88e624a | 28.911765 | 144 | 0.634464 | 4.514983 | false | false | false | false |
SoneeJohn/WWDC | ConfCore/NewsItemsJSONAdapter.swift | 1 | 1783 | //
// NewsItemsJSONAdapter.swift
// WWDC
//
// Created by Guilherme Rambo on 16/02/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Foundation
import SwiftyJSON
private enum NewsItemKeys: String, JSONSubscriptType {
case id, title, body, timestamp, visibility, photos, type
var jsonKey: JSONKey {
return JSONKey.key(rawValue)
}
}
final class NewsItemsJSONAdapter: Adapter {
typealias InputType = JSON
typealias OutputType = NewsItem
func adapt(_ input: JSON) -> Result<NewsItem, AdapterError> {
if let type = input[NewsItemKeys.type].string {
guard type != "pass" else { return .error(.unsupported) }
}
guard let id = input[NewsItemKeys.id].string else {
return .error(.missingKey(NewsItemKeys.id))
}
guard let title = input[NewsItemKeys.title].string else {
return .error(.missingKey(NewsItemKeys.title))
}
guard let timestamp = input[NewsItemKeys.timestamp].double else {
return .error(.missingKey(NewsItemKeys.timestamp))
}
let visibility = input[NewsItemKeys.visibility].stringValue
let item = NewsItem()
if let photosJson = input[NewsItemKeys.photos].array {
if case .success(let photos) = PhotosJSONAdapter().adapt(photosJson) {
item.photos.append(objectsIn: photos)
}
}
item.identifier = id
item.title = title
item.body = input[NewsItemKeys.body].stringValue
item.visibility = visibility
item.date = Date(timeIntervalSince1970: timestamp)
item.newsType = item.photos.count > 0 ? NewsType.gallery.rawValue : NewsType.news.rawValue
return .success(item)
}
}
| bsd-2-clause | 4a8c19b1c156b7bd6f49424c6b32d9bc | 27.285714 | 98 | 0.640853 | 4.304348 | false | false | false | false |
WEzou/weiXIn | swift-zw/PersonCell.swift | 1 | 2067 | //
// PersonCell.swift
// swift-zw
//
// Created by ymt on 2017/12/8.
// Copyright © 2017年 ymt. All rights reserved.
//
import UIKit
class PersonCell: UITableViewCell {
let headImageView: UIImageView = UIImageView()
let nameTextLabel: UILabel = UILabel()
let lineLabel : UILabel = UILabel()
let accessoryImage: UIImageView = UIImageView()
override func awakeFromNib() {
super.awakeFromNib()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
nameTextLabel.textColor = UIColor(0x2d2d2d)
nameTextLabel.font = UIFont.systemFont(ofSize: 15)
nameTextLabel.textAlignment = .left
accessoryImage.image = UIImage(named: "arrow")
lineLabel.backgroundColor = UIColor(0xe0e0e0)
self.addSubview(headImageView)
self.addSubview(nameTextLabel)
self.addSubview(accessoryImage)
self.addSubview(lineLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func layoutSubviews() {
let width = self.bounds.size.width
let height = self.bounds.size.height
headImageView.frame = CGRect(x: 12, y: (height-26)*0.5, width: 26, height: 26)
nameTextLabel.frame = CGRect(x: 46, y: 0, width: 100, height: height)
accessoryImage.frame = CGRect(x: (width-20-8), y: (height-12)*0.5, width: 20, height: 20)
lineLabel.frame = CGRect(x: 12, y: height-1, width: self.bounds.size.width-12, height: 1)
}
func configureCell(person: Dictionary<String, String>, hideLine: Bool){
let image = UIImage(named: person["image"]!)
headImageView.image = image
nameTextLabel.text = person["name"]
lineLabel.isHidden = hideLine
}
}
| apache-2.0 | 02db5049dc98371026b44b77e5c50694 | 31.25 | 97 | 0.638081 | 4.178138 | false | false | false | false |
NunoAlexandre/broccoli_mobile | ios/Carthage/Checkouts/Eureka/Source/Rows/AlertRow.swift | 7 | 2919 | // AlertRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class _AlertRow<Cell: CellType>: OptionsRow<Cell>, PresenterRowType where Cell: BaseCell {
open var onPresentCallback : ((FormViewController, SelectorAlertController<Cell.Value>)->())?
lazy open var presentationMode: PresentationMode<SelectorAlertController<Cell.Value>>? = {
return .presentModally(controllerProvider: ControllerProvider.callback { [weak self] in
let vc = SelectorAlertController<Cell.Value>(title: self?.selectorTitle, message: nil, preferredStyle: .alert)
vc.row = self
return vc
}, onDismiss: { [weak self] in
$0.dismiss(animated: true)
self?.cell?.formViewController()?.tableView?.reloadData()
}
)
}()
public required init(tag: String?) {
super.init(tag: tag)
}
open override func customDidSelect() {
super.customDidSelect()
if let presentationMode = presentationMode, !isDisabled {
if let controller = presentationMode.makeController(){
controller.row = self
onPresentCallback?(cell.formViewController()!, controller)
presentationMode.present(controller, row: self, presentingController: cell.formViewController()!)
}
else{
presentationMode.present(nil, row: self, presentingController: cell.formViewController()!)
}
}
}
}
/// An options row where the user can select an option from a modal Alert
public final class AlertRow<T: Equatable>: _AlertRow<AlertSelectorCell<T>>, RowType {
required public init(tag: String?) {
super.init(tag: tag)
}
}
| mit | 63ef66069867c9fc624328e3dcccd5c5 | 42.567164 | 122 | 0.684138 | 4.897651 | false | false | false | false |
JusticeBao/animated-tab-bar | RAMAnimatedTabBarController/Animations/RotationAnimation/RAMRotationAnimation.swift | 27 | 3310 | // RAMRotationAnimation.swift
//
// Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import QuartzCore
enum RAMRotationDirection {
case Left
case Right
}
class RAMRotationAnimation : RAMItemAnimation {
var direction : RAMRotationDirection!
override func playAnimation(icon : UIImageView, textLabel : UILabel) {
playRoatationAnimation(icon)
textLabel.textColor = textSelectedColor
}
override func deselectAnimation(icon : UIImageView, textLabel : UILabel, defaultTextColor : UIColor) {
textLabel.textColor = defaultTextColor
if let iconImage = icon.image {
let renderImage = iconImage.imageWithRenderingMode(.AlwaysTemplate)
icon.image = renderImage
icon.tintColor = defaultTextColor
}
}
override func selectedState(icon : UIImageView, textLabel : UILabel) {
textLabel.textColor = textSelectedColor
if let iconImage = icon.image {
let renderImage = iconImage.imageWithRenderingMode(.AlwaysTemplate)
icon.image = renderImage
icon.tintColor = textSelectedColor
}
}
func playRoatationAnimation(icon : UIImageView) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
var toValue = CGFloat(M_PI * 2.0)
if direction != nil && direction == RAMRotationDirection.Left {
toValue = toValue * -1.0
}
rotateAnimation.toValue = toValue
rotateAnimation.duration = NSTimeInterval(duration)
icon.layer.addAnimation(rotateAnimation, forKey: "rotation360")
if let iconImage = icon.image {
let renderImage = iconImage.imageWithRenderingMode(.AlwaysTemplate)
icon.image = renderImage
icon.tintColor = iconSelectedColor
}
}
}
class RAMLeftRotationAnimation : RAMRotationAnimation {
override init() {
super.init()
direction = RAMRotationDirection.Left
}
}
class RAMRightRotationAnimation : RAMRotationAnimation {
override init() {
super.init()
direction = RAMRotationDirection.Right
}
}
| mit | fbc74f41c2dec3d21dc9e5029514206d | 32.1 | 106 | 0.694562 | 5.11592 | false | false | false | false |
jay18001/brickkit-ios | Example/Source/Bricks/Custom/PostBrick.swift | 2 | 2045 |
//
// PostBrick.swift
// BrickKit
//
// Created by Yusheng Yang on 9/19/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
import UIKit
import BrickKit
protocol PostBrickCellDataSource: class {
func textImageBrickProfile(cell: PostBrickCell) -> UIImage
func textImageBrickName(cell: PostBrickCell) -> String
func textImageBrickText(cell: PostBrickCell) -> String
func textImageBrickImage(cell: PostBrickCell) -> UIImage
func textImageBrickAtTag(cell: PostBrickCell) ->String
}
class PostBrick: Brick {
weak var dataSource: PostBrickCellDataSource?
init(_ identifier: String, width: BrickDimension = .ratio(ratio: 1), height: BrickDimension = .auto(estimate: .fixed(size: 300)), backgroundColor: UIColor = UIColor.white, backgroundView: UIView? = nil, dataSource: PostBrickCellDataSource) {
self.dataSource = dataSource
super.init(identifier, size: BrickSize(width: width, height: height), backgroundColor: backgroundColor, backgroundView: backgroundView)
}
}
class PostBrickCell: BrickCell, Bricklike {
typealias BrickType = PostBrick
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var profileNameLabel: UILabel!
@IBOutlet weak var postLabel: UILabel!
@IBOutlet weak var postImage: UIImageView!
@IBOutlet weak var atTagLabel: UILabel!
override func updateContent() {
super.updateContent()
postImage.layer.cornerRadius = 6
postImage.clipsToBounds = true
profileImage.layer.cornerRadius = 4
profileImage.clipsToBounds = true
self.profileImage.image = brick.dataSource?.textImageBrickProfile(cell: self)
self.profileNameLabel.text = brick.dataSource?.textImageBrickName(cell: self)
self.postImage.image = brick.dataSource?.textImageBrickImage(cell: self)
self.postLabel.text = brick.dataSource?.textImageBrickText(cell: self)
self.atTagLabel.text = brick.dataSource?.textImageBrickAtTag(cell: self)
}
}
| apache-2.0 | e8388e5af906d375613bf5675d0bda6a | 33.644068 | 245 | 0.714775 | 4.367521 | false | false | false | false |
eduarenas80/MarvelClient | Pods/MD5/Sources/Generics.swift | 4 | 3211 | //
// Generics.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 02/09/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
/** Protocol and extensions for integerFromBitsArray. Bit hakish for me, but I can't do it in any other way */
protocol Initiable {
init(_ v: Int)
init(_ v: UInt)
}
extension Int:Initiable {}
extension UInt:Initiable {}
extension UInt8:Initiable {}
extension UInt16:Initiable {}
extension UInt32:Initiable {}
extension UInt64:Initiable {}
/// Array of bytes, little-endian representation. Don't use if not necessary.
/// I found this method slow
func arrayOfBytes<T>(value:T, length:Int? = nil) -> [UInt8] {
let totalBytes = length ?? sizeof(T)
let valuePointer = UnsafeMutablePointer<T>.alloc(1)
valuePointer.memory = value
let bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer)
var bytes = [UInt8](count: totalBytes, repeatedValue: 0)
for j in 0..<min(sizeof(T),totalBytes) {
bytes[totalBytes - 1 - j] = (bytesPointer + j).memory
}
valuePointer.destroy()
valuePointer.dealloc(1)
return bytes
}
// MARK: - shiftLeft
// helper to be able tomake shift operation on T
func << <T:SignedIntegerType>(lhs: T, rhs: Int) -> Int {
let a = lhs as! Int
let b = rhs
return a << b
}
func << <T:UnsignedIntegerType>(lhs: T, rhs: Int) -> UInt {
let a = lhs as! UInt
let b = rhs
return a << b
}
// Generic function itself
func shiftLeft<T: SignedIntegerType where T: Initiable>(value: T, count: Int) -> T {
if (value == 0) {
return 0;
}
let bitsCount = (sizeofValue(value) * 8)
let shiftCount = Int(Swift.min(count, bitsCount - 1))
var shiftedValue:T = 0;
for bitIdx in 0..<bitsCount {
let bit = T(IntMax(1 << bitIdx))
if ((value & bit) == bit) {
shiftedValue = shiftedValue | T(bit << shiftCount)
}
}
if (shiftedValue != 0 && count >= bitsCount) {
// clear last bit that couldn't be shifted out of range
shiftedValue = shiftedValue & T(~(1 << (bitsCount - 1)))
}
return shiftedValue
}
// for any f*** other Integer type - this part is so non-Generic
func shiftLeft(value: UInt, count: Int) -> UInt {
return UInt(shiftLeft(Int(value), count: count))
}
func shiftLeft(value: UInt8, count: Int) -> UInt8 {
return UInt8(shiftLeft(UInt(value), count: count))
}
func shiftLeft(value: UInt16, count: Int) -> UInt16 {
return UInt16(shiftLeft(UInt(value), count: count))
}
func shiftLeft(value: UInt32, count: Int) -> UInt32 {
return UInt32(shiftLeft(UInt(value), count: count))
}
func shiftLeft(value: UInt64, count: Int) -> UInt64 {
return UInt64(shiftLeft(UInt(value), count: count))
}
func shiftLeft(value: Int8, count: Int) -> Int8 {
return Int8(shiftLeft(Int(value), count: count))
}
func shiftLeft(value: Int16, count: Int) -> Int16 {
return Int16(shiftLeft(Int(value), count: count))
}
func shiftLeft(value: Int32, count: Int) -> Int32 {
return Int32(shiftLeft(Int(value), count: count))
}
func shiftLeft(value: Int64, count: Int) -> Int64 {
return Int64(shiftLeft(Int(value), count: count))
}
| mit | b1ab1919ad3d54fde84e649f069ea4bd | 26.444444 | 110 | 0.646216 | 3.478873 | false | false | false | false |
dreamsxin/swift | test/Generics/associated_types.swift | 2 | 3240 | // RUN: %target-parse-verify-swift
// Deduction of associated types.
protocol Fooable {
associatedtype AssocType
func foo(_ x : AssocType)
}
struct X : Fooable {
func foo(_ x: Float) {}
}
struct Y<T> : Fooable {
func foo(_ x: T) {}
}
struct Z : Fooable {
func foo(_ x: Float) {}
func blah() {
var a : AssocType // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} {{9-10=_}}
}
// FIXME: We should be able to find this.
func blarg() -> AssocType {} // expected-error{{use of undeclared type 'AssocType'}}
func wonka() -> Z.AssocType {}
}
var xa : X.AssocType = Float()
var yf : Y<Float>.AssocType = Float()
var yd : Y<Double>.AssocType = Double()
var f : Float
f = xa
f = yf
var d : Double
d = yd
protocol P1 {
associatedtype Assoc1
func foo() -> Assoc1
}
struct S1 : P1 {
func foo() -> X {}
}
prefix operator % {}
protocol P2 {
associatedtype Assoc2
prefix func %(target: Self) -> Assoc2
}
prefix func % <P:P1>(target: P) -> P.Assoc1 {
}
extension S1 : P2 {
typealias Assoc2 = X
}
// <rdar://problem/14418181>
protocol P3 {
associatedtype Assoc3
func foo() -> Assoc3
}
protocol P4 : P3 {
associatedtype Assoc4
func bar() -> Assoc4
}
func takeP4<T : P4>(_ x: T) { }
struct S4<T> : P3, P4 {
func foo() -> Int {}
func bar() -> Double {}
}
takeP4(S4<Int>())
// <rdar://problem/14680393>
infix operator ~> { precedence 255 }
protocol P5 { }
struct S7a {}
protocol P6 {
func foo<Target: P5>(_ target: inout Target)
}
protocol P7 : P6 {
associatedtype Assoc : P6
func ~> (x: Self, _: S7a) -> Assoc
}
func ~> <T:P6>(x: T, _: S7a) -> S7b { return S7b() }
struct S7b : P7 {
typealias Assoc = S7b
func foo<Target: P5>(_ target: inout Target) {}
}
// <rdar://problem/14685674>
struct zip<A : IteratorProtocol, B : IteratorProtocol>
: IteratorProtocol, Sequence {
func next() -> (A.Element, B.Element)? { }
typealias Generator = zip
func makeIterator() -> zip { }
}
protocol P8 { }
protocol P9 {
associatedtype A1 : P8
}
protocol P10 {
associatedtype A1b : P8
associatedtype A2 : P9
func f()
func g(_ a: A1b)
func h(_ a: A2)
}
struct X8 : P8 { }
struct Y9 : P9 {
typealias A1 = X8
}
struct Z10 : P10 {
func f() { }
func g(_ a: X8) { }
func h(_ a: Y9) { }
}
struct W : Fooable {
func foo(_ x: String) {}
}
struct V<T> : Fooable {
func foo(_ x: T) {}
}
// FIXME: <rdar://problem/16123805> associated Inferred types can't be used in expression contexts
var w = W.AssocType()
var v = V<String>.AssocType()
//
// SR-427
protocol A {
func c()
}
protocol B : A {
associatedtype e : A = C<Self> // expected-note {{default type 'C<C<a>>' for associated type 'e' (from protocol 'B') does not conform to 'A'}}
}
extension B {
func c() {
}
}
struct C<a : B> : B { // expected-error {{type 'C<a>' does not conform to protocol 'B'}}
}
// SR-511
protocol sr511 {
typealias Foo // expected-warning {{use of 'typealias' to declare associated types is deprecated; use 'associatedtype' instead}}
}
associatedtype Foo = Int // expected-error {{associated types can only be defined in a protocol; define a type or introduce a 'typealias' to satisfy an associated type requirement}}
| apache-2.0 | 4b2de72d43969aeb4f4a3f2fb5657ea1 | 17 | 181 | 0.624074 | 3.013953 | false | false | false | false |
katzbenj/MeBoard | Keyboard/ForwardingView.swift | 2 | 7230 | //
// ForwardingView.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/19/14.
// Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved.
//
import UIKit
class ForwardingView: UIView {
var touchToView: [UITouch:UIView]
override init(frame: CGRect) {
self.touchToView = [:]
super.init(frame: frame)
self.contentMode = UIViewContentMode.redraw
self.isMultipleTouchEnabled = true
self.isUserInteractionEnabled = true
self.isOpaque = false
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
// Why have this useless drawRect? Well, if we just set the backgroundColor to clearColor,
// then some weird optimization happens on UIKit's side where tapping down on a transparent pixel will
// not actually recognize the touch. Having a manual drawRect fixes this behavior, even though it doesn't
// actually do anything.
override func draw(_ rect: CGRect) {}
override func hitTest(_ point: CGPoint, with event: UIEvent!) -> UIView? {
if self.isHidden || self.alpha == 0 || !self.isUserInteractionEnabled {
return nil
}
else {
return (self.bounds.contains(point) ? self : nil)
}
}
func handleControl(_ view: UIView?, controlEvent: UIControlEvents) {
if let control = view as? UIControl {
let targets = control.allTargets
for target in targets {
if let actions = control.actions(forTarget: target, forControlEvent: controlEvent) {
for action in actions {
let selectorString = action
let selector = Selector(selectorString)
control.sendAction(selector, to: target, for: nil)
}
}
}
}
}
// TODO: there's a bit of "stickiness" to Apple's implementation
func findNearestView(_ position: CGPoint) -> UIView? {
if !self.bounds.contains(position) {
return nil
}
var closest: (UIView, CGFloat)? = nil
for anyView in self.subviews {
let view = anyView
if view.isHidden {
continue
}
view.alpha = 1
let distance = distanceBetween(view.frame, point: position)
if closest != nil {
if distance < closest!.1 {
closest = (view, distance)
}
}
else {
closest = (view, distance)
}
}
if closest != nil {
return closest!.0
}
else {
return nil
}
}
// http://stackoverflow.com/questions/3552108/finding-closest-object-to-cgpoint b/c I'm lazy
func distanceBetween(_ rect: CGRect, point: CGPoint) -> CGFloat {
if rect.contains(point) {
return 0
}
var closest = rect.origin
if (rect.origin.x + rect.size.width < point.x) {
closest.x += rect.size.width
}
else if (point.x > rect.origin.x) {
closest.x = point.x
}
if (rect.origin.y + rect.size.height < point.y) {
closest.y += rect.size.height
}
else if (point.y > rect.origin.y) {
closest.y = point.y
}
let a = pow(Double(closest.y - point.y), 2)
let b = pow(Double(closest.x - point.x), 2)
return CGFloat(sqrt(a + b));
}
// reset tracked views without cancelling current touch
func resetTrackedViews() {
for view in self.touchToView.values {
self.handleControl(view, controlEvent: .touchCancel)
}
self.touchToView.removeAll(keepingCapacity: true)
}
func ownView(_ newTouch: UITouch, viewToOwn: UIView?) -> Bool {
var foundView = false
if viewToOwn != nil {
for (touch, view) in self.touchToView {
if viewToOwn == view {
if touch == newTouch {
break
}
else {
self.touchToView[touch] = nil
foundView = true
}
break
}
}
}
self.touchToView[newTouch] = viewToOwn
return foundView
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let position = touch.location(in: self)
let view = findNearestView(position)
let viewChangedOwnership = self.ownView(touch, viewToOwn: view)
if !viewChangedOwnership {
self.handleControl(view, controlEvent: .touchDown)
if touch.tapCount > 1 {
// two events, I think this is the correct behavior but I have not tested with an actual UIControl
self.handleControl(view, controlEvent: .touchDownRepeat)
}
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let position = touch.location(in: self)
let oldView = self.touchToView[touch]
let newView = findNearestView(position)
if oldView != newView {
self.handleControl(oldView, controlEvent: .touchDragExit)
let viewChangedOwnership = self.ownView(touch, viewToOwn: newView)
if !viewChangedOwnership {
self.handleControl(newView, controlEvent: .touchDragEnter)
}
else {
self.handleControl(newView, controlEvent: .touchDragInside)
}
}
else {
self.handleControl(oldView, controlEvent: .touchDragInside)
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let view = self.touchToView[touch]
let touchPosition = touch.location(in: self)
if self.bounds.contains(touchPosition) {
self.handleControl(view, controlEvent: .touchUpInside)
}
else {
self.handleControl(view, controlEvent: .touchCancel)
}
self.touchToView[touch] = nil
}
}
override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) {
if let touches = touches {
for touch in touches {
let view = self.touchToView[touch]
self.handleControl(view, controlEvent: .touchCancel)
self.touchToView[touch] = nil
}
}
}
}
| bsd-3-clause | 6984dc96865813907b5dbdd778de47f5 | 31.276786 | 118 | 0.515076 | 5.24293 | false | false | false | false |
attaswift/Attabench | BenchmarkRunner/CommandLineProcess.swift | 2 | 5718 | // Copyright © 2017 Károly Lőrentey.
// This file is part of Attabench: https://github.com/attaswift/Attabench
// For licensing information, see the file LICENSE.md in the Git repository above.
import Foundation
public protocol CommandLineDelegate {
func commandLineProcess(_ process: CommandLineProcess, didPrintToStandardOutput line: String)
func commandLineProcess(_ process: CommandLineProcess, didPrintToStandardError line: String)
func commandLineProcess(_ process: CommandLineProcess, channel: CommandLineProcess.Channel, didFailWithError error: Int32)
func commandLineProcess(_ process: CommandLineProcess, didExitWithState state: CommandLineProcess.ExitState)
}
public class CommandLineProcess {
public enum Channel {
case input
case output
case error
}
public enum ExitState: Equatable {
case exit(Int32)
case uncaughtSignal(Int32)
public static func ==(left: ExitState, right: ExitState) -> Bool {
switch (left, right) {
case let (.exit(l), .exit(r)): return l == r
case let (.uncaughtSignal(l), .uncaughtSignal(r)): return l == r
default: return false
}
}
}
public let delegate: CommandLineDelegate // Note this isn't weak
public let delegateQueue: DispatchQueue
private let inputOutputQueue = DispatchQueue(label: "org.attaswift.CommandLineProcess.io")
private let process: Process
private let stdinChannel: DispatchIO
private let stdoutChannel: DispatchIO
private let stderrChannel: DispatchIO
public init(launchPath: String, workingDirectory: String, arguments: [String], delegate: CommandLineDelegate, on delegateQueue: DispatchQueue) {
self.delegate = delegate
self.delegateQueue = delegateQueue
// Create pipes for stdin/out/err.
let stdinPipe = Pipe()
let stdoutPipe = Pipe()
let stderrPipe = Pipe()
// Create task.
process = Process()
process.launchPath = launchPath
process.arguments = arguments
process.currentDirectoryPath = workingDirectory
process.standardInput = stdinPipe
process.standardOutput = stdoutPipe
process.standardError = stderrPipe
// Set up dispatch channels.
stdinChannel = DispatchIO(type: .stream,
fileDescriptor: stdinPipe.fileHandleForWriting.fileDescriptor,
queue: inputOutputQueue,
cleanupHandler: { result in stdinPipe.fileHandleForWriting.closeFile() })
stdoutChannel = DispatchIO(type: .stream,
fileDescriptor: stdoutPipe.fileHandleForReading.fileDescriptor,
queue: inputOutputQueue,
cleanupHandler: { result in stdoutPipe.fileHandleForReading.closeFile() })
stdoutChannel.setLimit(lowWater: 1)
stderrChannel = DispatchIO(type: .stream,
fileDescriptor: stderrPipe.fileHandleForReading.fileDescriptor,
queue: inputOutputQueue,
cleanupHandler: { result in stderrPipe.fileHandleForReading.closeFile() })
stderrChannel.setLimit(lowWater: 1)
process.terminationHandler = { process in
self.delegateQueue.async {
self.stdinChannel.close(flags: .stop)
self.stdoutChannel.close(flags: .stop)
self.stderrChannel.close(flags: .stop)
switch process.terminationReason {
case .exit:
self.delegate.commandLineProcess(self, didExitWithState: .exit(process.terminationStatus))
case .uncaughtSignal:
self.delegate.commandLineProcess(self, didExitWithState: .uncaughtSignal(process.terminationStatus))
}
}
}
}
var isRunning: Bool { return process.isRunning }
public func launch() {
// Start reading output channels.
stdoutChannel.readUTF8Lines(on: delegateQueue) { chunk in
switch chunk {
case .record(let line): self.delegate.commandLineProcess(self, didPrintToStandardOutput: line)
case .endOfFile: self.delegate.commandLineProcess(self, channel: .output, didFailWithError: 0)
case .error(let err): self.delegate.commandLineProcess(self, channel: .output, didFailWithError: err)
}
}
stderrChannel.readUTF8Lines(on: delegateQueue) { chunk in
switch chunk {
case .record(let line): self.delegate.commandLineProcess(self, didPrintToStandardError: line)
case .endOfFile: self.delegate.commandLineProcess(self, channel: .error, didFailWithError: 0)
case .error(let err): self.delegate.commandLineProcess(self, channel: .error, didFailWithError: err)
}
}
process.launch()
}
public func sendToStandardInput(_ data: Data) {
stdinChannel.write(offset: 0, data: DispatchData(data), queue: delegateQueue) { [weak self] done, data, err in
guard let this = self else { return }
if done {
this.delegate.commandLineProcess(this, channel: .input, didFailWithError: err)
}
}
}
public func closeStandardInput() {
stdinChannel.close(flags: [])
}
public func terminate() {
self.process.terminate()
}
public func kill() {
guard self.process.isRunning else { return }
Darwin.kill(self.process.processIdentifier, SIGKILL)
}
}
| mit | b459b9cac6a9b5600f36a05909d7d9cc | 41.022059 | 148 | 0.635696 | 5.321229 | false | false | false | false |
rnystrom/GitHawk | Classes/Search/SearchRecentViewModel.swift | 1 | 1676 | //
// SearchRecentViewModel.swift
// Freetime
//
// Created by Hesham Salman on 10/21/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
import IGListKit
private enum Keys {
static let search = "search"
static let viewed = "viewed"
}
final class SearchRecentViewModel: NSObject, ListDiffable {
let query: SearchQuery
init(query: SearchQuery) {
self.query = query
}
var displayText: NSAttributedString {
switch query {
case .search(let text):
return NSAttributedString(string: text, attributes: standardAttributes)
case .recentlyViewed(let repoDetails):
return RepositoryAttributedString(owner: repoDetails.owner, name: repoDetails.name)
}
}
var icon: UIImage {
switch query {
case .search:
return #imageLiteral(resourceName: "search")
case .recentlyViewed:
return #imageLiteral(resourceName: "repo")
}
}
// MARK: ListDiffable
func diffIdentifier() -> NSObjectProtocol {
var identifier: String
switch query {
case .recentlyViewed:
identifier = Keys.viewed
case .search:
identifier = Keys.search
}
return (identifier + displayText.string) as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
return true
}
// MARK: Private API
private var standardAttributes: [NSAttributedStringKey: Any] {
return [
.font: Styles.Text.body.preferredFont,
.foregroundColor: Styles.Colors.Gray.dark.color
]
}
}
| mit | 662ca4255d95f0c7809e8420ff80fafc | 23.632353 | 95 | 0.624478 | 4.813218 | false | false | false | false |
ben-ng/swift | test/decl/nested/type_in_type.swift | 1 | 6295 | // RUN: %target-typecheck-verify-swift
struct OuterNonGeneric {
struct MidNonGeneric {
struct InnerNonGeneric {}
struct InnerGeneric<A> {}
}
struct MidGeneric<B> {
struct InnerNonGeneric {}
struct InnerGeneric<C> {}
func flock(_ b: B) {}
}
}
struct OuterGeneric<D> {
struct MidNonGeneric {
struct InnerNonGeneric {}
struct InnerGeneric<E> {}
func roost(_ d: D) {}
}
struct MidGeneric<F> {
struct InnerNonGeneric {}
struct InnerGeneric<G> {}
func nest(_ d: D, f: F) {}
}
func nonGenericMethod(_ d: D) {
func genericFunction<E>(_ d: D, e: E) {}
genericFunction(d, e: ())
}
}
class OuterNonGenericClass {
enum InnerNonGeneric {
case Baz
case Zab
}
class InnerNonGenericBase {
init() {}
}
class InnerNonGenericClass1 : InnerNonGenericBase {
override init() {
super.init()
}
}
class InnerNonGenericClass2 : OuterNonGenericClass {
override init() {
super.init()
}
}
class InnerGenericClass<U> : OuterNonGenericClass {
override init() {
super.init()
}
}
}
class OuterGenericClass<T> {
enum InnerNonGeneric {
case Baz
case Zab
}
class InnerNonGenericBase {
init() {}
}
class InnerNonGenericClass1 : InnerNonGenericBase {
override init() {
super.init()
}
}
class InnerNonGenericClass2 : OuterGenericClass {
override init() {
super.init()
}
}
class InnerNonGenericClass3 : OuterGenericClass<Int> {
override init() {
super.init()
}
}
class InnerNonGenericClass4 : OuterGenericClass<T> {
override init() {
super.init()
}
}
class InnerGenericClass<U> : OuterGenericClass<U> {
override init() {
super.init()
}
}
}
// <rdar://problem/12895793>
struct AnyStream<T : Sequence> {
struct StreamRange<S : IteratorProtocol> {
var index : Int
var elements : S
// Conform to the IteratorProtocol protocol.
typealias Element = (Int, S.Element)
mutating
func next() -> Element? {
let result = (index, elements.next())
if result.1 == nil { return .none }
index += 1
return (result.0, result.1!)
}
}
var input : T
// Conform to the enumerable protocol.
typealias Elements = StreamRange<T.Iterator>
func getElements() -> Elements {
return Elements(index: 0, elements: input.makeIterator())
}
}
func enumerate<T : Sequence>(_ arg: T) -> AnyStream<T> {
return AnyStream<T>(input: arg)
}
// Check unqualified lookup of inherited types.
class Foo<T> {
typealias Nested = T
}
class Bar : Foo<Int> {
func f(_ x: Int) -> Nested {
return x
}
struct Inner {
func g(_ x: Int) -> Nested {
return x
}
func withLocal() {
struct Local {
func h(_ x: Int) -> Nested {
return x
}
}
}
}
}
extension Bar {
func g(_ x: Int) -> Nested {
return x
}
// <rdar://problem/14376418>
struct Inner2 {
func f(_ x: Int) -> Nested {
return x
}
}
}
class X6<T> {
let d: D<T>
init(_ value: T) {
d = D(value)
}
class D<T2> {
init(_ value: T2) {}
}
}
// ---------------------------------------------
// Unbound name references within a generic type
// ---------------------------------------------
struct GS<T> {
func f() -> GS {
let gs = GS()
return gs
}
struct Nested {
func ff() -> GS {
let gs = GS()
return gs
}
}
struct NestedGeneric<U> { // expected-note{{generic type 'NestedGeneric' declared here}}
func fff() -> (GS, NestedGeneric) {
let gs = GS()
let ns = NestedGeneric()
return (gs, ns)
}
}
// FIXME: We're losing some sugar here by performing the substitution.
func ng() -> NestedGeneric { } // expected-error{{reference to generic type 'GS<T>.NestedGeneric' requires arguments in <...>}}
}
extension GS {
func g() -> GS {
let gs = GS()
return gs
}
func h() {
_ = GS() as GS<Int> // expected-error{{cannot convert value of type 'GS<T>' to type 'GS<Int>' in coercion}}
}
}
struct HasNested<T> {
init<U>(_ t: T, _ u: U) {}
func f<U>(_ t: T, u: U) -> (T, U) {}
struct InnerGeneric<U> {
init() {}
func g<V>(_ t: T, u: U, v: V) -> (T, U, V) {}
}
struct Inner {
init (_ x: T) {}
func identity(_ x: T) -> T { return x }
}
}
func useNested(_ ii: Int, hni: HasNested<Int>,
xisi : HasNested<Int>.InnerGeneric<String>,
xfs: HasNested<Float>.InnerGeneric<String>) {
var i = ii, xis = xisi
typealias InnerI = HasNested<Int>.Inner
var innerI = InnerI(5)
typealias InnerF = HasNested<Float>.Inner
var innerF : InnerF = innerI // expected-error{{cannot convert value of type 'InnerI' (aka 'HasNested<Int>.Inner') to specified type 'InnerF' (aka 'HasNested<Float>.Inner')}}
_ = innerI.identity(i)
i = innerI.identity(i)
// Generic function in a generic class
typealias HNI = HasNested<Int>
var id = hni.f(1, u: 3.14159)
id = (2, 3.14159)
hni.f(1.5, 3.14159) // expected-error{{missing argument label 'u:' in call}}
hni.f(1.5, u: 3.14159) // expected-error{{cannot convert value of type 'Double' to expected argument type 'Int'}}
// Generic constructor of a generic struct
HNI(1, 2.71828) // expected-warning{{unused}}
HNI(1.5, 2.71828) // expected-error{{'Double' is not convertible to 'Int'}}
// Generic function in a nested generic struct
var ids = xis.g(1, u: "Hello", v: 3.14159)
ids = (2, "world", 2.71828)
xis = xfs // expected-error{{cannot assign value of type 'HasNested<Float>.InnerGeneric<String>' to type 'HasNested<Int>.InnerGeneric<String>'}}
}
// Extensions of nested generic types
extension OuterNonGeneric.MidGeneric {
func takesB(b: B) {}
}
extension OuterGeneric.MidNonGeneric {
func takesD(d: D) {}
}
extension OuterGeneric.MidGeneric {
func takesD(d: D) {}
func takesB(f: F) {}
}
protocol HasAssocType {
associatedtype FirstAssocType
associatedtype SecondAssocType
func takesAssocType(first: FirstAssocType, second: SecondAssocType)
}
extension OuterGeneric.MidGeneric : HasAssocType {
func takesAssocType(first: D, second: F) {}
}
typealias OuterGenericMidGeneric<T> = OuterGeneric<T>.MidGeneric
extension OuterGenericMidGeneric {
}
| apache-2.0 | fce6c4afa05d2fb05bfe4ae460949fe0 | 19.983333 | 176 | 0.604607 | 3.530566 | false | false | false | false |
mcudich/TemplateKit | Source/iOS/Text.swift | 1 | 3981 | //
// Text.swift
// TemplateKit
//
// Created by Matias Cudich on 9/3/16.
// Copyright © 2016 Matias Cudich. All rights reserved.
//
import Foundation
class TextLayout {
var properties: TextProperties
fileprivate lazy var layoutManager: NSLayoutManager = {
let layoutManager = NSLayoutManager()
layoutManager.addTextContainer(self.textContainer)
layoutManager.usesFontLeading = false
return layoutManager
}()
fileprivate lazy var textStorage: NSTextStorage = {
let textStorage = NSTextStorage()
textStorage.addLayoutManager(self.layoutManager)
return textStorage
}()
fileprivate lazy var textContainer: NSTextContainer = {
let textContainer = NSTextContainer()
textContainer.lineFragmentPadding = 0
return textContainer
}()
init(properties: TextProperties) {
self.properties = properties
}
func sizeThatFits(_ size: CGSize) -> CGSize {
applyProperties()
textContainer.size = size;
layoutManager.ensureLayout(for: textContainer)
let measuredSize = layoutManager.usedRect(for: textContainer).size
return CGSize(width: ceil(measuredSize.width), height: ceil(measuredSize.height))
}
fileprivate func drawText(in rect: CGRect) {
applyProperties()
textContainer.size = rect.size
let glyphRange = layoutManager.glyphRange(for: textContainer);
layoutManager.drawBackground(forGlyphRange: glyphRange, at: CGPoint.zero);
layoutManager.drawGlyphs(forGlyphRange: glyphRange, at: CGPoint.zero);
}
private func applyProperties() {
let fontName = properties.textStyle.fontName ?? UIFont.systemFont(ofSize: UIFont.systemFontSize).fontName
let fontSize = properties.textStyle.fontSize ?? UIFont.systemFontSize
guard let fontValue = UIFont(name: fontName, size: fontSize) else {
fatalError("Attempting to use unknown font")
}
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = properties.textStyle.textAlignment ?? .natural
let attributes: [String : Any] = [
NSFontAttributeName: fontValue,
NSForegroundColorAttributeName: properties.textStyle.color ?? .black,
NSParagraphStyleAttributeName: paragraphStyle
]
textStorage.setAttributedString(NSAttributedString(string: properties.text ?? "", attributes: attributes))
textContainer.lineBreakMode = properties.textStyle.lineBreakMode ?? .byTruncatingTail
}
}
public struct TextProperties: Properties {
public var core = CoreProperties()
public var textStyle = TextStyleProperties()
public var text: String?
public init() {}
public init(_ properties: [String : Any]) {
core = CoreProperties(properties)
textStyle = TextStyleProperties(properties)
text = properties.cast("text")
}
public mutating func merge(_ other: TextProperties) {
core.merge(other.core)
textStyle.merge(other.textStyle)
merge(&text, other.text)
}
}
public func ==(lhs: TextProperties, rhs: TextProperties) -> Bool {
return lhs.text == rhs.text && lhs.textStyle == rhs.textStyle && lhs.equals(otherProperties: rhs)
}
public class Text: UILabel, NativeView {
public weak var eventTarget: AnyObject?
public lazy var eventRecognizers = EventRecognizers()
public var properties = TextProperties() {
didSet {
applyCoreProperties()
textLayout.properties = properties
setNeedsDisplay()
}
}
private lazy var textLayout: TextLayout = {
return TextLayout(properties: self.properties)
}()
public required init() {
super.init(frame: CGRect.zero)
isUserInteractionEnabled = true
applyCoreProperties()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func drawText(in rect: CGRect) {
textLayout.drawText(in: rect)
}
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
touchesBegan()
}
}
| mit | efd348ef849b9893f38a8682c0de393a | 27.22695 | 110 | 0.724372 | 4.818402 | false | false | false | false |
nextcloud/ios | iOSClient/Data/NCManageDatabase.swift | 1 | 56551 | //
// NCManageDatabase.swift
// Nextcloud
//
// Created by Marino Faggiana on 06/05/17.
// Copyright © 2017 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
// Author Henrik Storch <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
import RealmSwift
import NextcloudKit
import SwiftyJSON
import CoreMedia
import Photos
class NCManageDatabase: NSObject {
@objc static let shared: NCManageDatabase = {
let instance = NCManageDatabase()
return instance
}()
override init() {
let dirGroup = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroups)
let databaseFileUrlPath = dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud + "/" + NCGlobal.shared.databaseDefault)
let bundleUrl: URL = Bundle.main.bundleURL
let bundlePathExtension: String = bundleUrl.pathExtension
let isAppex: Bool = bundlePathExtension == "appex"
if let databaseFilePath = databaseFileUrlPath?.path {
if FileManager.default.fileExists(atPath: databaseFilePath) {
NKCommon.shared.writeLog("DATABASE FOUND in " + databaseFilePath)
} else {
NKCommon.shared.writeLog("DATABASE NOT FOUND in " + databaseFilePath)
}
}
// Disable file protection for directory DB
// https://docs.mongodb.com/realm/sdk/ios/examples/configure-and-open-a-realm/#std-label-ios-open-a-local-realm
if let folderPathURL = dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud) {
let folderPath = folderPathURL.path
do {
try FileManager.default.setAttributes([FileAttributeKey.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], ofItemAtPath: folderPath)
} catch {
print("Dangerous error")
}
}
if isAppex {
// App Extension config
let config = Realm.Configuration(
fileURL: dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud + "/" + NCGlobal.shared.databaseDefault),
schemaVersion: NCGlobal.shared.databaseSchemaVersion,
objectTypes: [tableMetadata.self, tableLocalFile.self, tableDirectory.self, tableTag.self, tableAccount.self, tableCapabilities.self, tablePhotoLibrary.self, tableE2eEncryption.self, tableE2eEncryptionLock.self, tableShare.self, tableChunk.self, tableAvatar.self, tableDashboardWidget.self, tableDashboardWidgetButton.self]
)
Realm.Configuration.defaultConfiguration = config
} else {
// App config
let configCompact = Realm.Configuration(
fileURL: databaseFileUrlPath,
schemaVersion: NCGlobal.shared.databaseSchemaVersion,
migrationBlock: { migration, oldSchemaVersion in
if oldSchemaVersion < 255 {
migration.deleteData(forType: tableActivity.className())
migration.deleteData(forType: tableActivityLatestId.className())
migration.deleteData(forType: tableActivityPreview.className())
migration.deleteData(forType: tableActivitySubjectRich.className())
migration.deleteData(forType: tableDirectory.className())
migration.deleteData(forType: tableMetadata.className())
}
}, shouldCompactOnLaunch: { totalBytes, usedBytes in
// totalBytes refers to the size of the file on disk in bytes (data + free space)
// usedBytes refers to the number of bytes used by data in the file
// Compact if the file is over 100MB in size and less than 50% 'used'
let oneHundredMB = 100 * 1024 * 1024
return (totalBytes > oneHundredMB) && (Double(usedBytes) / Double(totalBytes)) < 0.5
}
)
do {
_ = try Realm(configuration: configCompact)
} catch {
if let databaseFileUrlPath = databaseFileUrlPath {
do {
#if !EXTENSION
let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_database_corrupt_")
NCContentPresenter.shared.showError(error: error, priority: .max)
#endif
NKCommon.shared.writeLog("DATABASE CORRUPT: removed")
try FileManager.default.removeItem(at: databaseFileUrlPath)
} catch {}
}
}
let config = Realm.Configuration(
fileURL: dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud + "/" + NCGlobal.shared.databaseDefault),
schemaVersion: NCGlobal.shared.databaseSchemaVersion
)
Realm.Configuration.defaultConfiguration = config
}
// Verify Database, if corrupt remove it
do {
_ = try Realm()
} catch {
if let databaseFileUrlPath = databaseFileUrlPath {
do {
#if !EXTENSION
let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_database_corrupt_")
NCContentPresenter.shared.showError(error: error, priority: .max)
#endif
NKCommon.shared.writeLog("DATABASE CORRUPT: removed")
try FileManager.default.removeItem(at: databaseFileUrlPath)
} catch {}
}
}
// Open Real
_ = try! Realm()
}
// MARK: -
// MARK: Utility Database
@objc func clearTable(_ table: Object.Type, account: String? = nil) {
let realm = try! Realm()
do {
try realm.write {
var results: Results<Object>
if let account = account {
results = realm.objects(table).filter("account == %@", account)
} else {
results = realm.objects(table)
}
realm.delete(results)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func clearDatabase(account: String?, removeAccount: Bool) {
self.clearTable(tableActivity.self, account: account)
self.clearTable(tableActivityLatestId.self, account: account)
self.clearTable(tableActivityPreview.self, account: account)
self.clearTable(tableActivitySubjectRich.self, account: account)
self.clearTable(tableAvatar.self)
self.clearTable(tableCapabilities.self, account: account)
self.clearTable(tableChunk.self, account: account)
self.clearTable(tableComments.self, account: account)
self.clearTable(tableDashboardWidget.self, account: account)
self.clearTable(tableDashboardWidgetButton.self, account: account)
self.clearTable(tableDirectEditingCreators.self, account: account)
self.clearTable(tableDirectEditingEditors.self, account: account)
self.clearTable(tableDirectory.self, account: account)
self.clearTable(tableE2eEncryption.self, account: account)
self.clearTable(tableE2eEncryptionLock.self, account: account)
self.clearTable(tableExternalSites.self, account: account)
self.clearTable(tableGPS.self, account: nil)
self.clearTable(tableLocalFile.self, account: account)
self.clearTable(tableMetadata.self, account: account)
self.clearTable(tablePhotoLibrary.self, account: account)
self.clearTable(tableShare.self, account: account)
self.clearTable(tableTag.self, account: account)
self.clearTable(tableTip.self)
self.clearTable(tableTrash.self, account: account)
self.clearTable(tableUserStatus.self, account: account)
self.clearTable(tableVideo.self, account: account)
if removeAccount {
self.clearTable(tableAccount.self, account: account)
}
}
@objc func removeDB() {
let realmURL = Realm.Configuration.defaultConfiguration.fileURL!
let realmURLs = [
realmURL,
realmURL.appendingPathExtension("lock"),
realmURL.appendingPathExtension("note"),
realmURL.appendingPathExtension("management")
]
for URL in realmURLs {
do {
try FileManager.default.removeItem(at: URL)
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
}
@objc func getThreadConfined(_ object: Object) -> Any {
// id tradeReference = [[NCManageDatabase shared] getThreadConfined:metadata];
return ThreadSafeReference(to: object)
}
@objc func putThreadConfined(_ tableRef: Any) -> Object? {
// tableMetadata *metadataThread = (tableMetadata *)[[NCManageDatabase shared] putThreadConfined:tradeReference];
let realm = try! Realm()
return realm.resolve(tableRef as! ThreadSafeReference<Object>)
}
@objc func isTableInvalidated(_ object: Object) -> Bool {
return object.isInvalidated
}
// MARK: -
// MARK: Table Avatar
@objc func addAvatar(fileName: String, etag: String) {
let realm = try! Realm()
do {
try realm.write {
// Add new
let addObject = tableAvatar()
addObject.date = NSDate()
addObject.etag = etag
addObject.fileName = fileName
addObject.loaded = true
realm.add(addObject, update: .all)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
func getTableAvatar(fileName: String) -> tableAvatar? {
let realm = try! Realm()
guard let result = realm.objects(tableAvatar.self).filter("fileName == %@", fileName).first else {
return nil
}
return tableAvatar.init(value: result)
}
func clearAllAvatarLoaded() {
let realm = try! Realm()
do {
try realm.write {
let results = realm.objects(tableAvatar.self)
for result in results {
result.loaded = false
realm.add(result, update: .all)
}
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@discardableResult
func setAvatarLoaded(fileName: String) -> UIImage? {
let realm = try! Realm()
let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
var image: UIImage?
do {
try realm.write {
if let result = realm.objects(tableAvatar.self).filter("fileName == %@", fileName).first {
if let imageAvatar = UIImage(contentsOfFile: fileNameLocalPath) {
result.loaded = true
image = imageAvatar
} else {
realm.delete(result)
}
}
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
return image
}
func getImageAvatarLoaded(fileName: String) -> UIImage? {
let realm = try! Realm()
let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
let result = realm.objects(tableAvatar.self).filter("fileName == %@", fileName).first
if result == nil {
NCUtilityFileSystem.shared.deleteFile(filePath: fileNameLocalPath)
return nil
} else if result?.loaded == false {
return nil
}
return UIImage(contentsOfFile: fileNameLocalPath)
}
// MARK: -
// MARK: Table Capabilities
@objc func addCapabilitiesJSon(_ data: Data, account: String) {
let realm = try! Realm()
do {
try realm.write {
let addObject = tableCapabilities()
addObject.account = account
addObject.jsondata = data
realm.add(addObject, update: .all)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func getCapabilities(account: String) -> String? {
let realm = try! Realm()
guard let result = realm.objects(tableCapabilities.self).filter("account == %@", account).first else {
return nil
}
guard let jsondata = result.jsondata else {
return nil
}
let json = JSON(jsondata)
return json.rawString()?.replacingOccurrences(of: "\\/", with: "/")
}
@objc func getCapabilitiesServerString(account: String, elements: [String]) -> String? {
let realm = try! Realm()
guard let result = realm.objects(tableCapabilities.self).filter("account == %@", account).first else {
return nil
}
guard let jsondata = result.jsondata else {
return nil
}
let json = JSON(jsondata)
return json[elements].string
}
@objc func getCapabilitiesServerInt(account: String, elements: [String]) -> Int {
let realm = try! Realm()
guard let result = realm.objects(tableCapabilities.self).filter("account == %@", account).first,
let jsondata = result.jsondata else {
return 0
}
let json = JSON(jsondata)
return json[elements].intValue
}
@objc func getCapabilitiesServerBool(account: String, elements: [String], exists: Bool) -> Bool {
let realm = try! Realm()
guard let result = realm.objects(tableCapabilities.self).filter("account == %@", account).first else {
return false
}
guard let jsondata = result.jsondata else {
return false
}
let json = JSON(jsondata)
if exists {
return json[elements].exists()
} else {
return json[elements].boolValue
}
}
@objc func getCapabilitiesServerArray(account: String, elements: [String]) -> [String]? {
let realm = try! Realm()
var resultArray: [String] = []
guard let result = realm.objects(tableCapabilities.self).filter("account == %@", account).first else {
return nil
}
guard let jsondata = result.jsondata else {
return nil
}
let json = JSON(jsondata)
if let results = json[elements].array {
for result in results {
resultArray.append(result.string ?? "")
}
return resultArray
}
return nil
}
// MARK: -
// MARK: Table Chunk
func getChunkFolder(account: String, ocId: String) -> String {
let realm = try! Realm()
if let result = realm.objects(tableChunk.self).filter("account == %@ AND ocId == %@", account, ocId).first {
return result.chunkFolder
}
return NSUUID().uuidString
}
func getChunks(account: String, ocId: String) -> [String] {
let realm = try! Realm()
var filesNames: [String] = []
let results = realm.objects(tableChunk.self).filter("account == %@ AND ocId == %@", account, ocId).sorted(byKeyPath: "fileName", ascending: true)
for result in results {
filesNames.append(result.fileName)
}
return filesNames
}
func addChunks(account: String, ocId: String, chunkFolder: String, fileNames: [String]) {
let realm = try! Realm()
var size: Int64 = 0
do {
try realm.write {
for fileName in fileNames {
let object = tableChunk()
size += NCUtilityFileSystem.shared.getFileSize(filePath: CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!)
object.account = account
object.chunkFolder = chunkFolder
object.fileName = fileName
object.index = ocId + fileName
object.ocId = ocId
object.size = size
realm.add(object, update: .all)
}
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
func getChunk(account: String, fileName: String) -> tableChunk? {
let realm = try! Realm()
if let result = realm.objects(tableChunk.self).filter("account == %@ AND fileName == %@", account, fileName).first {
return tableChunk.init(value: result)
} else {
return nil
}
}
func deleteChunk(account: String, ocId: String, fileName: String) {
let realm = try! Realm()
do {
try realm.write {
let result = realm.objects(tableChunk.self).filter(NSPredicate(format: "account == %@ AND ocId == %@ AND fileName == %@", account, ocId, fileName))
realm.delete(result)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
func deleteChunks(account: String, ocId: String) {
let realm = try! Realm()
do {
try realm.write {
let result = realm.objects(tableChunk.self).filter(NSPredicate(format: "account == %@ AND ocId == %@", account, ocId))
realm.delete(result)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
// MARK: -
// MARK: Table Direct Editing
@objc func addDirectEditing(account: String, editors: [NKEditorDetailsEditors], creators: [NKEditorDetailsCreators]) {
let realm = try! Realm()
do {
try realm.write {
let resultsCreators = realm.objects(tableDirectEditingCreators.self).filter("account == %@", account)
realm.delete(resultsCreators)
let resultsEditors = realm.objects(tableDirectEditingEditors.self).filter("account == %@", account)
realm.delete(resultsEditors)
for creator in creators {
let addObject = tableDirectEditingCreators()
addObject.account = account
addObject.editor = creator.editor
addObject.ext = creator.ext
addObject.identifier = creator.identifier
addObject.mimetype = creator.mimetype
addObject.name = creator.name
addObject.templates = creator.templates
realm.add(addObject)
}
for editor in editors {
let addObject = tableDirectEditingEditors()
addObject.account = account
for mimeType in editor.mimetypes {
addObject.mimetypes.append(mimeType)
}
addObject.name = editor.name
if editor.name.lowercased() == NCGlobal.shared.editorOnlyoffice {
addObject.editor = NCGlobal.shared.editorOnlyoffice
} else {
addObject.editor = NCGlobal.shared.editorText
}
for mimeType in editor.optionalMimetypes {
addObject.optionalMimetypes.append(mimeType)
}
addObject.secure = editor.secure
realm.add(addObject)
}
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func getDirectEditingCreators(account: String) -> [tableDirectEditingCreators]? {
let realm = try! Realm()
let results = realm.objects(tableDirectEditingCreators.self).filter("account == %@", account)
if results.count > 0 {
return Array(results.map { tableDirectEditingCreators.init(value: $0) })
} else {
return nil
}
}
@objc func getDirectEditingCreators(predicate: NSPredicate) -> [tableDirectEditingCreators]? {
let realm = try! Realm()
let results = realm.objects(tableDirectEditingCreators.self).filter(predicate)
if results.count > 0 {
return Array(results.map { tableDirectEditingCreators.init(value: $0) })
} else {
return nil
}
}
@objc func getDirectEditingEditors(account: String) -> [tableDirectEditingEditors]? {
let realm = try! Realm()
let results = realm.objects(tableDirectEditingEditors.self).filter("account == %@", account)
if results.count > 0 {
return Array(results.map { tableDirectEditingEditors.init(value: $0) })
} else {
return nil
}
}
// MARK: -
// MARK: Table Directory
@objc func addDirectory(encrypted: Bool, favorite: Bool, ocId: String, fileId: String, etag: String? = nil, permissions: String? = nil, serverUrl: String, account: String) {
let realm = try! Realm()
do {
try realm.write {
var addObject = tableDirectory()
let result = realm.objects(tableDirectory.self).filter("ocId == %@", ocId).first
if result != nil {
addObject = result!
} else {
addObject.ocId = ocId
}
addObject.account = account
addObject.e2eEncrypted = encrypted
addObject.favorite = favorite
addObject.fileId = fileId
if let etag = etag {
addObject.etag = etag
}
if let permissions = permissions {
addObject.permissions = permissions
}
addObject.serverUrl = serverUrl
realm.add(addObject, update: .all)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func deleteDirectoryAndSubDirectory(serverUrl: String, account: String) {
let realm = try! Realm()
let results = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl BEGINSWITH %@", account, serverUrl)
// Delete table Metadata & LocalFile
for result in results {
self.deleteMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", result.account, result.serverUrl))
self.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", result.ocId))
}
// Delete table Dirrectory
do {
try realm.write {
realm.delete(results)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func setDirectory(serverUrl: String, serverUrlTo: String? = nil, etag: String? = nil, ocId: String? = nil, fileId: String? = nil, encrypted: Bool, richWorkspace: String? = nil, account: String) {
let realm = try! Realm()
do {
try realm.write {
guard let result = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first else {
return
}
let directory = tableDirectory.init(value: result)
realm.delete(result)
directory.e2eEncrypted = encrypted
if let etag = etag {
directory.etag = etag
}
if let ocId = ocId {
directory.ocId = ocId
}
if let fileId = fileId {
directory.fileId = fileId
}
if let serverUrlTo = serverUrlTo {
directory.serverUrl = serverUrlTo
}
if let richWorkspace = richWorkspace {
directory.richWorkspace = richWorkspace
}
realm.add(directory, update: .all)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func getTableDirectory(predicate: NSPredicate) -> tableDirectory? {
let realm = try! Realm()
guard let result = realm.objects(tableDirectory.self).filter(predicate).first else {
return nil
}
return tableDirectory.init(value: result)
}
@objc func getTablesDirectory(predicate: NSPredicate, sorted: String, ascending: Bool) -> [tableDirectory]? {
let realm = try! Realm()
let results = realm.objects(tableDirectory.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
if results.count > 0 {
return Array(results.map { tableDirectory.init(value: $0) })
} else {
return nil
}
}
@objc func renameDirectory(ocId: String, serverUrl: String) {
let realm = try! Realm()
do {
try realm.write {
let result = realm.objects(tableDirectory.self).filter("ocId == %@", ocId).first
result?.serverUrl = serverUrl
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func setDirectory(serverUrl: String, offline: Bool, account: String) {
let realm = try! Realm()
do {
try realm.write {
let result = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first
result?.offline = offline
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@discardableResult
@objc func setDirectory(serverUrl: String, richWorkspace: String?, account: String) -> tableDirectory? {
let realm = try! Realm()
var result: tableDirectory?
do {
try realm.write {
result = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first
result?.richWorkspace = richWorkspace
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
if let result = result {
return tableDirectory.init(value: result)
} else {
return nil
}
}
@discardableResult
@objc func setDirectory(serverUrl: String, colorFolder: String?, account: String) -> tableDirectory? {
let realm = try! Realm()
var result: tableDirectory?
do {
try realm.write {
result = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first
result?.colorFolder = colorFolder
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
if let result = result {
return tableDirectory.init(value: result)
} else {
return nil
}
}
// MARK: -
// MARK: Table e2e Encryption
@objc func addE2eEncryption(_ e2e: tableE2eEncryption) {
let realm = try! Realm()
do {
try realm.write {
realm.add(e2e, update: .all)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func deleteE2eEncryption(predicate: NSPredicate) {
let realm = try! Realm()
do {
try realm.write {
let results = realm.objects(tableE2eEncryption.self).filter(predicate)
realm.delete(results)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func getE2eEncryption(predicate: NSPredicate) -> tableE2eEncryption? {
let realm = try! Realm()
guard let result = realm.objects(tableE2eEncryption.self).filter(predicate).sorted(byKeyPath: "metadataKeyIndex", ascending: false).first else {
return nil
}
return tableE2eEncryption.init(value: result)
}
@objc func getE2eEncryptions(predicate: NSPredicate) -> [tableE2eEncryption]? {
guard self.getActiveAccount() != nil else {
return nil
}
let realm = try! Realm()
let results: Results<tableE2eEncryption>
results = realm.objects(tableE2eEncryption.self).filter(predicate)
if results.count > 0 {
return Array(results.map { tableE2eEncryption.init(value: $0) })
} else {
return nil
}
}
@objc func renameFileE2eEncryption(serverUrl: String, fileNameIdentifier: String, newFileName: String, newFileNamePath: String) {
guard let activeAccount = self.getActiveAccount() else {
return
}
let realm = try! Realm()
realm.beginWrite()
guard let result = realm.objects(tableE2eEncryption.self).filter("account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", activeAccount.account, serverUrl, fileNameIdentifier).first else {
realm.cancelWrite()
return
}
let object = tableE2eEncryption.init(value: result)
realm.delete(result)
object.fileName = newFileName
object.fileNamePath = newFileNamePath
realm.add(object)
do {
try realm.commitWrite()
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
// MARK: -
// MARK: Table e2e Encryption Lock
@objc func getE2ETokenLock(account: String, serverUrl: String) -> tableE2eEncryptionLock? {
let realm = try! Realm()
guard let result = realm.objects(tableE2eEncryptionLock.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first else {
return nil
}
return tableE2eEncryptionLock.init(value: result)
}
@objc func setE2ETokenLock(account: String, serverUrl: String, fileId: String, e2eToken: String) {
let realm = try! Realm()
do {
try realm.write {
let addObject = tableE2eEncryptionLock()
addObject.account = account
addObject.fileId = fileId
addObject.serverUrl = serverUrl
addObject.e2eToken = e2eToken
realm.add(addObject, update: .all)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func deteleE2ETokenLock(account: String, serverUrl: String) {
let realm = try! Realm()
do {
try realm.write {
if let result = realm.objects(tableE2eEncryptionLock.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first {
realm.delete(result)
}
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
// MARK: -
// MARK: Table External Sites
@objc func addExternalSites(_ externalSite: NKExternalSite, account: String) {
let realm = try! Realm()
do {
try realm.write {
let addObject = tableExternalSites()
addObject.account = account
addObject.idExternalSite = externalSite.idExternalSite
addObject.icon = externalSite.icon
addObject.lang = externalSite.lang
addObject.name = externalSite.name
addObject.url = externalSite.url
addObject.type = externalSite.type
realm.add(addObject)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func deleteExternalSites(account: String) {
let realm = try! Realm()
do {
try realm.write {
let results = realm.objects(tableExternalSites.self).filter("account == %@", account)
realm.delete(results)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func getAllExternalSites(account: String) -> [tableExternalSites]? {
let realm = try! Realm()
let results = realm.objects(tableExternalSites.self).filter("account == %@", account).sorted(byKeyPath: "idExternalSite", ascending: true)
if results.count > 0 {
return Array(results.map { tableExternalSites.init(value: $0) })
} else {
return nil
}
}
// MARK: -
// MARK: Table GPS
@objc func addGeocoderLocation(_ location: String, placemarkAdministrativeArea: String, placemarkCountry: String, placemarkLocality: String, placemarkPostalCode: String, placemarkThoroughfare: String, latitude: String, longitude: String) {
let realm = try! Realm()
realm.beginWrite()
// Verify if exists
guard realm.objects(tableGPS.self).filter("latitude == %@ AND longitude == %@", latitude, longitude).first == nil else {
realm.cancelWrite()
return
}
// Add new GPS
let addObject = tableGPS()
addObject.latitude = latitude
addObject.location = location
addObject.longitude = longitude
addObject.placemarkAdministrativeArea = placemarkAdministrativeArea
addObject.placemarkCountry = placemarkCountry
addObject.placemarkLocality = placemarkLocality
addObject.placemarkPostalCode = placemarkPostalCode
addObject.placemarkThoroughfare = placemarkThoroughfare
realm.add(addObject)
do {
try realm.commitWrite()
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func getLocationFromGeoLatitude(_ latitude: String, longitude: String) -> String? {
let realm = try! Realm()
let result = realm.objects(tableGPS.self).filter("latitude == %@ AND longitude == %@", latitude, longitude).first
return result?.location
}
// MARK: -
// MARK: Table LocalFile
func addLocalFile(metadata: tableMetadata) {
let realm = try! Realm()
do {
try realm.write {
let addObject = getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) ?? tableLocalFile()
addObject.account = metadata.account
addObject.etag = metadata.etag
addObject.exifDate = NSDate()
addObject.exifLatitude = "-1"
addObject.exifLongitude = "-1"
addObject.ocId = metadata.ocId
addObject.fileName = metadata.fileName
realm.add(addObject, update: .all)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
func addLocalFile(account: String, etag: String, ocId: String, fileName: String) {
let realm = try! Realm()
do {
try realm.write {
let addObject = tableLocalFile()
addObject.account = account
addObject.etag = etag
addObject.exifDate = NSDate()
addObject.exifLatitude = "-1"
addObject.exifLongitude = "-1"
addObject.ocId = ocId
addObject.fileName = fileName
realm.add(addObject, update: .all)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func deleteLocalFile(predicate: NSPredicate) {
let realm = try! Realm()
do {
try realm.write {
let results = realm.objects(tableLocalFile.self).filter(predicate)
realm.delete(results)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func setLocalFile(ocId: String, fileName: String?, etag: String?) {
let realm = try! Realm()
do {
try realm.write {
let result = realm.objects(tableLocalFile.self).filter("ocId == %@", ocId).first
if let fileName = fileName {
result?.fileName = fileName
}
if let etag = etag {
result?.etag = etag
}
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func setLocalFile(ocId: String, exifDate: NSDate?, exifLatitude: String, exifLongitude: String, exifLensModel: String?) {
let realm = try! Realm()
do {
try realm.write {
if let result = realm.objects(tableLocalFile.self).filter("ocId == %@", ocId).first {
result.exifDate = exifDate
result.exifLatitude = exifLatitude
result.exifLongitude = exifLongitude
if exifLensModel?.count ?? 0 > 0 {
result.exifLensModel = exifLensModel
}
}
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func getTableLocalFile(account: String) -> [tableLocalFile] {
let realm = try! Realm()
let results = realm.objects(tableLocalFile.self).filter("account == %@", account)
return Array(results.map { tableLocalFile.init(value: $0) })
}
@objc func getTableLocalFile(predicate: NSPredicate) -> tableLocalFile? {
let realm = try! Realm()
guard let result = realm.objects(tableLocalFile.self).filter(predicate).first else {
return nil
}
return tableLocalFile.init(value: result)
}
@objc func getTableLocalFiles(predicate: NSPredicate, sorted: String, ascending: Bool) -> [tableLocalFile] {
let realm = try! Realm()
let results = realm.objects(tableLocalFile.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
return Array(results.map { tableLocalFile.init(value: $0) })
}
@objc func setLocalFile(ocId: String, offline: Bool) {
let realm = try! Realm()
do {
try realm.write {
let result = realm.objects(tableLocalFile.self).filter("ocId == %@", ocId).first
result?.offline = offline
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
// MARK: -
// MARK: Table Photo Library
@discardableResult
@objc func addPhotoLibrary(_ assets: [PHAsset], account: String) -> Bool {
let realm = try! Realm()
do {
try realm.write {
for asset in assets {
var creationDateString = ""
let addObject = tablePhotoLibrary()
addObject.account = account
addObject.assetLocalIdentifier = asset.localIdentifier
addObject.mediaType = asset.mediaType.rawValue
if let creationDate = asset.creationDate {
addObject.creationDate = creationDate as NSDate
creationDateString = String(describing: creationDate)
}
if let modificationDate = asset.modificationDate {
addObject.modificationDate = modificationDate as NSDate
}
addObject.idAsset = account + asset.localIdentifier + creationDateString
realm.add(addObject, update: .all)
}
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
return false
}
return true
}
@objc func getPhotoLibraryIdAsset(image: Bool, video: Bool, account: String) -> [String]? {
let realm = try! Realm()
var predicate = NSPredicate()
if image && video {
predicate = NSPredicate(format: "account == %@ AND (mediaType == %d OR mediaType == %d)", account, PHAssetMediaType.image.rawValue, PHAssetMediaType.video.rawValue)
} else if image {
predicate = NSPredicate(format: "account == %@ AND mediaType == %d", account, PHAssetMediaType.image.rawValue)
} else if video {
predicate = NSPredicate(format: "account == %@ AND mediaType == %d", account, PHAssetMediaType.video.rawValue)
}
let results = realm.objects(tablePhotoLibrary.self).filter(predicate)
let idsAsset = results.map { $0.idAsset }
return Array(idsAsset)
}
// MARK: -
// MARK: Table Share
@objc func addShare(account: String, home: String, shares: [NKShare]) {
let realm = try! Realm()
do {
try realm.write {
for share in shares {
let serverUrlPath = home + share.path
guard let serverUrl = NCUtilityFileSystem.shared.deleteLastPath(serverUrlPath: serverUrlPath, home: home) else {
continue
}
let object = tableShare()
object.account = account
if let fileName = share.path.components(separatedBy: "/").last {
object.fileName = fileName
}
object.serverUrl = serverUrl
object.canEdit = share.canEdit
object.canDelete = share.canDelete
object.date = share.date
object.displaynameFileOwner = share.displaynameFileOwner
object.displaynameOwner = share.displaynameOwner
object.expirationDate = share.expirationDate
object.fileParent = share.fileParent
object.fileSource = share.fileSource
object.fileTarget = share.fileTarget
object.hideDownload = share.hideDownload
object.idShare = share.idShare
object.itemSource = share.itemSource
object.itemType = share.itemType
object.label = share.label
object.mailSend = share.mailSend
object.mimeType = share.mimeType
object.note = share.note
object.parent = share.parent
object.password = share.password
object.path = share.path
object.permissions = share.permissions
object.primaryKey = account + " " + String(share.idShare)
object.sendPasswordByTalk = share.sendPasswordByTalk
object.shareType = share.shareType
object.shareWith = share.shareWith
object.shareWithDisplayname = share.shareWithDisplayname
object.storage = share.storage
object.storageId = share.storageId
object.token = share.token
object.uidOwner = share.uidOwner
object.uidFileOwner = share.uidFileOwner
object.url = share.url
object.userClearAt = share.userClearAt
object.userIcon = share.userIcon
object.userMessage = share.userMessage
object.userStatus = share.userStatus
realm.add(object, update: .all)
}
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func getTableShares(account: String) -> [tableShare] {
let realm = try! Realm()
let sortProperties = [SortDescriptor(keyPath: "shareType", ascending: false), SortDescriptor(keyPath: "idShare", ascending: false)]
let results = realm.objects(tableShare.self).filter("account == %@", account).sorted(by: sortProperties)
return Array(results.map { tableShare.init(value: $0) })
}
func getTableShares(metadata: tableMetadata) -> (firstShareLink: tableShare?, share: [tableShare]?) {
let realm = try! Realm()
let sortProperties = [SortDescriptor(keyPath: "shareType", ascending: false), SortDescriptor(keyPath: "idShare", ascending: false)]
let firstShareLink = realm.objects(tableShare.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@ AND shareType == 3", metadata.account, metadata.serverUrl, metadata.fileName).first
if let firstShareLink = firstShareLink {
let results = realm.objects(tableShare.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@ AND idShare != %d", metadata.account, metadata.serverUrl, metadata.fileName, firstShareLink.idShare).sorted(by: sortProperties)
return(firstShareLink: tableShare.init(value: firstShareLink), share: Array(results.map { tableShare.init(value: $0) }))
} else {
let results = realm.objects(tableShare.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", metadata.account, metadata.serverUrl, metadata.fileName).sorted(by: sortProperties)
return(firstShareLink: firstShareLink, share: Array(results.map { tableShare.init(value: $0) }))
}
}
func getTableShare(account: String, idShare: Int) -> tableShare? {
let realm = try! Realm()
guard let result = realm.objects(tableShare.self).filter("account = %@ AND idShare = %d", account, idShare).first else {
return nil
}
return tableShare.init(value: result)
}
@objc func getTableShares(account: String, serverUrl: String) -> [tableShare] {
let realm = try! Realm()
let sortProperties = [SortDescriptor(keyPath: "shareType", ascending: false), SortDescriptor(keyPath: "idShare", ascending: false)]
let results = realm.objects(tableShare.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).sorted(by: sortProperties)
return Array(results.map { tableShare.init(value: $0) })
}
@objc func getTableShares(account: String, serverUrl: String, fileName: String) -> [tableShare] {
let realm = try! Realm()
let sortProperties = [SortDescriptor(keyPath: "shareType", ascending: false), SortDescriptor(keyPath: "idShare", ascending: false)]
let results = realm.objects(tableShare.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", account, serverUrl, fileName).sorted(by: sortProperties)
return Array(results.map { tableShare.init(value: $0) })
}
@objc func deleteTableShare(account: String, idShare: Int) {
let realm = try! Realm()
realm.beginWrite()
let result = realm.objects(tableShare.self).filter("account == %@ AND idShare == %d", account, idShare)
realm.delete(result)
do {
try realm.commitWrite()
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func deleteTableShare(account: String) {
let realm = try! Realm()
realm.beginWrite()
let result = realm.objects(tableShare.self).filter("account == %@", account)
realm.delete(result)
do {
try realm.commitWrite()
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
// MARK: -
// MARK: Table Tag
@objc func addTag(_ ocId: String, tagIOS: Data?, account: String) {
let realm = try! Realm()
do {
try realm.write {
// Add new
let addObject = tableTag()
addObject.account = account
addObject.ocId = ocId
addObject.tagIOS = tagIOS
realm.add(addObject, update: .all)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func deleteTag(_ ocId: String) {
let realm = try! Realm()
realm.beginWrite()
let result = realm.objects(tableTag.self).filter("ocId == %@", ocId)
realm.delete(result)
do {
try realm.commitWrite()
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func getTags(predicate: NSPredicate) -> [tableTag] {
let realm = try! Realm()
let results = realm.objects(tableTag.self).filter(predicate)
return Array(results.map { tableTag.init(value: $0) })
}
@objc func getTag(predicate: NSPredicate) -> tableTag? {
let realm = try! Realm()
guard let result = realm.objects(tableTag.self).filter(predicate).first else {
return nil
}
return tableTag.init(value: result)
}
// MARK: -
// MARK: Table Tip
@objc func tipExists(_ tipName: String) -> Bool {
let realm = try! Realm()
guard (realm.objects(tableTip.self).where {
$0.tipName == tipName
}.first) == nil else {
return true
}
return false
}
@objc func addTip(_ tipName: String) {
let realm = try! Realm()
do {
try realm.write {
let addObject = tableTip()
addObject.tipName = tipName
realm.add(addObject, update: .all)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
// MARK: -
// MARK: Table Trash
@objc func addTrash(account: String, items: [NKTrash]) {
let realm = try! Realm()
do {
try realm.write {
for trash in items {
let object = tableTrash()
object.account = account
object.contentType = trash.contentType
object.date = trash.date
object.directory = trash.directory
object.fileId = trash.fileId
object.fileName = trash.fileName
object.filePath = trash.filePath
object.hasPreview = trash.hasPreview
object.iconName = trash.iconName
object.size = trash.size
object.trashbinDeletionTime = trash.trashbinDeletionTime
object.trashbinFileName = trash.trashbinFileName
object.trashbinOriginalLocation = trash.trashbinOriginalLocation
object.classFile = trash.classFile
realm.add(object, update: .all)
}
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func deleteTrash(filePath: String?, account: String) {
let realm = try! Realm()
var predicate = NSPredicate()
do {
try realm.write {
if filePath == nil {
predicate = NSPredicate(format: "account == %@", account)
} else {
predicate = NSPredicate(format: "account == %@ AND filePath == %@", account, filePath!)
}
let result = realm.objects(tableTrash.self).filter(predicate)
realm.delete(result)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
@objc func deleteTrash(fileId: String?, account: String) {
let realm = try! Realm()
var predicate = NSPredicate()
do {
try realm.write {
if fileId == nil {
predicate = NSPredicate(format: "account == %@", account)
} else {
predicate = NSPredicate(format: "account == %@ AND fileId == %@", account, fileId!)
}
let result = realm.objects(tableTrash.self).filter(predicate)
realm.delete(result)
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
func getTrash(filePath: String, sort: String?, ascending: Bool?, account: String) -> [tableTrash]? {
let realm = try! Realm()
let sort = sort ?? "date"
let ascending = ascending ?? false
let results = realm.objects(tableTrash.self).filter("account == %@ AND filePath == %@", account, filePath).sorted(byKeyPath: sort, ascending: ascending)
return Array(results.map { tableTrash.init(value: $0) })
}
@objc func getTrashItem(fileId: String, account: String) -> tableTrash? {
let realm = try! Realm()
guard let result = realm.objects(tableTrash.self).filter("account == %@ AND fileId == %@", account, fileId).first else {
return nil
}
return tableTrash.init(value: result)
}
// MARK: -
// MARK: Table UserStatus
@objc func addUserStatus(_ userStatuses: [NKUserStatus], account: String, predefined: Bool) {
let realm = try! Realm()
do {
try realm.write {
let results = realm.objects(tableUserStatus.self).filter("account == %@ AND predefined == %@", account, predefined)
realm.delete(results)
for userStatus in userStatuses {
let object = tableUserStatus()
object.account = account
object.clearAt = userStatus.clearAt
object.clearAtTime = userStatus.clearAtTime
object.clearAtType = userStatus.clearAtType
object.icon = userStatus.icon
object.id = userStatus.id
object.message = userStatus.message
object.predefined = userStatus.predefined
object.status = userStatus.status
object.userId = userStatus.userId
realm.add(object)
}
}
} catch let error {
NKCommon.shared.writeLog("Could not write to database: \(error)")
}
}
}
| gpl-3.0 | 51fb992e1ade4238871a72debe392f88 | 32.882564 | 339 | 0.567409 | 4.856161 | false | false | false | false |
HIIT/JustUsed | JustUsed/Model/LocationSingleton.swift | 1 | 2829 | //
// Copyright (c) 2015 Aalto University
//
// 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 Cocoa
import CoreLocation
/// Keeps track of the location controller, of which we should have only one instance at a time
class LocationSingleton {
fileprivate static let _locationController = LocationController()
static func getCurrentLocation() -> Location? {
return LocationSingleton._locationController.location
}
}
class LocationController: NSObject, CLLocationManagerDelegate {
var locMan: CLLocationManager
var geoMan: CLGeocoder
/// It will be true only if we are authorised to retrieve user's location
var authorised: Bool
/// Stores location in native form
var location: Location?
required override init() {
locMan = CLLocationManager()
geoMan = CLGeocoder()
let authStat = CLLocationManager.authorizationStatus()
switch authStat {
case .denied, .restricted:
authorised = false
default:
authorised = true
}
super.init()
locMan.delegate = self
if authorised {
if CLLocationManager.locationServicesEnabled() {
locMan.desiredAccuracy = kCLLocationAccuracyBest
locMan.distanceFilter = CLLocationDistance(1000)
locMan.startUpdatingLocation()
}
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.count >= 1 {
let loc = locations[0]
geoMan.getDescription(fromLoc: loc) {
describedLocation in
self.location = describedLocation
}
}
}
}
| mit | a09431da227cdbb5bbc45adfa2dd056f | 34.3625 | 100 | 0.677625 | 5.238889 | false | false | false | false |
google/JacquardSDKiOS | JacquardSDK/Classes/Internal/IMUDataCollectionAPI/IMUModuleComands.swift | 1 | 10696 | // Copyright 2021 Google LLC
//
// 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
/// Command request to retrieve all the modules available in the device.
struct ListIMUSessionsCommand: CommandRequest {
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionTrialList
let sessionListRequest = Google_Jacquard_Protocol_DataCollectionTrialListRequest()
request.Google_Jacquard_Protocol_DataCollectionTrialListRequest_trialList = sessionListRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionTrialListResponse_trialList {
return .success(())
}
return .failure(CommandResponseStatus.errorAppUnknown)
}
}
struct IMUSessionNotificationSubscription: NotificationSubscription {
func extract(from outerProto: Any) -> IMUSessionInfo? {
guard let notification = outerProto as? Google_Jacquard_Protocol_Notification else {
jqLogger.assert(
"calling extract() with anything other than Google_Jacquard_Protocol_Notification is an error"
)
return nil
}
// Silently ignore other notifications.
guard notification.hasGoogle_Jacquard_Protocol_DataCollectionTrialListNotification_trialList
else {
return nil
}
let trial =
notification.Google_Jacquard_Protocol_DataCollectionTrialListNotification_trialList.trial
// If no trials are available, An empty session notification is sent by the tag.
if trial.hasTrialID {
let session = IMUSessionInfo(trial: trial)
return session
} else {
return nil
}
}
}
/// Command request to start IMU recording.
struct StartIMUSessionCommand: CommandRequest {
let sessionID: String
let campaignID: String
let groupID: String
let productID: String
let subjectID: String
init(
sessionID: String,
campaignID: String,
groupID: String,
productID: String,
subjectID: String
) {
self.sessionID = sessionID
self.campaignID = campaignID
self.groupID = groupID
self.productID = productID
self.subjectID = subjectID
}
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionStart
var metaData = Google_Jacquard_Protocol_DataCollectionMetadata()
metaData.mode = .store
metaData.campaignID = campaignID
// The `trialID` is named as `sessionID` for the client app.
// `groupID` is introduced to replace `sessionID` for any public api's
metaData.sessionID = groupID
metaData.trialID = sessionID
metaData.subjectID = subjectID
metaData.productID = productID
var sessionStartRequest = Google_Jacquard_Protocol_DataCollectionStartRequest()
sessionStartRequest.metadata = metaData
request.Google_Jacquard_Protocol_DataCollectionStartRequest_start = sessionStartRequest
return request
}
func parseResponse(outerProto: Any)
-> Result<Google_Jacquard_Protocol_DataCollectionStatus, Error>
{
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionStartResponse_start {
return .success(
outerProto.Google_Jacquard_Protocol_DataCollectionStartResponse_start.dcStatus)
}
return .failure(CommandResponseStatus.errorUnknown)
}
}
/// Command request to stop IMU recording.
struct StopIMUSessionCommand: CommandRequest {
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionStop
var sessionStopRequest = Google_Jacquard_Protocol_DataCollectionStopRequest()
sessionStopRequest.isError = true
request.Google_Jacquard_Protocol_DataCollectionStopRequest_stop = sessionStopRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionStopResponse_stop {
return .success(())
}
return .failure(CommandResponseStatus.errorUnknown)
}
}
/// Command request to get the current status of datacollection.
struct IMUDataCollectionStatusCommand: CommandRequest {
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionStatus
let dcStatusRequest = Google_Jacquard_Protocol_DataCollectionStatusRequest()
request.Google_Jacquard_Protocol_DataCollectionStatusRequest_status = dcStatusRequest
return request
}
func parseResponse(
outerProto: Any
) -> Result<Google_Jacquard_Protocol_DataCollectionStatus, Error> {
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
let dcStatus = outerProto.Google_Jacquard_Protocol_DataCollectionStatusResponse_status.dcStatus
return .success(dcStatus)
}
}
/// Command request to delete a session on the tag.
struct DeleteIMUSessionCommand: CommandRequest {
let session: IMUSessionInfo
init(session: IMUSessionInfo) {
self.session = session
}
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionTrialDataErase
var deleteTrialRequest = Google_Jacquard_Protocol_DataCollectionEraseTrialDataRequest()
deleteTrialRequest.campaignID = session.campaignID
deleteTrialRequest.sessionID = session.groupID
deleteTrialRequest.trialID = session.sessionID
deleteTrialRequest.productID = session.productID
deleteTrialRequest.subjectID = session.subjectID
request.Google_Jacquard_Protocol_DataCollectionEraseTrialDataRequest_eraseTrialData =
deleteTrialRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard
let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionEraseTrialDataResponse_eraseTrialData {
return .success(())
}
return .failure(CommandResponseStatus.errorUnknown)
}
}
/// Command request to delete all sessions on the tag.
struct DeleteAllIMUSessionsCommand: CommandRequest {
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionDataErase
let deleteAllRequest = Google_Jacquard_Protocol_DataCollectionEraseAllDataRequest()
request.Google_Jacquard_Protocol_DataCollectionEraseAllDataRequest_eraseAllData =
deleteAllRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionEraseAllDataResponse_eraseAllData {
return .success(())
}
return .failure(CommandResponseStatus.errorUnknown)
}
}
/// Command request to retrieve session data.
struct RetreiveIMUSessionDataCommand: CommandRequest {
let session: IMUSessionInfo
let offset: UInt32
init(session: IMUSessionInfo, offset: UInt32) {
self.session = session
self.offset = offset
}
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionTrialData
var sessionDataRequest = Google_Jacquard_Protocol_DataCollectionTrialDataRequest()
sessionDataRequest.campaignID = session.campaignID
sessionDataRequest.sessionID = session.groupID
sessionDataRequest.trialID = session.sessionID
sessionDataRequest.productID = session.productID
sessionDataRequest.subjectID = session.subjectID
sessionDataRequest.sensorID = 0
sessionDataRequest.offset = offset
request.Google_Jacquard_Protocol_DataCollectionTrialDataRequest_trialData = sessionDataRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard
let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionTrialDataResponse_trialData {
return .success(())
}
return .failure(CommandResponseStatus.errorUnknown)
}
}
| apache-2.0 | dedee7e256097cf1ae3beca6d0eea119 | 33.063694 | 104 | 0.751309 | 4.57094 | false | false | false | false |
cplaverty/KeitaiWaniKani | AlliCrab/Util/XibLoadable.swift | 1 | 866 | //
// XibLoadable.swift
// AlliCrab
//
// Copyright © 2019 Chris Laverty. All rights reserved.
//
import UIKit
protocol XibLoadable {
var xibName: String { get }
}
extension XibLoadable where Self: UIView {
var xibName: String {
return String(describing: type(of: self))
}
func setupContentViewFromXib() -> UIView {
let contentView = loadViewFromXib()
contentView.frame = bounds
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(contentView)
return contentView
}
private func loadViewFromXib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: xibName, bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
}
| mit | e51d1b592af0ec7c08e632e453ed1108 | 23.027778 | 82 | 0.621965 | 4.528796 | false | false | false | false |
aschwaighofer/swift | stdlib/public/core/Result.swift | 2 | 5993 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A value that represents either a success or a failure, including an
/// associated value in each case.
@frozen
public enum Result<Success, Failure: Error> {
/// A success, storing a `Success` value.
case success(Success)
/// A failure, storing a `Failure` value.
case failure(Failure)
/// Returns a new result, mapping any success value using the given
/// transformation.
///
/// Use this method when you need to transform the value of a `Result`
/// instance when it represents a success. The following example transforms
/// the integer success value of a result into a string:
///
/// func getNextInteger() -> Result<Int, Error> { /* ... */ }
///
/// let integerResult = getNextInteger()
/// // integerResult == .success(5)
/// let stringResult = integerResult.map({ String($0) })
/// // stringResult == .success("5")
///
/// - Parameter transform: A closure that takes the success value of this
/// instance.
/// - Returns: A `Result` instance with the result of evaluating `transform`
/// as the new success value if this instance represents a success.
public func map<NewSuccess>(
_ transform: (Success) -> NewSuccess
) -> Result<NewSuccess, Failure> {
switch self {
case let .success(success):
return .success(transform(success))
case let .failure(failure):
return .failure(failure)
}
}
/// Returns a new result, mapping any failure value using the given
/// transformation.
///
/// Use this method when you need to transform the value of a `Result`
/// instance when it represents a failure. The following example transforms
/// the error value of a result by wrapping it in a custom `Error` type:
///
/// struct DatedError: Error {
/// var error: Error
/// var date: Date
///
/// init(_ error: Error) {
/// self.error = error
/// self.date = Date()
/// }
/// }
///
/// let result: Result<Int, Error> = // ...
/// // result == .failure(<error value>)
/// let resultWithDatedError = result.mapError({ e in DatedError(e) })
/// // result == .failure(DatedError(error: <error value>, date: <date>))
///
/// - Parameter transform: A closure that takes the failure value of the
/// instance.
/// - Returns: A `Result` instance with the result of evaluating `transform`
/// as the new failure value if this instance represents a failure.
public func mapError<NewFailure>(
_ transform: (Failure) -> NewFailure
) -> Result<Success, NewFailure> {
switch self {
case let .success(success):
return .success(success)
case let .failure(failure):
return .failure(transform(failure))
}
}
/// Returns a new result, mapping any success value using the given
/// transformation and unwrapping the produced result.
///
/// - Parameter transform: A closure that takes the success value of the
/// instance.
/// - Returns: A `Result` instance with the result of evaluating `transform`
/// as the new failure value if this instance represents a failure.
public func flatMap<NewSuccess>(
_ transform: (Success) -> Result<NewSuccess, Failure>
) -> Result<NewSuccess, Failure> {
switch self {
case let .success(success):
return transform(success)
case let .failure(failure):
return .failure(failure)
}
}
/// Returns a new result, mapping any failure value using the given
/// transformation and unwrapping the produced result.
///
/// - Parameter transform: A closure that takes the failure value of the
/// instance.
/// - Returns: A `Result` instance, either from the closure or the previous
/// `.success`.
public func flatMapError<NewFailure>(
_ transform: (Failure) -> Result<Success, NewFailure>
) -> Result<Success, NewFailure> {
switch self {
case let .success(success):
return .success(success)
case let .failure(failure):
return transform(failure)
}
}
/// Returns the success value as a throwing expression.
///
/// Use this method to retrieve the value of this result if it represents a
/// success, or to catch the value if it represents a failure.
///
/// let integerResult: Result<Int, Error> = .success(5)
/// do {
/// let value = try integerResult.get()
/// print("The value is \(value).")
/// } catch {
/// print("Error retrieving the value: \(error)")
/// }
/// // Prints "The value is 5."
///
/// - Returns: The success value, if the instance represents a success.
/// - Throws: The failure value, if the instance represents a failure.
public func get() throws -> Success {
switch self {
case let .success(success):
return success
case let .failure(failure):
throw failure
}
}
}
extension Result where Failure == Swift.Error {
/// Creates a new result by evaluating a throwing closure, capturing the
/// returned value as a success, or any thrown error as a failure.
///
/// - Parameter body: A throwing closure to evaluate.
@_transparent
public init(catching body: () throws -> Success) {
do {
self = .success(try body())
} catch {
self = .failure(error)
}
}
}
extension Result: Equatable where Success: Equatable, Failure: Equatable { }
extension Result: Hashable where Success: Hashable, Failure: Hashable { }
| apache-2.0 | 0cbcb60d38fb43be598cc82156fdaf5b | 34.672619 | 80 | 0.62306 | 4.384053 | false | false | false | false |
justin999/gitap | gitap/PayloadIssuesEvent.swift | 1 | 1062 | ////
//// PayloadIssuesEvent.swift
//// gitap
////
//// Created by Koichi Sato on 1/22/17.
//// Copyright © 2017 Koichi Sato. All rights reserved.
////
//
//import Foundation
//class PayloadIssuesEvent: Payload {
// var action: String?
// var issue: Issue?
// var changes: Dictionary<String, Any>?
// var changesTitleFrom: String?
// var changesBodyFrom: String?
// var assignee: User?
// // var label: Label?
//
// required init?(json: [String: Any]) {
// super.init(json: json)
// self.action = json["action"] as? String
// if let dataDictionary = json["issue"] as? [String: Any] {
// self.issue = Issue(json: dataDictionary)
// }
// self.changes = json["changes"] as? Dictionary
// self.changesTitleFrom = json["changes[title][from]"] as? String
// self.changesBodyFrom = json["changes[body][from]"] as? String
// if let dataDictionary = json["assignee"] as? [String: Any] {
// self.assignee = User(json: dataDictionary)
// }
// }
//}
| mit | f14adb18998edc0478f054e7b85887ba | 32.15625 | 73 | 0.583412 | 3.560403 | false | false | false | false |
garygriswold/Bible.js | SafeBible2/SafeBible_ios/SafeBible/ViewControllers/UserMessageController.swift | 1 | 1215 | //
// UserMessageController.swift
// Settings
//
// Created by Gary Griswold on 8/27/18.
// Copyright © 2018 ShortSands. All rights reserved.
//
import UIKit
import MessageUI
class UserMessageController : MFMessageComposeViewController, MFMessageComposeViewControllerDelegate {
static func isAvailable() -> Bool {
return MFMessageComposeViewController.canSendText()
}
static func present(controller: UIViewController?) {
let userMessageController = UserMessageController()
controller?.navigationController?.present(userMessageController, animated: true, completion: nil)
}
override func loadView() {
super.loadView()
self.modalTransitionStyle = .flipHorizontal
self.messageComposeDelegate = self
let message = NSLocalizedString("I like it!", comment: "User text in message to other")
self.body = message + "\nhttps://itunes.apple.com/app/id1073396349"
}
func messageComposeViewController(_ controller: MFMessageComposeViewController,
didFinishWith result: MessageComposeResult) {
controller.dismiss(animated: true, completion: nil)
}
}
| mit | 4cf049d5e0a965f970e413cd988cfc2c | 31.810811 | 105 | 0.686985 | 5.419643 | false | false | false | false |
gifsy/Gifsy | Frameworks/Bond/Bond/Core/ObservableArrayEvent.swift | 13 | 11544 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 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.
//
/// Abstraction over an event type generated by a ObservableArray.
/// ObservableArray event encapsulates current state of the array, as well
/// as the operation that has triggered an event.
public protocol ObservableArrayEventType {
typealias ObservableArrayEventSequenceType: SequenceType
var sequence: ObservableArrayEventSequenceType { get }
var operation: ObservableArrayOperation<ObservableArrayEventSequenceType.Generator.Element> { get }
}
/// A concrete array event type.
public struct ObservableArrayEvent<ObservableArrayEventSequenceType: SequenceType>: ObservableArrayEventType {
public let sequence: ObservableArrayEventSequenceType
public let operation: ObservableArrayOperation<ObservableArrayEventSequenceType.Generator.Element>
}
/// Represents an operation that can be applied to a ObservableArray.
/// Note: Nesting of the .Batch operations is not supported at the moment.
public indirect enum ObservableArrayOperation<ElementType> {
case Insert(elements: [ElementType], fromIndex: Int)
case Update(elements: [ElementType], fromIndex: Int)
case Remove(range: Range<Int>)
case Reset(array: [ElementType])
case Batch([ObservableArrayOperation<ElementType>])
}
/// A array event change set represents a description of the change that
/// the array event operation does to a array in a way suited for application
/// to the UIKit collection views like UITableView or UICollectionView
public enum ObservableArrayEventChangeSet {
case Inserts(Set<Int>)
case Updates(Set<Int>)
case Deletes(Set<Int>)
}
public func ==(lhs: ObservableArrayEventChangeSet, rhs: ObservableArrayEventChangeSet) -> Bool {
switch (lhs, rhs) {
case (.Inserts(let l), .Inserts(let r)):
return l == r
case (.Updates(let l), .Updates(let r)):
return l == r
case (.Deletes(let l), .Deletes(let r)):
return l == r
default:
return false
}
}
public extension ObservableArrayOperation {
/// Maps elements encapsulated in the operation.
public func map<X>(transform: ElementType -> X) -> ObservableArrayOperation<X> {
switch self {
case .Reset(let array):
return .Reset(array: array.map(transform))
case .Insert(let elements, let fromIndex):
return .Insert(elements: elements.map(transform), fromIndex: fromIndex)
case .Update(let elements, let fromIndex):
return .Update(elements: elements.map(transform), fromIndex: fromIndex)
case .Remove(let range):
return .Remove(range: range)
case .Batch(let operations):
return .Batch(operations.map{ $0.map(transform) })
}
}
public func filter(includeElement: ElementType -> Bool, inout pointers: [Int]) -> ObservableArrayOperation<ElementType>? {
switch self {
case .Insert(let elements, let fromIndex):
for (index, element) in pointers.enumerate() {
if element >= fromIndex {
pointers[index] = element + elements.count
}
}
var insertedIndices: [Int] = []
var insertedElements: [ElementType] = []
for (index, element) in elements.enumerate() {
if includeElement(element) {
insertedIndices.append(fromIndex + index)
insertedElements.append(element)
}
}
if insertedIndices.count > 0 {
let insertionPoint = startingIndexForIndex(fromIndex, forPointers: pointers)
pointers.insertContentsOf(insertedIndices, at: insertionPoint)
return .Insert(elements: insertedElements, fromIndex: insertionPoint)
}
case .Update(let elements, let fromIndex):
var operations: [ObservableArrayOperation<ElementType>] = []
for (index, element) in elements.enumerate() {
let realIndex = fromIndex + index
// if element on this index is currently included in filtered array
if let location = pointers.indexOf(realIndex) {
if includeElement(element) {
// update
operations.append(.Update(elements: [element], fromIndex: location))
} else {
// remove
pointers.removeAtIndex(location)
operations.append(.Remove(range: location..<location+1))
}
} else { // element in this index is currently NOT included
if includeElement(element) {
// insert
let insertionPoint = startingIndexForIndex(realIndex, forPointers: pointers)
pointers.insert(realIndex, atIndex: insertionPoint)
operations.append(.Insert(elements: [element], fromIndex: insertionPoint))
} else {
// not contained, not inserted - do nothing
}
}
}
if operations.count == 1 {
return operations.first!
} else if operations.count > 1 {
return .Batch(operations)
}
case .Remove(let range):
var startIndex = -1
var endIndex = -1
for (index, element) in pointers.enumerate() {
if element >= range.startIndex {
if element < range.endIndex {
if startIndex < 0 {
startIndex = index
endIndex = index + 1
} else {
endIndex = index + 1
}
}
pointers[index] = element - range.count
}
}
if startIndex >= 0 {
let removedRange = Range(start: startIndex, end: endIndex)
pointers.removeRange(removedRange)
return .Remove(range: removedRange)
}
case .Reset(let array):
pointers = pointersFromSequence(array, includeElement: includeElement)
return .Reset(array: array.filter(includeElement))
case .Batch(let operations):
var filteredOperations: [ObservableArrayOperation<ElementType>] = []
for operation in operations {
if let filtered = operation.filter(includeElement, pointers: &pointers) {
filteredOperations.append(filtered)
}
}
if filteredOperations.count == 1 {
return filteredOperations.first!
} else if filteredOperations.count > 0 {
return .Batch(filteredOperations)
}
}
return nil
}
/// Generates the `ObservableArrayEventChangeSet` representation of the operation.
public func changeSet() -> ObservableArrayEventChangeSet {
switch self {
case .Insert(let elements, let fromIndex):
return .Inserts(Set(fromIndex..<fromIndex+elements.count))
case .Update(let elements, let fromIndex):
return .Updates(Set(fromIndex..<fromIndex+elements.count))
case .Remove(let range):
return .Deletes(Set(range))
case .Reset:
fallthrough
case .Batch:
fatalError("Dear Sir/Madam, I cannot generate changeset for \(self) operation.")
}
}
}
internal func pointersFromSequence<S: SequenceType>(sequence: S, includeElement: S.Generator.Element -> Bool) -> [Int] {
var pointers: [Int] = []
for (index, element) in sequence.enumerate() {
if includeElement(element) {
pointers.append(index)
}
}
return pointers
}
internal func startingIndexForIndex(x: Int, forPointers pointers: [Int]) -> Int {
var idx: Int = -1
for (index, element) in pointers.enumerate() {
if element < x {
idx = index
} else {
break
}
}
return idx + 1
}
/// This function is used by UICollectionView and UITableView bindings.
/// Batch operations are expected to be sequentially applied to the array/array, which is not what those views do.
/// The function converts operations into a "diff" discribing elements at what indices changed and in what way.
///
/// For example, when following (valid) input is given:
/// [.Insert([A], 0), .Insert([B], 0)]
/// function should produce following output:
/// [.Inserts([0, 1])]
///
/// Or:
/// [.Insert([B], 0), .Remove(1)] -> [.Inserts([0]), .Deletes([0])]
/// [.Insert([A], 0), .Insert([B], 0), .Remove(1)] -> [.Inserts([0])]
/// [.Insert([A], 0), .Remove(0)] -> []
/// [.Insert([A, B], 0), .Insert([C, D], 1)] -> [.Inserts([0, 1, 2, 3])]
///
public func changeSetsFromBatchOperations<T>(operations: [ObservableArrayOperation<T>]) -> [ObservableArrayEventChangeSet] {
func shiftSet(set: Set<Int>, from: Int, by: Int) -> Set<Int> {
var shiftedSet = Set<Int>()
for element in set {
if element >= from {
shiftedSet.insert(element + by)
} else {
shiftedSet.insert(element)
}
}
return shiftedSet
}
var inserts = Set<Int>()
var updates = Set<Int>()
var deletes = Set<Int>()
for operation in operations {
switch operation {
case .Insert(let elements, let fromIndex):
inserts = shiftSet(inserts, from: fromIndex, by: elements.count)
updates = shiftSet(updates, from: fromIndex, by: elements.count)
let range = fromIndex..<fromIndex+elements.count
let replaced = deletes.intersect(range)
let new = Set(range).subtract(replaced)
deletes.subtractInPlace(replaced)
updates.unionInPlace(replaced)
deletes = shiftSet(deletes, from: fromIndex, by: elements.count)
inserts.unionInPlace(new)
case .Update(let elements, let fromIndex):
updates.unionInPlace(fromIndex..<fromIndex+elements.count)
case .Remove(let range):
let annihilated = inserts.intersect(range)
let reallyRemoved = Set(range).subtract(annihilated)
inserts.subtractInPlace(annihilated)
updates.subtractInPlace(range)
inserts = shiftSet(inserts, from: range.startIndex, by: -range.count)
updates = shiftSet(updates, from: range.startIndex, by: -range.count)
deletes = shiftSet(deletes, from: range.startIndex, by: -range.count)
deletes.unionInPlace(reallyRemoved)
case .Reset:
fatalError("Dear Sir/Madam, the .Reset operation within the .Batch is not supported at the moment!")
case .Batch:
fatalError("Dear Sir/Madam, nesting the .Batch operations is not supported at the moment!")
}
}
var changeSets: [ObservableArrayEventChangeSet] = []
if inserts.count > 0 {
changeSets.append(.Inserts(inserts))
}
if updates.count > 0 {
changeSets.append(.Updates(updates))
}
if deletes.count > 0 {
changeSets.append(.Deletes(deletes))
}
return changeSets
}
| apache-2.0 | 4fa0fae5bea528902afd97c9f2ed7460 | 34.088146 | 124 | 0.660776 | 4.509375 | false | false | false | false |
28stephlim/HeartbeatAnalysis-master | VoiceMemos/Controller/ApexSupineOutputViewController.swift | 1 | 5670 | //
// ApexSupineOutputViewController.swift
// VoiceMemos
//
// Created by Stephanie Lim on 02/10/2016.
// Copyright © 2016 Zhouqi Mo. All rights reserved.
//
import UIKit
import FDWaveformView
import Foundation
class ApexSupineOutputViewController: UIViewController {
var inputURL : NSURL!
///TEST ONLY/////
////CHANGE AFTER////////
var apexsup = "AS-MSC"
var supine = ["Early Systolic Murmur", "Holosystolic Murmur","Late Systolic Murmur", "Mid-Systolic Click","Mid-Systolic Murmur","Single S1 S2","Split S1" ]
//Setting up waveform view and waeform target connection
@IBOutlet weak var WaveformView: FDWaveformView!
//Diagnosis labels target connections
@IBOutlet weak var Diagnosis1: UILabel!
@IBOutlet weak var Diagnosis2: UILabel!
@IBOutlet weak var Diagnosis3: UILabel!
@IBOutlet weak var Diagnosis4: UILabel!
@IBOutlet weak var Diagnosis5: UILabel!
@IBOutlet weak var Diagnosis6: UILabel!
@IBOutlet weak var Diagnosis7: UILabel!
@IBOutlet weak var diagnosis8: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//preparing data for 2nd VC
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let VC2 : ApexSupineConditionViewController = segue.destinationViewController as! ApexSupineConditionViewController
VC2.condition = apexsup
}
override func viewDidAppear(animated: Bool) {
// self.Diagnosis1.text = ""
// self.Diagnosis2.text = ""
// self.Diagnosis3.text = ""
// self.Diagnosis4.text = ""
// self.Diagnosis5.text = ""
// self.Diagnosis6.text = ""
// self.Diagnosis7.text = ""
//
// self.WaveformView.audioURL = inputURL
// self.WaveformView.progressSamples = 0
// self.WaveformView.doesAllowScroll = true
// self.WaveformView.doesAllowStretch = true
// self.WaveformView.doesAllowScrubbing = false
// self.WaveformView.wavesColor = UIColor.blueColor()
//
// signalCompare(self.supine)
// }
//
// func signalCompare(type: [String]){
//
// var detective = LBAudioDetectiveNew()
// var bundle = NSBundle.mainBundle()
// var matchArray = [Float32]()
//
// dispatch_async(dispatch_get_main_queue(), {() -> Void in
//
// (type as NSArray).enumerateObjectsUsingBlock({(sequenceType: Any, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
//
// if let str = sequenceType as? String {
//
// var sequenceURL = bundle.URLForResource(str, withExtension: "caf")!
//
// var match: Float32 = 0.0
// LBAudioDetectiveCompareAudioURLs(detective, self.inputURL, sequenceURL, 0, &match)
// print("Match = \(match)")
// matchArray.append(match)
// }
// })
//
// var maxMatch = matchArray.maxElement()
// var maxLocationIndex = matchArray.indexOf(maxMatch!)
// var maxLocationInt = matchArray.startIndex.distanceTo(maxLocationIndex!)
// var typeSize = type.count
//
//
// self.Diagnosis1.text = type[0] + ": \(matchArray[0])"
// self.Diagnosis2.text = type[1] + ": \(matchArray[1])"
// self.Diagnosis3.text = type[2] + ": \(matchArray[2])"
// self.Diagnosis4.text = type[3] + ": \(matchArray[3])"
// if (typeSize>4){
// self.Diagnosis5.text = type[4] + ": \(matchArray[4])"
// self.Diagnosis6.text = type[5] + ": \(matchArray[5])"
// if (typeSize>6){ // These if statements make sure the data shows properly since we have
// self.Diagnosis7.text = type[6] + ": \(matchArray[6])" //different amounts of audio files for each category
//
// }
// }
// self.apexsup = type[maxLocationIndex!]
//
// switch maxLocationInt {
// case 0:
// self.Diagnosis1.textColor = UIColor.redColor()
// case 1:
// self.Diagnosis2.textColor = UIColor.redColor()
// case 2:
// self.Diagnosis3.textColor = UIColor.redColor()
// case 3:
// self.Diagnosis4.textColor = UIColor.redColor()
// case 4:
// self.Diagnosis5.textColor = UIColor.redColor()
// case 5:
// self.Diagnosis6.textColor = UIColor.redColor()
// case 6:
// self.Diagnosis7.textColor = UIColor.redColor()
// default:
// print("error has occurred changing text colour") //This probably wont happen
// }
//
// //let diagnosisAlert = UIAlertController(title: "Diagnosis", message: "\(type[maxLocation!])", preferredStyle: .Alert)
// //let okButton = UIAlertAction(title: "OK", style: .Default){(diagnosisAlert: UIAlertAction!)->Void in }
// //diagnosisAlert.addAction(okButton)
// //self.presentViewController(diagnosisAlert, animated: true, completion: nil)
//
// })
}
}
| mit | 9ed53d3e8bbedc3e22ef01c4a3c8e1b5 | 36.296053 | 159 | 0.561827 | 4.344061 | false | false | false | false |
picaso/parrot-zik-status | ParrotStatus/views/ButtonEffects.swift | 1 | 1919 | /*
A re-write of https://github.com/Swift-Kit/JZHoverNSButton/blob/master/JZHoverNSButton.swift
Basically I want my buttons to give feedback of mouse over.
*/
class ButtonEffects: NSButton {
var trackingArea: NSTrackingArea!
// MARK: - Initializers
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
enableTracking()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
enableTracking()
}
fileprivate func enableTracking() {
// set tracking area
let opts: NSTrackingAreaOptions =
[NSTrackingAreaOptions.mouseEnteredAndExited, NSTrackingAreaOptions.activeAlways]
trackingArea = NSTrackingArea(rect: bounds, options: opts, owner: self, userInfo: nil)
self.addTrackingArea(trackingArea)
}
// MARK: mouse events
override func mouseEntered(with theEvent: NSEvent) {
self.alphaValue = 0.5
}
override func mouseExited(with theEvent: NSEvent) {
self.alphaValue = 1
}
}
class PopUpButtonEffects: NSPopUpButton {
var trackingArea: NSTrackingArea!
// MARK: - Initializers
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setTrackingArea()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setTrackingArea()
}
fileprivate func setTrackingArea() {
let opts: NSTrackingAreaOptions =
[NSTrackingAreaOptions.mouseEnteredAndExited, NSTrackingAreaOptions.activeAlways]
trackingArea = NSTrackingArea(rect: bounds, options: opts, owner: self, userInfo: nil)
self.addTrackingArea(trackingArea)
}
// MARK: mouse events
override func mouseEntered(with theEvent: NSEvent) {
self.alphaValue = 0.5
}
override func mouseExited(with theEvent: NSEvent) {
self.alphaValue = 1
}
}
| mit | dc536623f901fcef498b1e71b9661c1a | 26.414286 | 96 | 0.661282 | 4.84596 | false | false | false | false |
RamonGilabert/Prodam | Prodam/Prodam/ViewModel.swift | 1 | 21218 | import Cocoa
struct Constant {
struct Window {
static let Width = 300 as CGFloat
static let Height = 190 as CGFloat
}
struct WindowLayout {
static let MinimumPaddingButton = 6 as CGFloat
static let HeightOfButton = Constant.Window.Height / 4
static let WidthDonePauseButtons = Constant.Window.Width/2 - (1.5 * Constant.WindowLayout.MinimumPaddingButton)
static let WidthMainButton = Constant.Window.Width - (2 * Constant.WindowLayout.MinimumPaddingButton)
static let HalfScreenPadding = Constant.WindowLayout.MinimumPaddingButton/2 + Constant.Window.Width/2
static let SizeHelperButtons = 20 as CGFloat
}
struct BreakLayout {
static let WidthMainView = 1200 as CGFloat
static let HeightMainView = 700 as CGFloat
static let WidthMainButton = 265 as CGFloat
static let HeightMainButton = 55 as CGFloat
static let TopEditableYPadding = 65 as CGFloat
static let PaddingXButton = 25 as CGFloat
static let PaddingYButton = 115 as CGFloat
static let SizeCloseButton = 17 as CGFloat
static let AlphaValueTextFields = 0.6 as CGFloat
static let AlphaValueButtons = 0.8 as CGFloat
static let MinutesLabelXPadding = 15 as CGFloat
static let MinutesLabelYPadding = 55 as CGFloat
}
}
class ViewModel: NSObject {
let userDefaults = NSUserDefaults.standardUserDefaults()
// MARK: Main View Controller: Layout
func layoutFunctionalButtonsMainView(viewController: NSViewController) -> NSButton {
let button = addButtonMainView(Constant.WindowLayout.MinimumPaddingButton, width: Constant.WindowLayout.WidthMainButton, alpha: 1.0, text: "start", viewController: viewController)
button.attributedTitle = TextAttributter.attributedStringForButtons("START WORKING", font: "AvenirNext-DemiBold", color: NSColor.whiteColor())
return button
}
func layoutDoneButtonMainView(viewController: NSViewController) -> NSButton {
let button = addButtonMainView(Constant.WindowLayout.MinimumPaddingButton, width: Constant.WindowLayout.WidthDonePauseButtons, alpha: 0.0, text: "stop", viewController: viewController)
return button
}
func layoutPauseButtonMainView(viewController: NSViewController) -> NSButton {
let button = addButtonMainView(Constant.WindowLayout.HalfScreenPadding, width: Constant.WindowLayout.WidthDonePauseButtons, alpha: 0.0, text: "pause", viewController: viewController)
return button
}
func layoutTaskTextFieldMainView(fieldDelegate: NSTextFieldDelegate, viewController: NSViewController) -> NSTextField {
let textField = addBasicTextField(viewController, text: "")
textField.frame = NSMakeRect(50, Constant.Window.Height - 32, Constant.Window.Width - 100, 24)
textField.placeholderString = "Enter your new task..."
textField.font = NSFont_Prodam.textFieldNormalField()
textField.focusRingType = NSFocusRingType.None
textField.allowsEditingTextAttributes = true
textField.delegate = fieldDelegate
viewController.view.addSubview(textField)
return textField
}
func layoutTimerTextFieldMainView(viewController: NSViewController) -> NSTextField {
let textField = addBasicTextField(viewController, text: "50:00")
textField.editable = false
textField.selectable = false
textField.font = NSFont_Prodam.mainTimer()
textField.sizeToFit()
textField.frame = NSMakeRect((Constant.Window.Width - (textField.frame.width + 100))/2, (Constant.Window.Height - textField.frame.height)/2 + 20, textField.frame.width + 100, textField.frame.height)
textField.alphaValue = 0.0
return textField
}
func layoutEditableTextFieldMainView(viewController: NSViewController) -> NSTextField {
let textField = addBasicTextField(viewController, text: "50")
textField.alignment = NSTextAlignment.RightTextAlignment
textField.font = NSFont_Prodam.mainTimerEditable()
textField.sizeToFit()
textField.frame = NSMakeRect((Constant.Window.Width - textField.frame.width)/2 - 100, (Constant.Window.Height - textField.frame.height)/2 + 10, textField.frame.width + 100, textField.frame.height)
textField.becomeFirstResponder()
textField.focusRingType = NSFocusRingType.None
return textField
}
func layoutMinutesTextFieldMainView(viewController: NSViewController, editableTextField: NSTextField) -> NSTextField {
let textField = addBasicTextField(viewController, text: "min")
textField.editable = false
textField.selectable = false
textField.font = NSFont_Prodam.mainMinutesTextField()
textField.sizeToFit()
textField.frame = NSMakeRect(editableTextField.frame.origin.x + editableTextField.frame.width, editableTextField.frame.origin.y + 5, textField.frame.width, textField.frame.height)
return textField
}
func layoutButtonTasksMainView(viewController: NSViewController) -> NSButton {
let button = NSButton(frame: NSMakeRect(14, Constant.Window.Height - 30, Constant.WindowLayout.SizeHelperButtons, Constant.WindowLayout.SizeHelperButtons))
button.image = NSImage(named: "done-button")
button.bordered = false
button.target = viewController
button.action = "onTasksButtonPressed"
button.enabled = false
viewController.view.addSubview(button)
return button
}
func layoutButtonSettingsMainView(viewController: NSViewController) -> NSButton {
let button = NSButton(frame: NSMakeRect(Constant.Window.Width - 34, Constant.Window.Height - 30, Constant.WindowLayout.SizeHelperButtons, Constant.WindowLayout.SizeHelperButtons))
button.image = NSImage(named: "settings-button")
button.bordered = false
button.target = viewController
button.action = "onSettingsButtonPressed"
viewController.view.addSubview(button)
return button
}
// MARK: Break View Controller: Layout
func breakLayoutHeaderLabel(viewController: NSViewController) -> NSTextField {
var label = addBasicTextField(viewController, text: "TAKING A BREAK")
label = addBreakLabelConfiguration(label, font: NSFont_Prodam.breakHeaderTextField())
label.frame = NSMakeRect((viewController.view.frame.width - label.frame.width)/2, viewController.view.frame.height - label.frame.height - 25, label.frame.width, label.frame.height)
return label
}
func breakLayoutEditableLabel(viewController: NSViewController) -> NSTextField {
var label = addBasicTextField(viewController, text: "5")
label = addBreakLabelConfiguration(label, font: NSFont_Prodam.breakTimerFont())
label.alignment = NSTextAlignment.RightTextAlignment
label.editable = true
label.frame = NSMakeRect((viewController.view.frame.width - label.frame.width*4.75)/2, (viewController.view.frame.height - label.frame.height)/2 + Constant.BreakLayout.TopEditableYPadding, label.frame.width * 3, label.frame.height)
return label
}
func breakLayoutMinutesLabel(viewController: NSViewController, sideLabel: NSTextField) -> NSTextField {
var label = addBasicTextField(viewController, text: "min")
label = addBreakLabelConfiguration(label, font: NSFont_Prodam.breakMinutesFont())
label.frame = NSMakeRect(sideLabel.frame.origin.x + sideLabel.frame.width + Constant.BreakLayout.MinutesLabelXPadding, sideLabel.frame.origin.y + Constant.BreakLayout.MinutesLabelYPadding, label.frame.width, label.frame.height)
return label
}
func breakLayoutWorkAgainButton(viewController: NSViewController, sideLabel: NSTextField) -> NSButton {
var button = NSButton(frame: NSMakeRect((viewController.view.frame.width / 2) - (Constant.BreakLayout.PaddingXButton + Constant.BreakLayout.WidthMainButton), sideLabel.frame.origin.y - Constant.BreakLayout.PaddingYButton, Constant.BreakLayout.WidthMainButton, Constant.BreakLayout.HeightMainButton))
button.image = NSImage(named: "background-break-button")
button = addButtonConfiguration(button, viewController: viewController, text: "WORK AGAIN", color: NSColor(calibratedHue:0, saturation:0, brightness:0.22, alpha:1))
button.action = "onWorkAgainButtonPressed"
return button
}
func breakLayoutStartBreakButton(viewController: NSViewController, sideLabel: NSTextField) -> NSButton {
var button = NSButton(frame: NSMakeRect((viewController.view.frame.width / 2) + Constant.BreakLayout.PaddingXButton, sideLabel.frame.origin.y - Constant.BreakLayout.PaddingYButton, Constant.BreakLayout.WidthMainButton, Constant.BreakLayout.HeightMainButton))
button.image = NSImage(named: "background-break-button")
button = addButtonConfiguration(button, viewController: viewController, text: "START BREAK", color: NSColor(calibratedHue:0, saturation:0, brightness:0.22, alpha:1))
button.action = "onStartBreakButtonPressed"
return button
}
func breakLayoutCloseButton(viewController: NSViewController) -> NSButton {
var button = NSButton(frame: NSMakeRect(Constant.BreakLayout.SizeCloseButton, viewController.view.frame.height - (Constant.BreakLayout.SizeCloseButton * 2), Constant.BreakLayout.SizeCloseButton, Constant.BreakLayout.SizeCloseButton))
button = addButtonConfiguration(button, viewController: viewController, text: "", color: NSColor.whiteColor())
button.image = NSImage(named: "close-break-button")
button.action = "onCloseButtonPressed"
return button
}
func breakLayoutQuote(viewController: NSViewController, topButton: NSButton, randomNumber: Int) -> NSTextField {
var label = addBasicTextField(viewController, text: Quote.ArrayOfQuotes[randomNumber]["quote"]!)
label = addBreakLabelConfiguration(label, font: NSFont_Prodam.breakQuoteFont())
label.frame = NSMakeRect((viewController.view.frame.width - label.frame.width)/2, (topButton.frame.origin.y - label.frame.height)/2 + label.frame.height/2, label.frame.width, label.frame.height)
return label
}
func breakLayoutAuthorQuote(viewController: NSViewController, authorLabel: NSTextField, randomNumber: Int) -> NSTextField {
var label = addBasicTextField(viewController, text: Quote.ArrayOfQuotes[randomNumber]["author"]!)
label = addBreakLabelConfiguration(label, font: NSFont_Prodam.breakAuthorFont())
label.frame = NSMakeRect(authorLabel.frame.origin.x + authorLabel.frame.width - label.frame.width, authorLabel.frame.origin.y - label.frame.height, label.frame.width, label.frame.height)
return label
}
// MARK: Preferences View Controller: Layout
func layoutPreferencesView(view: NSView, viewController: NSViewController) {
layoutPreferencesLabel("Preferences", view: view)
let separatorView = layoutSeparatorView(view, frame: NSMakeRect(0, view.frame.height - 42.5, view.frame.width, 1))
let generalLabel = layoutGeneralLabelPreferences("General", view: view, separatorView: separatorView)
layoutLaunchLogin("Launch at login", view: view, separatorView: separatorView, anotherTextField: generalLabel, viewController: viewController)
let soundDoneLabel = layoutSoundWhenDonePreferences("Play notification sound", view: view, separatorView: separatorView, labelGeneral: generalLabel, viewController: viewController)
let separatorViewBottom = layoutSeparatorView(view, frame: NSMakeRect(0, soundDoneLabel.frame.origin.y - 30, view.frame.width, 1))
layoutFirstButtonPreferences(view, viewController: viewController)
layoutSecondButtonPreferences(view, viewController: viewController)
let labelName = layoutNameLabel(view, bottomSeparator: separatorViewBottom)
layoutSocialButtons(view, viewController: viewController, labelName: labelName)
}
func layoutPreferencesLabel(text: String, view: NSView) -> NSTextField {
let textField = layoutBasicTextField()
textField.stringValue = text
textField.font = NSFont(name: "Helvetica Neue", size: 18)
textField.alignment = NSTextAlignment.CenterTextAlignment
textField.sizeToFit()
textField.frame = NSMakeRect((view.frame.width - textField.frame.width)/2, view.frame.height - textField.frame.height - 10, textField.frame.width, textField.frame.height)
view.addSubview(textField)
return textField
}
func layoutSeparatorView(view: NSView, frame: NSRect) -> NSView {
let separatorView = NSView(frame: frame)
separatorView.wantsLayer = true
separatorView.layer?.backgroundColor = NSColor.lightGrayColor().CGColor
view.addSubview(separatorView)
return separatorView
}
func layoutGeneralLabelPreferences(text: String, view: NSView, separatorView: NSView) -> NSTextField {
let textField = layoutBasicTextField()
textField.stringValue = text
textField.textColor = NSColor(calibratedHue:0.67, saturation:0.06, brightness:0.49, alpha:1)
textField.font = NSFont(name: "Helvetica Neue", size: 15)
textField.alignment = NSTextAlignment.CenterTextAlignment
textField.sizeToFit()
textField.frame = NSMakeRect(100, separatorView.frame.origin.y - 40, textField.frame.width, textField.frame.height)
view.addSubview(textField)
return textField
}
func layoutLaunchLogin(text: String, view: NSView, separatorView: NSView, anotherTextField: NSTextField, viewController: NSViewController) {
let textField = layoutBasicTextField()
textField.stringValue = text
textField.textColor = NSColor(calibratedHue:1, saturation:0.04, brightness:0.19, alpha:1)
textField.font = NSFont(name: "Helvetica Neue", size: 15)
textField.alignment = NSTextAlignment.CenterTextAlignment
textField.sizeToFit()
textField.frame = NSMakeRect(150 + anotherTextField.frame.width, separatorView.frame.origin.y - 40, textField.frame.width, textField.frame.height)
view.addSubview(textField)
let switcher = layoutBasicSwitcher(NSMakeRect(textField.frame.origin.x - 17.5, textField.frame.origin.y, 18, 18), viewController: viewController)
switcher.action = "onSwitchLaunchLoginButtonPressed:"
switcher.integerValue = Int(self.userDefaults.boolForKey("startLaunch"))
view.addSubview(switcher)
}
func layoutSoundWhenDonePreferences(text: String, view: NSView, separatorView: NSView, labelGeneral: NSTextField, viewController: NSViewController) -> NSTextField {
let textField = layoutBasicTextField()
textField.stringValue = text
textField.textColor = NSColor(calibratedHue:1, saturation:0.04, brightness:0.19, alpha:1)
textField.font = NSFont(name: "Helvetica Neue", size: 15)
textField.alignment = NSTextAlignment.CenterTextAlignment
textField.sizeToFit()
textField.frame = NSMakeRect(150 + labelGeneral.frame.width, separatorView.frame.origin.y - 80, textField.frame.width, textField.frame.height)
view.addSubview(textField)
let switcher = layoutBasicSwitcher(NSMakeRect(textField.frame.origin.x - 17.5, textField.frame.origin.y, 18, 18), viewController: viewController)
switcher.action = "onSwitchPlaySoundButtonPressed:"
switcher.integerValue = Int(self.userDefaults.boolForKey("soundDone"))
view.addSubview(switcher)
return textField
}
func layoutNameLabel(view: NSView, bottomSeparator: NSView) -> NSTextField {
let textField = layoutBasicTextField()
textField.attributedStringValue = TextSplitter.checkNewStringForTextField("Ramon Gilabert", fontSize: 25)
textField.sizeToFit()
textField.frame = NSMakeRect((view.frame.width - textField.frame.width)/2, bottomSeparator.frame.origin.y - textField.frame.height - 25, textField.frame.width, textField.frame.height)
view.addSubview(textField)
return textField
}
func layoutFirstButtonPreferences(view: NSView, viewController: NSViewController) {
let button = layoutBasicButton(NSMakeRect(12, view.frame.height - 28, 16, 16), image: "button-close-preferences", viewController: viewController)
button.action = "onClosePreferencesButtonPressed"
view.addSubview(button)
}
func layoutSecondButtonPreferences(view: NSView, viewController: NSViewController) {
let button = layoutBasicButton(NSMakeRect(view.frame.width - 29, view.frame.height - 28, 17, 18), image: "button-quit-preferences", viewController: viewController)
button.action = "onQuitAppButtonPressed"
view.addSubview(button)
}
func layoutSocialButtons(view: NSView, viewController: NSViewController, labelName: NSTextField) {
let buttonTwitter = layoutBasicButton(NSMakeRect((view.frame.width - 64)/2 - 100, labelName.frame.origin.y - 83, 64, 66), image: "twitter-icon-social", viewController: viewController)
buttonTwitter.action = "onTwitterButtonPressed"
view.addSubview(buttonTwitter)
let buttonWebsite = layoutBasicButton(NSMakeRect((view.frame.width - 64)/2 + 100, labelName.frame.origin.y - 83, 64, 66), image: "dribbble-icon-social", viewController: viewController)
buttonWebsite.action = "onDribbbleButtonPressed"
view.addSubview(buttonWebsite)
let buttonEmail = layoutBasicButton(NSMakeRect((view.frame.width - 64)/2, labelName.frame.origin.y - 83, 64, 66), image: "email-icon-social", viewController: viewController)
buttonEmail.action = "onEmailButtonPressed"
view.addSubview(buttonEmail)
}
// MARK: Preferences View Controller: Helper methods
func layoutBasicTextField() -> NSTextField {
let textField = NSTextField()
textField.bordered = false
textField.bezeled = false
textField.editable = false
textField.selectable = false
textField.drawsBackground = false
textField.textColor = NSColor(calibratedHue:0, saturation:0, brightness:0.16, alpha:1)
return textField
}
func layoutBasicButton(frame: NSRect, image: String, viewController: NSViewController) -> NSButton {
let button = NSButton(frame: frame)
button.bordered = false
button.image = NSImage(named: image)
button.setButtonType(NSButtonType.MomentaryChangeButton)
button.target = viewController
return button
}
func layoutBasicSwitcher(frame: NSRect, viewController: NSViewController) -> NSButton {
let button = NSButton(frame: frame)
button.bordered = false
button.setButtonType(NSButtonType.SwitchButton)
button.title = ""
button.target = viewController
return button
}
// MARK: Main View Controller: Helper methods
func addButtonMainView(xPosition: CGFloat, width: CGFloat, alpha: CGFloat, text: NSString, viewController: NSViewController) -> NSButton {
var button = NSButton(frame: NSMakeRect(xPosition, Constant.WindowLayout.MinimumPaddingButton, width, Constant.WindowLayout.HeightOfButton))
button.image = NSImage(named: "background-\(text)-button")
button = addButtonConfiguration(button, viewController: viewController, text: text.uppercaseString, color: NSColor.whiteColor())
button.alphaValue = alpha
button.action = NSSelectorFromString("on\(text.capitalizedString)ButtonPressed")
return button
}
func addBreakLabelConfiguration(label: NSTextField, font: NSFont) -> NSTextField {
label.editable = false
label.selectable = false
label.textColor = NSColor_Prodam.colorBreakLabels()
label.alphaValue = Constant.BreakLayout.AlphaValueTextFields
label.focusRingType = NSFocusRingType.None
label.font = font
label.alignment = NSTextAlignment.CenterTextAlignment
label.sizeToFit()
return label
}
func addButtonConfiguration(button: NSButton, viewController: NSViewController, text: String, color: NSColor) -> NSButton {
button.bordered = false
button.attributedTitle = TextAttributter.attributedStringForButtons(text, font: "AvenirNext-DemiBold", color: color)
button.setButtonType(NSButtonType.MomentaryChangeButton)
button.alphaValue = Constant.BreakLayout.AlphaValueButtons
button.target = viewController
viewController.view.addSubview(button)
return button
}
func addBasicTextField(viewController: NSViewController, text: String) -> NSTextField {
let textField = NSTextField(frame: NSMakeRect(0, 0, 0, 0))
textField.bezeled = false
textField.bordered = false
textField.drawsBackground = false
textField.textColor = NSColor_Prodam.almostBlackColor()
textField.alignment = NSTextAlignment.CenterTextAlignment
textField.stringValue = text
viewController.view.addSubview(textField)
return textField
}
}
| mit | d09cbd0ada0da08b09d4765247af6d86 | 51.132678 | 307 | 0.726553 | 4.780982 | false | false | false | false |
ElSquash/weavr-team | CustomStuff/Artwork.swift | 1 | 1452 | //
// Artwork.swift
// Weavr
//
// Created by Joshua Peeling on 3/23/16.
// Copyright © 2016 Evan Dekhayser. All rights reserved.
//
import Foundation
import MapKit
class Artwork: NSObject, MKAnnotation {
let title: String?
let locationName: String
let discipline: String
let coordinate: CLLocationCoordinate2D
init(title: String, locationName: String, discipline: String, coordinate: CLLocationCoordinate2D) {
self.title = title
self.locationName = locationName
self.discipline = discipline
self.coordinate = coordinate
super.init()
}
class func fromJSON(json: [JSONValue]) -> Artwork? {
// 1
var title: String
if let titleOrNil = json[16].string {
title = titleOrNil
}
else {
title = ""
}
let locationName = json[12].string
let discipline = json[15].string
// 2
let latitude = (json[18].string! as NSString).doubleValue
let longitude = (json[19].string! as NSString).doubleValue
let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
// 3
return Artwork(title: title, locationName: locationName!, discipline: discipline!, coordinate: coordinate)
}
var subtitle: String? {
return locationName
}
} | mit | e066cbf0d22e47e844c1ee825c2f0756 | 24.473684 | 114 | 0.589249 | 4.902027 | false | false | false | false |
CarterPape/Photo-Organizer | Photo Organizer/main.swift | 1 | 1455 | //
// main.swift
// Photo Organizer
//
// Created by Carter Pape on 7/11/15.
// Copyright (c) 2015 Carter Pape. All rights reserved.
//
import Foundation
var absSourceDir: String
var absDestinationSpace: String
if CommandLine.arguments.count == 3 {
absSourceDir = CommandLine.arguments[1]
absDestinationSpace = CommandLine.arguments[2]
}
else {
print("Bad argument count: \(CommandLine.arguments.count - 1)\n" +
"(we require 2: first, the source directory, and second, the destination space)")
exit(1)
}
if !absSourceDir.hasSuffix("/") {
absSourceDir += "/"
}
if !absDestinationSpace.hasSuffix("/") {
absDestinationSpace += "/"
}
var fileManager = FileManager.default
var fileEnumerator = fileManager.enumerator(atPath: absSourceDir)
while let srcRelPath = fileEnumerator?.nextObject() as? String {
let srcRelPathAsURL = URL(fileURLWithPath: srcRelPath)
let srcFile = FileBean(fileManager: fileManager,
absPath: absSourceDir + srcRelPath)
if srcFile.fileType != "NSFileTypeDirectory" && !srcFile.fileName.hasPrefix(".") {
var destination = FileDestination(space: absDestinationSpace,
dates: srcFile.dates,
originalFileName: srcRelPathAsURL.lastPathComponent)
var fileMover = FileMover(srcFile: srcFile,
destination: destination,
fileManager: fileManager)
fileMover.moveFileToDestination()
}
}
| mit | f9f2d0e9da4dc808862f19ebe2f09957 | 27.529412 | 89 | 0.685911 | 4.169054 | false | false | false | false |
oliverbarreto/PersonalFavs | PersonalFavs/PersonalFavs/Classes/Models/DataStoreManager.swift | 1 | 14365 | //
// DataStoreManager.swift
// PersonalFavs
//
// Created by David Oliver Barreto Rodríguez on 23/6/17.
// Copyright © 2017 David Oliver Barreto Rodríguez. All rights reserved.
//
import Foundation
class DataStoreManager {
// MARK: - Shared Singleton Instance
static let shared = DataStoreManager()
// MARK: Init - It is a private init, it's singleton
private init() {
// initWithDummyValues()
}
// MARK: - Internal Storage
private var favFeeds:[FavFeed] = []
private var personalGroups:[Group] = []
private var sharedGroups:[Group] = []
private var recommendedGroups:[Group] = []
private var favs: [Fav] = []
// Persistency
let personalGroupsFileName = "personalGroupsDataFile"
let sharedGroupsFileName = "sharedGroupsDataFile"
let recommendedGroupsFileName = "recommendedGroupsDataFile"
let favsFileName = "favsDataFile"
// MARK: - FavFeeds Group CRUD Methods
func getFavFeeds() -> [FavFeed] {
return favFeeds
}
// MARK: - Personal Group CRUD Methods
func getPersonalGroups() -> [Group] {
return personalGroups
}
func deletePersonalGroup(atIndex index: Int) {
if (personalGroups.count >= index) {
personalGroups.remove(at: index)
}
}
func addPersonalGroup(group: Group, atIndex index: Int) {
if (personalGroups.count >= index) {
personalGroups.append(group)
} else {
personalGroups.insert(group, at: index)
}
}
// MARK: - Shared Group CRUD Methods
func getSharedGroups() -> [Group] {
return sharedGroups
}
func deleteSharedGroup(atIndex index: Int) {
if (sharedGroups.count >= index) {
sharedGroups.remove(at: index)
}
}
func addSharedGroup(group: Group, atIndex index: Int) {
if (sharedGroups.count >= index) {
sharedGroups.append(group)
} else {
sharedGroups.insert(group, at: index)
}
}
// MARK: - Recommended Group CRUD Methods
func getRecommendedGroups() -> [Group] {
return recommendedGroups
}
func deleteRecommendedGroup(atIndex index: Int) {
if (recommendedGroups.count >= index) {
recommendedGroups.remove(at: index)
}
}
func addRecommendedGroup(group: Group, atIndex index: Int) {
if (recommendedGroups.count >= index) {
recommendedGroups.append(group)
} else {
recommendedGroups.insert(group, at: index)
}
}
// MARK: - Favs CRUD Methods
func getFavs() -> [Fav] {
return favs
}
func getFavs(forGroup group: Group) -> [Fav] {
let found = favs.filter({ $0.groupName == group.name })
return found
}
func deleteFav(atIndex index: Int) {
favs.remove(at: index)
}
func addFav(fav: Fav, atIndex index: Int) {
favs.insert(fav, at: index)
}
// MARK: - Utility Methods: Persistency
func archiveModel () {
// Persist using Archiving/Unarchiving Objetcs to filesystem
let filemanager = FileManager.default
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
print("*** Writing ***")
var filepath = dir.appendingPathComponent(personalGroupsFileName)
var data = NSKeyedArchiver.archivedData(withRootObject: personalGroups)
filemanager.createFile(atPath: filepath.path, contents: data, attributes: nil)
filepath = dir.appendingPathComponent(sharedGroupsFileName)
data = NSKeyedArchiver.archivedData(withRootObject: sharedGroups)
filemanager.createFile(atPath: filepath.path, contents: data, attributes: nil)
filepath = dir.appendingPathComponent(recommendedGroupsFileName)
data = NSKeyedArchiver.archivedData(withRootObject: recommendedGroups)
filemanager.createFile(atPath: filepath.path, contents: data, attributes: nil)
filepath = dir.appendingPathComponent(favsFileName)
data = NSKeyedArchiver.archivedData(withRootObject: favs)
filemanager.createFile(atPath: filepath.path, contents: data, attributes: nil)
}
}
func unarchiveModel() {
let filemanager = FileManager.default
if let dir = filemanager.urls(for: .documentDirectory, in: .userDomainMask).first {
print("*** Reading ***")
var filepath = dir.appendingPathComponent(personalGroupsFileName)
guard let readPersonalGroups = NSKeyedUnarchiver.unarchiveObject(withFile: filepath.path) as? [Group] else { return }
print(readPersonalGroups)
filepath = dir.appendingPathComponent(sharedGroupsFileName)
guard let readSharedGroups = NSKeyedUnarchiver.unarchiveObject(withFile: filepath.path) as? [Group] else { return }
print(readSharedGroups)
filepath = dir.appendingPathComponent(recommendedGroupsFileName)
guard let readRecommendedGroups = NSKeyedUnarchiver.unarchiveObject(withFile: filepath.path) as? [Group] else { return }
print(readRecommendedGroups)
filepath = dir.appendingPathComponent(favsFileName)
guard let readFavs = NSKeyedUnarchiver.unarchiveObject(withFile: filepath.path) as? [Fav] else { return }
print("*** Reading Favs from disk ***")
print(readFavs)
// Uncomment if it is not the first run of the app and you don't need to preload data model
personalGroups = readPersonalGroups
sharedGroups = readSharedGroups
recommendedGroups = readRecommendedGroups
favs = readFavs
print(favs)
}
}
// MARK: - Utility Methods: Dummy DataBase
func initWithDummyValues() {
loadFavFeeds()
// Load Dummy Groups
personalGroups = loadDummyGroups(withFeedType: .personal)
sharedGroups = loadDummyGroups(withFeedType: .shared)
recommendedGroups = loadDummyGroups(withFeedType: .recommended)
// Load Dummy Favs for all groups
for group in personalGroups {
loadDummyFavs(forGroup: group)
}
for group in sharedGroups {
loadDummyFavs(forGroup: group)
}
for group in recommendedGroups{
loadDummyFavs(forGroup: group)
}
}
func loadFavFeeds() {
favFeeds = [FavFeed(feedType: .personal), FavFeed(feedType: .shared),FavFeed(feedType: .recommended)]
}
func loadDummyGroups(withFeedType feedType: FavFeed.FeedType) -> [Group] {
let family = Group(name: "Family", color: Config.Colors.FlatColors.carrot, iconPath: "Icon_Family")
let work = Group(name: "Work", color: Config.Colors.FlatColors.peterRiver, iconPath: "Icon_Work")
let gym = Group(name: "Gym", color: Config.Colors.FlatColors.wisteria, iconPath: "Icon_Gym")
let bday = Group(name: "Miguel's Birthday", color: Config.Colors.FlatColors.midnightBlue, iconPath: "Icon_GroupOfFriends")
let wwdc = Group(name: "WWDC 2017", color: Config.Colors.FlatColors.orange, iconPath: "Icon_GroupOfFriends")
let team = Group(name: "Nautico Team Party", color: Config.Colors.FlatColors.greenSea, iconPath: "Icon_Sports")
let wheretoeat = Group(name: "Where To Eat", color: Config.Colors.FlatColors.pomegranate, iconPath: "Icon_Food")
let excursions = Group(name: "Cool Excursions", color: Config.Colors.FlatColors.peterRiver, iconPath: "Icon_Earth")
switch feedType.rawValue {
case "personal":
return [family, work, gym, bday]
case "shared":
return [wwdc, team]
case "recommended":
return [wheretoeat, excursions]
default:
return [family, work, gym, bday]
}
}
private func loadDummyFavs(forGroup group: Group) {
let oli = Fav(givenName: "Oliver Barreto", familyName: "Barreto", value: "+34610700505", tag: "personal", type: "iPhone", imageName:"Oliver", groupName: group.name!)
let oliMail = Fav(givenName: "Oliver eMail", familyName: "Barreto", value: "[email protected]", tag: "personal", type: "eMail", imageName:"Oliver", groupName: group.name!)
let oliverInnovation = Fav(givenName: "Oliver Atos", familyName: "Atos ARI", value: "[email protected]", tag: "Work", type: "eMail", imageName:"OliverInnovation", groupName: group.name!)
let oliverInnovationText = Fav(givenName: "Oliver Message", familyName: "Personal", value: "[email protected]", tag: "Work", type: "Text", imageName:"Oliver", groupName: group.name!)
let ana = Fav(givenName: "Ana Acosta", familyName: "Acosta", value: "+34670875979", tag: "personal", type: "iPhone", imageName:"Ana", groupName: group.name!)
let anaText = Fav(givenName: "Ana Acosta", familyName: "Acosta", value: "+34670875979", tag: "personal", type: "Text", imageName:"Ana", groupName: group.name!)
let anaFaceTime = Fav(givenName: "Ana FaceTime", familyName: "Acosta", value: "+34670875979", tag: "personal", type: "FaceTime", imageName:"Ana", groupName: group.name!)
let anaWhatsapp = Fav(givenName: "Ana Whatsapp", familyName: "Acosta", value: "+34670875979", tag: "personal", type: "Whatsapp", imageName:"Ana", groupName: group.name!)
let miguelBFaceTimeAudio = Fav(givenName: "Miguel FaceTimeAudio", familyName: "Acosta", value: "[email protected]", tag: "personal", type: "FaceTimeAudio", imageName:"MiguelBA", groupName: group.name!)
let mima = Fav(givenName: "Mima Rodríguez", familyName: "Rodirguez", value: "+34697414021", tag: "personal", type: "Phone", imageName:"Mima", groupName: group.name!)
let miguelB = Fav(givenName: "Miguel Barreto", familyName: "Barreto", value: "+34636885214", tag: "personal", type: "Phone", imageName:"MiguelBA", groupName: group.name!)
let miguelH = Fav(givenName: "Miguel Herrera", familyName: "Herrera", value: "+34600281097", tag: "personal", type: "Phone", imageName:"MiguelHerrera", groupName: group.name!)
let raul = Fav(givenName: "Raúl Barreto", familyName: "Barreto", value: "+34610700505", tag: "personal", type: "Phone", imageName:"RaulBA", groupName: group.name!)
let mary = Fav(givenName: "Mary Luis Peña", familyName: "Luis Peña", value: "+34670780741", tag: "personal", type: "Phone", imageName:"Mary", groupName: group.name!)
let pureza = Fav(givenName: "Colegio Pureza", familyName: "Pureza", value: "+34922277763", tag: "personal", type: "Phone", imageName:"PurezaMaria", groupName: group.name!)
let restauranteLaHierbita = Fav(givenName: "La Hierbita", familyName: "Restaurante", value: "+34922244617", tag: "personal", type: "Phone", imageName:"Restaurante_LaHierbita", groupName: group.name!)
let restauranteLaHierbitaMap = Fav(givenName: "La Hierbita", familyName: "Restaurante", value: "www.google.es/maps/place/Restaurante+La+Hierbita/@28.4661701,-16.25194,17z/data=!3m1!4b1!4m5!3m4!1s0xc41cb7da9cbb077:0xeb50cabbcc6989ec!8m2!3d28.4661701!4d-16.2497513", tag: "personal", type: "Map", imageName:"Restaurante_LaHierbita", groupName: group.name!)
let restauranteLaHierbitaWeb = Fav(givenName: "La Hierbita", familyName: "Restaurante", value: "www.lahierbita.com", tag: "personal", type: "Web", imageName:"Restaurante_LaHierbita", groupName: group.name!)
let restaurantePanzaBurroGastrotasca = Fav(givenName: "Panzaburro Gastrotasca", familyName: "Restaurante", value: "+34674962041", tag: "personal", type: "Phone", imageName:"Restaurante_Panzaburro", groupName: group.name!)
let restauranteThai = Fav(givenName: "Tailandes Tarathai", familyName: "Restaurante", value: "+34922293698", tag: "restaurantes", type: "Phone", imageName:"Restaurante_Thai", groupName: group.name!)
let restauranteLibanes = Fav(givenName: "El Capricho Libanes", familyName: "Restaurante", value: "+34922252993", tag: "restaurantes", type: "Phone", imageName:"Restaurante_Libanes", groupName: group.name!)
let bicisElParque = Fav(givenName: "Bicis El Parque", familyName: "Bicicletas", value: "+34942802292", tag: "Ocio", type: "Phone", imageName:"BicisElParque", groupName: group.name!)
let telefericoElTeide = Fav(givenName: "Telférico El Teide", familyName: "Bicicletas", value: "+34922010440", tag: "Ocio", type: "Phone", imageName:"TelefericoElTeide", groupName: group.name!)
let wwdc2017 = Fav(givenName: "WWDC 2017", familyName: "Apple", value: "[email protected]", tag: "Work", type: "eMail", imageName:"WWDC", groupName: group.name!)
guard let groupName = group.name else {return}
switch groupName {
case "Family", "Miguel's Birthday", "Nautico Team Party":
favs.append(contentsOf: [ana, anaText, oli, miguelB, miguelH, raul, mima, mary, pureza, oliMail, anaFaceTime, miguelBFaceTimeAudio, anaWhatsapp])
case "Work":
favs.append(contentsOf: [oliverInnovation, oliverInnovationText])
case "Gym":
favs.append(contentsOf: [ana, oli])
case "WWDC 2017":
favs.append(contentsOf: [wwdc2017])
case "Where To Eat", "Cool Excxursions":
favs.append(contentsOf: [restauranteLaHierbita,restaurantePanzaBurroGastrotasca, restauranteLibanes, restauranteThai, restauranteLaHierbitaWeb, restauranteLaHierbitaMap])
case "Cool Excursions":
favs.append(contentsOf: [bicisElParque, telefericoElTeide])
default:
return
}
}
}
| apache-2.0 | d73930751ee8bbde8df42261335fca3c | 46.226974 | 362 | 0.633071 | 4.024951 | false | false | false | false |
narner/AudioKit | Playgrounds/AudioKitPlaygrounds/Playgrounds/Filters.playground/Pages/High Pass Filter Operation.xcplaygroundpage/Contents.swift | 1 | 1067 | //: ## High Pass Filter Operation
//:
import AudioKitPlaygrounds
import AudioKit
//: Noise Example
// Bring down the amplitude so that when it is mixed it is not so loud
let whiteNoise = AKWhiteNoise(amplitude: 0.1)
let filteredNoise = AKOperationEffect(whiteNoise) { whiteNoise, _ in
let halfPower = AKOperation.sineWave(frequency: 0.2).scale(minimum: 12_000, maximum: 100)
return whiteNoise.highPassFilter(halfPowerPoint: halfPower)
}
//: Music Example
let file = try AKAudioFile(readFileName: playgroundAudioFiles[0])
let player = try AKAudioPlayer(file: file)
player.looping = true
let filteredPlayer = AKOperationEffect(player) { player, _ in
let halfPower = AKOperation.sineWave(frequency: 0.2).scale(minimum: 12_000, maximum: 100)
return player.highPassFilter(halfPowerPoint: halfPower)
}
//: Mixdown and playback
let mixer = AKDryWetMixer(filteredNoise, filteredPlayer, balance: 0.5)
AudioKit.output = mixer
AudioKit.start()
whiteNoise.start()
player.play()
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
| mit | 8037bc795c759efa264ffbedf322e6f5 | 32.34375 | 93 | 0.774133 | 4.072519 | false | false | false | false |
freak4pc/netfox | netfox_ios_demo/TextViewController.swift | 1 | 2656 | //
// TextViewController.swift
// netfox_ios_demo
//
// Created by Nathan Jangula on 10/12/17.
// Copyright © 2017 kasketis. All rights reserved.
//
import UIKit
class TextViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
var session: URLSession!
var dataTask: URLSessionDataTask?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBAction func tappedLoad(_ sender: Any) {
dataTask?.cancel()
if session == nil {
session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
}
guard let url = URL(string: "https://api.chucknorris.io/jokes/random") else { return }
var request = URLRequest(url: url)
request.httpBody = "TEST".data(using: .utf8)
dataTask = session.dataTask(with: request) { (data, response, error) in
if let error = error {
self.handleCompletion(error: error.localizedDescription, data: data)
} else {
guard let data = data else { self.handleCompletion(error: "Invalid data", data: nil); return }
guard let response = response as? HTTPURLResponse else { self.handleCompletion(error: "Invalid response", data: data); return }
guard response.statusCode >= 200 && response.statusCode < 300 else { self.handleCompletion(error: "Invalid response code", data: data); return }
self.handleCompletion(error: error?.localizedDescription, data: data)
}
}
dataTask?.resume()
}
private func handleCompletion(error: String?, data: Data?) {
DispatchQueue.main.async {
if let error = error {
NSLog(error)
return
}
if let data = data {
do {
let dict = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
if let message = dict?["value"] as? String {
self.textView.text = message
}
} catch {
}
}
}
}
}
extension TextViewController : URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
}
}
| mit | 81659d432b2f1744d2232296e9fa7f42 | 34.878378 | 186 | 0.577024 | 5.15534 | false | false | false | false |
asm-products/cakebird | CakeBird/StreamViewController.swift | 1 | 1807 | //
// StreamViewController.swift
// CakeBird
//
// Created by Rhett Rogers on 8/23/14.
// Copyright (c) 2014 Lyokotech. All rights reserved.
//
import Foundation
import UIKit
import SwifteriOS
class StreamViewController: SuperViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var tweetStream: UICollectionView!
var tweets: [Tweet] = [Tweet]()
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
if let user = UserManager.sharedInstance(){
user.getUserStream({ (error, jsonTweets) -> Void in
if error != nil {
println(error)
}
if let jTweets = jsonTweets {
for jsonTweet in jTweets {
self.tweets.append(Tweet(jsonTweet: jsonTweet))
}
}
self.tweetStream.reloadData()
})
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tweets.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("tweet", forIndexPath: indexPath) as TweetCell
var tweet = tweets[indexPath.item]
cell.text.text = tweet.text
cell.favoriteCountLabel.text = tweet.favoriteCount
cell.retweetCountLabel.text = tweet.retweetCount
cell.screenNameLabel.text = "@bob" //tweet.author
cell.realNameLabel.text = "Bob" //tweet.authorName
// cell.authorAvatarView.image = tweet.authorAvatar
return cell
}
} | agpl-3.0 | 822d7db62e6b5f27aecc9bde11a639c3 | 26.393939 | 128 | 0.6829 | 4.755263 | false | false | false | false |
hanwanjie853710069/Easy-living | 易持家/Class/Class_project/ELLogin/Controller/ELRegisteredVC.swift | 1 | 4176 | //
// ELRegisteredVC.swift
// EasyLiving
//
// Created by 王木木 on 16/6/8.
// Copyright © 2016年 王木木. All rights reserved.
//
import UIKit
class ELRegisteredVC: CMBaseViewController {
var nextView: ELloginView!
var nameView: ELloginView!
var psWdView: ELloginView!
var loginBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.title = "注册"
creatTextFiled()
}
func creatTextFiled(){
nextView = ELloginView.init(frame: CGRectMake(0, 0, 0, 0),
placeholder: "请输入账户名",
imageName: "zhanghao")
self.view.addSubview(nextView)
nextView.autoPinEdgeToSuperviewEdge(.Left, withInset: 10)
nextView.autoPinEdgeToSuperviewEdge(.Right, withInset: 10)
nextView.autoPinEdgeToSuperviewEdge(.Top, withInset: 114)
nextView.autoSetDimension(.Height, toSize: 40)
nameView = ELloginView.init(frame: CGRectMake(0, 0, 0, 0),
placeholder: "请输入密码",
imageName: "passWord")
self.view.addSubview(nameView)
nameView.autoPinEdgeToSuperviewEdge(.Left, withInset: 10)
nameView.autoPinEdgeToSuperviewEdge(.Right, withInset: 10)
nameView.autoPinEdge(.Top, toEdge: .Bottom, ofView: nextView, withOffset: 20)
nameView.autoSetDimension(.Height, toSize: 40)
psWdView = ELloginView.init(frame: CGRectMake(0, 0, 0, 0),
placeholder: "请再次输入密码",
imageName: "passWord")
self.view.addSubview(psWdView)
psWdView.autoPinEdgeToSuperviewEdge(.Left, withInset: 10)
psWdView.autoPinEdgeToSuperviewEdge(.Right, withInset: 10)
psWdView.autoPinEdge(.Top, toEdge: .Bottom, ofView: nameView, withOffset: 20)
psWdView.autoSetDimension(.Height, toSize: 40)
loginBtn = UIButton()
loginBtn.layer.cornerRadius = 6
loginBtn.layer.masksToBounds = true
loginBtn.setTitle("注册", forState: .Normal)
self.view.addSubview(loginBtn)
loginBtn.setBackgroundImage(getColorImageWithColor(UIColor.init(red: 0.32,
green: 0.67,
blue: 0.90,
alpha: 1.00)),
forState: .Normal)
loginBtn.autoPinEdgeToSuperviewEdge(.Left, withInset: 30)
loginBtn.autoPinEdgeToSuperviewEdge(.Right, withInset: 30)
loginBtn.autoPinEdge(.Top, toEdge: .Bottom, ofView: psWdView, withOffset: 40)
loginBtn.autoSetDimension(.Height, toSize: 40)
loginBtn.addTarget(self, action: #selector(self.registeredTouch), forControlEvents: .TouchUpInside)
}
func registeredTouch(){
if (nextView.textFiled.text?.characters.count == 0) {
SVProgressHUD.showInfoWithStatus("请输入用户名")
return
}
if (nameView.textFiled.text?.characters.count == 0) {
SVProgressHUD.showInfoWithStatus("请输入密码")
return
}
if (psWdView.textFiled.text?.characters.count == 0) {
SVProgressHUD.showInfoWithStatus("请输入确认密码")
return
}
if nameView.textFiled.text != psWdView.textFiled.text{
SVProgressHUD.showInfoWithStatus("两次密码输入不一致")
return
}
modifyTheUserData("age", modifyValue: "0")
modifyTheUserData("nickName", modifyValue: nextView.textFiled.text!)
modifyTheUserData("passWord", modifyValue: psWdView.textFiled.text!)
modifyTheUserData("sex", modifyValue: "男")
modifyTheUserData("userName", modifyValue: nextView.textFiled.text!)
SVProgressHUD.showInfoWithStatus("注册成功")
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
}
}
| apache-2.0 | 68966b489a6777596cbfa2b420a69aa9 | 36.878505 | 107 | 0.599803 | 4.836516 | false | false | false | false |
immortal79/BetterUpdates | BetterUpdatesStartupLauncher/AppDelegate.swift | 1 | 1249 | //
// AppDelegate.swift
// BetterUpdatesStartupLauncher
//
// Created by Philippe Weidmann on 16.02.17.
// Copyright © 2017 Philippe Weidmann. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
let mainAppIdentifier = "ch.immortal.BetterUpdates"
let running = NSWorkspace.shared().runningApplications
var alreadyRunning = false
for app in running {
if app.bundleIdentifier == mainAppIdentifier {
alreadyRunning = true
break
}
}
if !alreadyRunning {
DistributedNotificationCenter.default().addObserver(self, selector: #selector(self.terminate), name: Notification.Name("killme"), object: mainAppIdentifier)
NSWorkspace.shared().launchApplication("/Applications/BetterUpdates.app")
}
else {
self.terminate()
}
}
func terminate() {
NSApp.terminate(nil)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| mit | c622d5a3f718cee8a24c8acbf83a966e | 25.553191 | 168 | 0.630609 | 5.333333 | false | false | false | false |
tad-iizuka/swift-sdk | Source/NaturalLanguageUnderstandingV1/Models/Parameters.swift | 1 | 4390 | /**
* Copyright IBM Corporation 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import RestKit
/** JSON object containing request parameters */
public struct Parameters: JSONEncodable {
/// The plain text to analyze.
public let text: String?
/// The HTML file to analyze.
public let html: URL?
/// The web page to analyze.
public let url: String?
/// Specific features to analyze the document for.
public let features: Features
/// Remove website elements, such as links, ads, etc.
public let clean: Bool?
/// XPath query for targeting nodes in HTML.
public let xpath: String?
/// Whether to use raw HTML content if text cleaning fails.
public let fallbackToRaw: Bool?
/// Whether or not to return the analyzed text.
public let returnAnalyzedText: Bool?
/// ISO 639-1 code indicating the language to use in the analysis
public let language: String?
/// Error domain for when errors are thrown.
private let errorDomain = "com.watsonplatform.naturalLanguageUnderstanding"
/**
Initialize a `Parameters` with all member variables. It is required to have either the text,
html, or url parameter.
- parameter text: The plain text to analyze.
- parameter html: The HTML file to analyze.
- parameter url: The web page to analyze.
- parameter features: Specific features to analyze the document for.
- parameter clean: Remove website elements, such as links, ads, etc.
- parameter xpath: XPath query for targeting nodes in HTML.
- parameter fallbackToRaw: Whether to use raw HTML content if text cleaning fails.
- parameter returnAnalyzedText: Whether or not to return the analyzed text.
- parameter language: ISO 639-1 code indicating the language to use in the analysis.
- returns: An initialized `Parameters`.
*/
public init(
features: Features,
text: String? = nil,
html: URL? = nil,
url: String? = nil,
clean: Bool? = nil,
xpath: String? = nil,
fallbackToRaw: Bool? = nil,
returnAnalyzedText: Bool? = nil,
language: String? = nil)
{
self.text = text
self.html = html
self.url = url
self.features = features
self.clean = clean
self.xpath = xpath
self.fallbackToRaw = fallbackToRaw
self.returnAnalyzedText = returnAnalyzedText
self.language = language
}
/// Used internally to serialize a `Parameters` model to JSON.
public func toJSONObject() -> Any {
var json = [String: Any]()
json["features"] = features.toJSONObject()
if let text = text { json["text"] = text }
if let html = html {
let htmlAsString = try? docAsString(document: html)
json["html"] = htmlAsString
}
if let url = url { json["url"] = url }
if let clean = clean { json["clean"] = clean }
if let xpath = xpath { json["xpath"] = xpath }
if let fallbackToRaw = fallbackToRaw { json["fallback_to_raw"] = fallbackToRaw }
if let returnAnalyzedText = returnAnalyzedText { json["return_analyzed_text"] = returnAnalyzedText }
if let language = language { json["language"] = language }
return json
}
/// Build HTML as string.
private func docAsString(document: URL) throws -> String {
guard let docAsString = try? String(contentsOfFile: document.relativePath, encoding:.utf8) else {
let failureReason = "Unable to convert document to string."
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
let error = NSError(domain: errorDomain, code: 0, userInfo: userInfo)
throw error
}
return docAsString
}
}
| apache-2.0 | 6f964ecca0ea9951e562b235a94e5f59 | 35.583333 | 108 | 0.648064 | 4.596859 | false | false | false | false |
lulee007/GankMeizi | GankMeizi/Recent/RecentArticlesViewController.swift | 1 | 9137 | //
// ViewController.swift
// GankMeizi
//
// Created by 卢小辉 on 16/5/16.
// Copyright © 2016年 lulee007. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
import CHTCollectionViewWaterfallLayout
import MJRefresh
import CocoaLumberjack
import SDWebImage
import IDMPhotoBrowser
import Toast_Swift
extension String {
func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: CGFloat.max)
let boundingBox = self.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return boundingBox.height
}
}
class RecentArticlesViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate, CHTCollectionViewDelegateWaterfallLayout {
let whiteSpace: CGFloat = 8.0
let articleModel = RecentArticlesModel()
let disposeBag = DisposeBag()
@IBOutlet weak var articleCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
registerNibs()
setupCollectionView()
//refresh
self.articleCollectionView.mj_header.executeRefreshingCallback()
}
//MARK: setup uiview
func setupCollectionView() {
self.articleCollectionView.dataSource = self
self.articleCollectionView.delegate = self
let layout = CHTCollectionViewWaterfallLayout()
layout.minimumColumnSpacing = whiteSpace
layout.minimumInteritemSpacing = whiteSpace
// 设置外边距
layout.sectionInset = UIEdgeInsetsMake(whiteSpace, whiteSpace, whiteSpace, whiteSpace)
self.articleCollectionView.alwaysBounceVertical = true
self.articleCollectionView.collectionViewLayout = layout
//刷新头部
self.articleCollectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
if self.articleCollectionView.mj_footer.isRefreshing() {
DDLogDebug("mj_footer isRefreshing")
self.articleCollectionView.mj_header.endRefreshing()
return
}
self.articleModel.refresh()
.subscribe(
onNext: { (entities) in
self.articleCollectionView.mj_footer.resetNoMoreData()
self.articleCollectionView.reloadData()
},
onError: { (error) in
print(error)
ErrorTipsHelper.sharedInstance.requestError(self.view)
self.articleCollectionView.mj_header.endRefreshing()
},
onCompleted: {
self.articleCollectionView.mj_header.endRefreshing()
DDLogDebug("on complated")
},
onDisposed: {
})
.addDisposableTo(self.disposeBag)
})
//加载更多底部
let mjFooter = MJRefreshAutoStateFooter.init(refreshingBlock: {
if self.articleCollectionView.mj_header.isRefreshing() {
DDLogDebug("mj_footer isRefreshing")
self.articleCollectionView.mj_footer.endRefreshing()
return
}
self.articleModel.loadMore()
.subscribe(
onNext: { (entities) in
if entities.isEmpty {
self.articleCollectionView.mj_footer.endRefreshingWithNoMoreData()
}else {
self.articleCollectionView.mj_footer.endRefreshing()
}
self.articleCollectionView.reloadData()
},
onError: { (error) in
ErrorTipsHelper.sharedInstance.requestError(self.view)
self.articleCollectionView.mj_footer.endRefreshing()
print(error)
},
onCompleted: {
DDLogDebug("on complated")
},
onDisposed: {
})
.addDisposableTo(self.disposeBag)
})
self.articleCollectionView.mj_footer = mjFooter
self.articleCollectionView.mj_footer.hidden = true
}
// 注册 collection view cell
func registerNibs() {
let viewNib = UINib(nibName: "ArticleCollectionViewCell", bundle: nil)
self.articleCollectionView.registerNib(viewNib, forCellWithReuseIdentifier: "cell")
}
//MARK: delegate
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// 数据为空 隐藏 footer
self.articleCollectionView.mj_footer.hidden = self.articleModel.articleEntities.count == 0
return self.articleModel.articleEntities.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! ArticleCollectionViewCell
cell.backgroundColor = UIColor.whiteColor()
cell.title.text = self.articleModel.articleEntities[indexPath.item].desc!
cell.image.clipsToBounds = true
cell.image.sd_setImageWithURL(NSURL(string: self.articleModel.articleEntities[indexPath.item].url!)!, placeholderImage: nil, options: SDWebImageOptions.AvoidAutoSetImage, completed: { (image, error, cacheType, url) in
if error == nil {
cell.image.image = image
if cacheType == SDImageCacheType.None {
cell.image.alpha = 0
UIView.animateWithDuration(0.5, animations: {
cell.image.alpha = 1
})
}else{
cell.image.alpha = 1
}
}
})
let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(RecentArticlesViewController.imageTapped(_:)))
cell.image.tag = indexPath.item
cell.image.userInteractionEnabled = true
cell.image.addGestureRecognizer(tapGestureRecognizer)
// 设置圆角
cell.anchorView.layer.cornerRadius = 3;
cell.anchorView.layer.masksToBounds = true
//在self.layer上设置阴影
cell.layer.cornerRadius = 3;
cell.layer.shadowColor = UIColor.darkGrayColor().CGColor;
cell.layer.masksToBounds = false;
cell.layer.shadowOffset = CGSizeMake(1, 1.5);
cell.layer.shadowRadius = 2;
cell.layer.shadowOpacity = 0.75;
cell.layer.shadowPath = UIBezierPath.init(roundedRect: cell.layer.bounds, cornerRadius: 3).CGPath
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let entity = self.articleModel.articleEntities[indexPath.item]
let controller = DailyArticleViewController.buildController(entity.publishedAt!)
self.navigationController?.pushViewController(controller, animated: true)
DDLogDebug("\(indexPath.item)")
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let desc = self.articleModel.articleEntities[indexPath.item].desc!
let width = (articleCollectionView.bounds.width - whiteSpace * 3) / 2
let height = desc.heightWithConstrainedWidth(width, font: UIFont.systemFontOfSize(15))
// height = img.height+ text.height + text.paddingTop
return CGSize.init(width: width, height: width + height + 10.0)
}
static func buildController() -> RecentArticlesViewController{
let controller = ControllerUtil.loadViewControllerWithName("RecentArticles", sbName: "Main") as! RecentArticlesViewController
controller.title = "最新"
return controller
}
//MARK: 私有方法
func imageTapped(sender:UITapGestureRecognizer) {
if ((sender.view?.isKindOfClass(UIImageView)) == true){
let entity = articleModel.articleEntities[(sender.view?.tag)!]
let photoBrowser = IDMPhotoBrowser.init(photoURLs: [NSURL(string: entity.url!)!], animatedFromView: sender.view)
photoBrowser.usePopAnimation = true
self.presentViewController(photoBrowser, animated: true, completion: nil)
}
}
}
| mit | 32433da68173fe30b241b5de3b497375 | 38.684211 | 225 | 0.611516 | 5.730209 | false | false | false | false |
iosliutingxin/DYVeideoVideo | DYZB/DYZB/Classes/Tools/BaseView/Eject01.swift | 1 | 2368 | //
// Eject01.swift
// DYZB
//
// Created by 李孔文 on 2018/2/26.
// Copyright © 2018年 iOS _Liu. All rights reserved.
//
import UIKit
class Eject01: UIView {
var dataArray : NSArray = []
var baseView : UIView = UIView()
var closeButtonView : UIView = UIView()
var closeButton : UIButton = UIButton()
var grayView : UIView = UIView()
}
//功能扩展
extension Eject01 {
func setTitle(titleStr : NSString , dataArr : NSArray) {
self.frame = CGRect(x: 0, y: 0, width: screenW, height: screenH)
self.dataArray = dataArr
self.grayView.frame = CGRect(x: 0, y: 0, width: screenW, height: screenH)
self.grayView.backgroundColor = UIColor.black
self.grayView.alpha = 0.7
self.grayView.isUserInteractionEnabled = true
self.addSubview(self.grayView)
// 当前顶层窗口
let wind = UIApplication.shared.delegate?.window
wind!?.addSubview(self)
//显示视图
self.baseView.frame = CGRect(x: 23, y: 0, width: Int(screenW-59), height: dataArray.count*57+106)
self.baseView.center = CGPoint(x: screenW/2, y: screenH/2)
self.baseView.layer.masksToBounds = true
self.baseView.layer.cornerRadius = 9
self.baseView.backgroundColor = UIColor.red
self.addSubview(self.baseView)
//titleLab
let titlelable = UILabel()
titlelable.frame = CGRect(x: 0, y: 0, width: screenW-59, height: 40)
titlelable.text = titleStr as String
titlelable.textAlignment = .center
titlelable.font = UIFont.systemFont(ofSize: 23.0)
titlelable.backgroundColor = UIColor.white
self.baseView .addSubview(titlelable)
//关闭按钮
self.closeButtonView.frame = self.baseView.bounds
self.closeButtonView.center = CGPoint(x: screenW/2, y: screenH/2)
self.closeButtonView.backgroundColor = UIColor.clear
self.addSubview(self.closeButtonView)
self.closeButton.frame = CGRect(x: screenW-72, y: -13, width: 26, height: 26)
self.closeButton.setImage(UIImage (named: "iocn_memberClose"), for: .normal)
self.closeButtonView.addSubview(self.closeButton)
}
func tapClose() {
print("hello")
}
}
| mit | dea682e8f7e0b9ab44bc5e428422c6b1 | 28.392405 | 105 | 0.617571 | 3.935593 | false | false | false | false |
adamontherun/Study-iOS-With-Adam-Live | DragAndDropPlaceholder/DragAndDropPlaceholder/ViewController.swift | 1 | 823 | //😘 it is 8/9/17
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var donkeyImageView: UIImageView!
let photo = Photo(image: #imageLiteral(resourceName: "donkey"))
override func viewDidLoad() {
super.viewDidLoad()
donkeyImageView.image = photo.image
let dragInteraction = UIDragInteraction(delegate: self)
donkeyImageView.addInteraction(dragInteraction)
donkeyImageView.isUserInteractionEnabled = true
}
}
extension ViewController: UIDragInteractionDelegate {
func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
let itemProvider = NSItemProvider(object: photo)
let dragItem = UIDragItem(itemProvider: itemProvider)
return [dragItem]
}
}
| mit | 9414a64205d416a1aa166eaedeb81751 | 29.37037 | 118 | 0.715854 | 4.939759 | false | false | false | false |
Tyrant2013/LeetCodePractice | LeetCodePractice/Easy/88_Merge_Sorted_Array.swift | 1 | 1739 | //
// Merge _Sorted_Array.swift
// LeetCodePractice
//
// Created by 庄晓伟 on 2018/2/22.
// Copyright © 2018年 Zhuang Xiaowei. All rights reserved.
//
//Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
//
//Note:
//You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
import UIKit
class Merge_Sorted_Array: Solution {
override func ExampleTest() {
var nums1 = [1, 3, 5, 7, 9, 10, 55]
let nums2 = [2, 4, 6, 8, 10, 12]
self.merge(&nums1, nums1.count, nums2, nums2.count)
print(nums1.map({ String($0) }).joined(separator: ","))
}
func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) {
var indexOne = 0, indexTwo = 0
var ret = [Int]()
while ret.count < (m + n) {
var retNum = Int.max
if (indexOne < m && indexTwo < n) {
let numOne = nums1[indexOne]
let numTwo = nums2[indexTwo]
if numOne < numTwo {
retNum = numOne
indexOne += 1
}
else {
retNum = numTwo
indexTwo += 1
}
}
else if (indexOne < m) {
retNum = nums1[indexOne]
indexOne += 1
}
else if (indexTwo < n) {
retNum = nums2[indexTwo]
indexTwo += 1
}
ret.append(retNum)
}
nums1.removeAll()
nums1.append(contentsOf: ret)
}
}
| mit | 9d3758d275a3c16b33503b5a8f904086 | 30.454545 | 205 | 0.504624 | 3.769063 | false | false | false | false |
sztoth/PodcastChapters | PodcastChapters/UI/Views/ChapterCell/ChapterViewItemView.swift | 1 | 1500 | //
// ChapterViewItemView.swift
// PodcastChapters
//
// Created by Szabolcs Toth on 2016. 10. 25..
// Copyright © 2016. Szabolcs Toth. All rights reserved.
//
import Cocoa
class ChapterViewItemView: NSView {
var text: String {
get { return titleLabel.stringValue }
set { titleLabel.stringValue = newValue }
}
var highlighted: Bool = false {
didSet {
highlighted ? select() : deselect()
}
}
@IBOutlet fileprivate weak var titleLabel: NSTextField!
fileprivate var backgroundColor = ColorSettings.subBackgroundColor {
didSet {
wantsLayer = true
layer?.backgroundColor = backgroundColor.cgColor
}
}
override func resizeSubviews(withOldSize oldSize: NSSize) {
super.resizeSubviews(withOldSize: oldSize)
titleLabel.preferredMaxLayoutWidth = bounds.width
super.resizeSubviews(withOldSize: oldSize)
}
}
// MARK: - Setup
extension ChapterViewItemView {
// After loading the ChapterViewItemView from the nib the titleLabel is nil but later it will have a value.
// Do not know the reason yet, this is a workaround.
func setup() {
titleLabel.textColor = ColorSettings.textColor
}
}
// MARK: - Highlight state
fileprivate extension ChapterViewItemView {
func select() {
backgroundColor = ColorSettings.cellSelectionColor
}
func deselect() {
backgroundColor = ColorSettings.subBackgroundColor
}
}
| mit | 0e239d1a38cefa295259112503f7a08a | 24.844828 | 111 | 0.667779 | 4.866883 | false | false | false | false |
robertzhang/Gank.RZ | Gank.RZ/Cells/GirlTableViewCell.swift | 1 | 1154 | //
// GirlTableViewCell.swift
// Gank.RZ
//
// Created by Robert Zhang on 16/5/5.
// Copyright © 2016年 robertzhang. All rights reserved.
//
import UIKit
import Kingfisher
class GirlTableViewCell: UITableViewCell {
@IBOutlet weak var cardView: UIView!
@IBOutlet weak var girlImage: UIImageView!
@IBOutlet weak var author: UILabel!
@IBOutlet weak var updateTime: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
cardView.layer.cornerRadius = 5
cardView.layer.masksToBounds = true
}
func setCell(gank: GankModel) {
self.girlImage.backgroundColor = UIColor.randomColor()
self.girlImage.kf_setImageWithURL(NSURL(string: gank.url!)!)
self.author.text = gank.who
let date = DateUtil.stringToDate(gank.publishedAt!)
self.updateTime.text = DateUtil.dateToString(date, dateFormat: "yyyy年MM月dd日")
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 6967ee71b915f62955232b14f7771dd7 | 25.627907 | 85 | 0.652402 | 4.437984 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Views/AlertView/AlertModel.swift | 1 | 2545 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import UIKit
public struct AlertModel {
public var image: UIImage?
public var imageTintColor: UIColor?
public var topNote: String?
public var headline: String?
public var body: String?
public var note: String?
public var actions: [AlertAction]
public var dismissable: Bool
public var style: AlertViewStyle
public init(
headline: String?,
body: String?,
note: String? = nil,
topNote: String? = nil,
actions: [AlertAction] = [.defaultDismissal],
image: UIImage? = nil,
imageTintColor: UIColor? = nil,
dismissable: Bool = true,
style: AlertViewStyle = .default
) {
self.headline = headline
self.body = body
self.note = note
self.topNote = topNote
self.actions = actions
self.image = image
self.imageTintColor = imageTintColor
self.dismissable = dismissable
self.style = style
}
}
public struct AlertAction {
public let style: AlertActionStyle
public let metadata: ActionMetadata?
public init(style: AlertActionStyle, metadata: ActionMetadata? = nil) {
self.style = style
self.metadata = metadata
}
}
extension AlertAction {
public static let defaultDismissal = AlertAction(style: .dismiss)
public var title: String? {
switch style {
case .confirm(let title):
return title
case .default(let title):
return title
case .dismiss:
return nil
}
}
}
public enum AlertActionStyle: Equatable {
public typealias Title = String
/// Filled in `UIButton` with white text.
/// It appears _above_ the `default` style button.
case confirm(Title)
/// `UIButton` with blue border and blue text.
/// It appears _below_ the `confirm` style button.
case `default`(Title)
/// When the user taps outside of the view to dismiss it.
case dismiss
}
extension AlertActionStyle {
public static func == (lhs: AlertActionStyle, rhs: AlertActionStyle) -> Bool {
switch (lhs, rhs) {
case (.confirm(let left), .confirm(let right)):
return left == right
case (.default(let left), .default(let right)):
return left == right
case (.dismiss, .dismiss):
return true
default:
return false
}
}
}
public enum AlertViewStyle {
case `default`
case sheet
}
| lgpl-3.0 | 0d6cf09b3cc7db181c5c7bcac9c49e93 | 25.778947 | 82 | 0.612814 | 4.592058 | false | false | false | false |
PigDogBay/Food-Hygiene-Ratings | Food Hygiene Ratings/ObservableProperty.swift | 1 | 1595 | //
// ObservableProperty.swift
// Food Hygiene Ratings
//
// Created by Mark Bailey on 20/09/2018.
// Copyright © 2018 MPD Bailey Technology. All rights reserved.
//
import Foundation
class ObservableProperty<T : Equatable> {
typealias Observer = (Any?,T) -> Void
private var observers = [String : Observer]()
//To synchronize functions, see
//https://stackoverflow.com/questions/24045895/what-is-the-swift-equivalent-to-objective-cs-synchronized
private var internalValue : T
private let internalQueue : DispatchQueue = DispatchQueue(label: "lockingQueue")
var owner : Any? = nil
var value : T {
get {
return internalQueue.sync{internalValue}
}
set (newValue){
internalQueue.sync {
if newValue != internalValue {
internalValue = newValue
for (_, ob) in observers {
ob(owner, internalValue)
}
}
}
}
}
init (_ v : T){
internalValue = v
}
//Need to use @escaping as the closure Observer will be called after this function returns
func addObserver(named : String, observer : @escaping Observer){
internalQueue.sync{
observers[named] = observer
}
}
func removeObserver(named : String){
_ = internalQueue.sync {
_ = observers.removeValue(forKey: named)
}
}
func removeAllObservers(){
internalQueue.sync {
observers.removeAll()
}
}
}
| apache-2.0 | 376a8ba8d7812ff4f7328faaf6f198df | 27.464286 | 108 | 0.5734 | 4.889571 | false | false | false | false |
che1404/RGViperChat | RGViperChat/AppDelegate/Presenter/AppDelegatePresenterSpec.swift | 1 | 2942 | //
// Created by Roberto Garrido
// Copyright (c) 2017 Roberto Garrido. All rights reserved.
//
import Quick
import Nimble
import Cuckoo
@testable import RGViperChat
class AppDelegatePresenterSpec: QuickSpec {
var presenter: AppDelegatePresenter!
var mockView: MockAppDelegateViewProtocol!
var mockWireframe: MockAppDelegateWireframeProtocol!
var mockInteractor: MockAppDelegateInteractorInputProtocol!
// swiftlint:disable function_body_length
override func spec() {
beforeEach {
self.mockInteractor = MockAppDelegateInteractorInputProtocol()
self.mockView = MockAppDelegateViewProtocol()
self.mockWireframe = MockAppDelegateWireframeProtocol()
self.presenter = AppDelegatePresenter()
self.presenter.view = self.mockView
self.presenter.wireframe = self.mockWireframe
self.presenter.interactor = self.mockInteractor
}
context ("App did finish launching with options") {
beforeEach {
stub(self.mockInteractor) { mock in
when(mock).isUserLoggedIn().thenReturn(true)
}
stub(self.mockWireframe) { mock in
when(mock).presentChatListModule().thenDoNothing()
}
self.presenter.didFinishLaunchingWithOptions()
}
it("Asks whether the user is logged in or not") {
verify(self.mockInteractor).isUserLoggedIn()
}
context("User is logged in") {
beforeEach {
stub(self.mockInteractor) { mock in
when(mock).isUserLoggedIn().thenReturn(true)
}
self.presenter.didFinishLaunchingWithOptions()
}
it("Launches the ChatList module") {
verify(self.mockWireframe, atLeast(1)).presentChatListModule()
}
}
context("User is NOT logged in") {
beforeEach {
stub(self.mockInteractor) { mock in
when(mock).isUserLoggedIn().thenReturn(false)
}
stub(self.mockWireframe) { mock in
when(mock).presentAuthorizationModule().thenDoNothing()
}
self.presenter.didFinishLaunchingWithOptions()
}
it("Launches the ChatList module") {
verify(self.mockWireframe).presentAuthorizationModule()
}
}
}
afterEach {
self.mockInteractor = nil
self.mockView = nil
self.mockWireframe = nil
self.presenter.view = nil
self.presenter.wireframe = nil
self.presenter.interactor = nil
self.presenter = nil
}
}
}
| mit | 908765ea3cb99cb8af5820b4834161a9 | 32.431818 | 82 | 0.557784 | 5.779961 | false | false | false | false |
Palleas/GIF-Keyboard | AdventCalendar/DayCollectionViewCell.swift | 1 | 1031 | //
// DayCollectionViewCell.swift
// AdventCalendar
//
// Created by Romain Pouclet on 2015-11-30.
// Copyright © 2015 Perfectly-Cooked. All rights reserved.
//
import UIKit
class DayCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var dayLabel: UILabel! {
didSet {
dayLabel.textColor = .whiteColor()
dayLabel.font = UIFont(name: "PWChristmasfont", size: 50)!
}
}
override func awakeFromNib() {
super.awakeFromNib()
contentView.layer.borderColor = UIColor.whiteColor().CGColor
contentView.layer.borderWidth = 1.0
contentView.layer.cornerRadius = 20
}
override var selected: Bool {
didSet {
if selected {
contentView.backgroundColor = .whiteColor()
dayLabel.textColor = .blackColor()
} else {
contentView.backgroundColor = .clearColor()
dayLabel.textColor = .whiteColor()
}
}
}
}
| mit | b73cc71d54bf7768927fc37b24717f9f | 25.410256 | 70 | 0.582524 | 5.04902 | false | false | false | false |
kl/dehub | Model/ModelError.swift | 2 | 512 | //
// ModelError.swift
// DeHub
//
// Created by Kalle Lindström on 2017-02-11.
// Copyright © 2017 Dewire. All rights reserved.
//
import Foundation
struct ModelError: Error {
enum ErrorKind {
case jsonParseError
case stringParseError
case responseNot200
}
let kind: ErrorKind
let hint: String
let underlying: NSError?
init(_ kind: ErrorKind, hint: String = "", underlying: NSError? = nil) {
self.kind = kind
self.hint = hint
self.underlying = underlying
}
}
| mit | 5e5c57178bb5ffc7af76917b55dfde2e | 17.888889 | 74 | 0.664706 | 3.75 | false | false | false | false |
kevinlindkvist/lind | lind/ULCEvaluation.swift | 1 | 1873 | //
// UntypedLambdaCalculusEvaluation.swift
// lind
//
// Created by Kevin Lindkvist on 8/31/16.
// Copyright © 2016 lindkvist. All rights reserved.
//
import Foundation
private typealias NameLookup = [Int:ULCTerm]
func evaluate(_ term: ULCTerm) -> ULCTerm {
switch evaluate(term, [:]) {
case let .some(t): return evaluate(t)
case .none: return term
}
}
private func evaluate(_ term: ULCTerm, _ context: NameLookup) -> ULCTerm? {
switch term {
case let .app(.abs(_,body), v2) where isValue(v2, context):
return termSubstop(v2, body)
case let .app(v1, t2) where isValue(v1, context):
if let t2p = evaluate(t2, context) {
return .app(v1, t2p)
}
return nil
case let .app(t1, t2):
if let t1p = evaluate(t1, context) {
return .app(t1p, t2)
}
return nil
default: return nil
}
}
private func isValue(_ term: ULCTerm, _ context: NameLookup) -> Bool {
switch term {
case .abs: return true
default: return false
}
}
private func shift(_ d: Int, _ c: Int, _ t: ULCTerm) -> ULCTerm {
switch t {
case let .va(name, index) where index < c: return .va(name, index)
case let .va(name, index): return .va(name, index+d)
case let .abs(name, body): return .abs(name, shift(d, c+1, body))
case let .app(lhs, rhs): return .app(shift(d, c, lhs), shift(d, c, rhs))
}
}
private func substitute(_ j: Int, _ s: ULCTerm, _ t: ULCTerm, _ c: Int) -> ULCTerm {
switch t {
case let .va(_, index) where index == j+c: return shift(c, 0, s)
case let .va(name, index): return .va(name, index)
case let .abs(name, body): return .abs(name, substitute(j, s, body, c+1))
case let .app(lhs, rhs): return .app(substitute(j, s, lhs, c), substitute(j, s, rhs, c))
}
}
private func termSubstop(_ s: ULCTerm, _ t: ULCTerm) -> ULCTerm {
return shift(-1, 0, substitute(0, shift(1, 0, s), t, 0))
}
| apache-2.0 | 5e6f57cd830bddbc2174d36272f9f534 | 27.8 | 90 | 0.626068 | 2.79403 | false | false | false | false |
edmw/Volumio_ios | Volumio/VolumioIOManagerNotifications.swift | 1 | 1397 | //
// VolumioIOManagerNotifications.swift
// Volumio
//
// Created by Michael Baumgärtner on 10.01.17.
// Copyright © 2017 Federico Sintucci. All rights reserved.
//
import Foundation
// Notifications posted by VolumioIOManager
extension Notification.Name {
static let connected = Notification.Name("connected")
static let disconnected = Notification.Name("disconnected")
static let currentTrack = Notification.Name("currentTrack")
static let browseSources = Notification.Name("browseSources")
static let browseLibrary = Notification.Name("browseLibrary")
static let browseSearch = Notification.Name("browseSearch")
static let currentQueue = Notification.Name("currentQueue")
static let addedToQueue = Notification.Name("addedToQueue")
static let removedfromQueue = Notification.Name("removedfromQueue")
static let listPlaylists = Notification.Name("listPlaylists")
static let addedToPlaylist = Notification.Name("addedToPlaylist")
static let removedFromPlaylist = Notification.Name("removedFromPlaylist")
static let playlistPlaying = Notification.Name("playlistPlaying")
static let playlistDeleted = Notification.Name("playlistDeleted")
static let browsePlugins = Notification.Name("browsePlugins")
static let browseNetwork = Notification.Name("browseNetwork")
static let browseWifi = Notification.Name("browseWifi")
}
| gpl-3.0 | 6e41bee6f8291c1a3ba729ef88476990 | 44 | 77 | 0.769176 | 4.60396 | false | false | false | false |
argent-os/argent-ios | app-ios/PersonInformationEntryModalViewController.swift | 1 | 11359 | //
// PersonInformationEntryModalViewController.swift
// app-ios
//
// Created by Sinan Ulkuatam on 6/5/16.
// Copyright © 2016 Sinan Ulkuatam. All rights reserved.
//
import Foundation
import UIKit
import MZFormSheetPresentationController
import Stripe
import CWStatusBarNotification
import Alamofire
import SwiftyJSON
import Crashlytics
class PersonInformationEntryModalViewController: UIViewController, UITextFieldDelegate, STPPaymentCardTextFieldDelegate {
let titleLabel = UILabel()
var submitInformationButton = UIButton()
var informationTextField = UITextField()
var receiptAmount: String?
let yesButton = UIButton()
let noButton = UIButton()
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func viewDidLoad() {
super.viewDidLoad()
// This will set to only one instance
configureView()
setupNav()
}
func configureView() {
// screen width and height:
let screen = UIScreen.mainScreen().bounds
_ = screen.size.width
_ = screen.size.height
// Transparent navigation bar
self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.tintColor = UIColor.lightBlue()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.translucent = true
self.navigationController?.navigationBar.titleTextAttributes = [
NSForegroundColorAttributeName : UIColor.mediumBlue(),
NSFontAttributeName : UIFont(name: "SFUIText-Regular", size: 18.0)!
]
titleLabel.frame = CGRect(x: 0, y: 65, width: 280, height: 30)
titleLabel.text = "Would you like a receipt?"
titleLabel.textAlignment = .Center
titleLabel.font = UIFont(name: "SFUIText-Regular", size: 18)
titleLabel.textColor = UIColor.darkBlue()
self.view.addSubview(titleLabel)
informationTextField.frame = CGRect(x: 0, y: 110, width: 280, height: 60)
informationTextField.textColor = UIColor.lightBlue()
informationTextField.layer.borderColor = UIColor.lightBlue().colorWithAlphaComponent(0.5).CGColor
informationTextField.layer.cornerRadius = 0
informationTextField.layer.borderWidth = 0
informationTextField.textAlignment = .Center
informationTextField.autocapitalizationType = .None
informationTextField.autocorrectionType = .No
informationTextField.keyboardType = .EmailAddress
informationTextField.becomeFirstResponder()
submitInformationButton.frame = CGRect(x: 0, y: 190, width: 280, height: 60)
submitInformationButton.layer.borderColor = UIColor.whiteColor().CGColor
submitInformationButton.layer.borderWidth = 0
submitInformationButton.layer.cornerRadius = 0
submitInformationButton.layer.masksToBounds = true
submitInformationButton.setBackgroundColor(UIColor.brandGreen(), forState: .Normal)
submitInformationButton.setBackgroundColor(UIColor.brandGreen().colorWithAlphaComponent(0.5), forState: .Highlighted)
var attribs: [String: AnyObject] = [:]
attribs[NSFontAttributeName] = UIFont(name: "SFUIText-Regular", size: 14)
attribs[NSForegroundColorAttributeName] = UIColor.whiteColor()
let str = adjustAttributedString("SUBMIT", spacing: 2, fontName: "SFUIText-Regular", fontSize: 14, fontColor: UIColor.whiteColor(), lineSpacing: 0.0, alignment: .Center)
submitInformationButton.setAttributedTitle(str, forState: .Normal)
submitInformationButton.addTarget(self, action: #selector(self.configureBeforeSendingReceipt(_:)), forControlEvents: .TouchUpInside)
yesButton.setBackgroundColor(UIColor.pastelBlue(), forState: .Normal)
yesButton.setBackgroundColor(UIColor.pastelBlue().lighterColor(), forState: .Highlighted)
yesButton.frame = CGRect(x: 0, y: 190, width: 280, height: 60)
let yesStr = adjustAttributedString("Yes please!", spacing: 2, fontName: "SFUIText-Regular", fontSize: 14, fontColor: UIColor.whiteColor(), lineSpacing: 0.0, alignment: .Center)
let yesStr2 = adjustAttributedString("Yes please!", spacing: 2, fontName: "SFUIText-Regular", fontSize: 14, fontColor: UIColor.whiteColor().colorWithAlphaComponent(0.8), lineSpacing: 0.0, alignment: .Center)
yesButton.setAttributedTitle(yesStr, forState: .Normal)
yesButton.setAttributedTitle(yesStr2, forState: .Highlighted)
yesButton.layer.cornerRadius = 0
yesButton.layer.masksToBounds = true
yesButton.addTarget(self, action: #selector(yesClicked(_:)), forControlEvents: .TouchUpInside)
addSubviewWithBounce(yesButton, parentView: self, duration: 0.3)
noButton.setBackgroundColor(UIColor.whiteColor(), forState: .Normal)
noButton.setBackgroundColor(UIColor.whiteColor(), forState: .Highlighted)
noButton.frame = CGRect(x: 0, y: 130, width: 280, height: 50)
let noStr = adjustAttributedString("No, thank you.", spacing: 2, fontName: "SFUIText-Regular", fontSize: 14, fontColor: UIColor.pastelBlue(), lineSpacing: 0.0, alignment: .Center)
let noStr2 = adjustAttributedString("No, thank you.", spacing: 2, fontName: "SFUIText-Regular", fontSize: 14, fontColor: UIColor.pastelBlue().darkerColor(), lineSpacing: 0.0, alignment: .Center)
noButton.setAttributedTitle(noStr, forState: .Normal)
noButton.setAttributedTitle(noStr2, forState: .Highlighted)
noButton.addTarget(self, action: #selector(noClicked(_:)), forControlEvents: .TouchUpInside)
addSubviewWithBounce(noButton, parentView: self, duration: 0.3)
}
private func setupNav() {
let navigationBar = self.navigationController?.navigationBar
navigationBar!.backgroundColor = UIColor.offWhite()
navigationBar!.tintColor = UIColor.darkBlue()
// Create a navigation item with a title
let navigationItem = UINavigationItem()
// Create left and right button for navigation item
let leftButton = UIBarButtonItem(title: "Close", style: .Plain, target: self, action: #selector(self.close(_:)))
let font = UIFont(name: "SFUIText-Regular", size: 17)!
leftButton.setTitleTextAttributes([NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.mediumBlue()], forState: UIControlState.Normal)
leftButton.setTitleTextAttributes([NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.darkBlue()], forState: UIControlState.Highlighted)
// Create two buttons for the navigation item
navigationItem.leftBarButtonItem = leftButton
// Assign the navigation item to the navigation bar
navigationBar!.titleTextAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.darkGrayColor()]
navigationBar!.items = [navigationItem]
}
func close(sender: AnyObject) -> Void {
self.dismissViewControllerAnimated(true, completion: nil)
}
func yesClicked(sender: AnyObject) {
addSubviewWithBounce(informationTextField, parentView: self, duration: 0.3)
addSubviewWithBounce(submitInformationButton, parentView: self, duration: 0.3)
yesButton.removeFromSuperview()
noButton.removeFromSuperview()
titleLabel.text = "Please enter your email"
}
func noClicked(sender: AnyObject) {
self.dismissViewControllerAnimated(true) { }
}
//Calls this function when the tap is recognized.
func dismissKeyboard(sender: AnyObject) {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
self.view.endEditing(true)
informationTextField.endEditing(true)
}
func configureBeforeSendingReceipt(sender: AnyObject) {
addActivityIndicatorButton(UIActivityIndicatorView(), button: submitInformationButton, color: .White)
if informationTextField.text != "" && receiptAmount != "" {
print("sending email receipt")
self.sendInformation(self, email: informationTextField.text!, amount: receiptAmount!)
} else {
showGlobalNotification("Amount nil or email empty!", duration: 3.0, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.StatusBarNotification, color: UIColor.neonOrange())
}
}
func sendInformation(sender: AnyObject, email: String, amount: String) {
// SEND REQUEST TO Argent API ENDPOINT TO SEND RECEIPT
User.getProfile { (user, err) in
let headers : [String : String] = [
"Content-Type": "application/json"
]
let parameters = [
"message": "Hello! \n\n This is an email receipt for a recent transaction made on Argent in the amount of " + amount + " on " + NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .ShortStyle)
]
print("customer email is", email)
// /v1/receipt/8s9g8a0sd9asdjk2/[email protected]
Alamofire.request(.POST, API_URL + "/receipts/" + (user?.id)! + "/customer?email=" + email, parameters: parameters, encoding: .JSON, headers: headers)
.responseJSON { (response) in
switch response.result {
case .Success:
if let value = response.result.value {
//let data = JSON(value)
showGlobalNotification("Receipt sent!", duration: 3.0, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.NavigationBarNotification, color: UIColor.pastelBlue())
self.informationTextField.text = ""
Answers.logCustomEventWithName("Receipt Sent Success",
customAttributes: [
"to_email": email
])
self.dismissViewControllerAnimated(true) {
//
}
}
case .Failure(let error):
print(error)
showGlobalNotification("Error sending receipt", duration: 3.0, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.StatusBarNotification, color: UIColor.neonOrange())
Answers.logCustomEventWithName("Receipt Failed to Send",
customAttributes: [
"error": error.localizedDescription
])
self.dismissViewControllerAnimated(true) {
//
}
}
}
}
}
}
| mit | 0eeca10e650dff7f5be56138d943d963 | 50.393665 | 260 | 0.667547 | 5.260769 | false | false | false | false |
WangGuibin/MyCodeSnippets | 工具类/布局类/实时调试UI/TestDemo/ViewChaosInfo.swift | 1 | 62726 | //
// ViewChaosInfo.swift
// ViewChaosDemo
//
// Created by Tyrant on 11/5/15.
// Copyright © 2015 Qfq. All rights reserved.
//
import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l >= r
default:
return !(lhs < rhs)
}
}
class ViewChaosInfo: UIView,UITableViewDataSource,UITableViewDelegate {
enum tbType:Int{
case general = 0
case superview = 1
case subview = 2
case constrain = 3
case trace = 4
case about = 5
}
weak var viewHit:UIView?
var lblCurrentView:UILabel
var btnHit:UIButton
var btnClose:UIButton
var btnControl:UIButton
var tbLeft:UITableView
var tbRight:UITableView
var btnBack:UIButton
var btnMinimize:UIButton
var type:tbType = .general
var arrSuperView:[ViewChaosObject]?
var arrSubview:[ViewChaosObject]?
var isTouch:Bool = false
var top:CGFloat = 0
var left:CGFloat = 0
var originFrame:CGRect?
var arrTrace:[[String:AnyObject]]?
var viewTrackBorderWith:CGFloat?
var viewTrackBorderColor:UIColor?
var arrConstrains:[[String:AnyObject]]?
var arrStackView:[ViewChaosObject]?
var arrGeneral:[String]?
var arrAbout:[String]?
var arrLeft:[String]?
var isTrace:Bool?
init(){
tbLeft = UITableView()
tbRight = UITableView()
btnClose = UIButton()
btnBack = UIButton()
lblCurrentView = UILabel()
btnHit = UIButton()
btnControl = UIButton()
btnMinimize = UIButton()
super.init(frame: CGRect(x: 10, y: 80, width: UIScreen.main.bounds.width-20, height: UIScreen.main.bounds.height-160))
backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)
tbLeft.frame = CGRect(x: 0, y: 50, width: self.frame.size.width / 3, height: self.frame.size.height - 50)
tbLeft.backgroundView?.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.6)
tbLeft.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.6)
tbLeft.tableFooterView = UIView()
tbRight.frame = CGRect(x: tbLeft.frame.size.width, y: 50, width: self.frame.size.width - tbLeft.frame.size.width, height: self.frame.size.height - 50)
tbRight.backgroundView?.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.6)
tbRight.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.6)
addSubview(tbLeft)
addSubview(tbRight)
btnClose.frame = CGRect(x: self.frame.size.width - 45, y: 5, width: 45, height: 22)
btnClose.setTitle("Close", for: UIControlState())
btnClose.titleLabel?.font = UIFont.systemFont(ofSize: 13)
btnClose.setTitleColor(UIColor.orange, for: UIControlState())
btnClose.addTarget(self, action: #selector(ViewChaosInfo.close(_:)), for: UIControlEvents.touchUpInside)
addSubview(btnClose)
btnBack.frame = CGRect(x: self.frame.size.width - btnClose.frame.size.width - 45, y: 5, width: 45, height: 22)
btnBack.setTitle("Back", for: UIControlState())
btnBack.titleLabel?.font = UIFont.systemFont(ofSize: 12)
btnBack.setTitleColor(UIColor.orange, for: UIControlState())
btnBack.addTarget(self, action: #selector(ViewChaosInfo.back(_:)), for: UIControlEvents.touchUpInside)
addSubview(btnBack)
btnHit.frame = CGRect(x: btnBack.frame.origin.x - 45, y: 5, width: 45, height: 22)
btnHit.setTitle("Hit", for: UIControlState())
btnHit.titleLabel?.font = UIFont.systemFont(ofSize: 13)
btnHit.setTitleColor(UIColor.orange, for: UIControlState())
btnHit.addTarget(self, action: #selector(ViewChaosInfo.hit(_:)), for: UIControlEvents.touchUpInside)
addSubview(btnHit)
btnControl.frame = CGRect(x: btnHit.frame.origin.x - 45, y: 5, width: 45, height: 22)
btnControl.setTitle("Control", for: UIControlState())
btnControl.titleLabel?.font = UIFont.systemFont(ofSize: 13)
btnControl.setTitleColor(UIColor.orange, for: UIControlState())
btnControl.addTarget(self, action: #selector(ViewChaosInfo.control(_:)), for: UIControlEvents.touchUpInside)
addSubview(btnControl)
let lblCurrent = UILabel(frame: CGRect(x: 2, y: 5, width: 100, height: 22))
lblCurrent.text = "Current View:"
lblCurrent.textColor = UIColor.white
lblCurrent.font = UIFont.systemFont(ofSize: 13)
addSubview(lblCurrent)
lblCurrentView.frame = CGRect(x: 2, y: lblCurrent.frame.maxY + 3, width: self.frame.size.width - 3, height: 20)
lblCurrentView.textColor = UIColor.white
lblCurrentView.font = UIFont.systemFont(ofSize: 13)
addSubview(lblCurrentView)
btnMinimize.frame = CGRect(x: self.frame.size.width-20, y: self.frame.size.height / 2 - 20, width: 20, height: 40)
btnMinimize.backgroundColor = UIColor.black
btnMinimize.setTitleColor(UIColor.white, for: UIControlState())
btnMinimize.setTitle(">", for: UIControlState())
btnMinimize.addTarget(self, action: #selector(ViewChaosInfo.minimize(_:)), for: UIControlEvents.touchUpInside)
addSubview(btnMinimize)
}
override convenience init(frame: CGRect) {
self.init()
}
override func willMove(toWindow newWindow: UIWindow?) {
if let _ = newWindow{
isTouch = false
isTrace = false
self.clipsToBounds = true
self.translatesAutoresizingMaskIntoConstraints = true
self.layer.borderWidth = 2
self.layer.borderColor = UIColor.black.cgColor
tbLeft.delegate = self
tbLeft.dataSource = self
tbRight.delegate = self
tbRight.dataSource = self
btnBack.isHidden = true
arrLeft = ["General","SuperView","SubView","Constrains","Trace","About"]
arrStackView = [ViewChaosObject]()
arrGeneral = [String]()
arrAbout = ["这是一个测试UI的工具",",这个工具是RunTrace的Swift版本.希望大家用得开心"]
initView(viewHit!, back: false)
NotificationCenter.default.addObserver(self, selector: #selector(ViewChaosInfo.handleRemoveView(_:)), name: NSNotification.Name(rawValue: handleTraceRemoveView), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewChaosInfo.handleRemoveSubView(_:)), name: NSNotification.Name(rawValue: handleTraceRemoveSubView), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewChaosInfo.handleAddSubView(_:)), name: NSNotification.Name(rawValue: handleTraceAddSubView), object: nil)
}
else{
NotificationCenter.default.removeObserver(self)
if isTrace! && viewHit != nil{
stopTrace()
}
NotificationCenter.default.post(name: Notification.Name(rawValue: handleTraceShow), object: nil)
}
}
func handleRemoveSubView(_ notif:Notification){
var view = notif.object as! UIView
if viewHit! == view{
view = (notif as NSNotification).userInfo!["subview" as NSObject] as! UIView
var dict:[String:AnyObject] = [String:AnyObject]()
dict["key"] = "Add Subview" as AnyObject?
dict["Time"] = Chaos.currentDate(nil) as AnyObject?
dict["OldValue"] = "\(type(of: view))l:\(view.frame.origin.x.format(".1f"))t:\(view.frame.origin.y.format(".1f"))w:\(view.frame.size.width.format(".1f"))h:\(view.frame.size.height.format(".1f"))" as AnyObject?
dict["NewValue"] = "nil" as AnyObject?
arrTrace?.append(dict)
if type == .trace{
tbRight.reloadData()
tbRight.tableFooterView = UIView()
}
}
}
func handleAddSubView(_ notif:Notification)
{
var view = notif.object as! UIView
if viewHit! == view{
view = (notif as NSNotification).userInfo!["subview" as NSObject] as! UIView
var dict:[String:AnyObject] = [String:AnyObject]()
dict["key"] = "Add Subview" as AnyObject?
dict["Time"] = Chaos.currentDate(nil) as AnyObject?
dict["OldValue"] = "nil" as AnyObject?
dict["NewValue"] = "\(type(of: view))l:\(view.frame.origin.x.format(".1f"))t:\(view.frame.origin.y.format(".1f"))w:\(view.frame.size.width.format(".1f"))h:\(view.frame.size.height.format(".1f"))" as AnyObject?
arrTrace?.append(dict)
if type == .trace{
tbRight.reloadData()
tbRight.tableFooterView = UIView()
}
}
}
func handleRemoveView(_ notif:Notification){
let view = notif.object as! UIView
if viewHit! == view{
stopTrace()
viewHit?.layer.borderColor = viewTrackBorderColor?.cgColor
viewHit?.layer.borderWidth = viewTrackBorderWith!
var dict:[String:AnyObject] = [String:AnyObject]()
dict["key"] = "RemoveFromSuperview" as AnyObject?
dict["Time"] = Chaos.currentDate(nil) as AnyObject?
dict["OldValue"] = "\(type(of: view))l:\(view.frame.origin.x.format(".1f"))t:\(view.frame.origin.y.format(".1f"))w:\(view.frame.size.width.format(".1f"))h:\(view.frame.size.height.format(".1f"))" as AnyObject?
dict["NewValue"] = "nil" as AnyObject?
arrTrace?.append(dict)
if type == .trace{
tbRight.reloadData()
tbRight.tableFooterView = UIView()
if let btn = tbRight.tableHeaderView as? UIButton{
btn.setTitle("Start", for: UIControlState())
}
}
arrSubview?.removeAll()
arrSuperView?.removeAll()
arrConstrains?.removeAll()
let alert = UIAlertView(title: "ViewChecl", message: "\(type(of: view))RemoveFromSuperview", delegate: nil, cancelButtonTitle: "OK")
alert.show()
lblCurrentView.text = lblCurrentView.text! + "has removed"
}
}
func initView(_ view:UIView,back:Bool){
stopTrace()
viewHit = view
if let name = viewHit?.chaosName{
lblCurrentView.text = "\(type(of: viewHit!)) name:\(name) (\(viewHit!.description))"
}
else{
lblCurrentView.text = "\(type(of: viewHit!))(\(viewHit!.description))"
}
if !back {
arrStackView?.append(ViewChaosObject.objectWithWeak(view) as! ViewChaosObject)
if arrStackView?.count >= 2{
btnBack.isHidden = false
}
}
arrSuperView = [ViewChaosObject]()
var viewSuper = viewHit
while viewSuper?.superview != nil{
viewSuper = viewSuper?.superview
arrSuperView?.append(ViewChaosObject.objectWithWeak(viewSuper!) as! ViewChaosObject)
}
arrSubview = [ViewChaosObject]()
for sub in viewHit!.subviews{
arrSubview?.append(ViewChaosObject.objectWithWeak(sub) as! ViewChaosObject)
}
arrTrace = [[String:AnyObject]]()
arrConstrains = [[String:AnyObject]]()
arrGeneral = [String]()
arrGeneral?.append( "Class Name:\(type(of: viewHit!))")
arrGeneral?.append("AutoLayout:\(viewHit!.translatesAutoresizingMaskIntoConstraints ? "NO" : "YES")")
arrGeneral?.append("Left:\(viewHit!.frame.origin.x.format(".2f"))")
arrGeneral?.append("Top:\(viewHit!.frame.origin.y.format(".2f"))")
arrGeneral?.append("Width:\(viewHit!.frame.size.width.format(".2f"))")
arrGeneral?.append("Height:\(viewHit!.frame.size.height.format(".2f"))")
analysisAutolayout()
tbRight.reloadData()
tbRight.tableFooterView = UIView()
}
func onTrace(_ sender:UIButton)
{
if sender.title(for: UIControlState()) == "Start"{
startTrace()
}
else{
stopTrace()
}
}
func startTrace(){
let btn = tbRight.tableHeaderView! as! UIButton
if viewHit == nil{
let alert = UIAlertView(title: "ViewCheck", message: "View has removed and can't trace!", delegate: nil, cancelButtonTitle: "OK")
alert.show()
return
}
isTrace = true
btn.setTitle("Stop", for: UIControlState())
arrTrace?.removeAll()
tbRight.reloadData()
tbRight.tableFooterView = UIView()
viewHit?.addObserver(self, forKeyPath: "frame", options: [NSKeyValueObservingOptions.old,NSKeyValueObservingOptions.new], context: nil)
viewHit?.addObserver(self, forKeyPath: "center", options: [NSKeyValueObservingOptions.old,NSKeyValueObservingOptions.new], context: nil)
viewHit?.addObserver(self, forKeyPath: "superview.frame", options: [NSKeyValueObservingOptions.old,NSKeyValueObservingOptions.new], context: nil)
viewHit?.addObserver(self, forKeyPath: "tag", options: [NSKeyValueObservingOptions.old,NSKeyValueObservingOptions.new], context: nil)
viewHit?.addObserver(self, forKeyPath: "userInteractionEnabled", options: [NSKeyValueObservingOptions.old,NSKeyValueObservingOptions.new], context: nil)
viewHit?.addObserver(self, forKeyPath: "hidden", options: [NSKeyValueObservingOptions.old,NSKeyValueObservingOptions.new], context: nil)
viewHit?.addObserver(self, forKeyPath: "bounds", options: [NSKeyValueObservingOptions.old,NSKeyValueObservingOptions.new], context: nil)
if viewHit! is UIScrollView{
viewHit?.addObserver(self, forKeyPath: "contentSize", options: [NSKeyValueObservingOptions.old,NSKeyValueObservingOptions.new], context: nil)
viewHit?.addObserver(self, forKeyPath: "contentOffset", options: [NSKeyValueObservingOptions.old,NSKeyValueObservingOptions.new], context: nil)
viewHit?.addObserver(self, forKeyPath: "contentInset", options: [NSKeyValueObservingOptions.old,NSKeyValueObservingOptions.new], context: nil)
}
traceSuperAndSubView()
Chaos.toast("Start Trace")
}
func stopTrace(){
if !isTrace!{
return
}
isTrace = false
viewHit?.removeObserver(self, forKeyPath: "frame")
viewHit?.removeObserver(self, forKeyPath: "center")
viewHit?.removeObserver(self, forKeyPath: "superview.frame")
viewHit?.removeObserver(self, forKeyPath: "tag")
viewHit?.removeObserver(self, forKeyPath: "userInteractionEnabled")
viewHit?.removeObserver(self, forKeyPath: "hidden")
viewHit?.removeObserver(self, forKeyPath: "bounds")
if viewHit is UIScrollView{
viewHit?.removeObserver(self, forKeyPath: "contentSize")
viewHit?.removeObserver(self, forKeyPath: "contentOffset")
viewHit?.removeObserver(self, forKeyPath: "contentInset")
}
viewHit?.layer.borderColor = viewTrackBorderColor?.cgColor
viewHit?.layer.borderWidth = viewTrackBorderWith!
if tbRight.tableHeaderView == nil {
return;
}
let btn = tbRight.tableHeaderView! as! UIButton
btn.setTitle("Start", for: UIControlState())
}
func close(_ sender:UIButton){
if btnClose.title(for: UIControlState()) == "Close"{
self.removeFromSuperview()
NotificationCenter.default.post(name: Notification.Name(rawValue: "handleTraceViewClose"), object: nil)
}
else if btnClose.title(for: UIControlState()) == "Stop"{
stopTrace()
if isTrace! && viewHit != nil{
viewHit?.layer.borderColor = viewTrackBorderColor?.cgColor
viewHit?.layer.borderWidth = viewTrackBorderWith!
isTrace = false
}
}
}
func back(_ sender:UIButton){
arrStackView?.removeLast()
let view = arrStackView!.last!.obj as! UIView
if arrStackView?.count == 1{
btnBack.isHidden = true
}
initView(view, back: true)
}
func hit(_ sender:UIButton){
if viewHit == nil{
let alert = UIAlertView(title: "ViewChaos", message: "View has removed and can't hit!", delegate: self, cancelButtonTitle: "OK")
alert.show()
return
}
NotificationCenter.default.post(name: Notification.Name(rawValue: "handleTraceView"), object: viewHit!)
minimize()
}
func control(_ sender:UIButton){
if viewHit == nil{
let alert = UIAlertView(title: "ViewChaos", message: "View has removed and can't control!", delegate: self, cancelButtonTitle: "OK")
alert.show()
return
}
NotificationCenter.default.post(name: Notification.Name(rawValue: controlTraceView), object: viewHit!)
minimize()
}
func analysisAutolayout(){
if viewHit == nil
{
return
}
if viewHit!.translatesAutoresizingMaskIntoConstraints{
return
}
var viewConstraint = viewHit
while viewConstraint != nil && !(viewConstraint!.isKind(of: NSClassFromString("UIViewControllerWrapperView")!))
{
for con in viewConstraint!.constraints{
var constant = con.constant
let viewFirst = con.firstItem as! UIView
let viewSecond = con.secondItem as? UIView
if con.secondItem != nil{
if con.firstItem as! UIView == viewHit! && con.firstAttribute == con.secondAttribute{
if viewFirst.isDescendant(of: viewSecond!){
constant = con.constant
}
else if viewSecond!.isDescendant(of: viewFirst){
constant = -con.constant
}
else{
constant = con.constant
}
}
else if con.firstItem as! UIView == viewHit! && con.firstAttribute != con.secondAttribute{
constant = con.constant
}
else if(con.secondItem as! UIView == viewHit! && con.firstAttribute == con.secondAttribute){
if viewFirst.isDescendant(of: viewSecond!){
constant = -con.constant
}
else if viewSecond!.isDescendant(of: viewFirst)
{
constant = con.constant
}
else{
constant = con.constant
}
}
else if con.secondItem as! UIView == viewHit! && con.firstAttribute != con.secondAttribute{
constant = con.constant
}
}
if con.firstItem as! UIView == viewHit! && (con.firstAttribute == NSLayoutAttribute.leading || con.firstAttribute == NSLayoutAttribute.left || con.firstAttribute == NSLayoutAttribute.leadingMargin || con.firstAttribute == NSLayoutAttribute.leftMargin){
var dict = [String:AnyObject]()
dict["Type"] = "Left" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["ToView"] = ViewChaosObject.objectWithWeak(con.secondItem!)
dict["Constant"] = con.constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
else if con.secondItem as? UIView == viewHit! && (con.secondAttribute == NSLayoutAttribute.leading || con.secondAttribute == NSLayoutAttribute.left || con.secondAttribute == NSLayoutAttribute.leadingMargin || con.secondAttribute == NSLayoutAttribute.leftMargin){
var dict = [String:AnyObject]()
dict["Type"] = "Left" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["ToView"] = ViewChaosObject.objectWithWeak(con.firstItem)
dict["Constant"] = constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
else if con.firstItem as! UIView == viewHit! && (con.firstAttribute == NSLayoutAttribute.top || con.firstAttribute == NSLayoutAttribute.topMargin) {
var dict = [String:AnyObject]()
dict["Type"] = "Top" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["ToView"] = ViewChaosObject.objectWithWeak(con.secondItem!)
dict["Constant"] = constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
else if con.secondItem as? UIView == viewHit! && (con.secondAttribute == NSLayoutAttribute.top || con.secondAttribute == NSLayoutAttribute.topMargin) {
var dict = [String:AnyObject]()
dict["Type"] = "Top" as AnyObject?
dict["Value"] = con.description as AnyObject?
Chaos.Log(con.description)
dict["ToView"] = ViewChaosObject.objectWithWeak(con.firstItem)
dict["Constant"] = constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
else if con.firstItem as! UIView == viewHit! && (con.firstAttribute == NSLayoutAttribute.trailing || con.firstAttribute == NSLayoutAttribute.trailingMargin || con.firstAttribute == NSLayoutAttribute.right || con.firstAttribute == NSLayoutAttribute.rightMargin){
var dict = [String:AnyObject]()
dict["Type"] = "Right" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["ToView"] = ViewChaosObject.objectWithWeak(con.secondItem!)
dict["Constant"] = constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
else if con.secondItem as? UIView == viewHit! && (con.secondAttribute == NSLayoutAttribute.trailing || con.secondAttribute == NSLayoutAttribute.trailingMargin || con.secondAttribute == NSLayoutAttribute.right || con.secondAttribute == NSLayoutAttribute.rightMargin){
var dict = [String:AnyObject]()
dict["Type"] = "Right" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["ToView"] = ViewChaosObject.objectWithWeak(con.firstItem)
dict["Constant"] = constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
else if con.firstItem as! UIView == viewHit! && (con.firstAttribute == NSLayoutAttribute.bottom || con.firstAttribute == NSLayoutAttribute.bottomMargin) {
var dict = [String:AnyObject]()
dict["Type"] = "Bottom" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["ToView"] = ViewChaosObject.objectWithWeak(con.secondItem!)
dict["Constant"] = constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
else if con.secondItem as? UIView == viewHit! && (con.secondAttribute == NSLayoutAttribute.bottom || con.secondAttribute == NSLayoutAttribute.bottomMargin) {
var dict = [String:AnyObject]()
dict["Type"] = "Bottom" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["ToView"] = ViewChaosObject.objectWithWeak(con.firstItem)
dict["Constant"] = constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
else if (con.firstItem as! UIView == viewHit! && con.firstAttribute == NSLayoutAttribute.width) || (con.secondItem as? UIView == viewHit && con.secondAttribute == NSLayoutAttribute.width){
if con.isKind(of: NSClassFromString("NSContentSizeLayoutConstraint")!){
var dict = [String:AnyObject]()
dict["Type"] = "IntrinsicContent Width" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["Constant"] = constant as AnyObject?
arrConstrains?.append(dict)
}
else{
var dict = [String:AnyObject]()
dict["Type"] = "Width" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["ToView"] = ViewChaosObject.objectWithWeak(con.firstItem)
dict["Constant"] = constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
}
else if (con.firstItem as! UIView == viewHit! && con.firstAttribute == NSLayoutAttribute.height) || (con.secondItem as? UIView == viewHit && con.secondAttribute == NSLayoutAttribute.height){
if con.isKind(of: NSClassFromString("NSContentSizeLayoutConstraint")!){
var dict = [String:AnyObject]()
dict["Type"] = "IntrinsicContent Height" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["Constant"] = con.constant as AnyObject?
arrConstrains?.append(dict)
}
else{
var dict = [String:AnyObject]()
dict["Type"] = "Height" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["ToView"] = ViewChaosObject.objectWithWeak(con.firstItem)
dict["Constant"] = constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
}
else if con.firstItem as! UIView == viewHit! && con.firstAttribute == NSLayoutAttribute.centerX{
var dict = [String:AnyObject]()
dict["Type"] = "CenterX" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["ToView"] = ViewChaosObject.objectWithWeak(con.secondItem!)
dict["Constant"] = constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
else if con.secondItem as? UIView == viewHit! && con.firstAttribute == NSLayoutAttribute.centerX{
var dict = [String:AnyObject]()
dict["Type"] = "CenterX" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["ToView"] = ViewChaosObject.objectWithWeak(con.firstItem)
dict["Constant"] = constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
else if con.firstItem as! UIView == viewHit! && con.firstAttribute == NSLayoutAttribute.centerY{
var dict = [String:AnyObject]()
dict["Type"] = "CenterY" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["ToView"] = ViewChaosObject.objectWithWeak(con.secondItem!)
dict["Constant"] = constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
else if con.secondItem as? UIView == viewHit! && con.firstAttribute == NSLayoutAttribute.centerY{
var dict = [String:AnyObject]()
dict["Type"] = "CenterY" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["ToView"] = ViewChaosObject.objectWithWeak(con.firstItem)
dict["Constant"] = constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
else if con.firstItem as! UIView == viewHit! && con.firstAttribute == NSLayoutAttribute.lastBaseline{
var dict = [String:AnyObject]()
dict["Type"] = "BaseLine" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["ToView"] = ViewChaosObject.objectWithWeak(con.secondItem!)
dict["Constant"] = constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
else if con.secondItem as? UIView == viewHit! && con.firstAttribute == NSLayoutAttribute.lastBaseline{
var dict = [String:AnyObject]()
dict["Type"] = "BaseLine" as AnyObject?
dict["Value"] = con.description as AnyObject?
dict["ToView"] = ViewChaosObject.objectWithWeak(con.firstItem)
dict["Constant"] = constant as AnyObject?
dict["Multiplier"] = con.multiplier as AnyObject?
dict["Priority"] = con.priority as AnyObject?
arrConstrains?.append(dict)
}
}
viewConstraint = viewConstraint?.superview
}
}
func minimize(){
originFrame = self.frame
let fm = CGRect(x: UIScreen.main.bounds.width - 20, y: UIScreen.main.bounds.height / 2 - 20, width: 20, height: 40)
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.frame = fm
}, completion: { (finished) -> Void in
let btn = UIButton(frame: self.bounds)
btn.setTitle("<", for: UIControlState())
btn.backgroundColor = UIColor.black
btn.setTitleColor(UIColor.white, for: UIControlState())
btn.addTarget(self, action: #selector(ViewChaosInfo.expand(_:)), for: UIControlEvents.touchUpInside)
self.addSubview(btn)
})
}
func expand(_ sender:UIButton){
sender.removeFromSuperview()
NotificationCenter.default.post(name: Notification.Name(rawValue: "handleTraceViewClose"), object: nil)
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.frame = self.originFrame!
})
}
func minimize(_ sender:UIButton){
minimize()
}
func traceSuperAndSubView(){
if viewHit == nil{
let alert = UIAlertView(title: "ViewChecK", message: "View has removed and can't trace!", delegate: nil, cancelButtonTitle: "OK")
alert.show()
return
}
viewTrackBorderWith = viewHit!.layer.borderWidth
viewTrackBorderColor = UIColor(cgColor: viewHit!.layer.borderColor!)
viewHit?.layer.borderWidth = 3
viewHit?.layer.borderColor = UIColor.black.cgColor
minimize()
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "frame"{
let oldFrame = (change![NSKeyValueChangeKey.oldKey]! as AnyObject).cgRectValue
let newFrame = (change![NSKeyValueChangeKey.newKey]! as AnyObject).cgRectValue
if (oldFrame?.equalTo(newFrame!))!
{
return
}
var dict = [String:AnyObject]()
dict["Key"] = "Frame Change" as AnyObject?
dict["Time"] = Chaos.currentDate(nil) as AnyObject?
dict["OldValue"] = "l:\(oldFrame?.origin.x.format(".1f")) t:\(oldFrame?.origin.y.format(".1f")) w:\(oldFrame?.origin.x.format(".1f")) :h\(oldFrame?.origin.x.format(".1f"))" as AnyObject?
dict["NewValue"] = "l:\(newFrame?.origin.x.format(".1f")) t:\(newFrame?.origin.y.format(".1f")) w:\(newFrame?.origin.x.format(".1f")) h:\(newFrame?.origin.x.format(".1f"))" as AnyObject?
arrTrace?.append(dict)
}
else if keyPath == " center"{
let oldCenter = (change![NSKeyValueChangeKey.oldKey]! as AnyObject).cgPointValue
let newCenter = (change![NSKeyValueChangeKey.newKey]! as AnyObject).cgPointValue
if (oldCenter?.equalTo(newCenter!))!
{
return
}
var dict = [String:AnyObject]()
dict["Key"] = "Center Change" as AnyObject?
dict["Time"] = Chaos.currentDate(nil) as AnyObject?
dict["OldValue"] = "l:\(oldCenter?.x.format(".1f")) t:\(oldCenter?.y.format(".1f"))" as AnyObject?
dict["NewValue"] = "l:\(newCenter?.x.format(".1f")) t:\(newCenter?.y.format(".1f"))" as AnyObject?
arrTrace?.append(dict)
}
else if keyPath == "superview.frame"{
let oldFrame = (change![NSKeyValueChangeKey.oldKey]! as AnyObject).cgRectValue
let newFrame = (change![NSKeyValueChangeKey.newKey]! as AnyObject).cgRectValue
if (oldFrame?.equalTo(newFrame!))!
{
return
}
var dict = [String:AnyObject]()
dict["Key"] = "Superview Frame Change" as AnyObject?
dict["Time"] = Chaos.currentDate(nil) as AnyObject?
dict["OldValue"] = "l:\(oldFrame?.origin.x.format(".1f")) t:\(oldFrame?.origin.y.format(".1f")) w:\(oldFrame?.origin.x.format(".1f")) :h\(oldFrame?.origin.x.format(".1f"))" as AnyObject?
dict["NewValue"] = "l:\(newFrame?.origin.x.format(".1f")) t:\(newFrame?.origin.y.format(".1f")) w:\(newFrame?.origin.x.format(".1f")) h:\(newFrame?.origin.x.format(".1f"))" as AnyObject?
dict["SuperView"] = "\(type(of: (object! as! UIView).superview))" as AnyObject?
arrTrace?.append(dict)
}
else if keyPath == "tag"{
let oldValue = (change![NSKeyValueChangeKey.oldKey]! as AnyObject)
let newValue = (change![NSKeyValueChangeKey.newKey]! as AnyObject)
var dict = [String:AnyObject]()
dict["Key"] = "Tag Change" as AnyObject?
dict["Time"] = Chaos.currentDate(nil) as AnyObject?
dict["OldValue"] = oldValue
dict["NewValue"] = newValue
arrTrace?.append(dict)
}
else if keyPath == "userInteractionEnabled"{
let oldValue = (change![NSKeyValueChangeKey.oldKey]! as AnyObject).boolValue
let newValue = (change![NSKeyValueChangeKey.newKey]! as AnyObject).boolValue
var dict = [String:AnyObject]()
dict["Key"] = "UserInteractionEnabled Change" as AnyObject?
dict["Time"] = Chaos.currentDate(nil) as AnyObject?
dict["OldValue"] = (oldValue! ? "Yes" : "No") as AnyObject
dict["NewValue"] = (newValue! ? "Yes" : "No") as AnyObject
arrTrace?.append(dict)
}
else if keyPath == "hidden"{
let oldValue = (change![NSKeyValueChangeKey.oldKey]! as AnyObject).boolValue
let newValue = (change![NSKeyValueChangeKey.newKey]! as AnyObject).boolValue
var dict = [String:AnyObject]()
dict["Key"] = "Hidden Change" as AnyObject?
dict["Time"] = Chaos.currentDate(nil) as AnyObject?
dict["OldValue"] = (oldValue! ? "Yes" : "No") as AnyObject
dict["NewValue"] = (newValue! ? "Yes" : "No") as AnyObject
arrTrace?.append(dict)
}
else if keyPath == "bounds"{
let oldFrame = (change![NSKeyValueChangeKey.oldKey]! as AnyObject).cgRectValue
let newFrame = (change![NSKeyValueChangeKey.newKey]! as AnyObject).cgRectValue
if (oldFrame?.equalTo(newFrame!))!
{
return
}
var dict = [String:AnyObject]()
dict["Key"] = "Bounds Change" as AnyObject?
dict["Time"] = Chaos.currentDate(nil) as AnyObject?
dict["OldValue"] = "l:\(oldFrame?.origin.x.format(".1f")) t:\(oldFrame?.origin.y.format(".1f")) w:\(oldFrame?.origin.x.format(".1f")) :h\(oldFrame?.origin.x.format(".1f"))" as AnyObject?
dict["NewValue"] = "l:\(newFrame?.origin.x.format(".1f")) t:\(newFrame?.origin.y.format(".1f")) w:\(newFrame?.origin.x.format(".1f")) h:\(newFrame?.origin.x.format(".1f"))" as AnyObject?
arrTrace?.append(dict)
}
else if keyPath == "contentSize"{
let oldSize = (change![NSKeyValueChangeKey.oldKey]! as AnyObject).cgSizeValue
let newSize = (change![NSKeyValueChangeKey.newKey]! as AnyObject).cgSizeValue
if (oldSize?.equalTo(newSize!))!
{
return
}
var dict = [String:AnyObject]()
dict["Key"] = "ContentSize Change" as AnyObject?
dict["Time"] = Chaos.currentDate(nil) as AnyObject?
dict["OldValue"] = "w:\(oldSize?.width.format(".1f")) h:\(oldSize?.height.format(".1f"))" as AnyObject?
dict["NewValue"] = "w:\(newSize?.width.format(".1f")) h:\(newSize?.height.format(".1f"))" as AnyObject?
arrTrace?.append(dict)
}
else if keyPath == "contentOffset"{
let oldOffset = (change![NSKeyValueChangeKey.oldKey]! as AnyObject).cgPointValue
let newOffset = (change![NSKeyValueChangeKey.newKey]! as AnyObject).cgPointValue
if (oldOffset?.equalTo(newOffset!))!
{
return
}
var dict = [String:AnyObject]()
dict["Key"] = "ContentOffset Change" as AnyObject?
dict["Time"] = Chaos.currentDate(nil) as AnyObject?
dict["OldValue"] = "l:\(oldOffset?.x.format(".1f")) t:\(oldOffset?.y.format(".1f"))" as AnyObject?
dict["NewValue"] = "l:\(newOffset?.x.format(".1f")) t:\(newOffset?.y.format(".1f"))" as AnyObject?
arrTrace?.append(dict)
}
else if keyPath == "contentInset"{
let oldEdge = (change![NSKeyValueChangeKey.oldKey]! as AnyObject).uiEdgeInsetsValue
let newEdge = (change![NSKeyValueChangeKey.newKey]! as AnyObject).uiEdgeInsetsValue
if UIEdgeInsetsEqualToEdgeInsets(oldEdge!, newEdge!){
return
}
var dict = [String:AnyObject]()
dict["Key"] = "ContentInset Change" as AnyObject?
dict["Time"] = Chaos.currentDate(nil) as AnyObject?
dict["OldValue"] = "l:\(oldEdge?.left.format(".1f")) t:\(oldEdge?.top.format(".1f")) r:\(oldEdge?.right.format(".1f")) b:\(oldEdge?.bottom.format(".1f"))" as AnyObject?
dict["NewValue"] = "l:\(newEdge?.left.format(".1f")) t:\(newEdge?.top.format(".1f")) r:\(newEdge?.right.format(".1f")) :b\(newEdge?.bottom.format(".1f"))" as AnyObject?
arrTrace?.append(dict)
}
tbRight .reloadData()
tbRight.tableFooterView = UIView()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
isTouch = true
if let touch = touches.first{
let p = touch.location(in: self)
left = p.x
top = p.y
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if !isTouch{
return
}
if let touch = touches.first
{
let p = touch.location(in: self.window)
self.frame = CGRect(x: p.x - left, y: p.y - top, width: self.frame.size.width, height: self.frame.size.height)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
isTouch = false
}
override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) {
isTouch = false
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == tbLeft{
return tbType.about.rawValue + 1
}
else if tableView == tbRight{
if type == .general{
return (arrGeneral!.count)
}
else if type == .superview{
return arrSuperView!.count
}
else if type == .subview{
return arrSubview!.count
}
else if type == .constrain{
return arrConstrains!.count
}
else if type == .trace{
return arrTrace!.count
}
else if type == .about{
return arrAbout!.count
}
else
{
return 0
}
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell?
if tableView == tbLeft{
cell = tableView.dequeueReusableCell(withIdentifier: "cellLeft")
if cell == nil{
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cellLeft")
cell?.backgroundColor = UIColor.clear
}
cell?.textLabel?.font = UIFont.systemFont(ofSize: 14)
cell?.textLabel?.text = arrLeft![(indexPath as NSIndexPath).row]
return cell!
}
else{
switch type{
case .general:cell = handleGeneralCell(indexPath)
case .superview:cell = handleSuperViewCell(indexPath)
case .subview:cell = handleSubViewCell(indexPath)
case .constrain:cell = handleConstrainCell(indexPath)
case .trace:cell = handleTraceCell(indexPath)
case .about:cell = handleAboutCell(indexPath)
}
return cell!
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == tbLeft{
type = tbType.init(rawValue: (indexPath as NSIndexPath).row)!
tbRight.reloadData()
if type == .trace{
let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 0, height: 30))
btn.setTitle(isTrace! ? "Stop" : "Start", for: UIControlState())
btn.setTitleColor(UIColor.orange, for: UIControlState())
btn.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.74, alpha: 1.0)
btn.addTarget(self, action: #selector(ViewChaosInfo.onTrace(_:)), for: UIControlEvents.touchUpInside)
tbRight.tableHeaderView = btn
}
else
{
tbRight.tableHeaderView = nil
}
}
else{
switch type{
case .superview: let view = arrSuperView![(indexPath as NSIndexPath).row].obj as? UIView
if view != nil{
NotificationCenter.default.post(name: Notification.Name(rawValue: handleTraceView), object: view!) //不需要点一下就跳进去看那个View, 所以这里不要缩小
initView(view!, back: false)
}
case .subview: let view = arrSubview![(indexPath as NSIndexPath).row].obj as? UIView
if view != nil{
NotificationCenter.default.post(name: Notification.Name(rawValue: handleTraceView), object: view!) //不需要点一下就跳进去看那个View, 所以这里不要缩小
initView(view!, back: false)
}
case .constrain: let strType = arrConstrains![(indexPath as NSIndexPath).row]["Type"] as! String
if strType == "IntrinsicContent Width" || strType == "IntrinsicContent Height" || strType == "BaseLine" {
return
}
if viewHit == nil{
return;
}
var dict = arrConstrains![(indexPath as NSIndexPath).row]
dict["View"] = ViewChaosObject.objectWithWeak(viewHit!)
NotificationCenter.default.post(name: Notification.Name(rawValue: handleTraceContraints), object: dict)
minimize() //只有这里可以缩小一下
default: return
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if tableView == tbLeft{
return 44
}
else
{
switch type{
case .general: return heightForGeneralCell(indexPath, width: tableView.bounds.size.width - 2 * tableView.separatorInset.left)
case .superview: return heightForSuperViewCell(indexPath, width: tableView.bounds.size.width - 2 * tableView.separatorInset.left)
case .subview: return heightForSubViewCell(indexPath, width: tableView.bounds.size.width - 2 * tableView.separatorInset.left)
case .constrain: return heightForConstrainCell(indexPath, width: tableView.bounds.size.width - 2 * tableView.separatorInset.left)
case .trace: return heightForTraceCell(indexPath, width: tableView.bounds.size.width - 2 * tableView.separatorInset.left)
case .about: return heightForAboutCell(indexPath, width: tableView.bounds.size.width - 2 * tableView.separatorInset.left)
}
}
}
func handleGeneralCell(_ index:IndexPath)->UITableViewCell{
var cell = tbRight.dequeueReusableCell(withIdentifier: "tbrightGeneral")
if cell == nil{
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "tbrightGeneral")
cell?.backgroundColor = UIColor.clear
}
cell?.textLabel?.numberOfLines = 0
cell?.textLabel?.lineBreakMode = NSLineBreakMode.byCharWrapping
cell?.textLabel?.frame = CGRect(x: 0, y: 0, width: cell!.textLabel!.frame.size.width, height: 40)
cell?.textLabel?.text = arrGeneral![(index as NSIndexPath).row]
cell?.textLabel?.sizeToFit()
return cell!
}
func handleSuperViewCell(_ index:IndexPath)->UITableViewCell{
var cell = tbRight.dequeueReusableCell(withIdentifier: "tbrightSuperView")
if cell == nil{
cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "tbrightSuperView")
cell?.backgroundColor = UIColor.clear
}
let view = (arrSuperView![(index as NSIndexPath).row]).obj as? UIView
if view == nil{
cell?.textLabel?.text = "view has released"
cell?.detailTextLabel?.text = ""
}
else{
cell?.textLabel?.numberOfLines = 0
cell?.textLabel?.lineBreakMode = NSLineBreakMode.byCharWrapping
cell?.textLabel?.frame = CGRect(x: 0, y: 0, width: cell!.textLabel!.frame.size.width, height: 40)
cell?.textLabel?.font = UIFont.systemFont(ofSize: 15)
cell?.textLabel?.text = "\(type(of: view!))"
cell?.textLabel?.sizeToFit()
cell?.detailTextLabel?.numberOfLines = 0
cell?.detailTextLabel?.lineBreakMode = NSLineBreakMode.byCharWrapping
cell?.detailTextLabel?.frame = CGRect(x: 0, y: 0, width: cell!.detailTextLabel!.frame.size.width, height: 40)
cell?.detailTextLabel?.text = "l:\(view!.frame.origin.x.format(".1f")) t:\(view!.frame.origin.y.format(".1f")) w:\(view!.frame.size.width.format(".1f")) h:\(view!.frame.size.height.format(".1f"))"
if view is UILabel || view is UITextField || view is UITextView{
if let text = view?.value(forKey: "text") as? String{
cell?.detailTextLabel?.text = cell!.detailTextLabel!.text! + " text(\((text as NSString).length): \(text))"
}
}
else if view is UIButton{
let btn = view as! UIButton
let title = btn.title(for: UIControlState()) == nil ? "": btn.title(for: UIControlState())!
cell?.detailTextLabel?.text = cell!.detailTextLabel!.text! + " text(\((title as NSString).length): \(title))"
}
cell?.detailTextLabel?.sizeToFit()
}
return cell!
}
func handleSubViewCell(_ index:IndexPath)->UITableViewCell{
var cell = tbRight.dequeueReusableCell(withIdentifier: "tbrightSubView")
if cell == nil{
cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "tbrightSubView")
cell?.backgroundColor = UIColor.clear
}
let view = (arrSubview![(index as NSIndexPath).row]).obj as? UIView
if view == nil{
cell?.textLabel?.text = "view has released"
cell?.detailTextLabel?.text = ""
}
else{
cell?.textLabel?.numberOfLines = 0
cell?.textLabel?.lineBreakMode = NSLineBreakMode.byCharWrapping
cell?.textLabel?.frame = CGRect(x: 0, y: 0, width: cell!.textLabel!.frame.size.width, height: 40)
cell?.textLabel?.text = "\(type(of: view!))"
cell?.textLabel?.sizeToFit()
cell?.detailTextLabel?.numberOfLines = 0
cell?.detailTextLabel?.lineBreakMode = NSLineBreakMode.byCharWrapping
cell?.detailTextLabel?.frame = CGRect(x: 0, y: 0, width: cell!.detailTextLabel!.frame.size.width, height: 40)
cell?.detailTextLabel?.text = "l:\(view!.frame.origin.x.format(".1f")) t:\(view!.frame.origin.y.format(".1f")) w:\(view!.frame.size.width.format(".1f")) h:\(view!.frame.size.height.format(".1f"))"
if view is UILabel || view is UITextField || view is UITextView{
if let text = view?.value(forKey: "text") as? String{
cell?.detailTextLabel?.text = cell!.detailTextLabel!.text! + " text(\((text as NSString).length): \(text))"
}
}
else if view is UIButton{
let btn = view as! UIButton
let title = btn.title(for: UIControlState()) == nil ? "": btn.title(for: UIControlState())!
cell?.detailTextLabel?.text = cell!.detailTextLabel!.text! + " text(\((title as NSString).length): \(title))"
}
cell?.detailTextLabel?.sizeToFit()
}
return cell!
}
func handleConstrainCell(_ index:IndexPath)->UITableViewCell{
var cell = tbRight.dequeueReusableCell(withIdentifier: "tbrightConstrain")
if cell == nil{
cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "tbrightConstrain")
cell?.backgroundColor = UIColor.clear
}
let dict = arrConstrains![(index as NSIndexPath).row]
cell?.textLabel?.numberOfLines = 0
cell?.textLabel?.lineBreakMode = NSLineBreakMode.byCharWrapping
cell?.textLabel?.frame = CGRect(x: 0, y: 0, width: cell!.textLabel!.frame.size.width, height: 40)
cell?.textLabel?.text = "\(dict["Type"]!)(Priority:\(dict["Priority"] == nil ? "" : dict["Priority"]! as! String))"
cell?.textLabel?.sizeToFit()
cell?.detailTextLabel?.numberOfLines = 0
cell?.detailTextLabel?.lineBreakMode = NSLineBreakMode.byCharWrapping
cell?.detailTextLabel?.frame = CGRect(x: 0, y: 0, width: cell!.detailTextLabel!.frame.size.width, height: 30)
let arrTemp = (dict["Value"] as! NSString).components(separatedBy: " ")
var arr = [String]()
for t in arrTemp{
arr.append(t)
}
let text = (arr as NSArray).componentsJoined(by: " ").replacingOccurrences(of: ">", with: "")
cell?.detailTextLabel?.text = text
cell?.detailTextLabel?.sizeToFit()
return cell!
}
func handleTraceCell(_ index:IndexPath)->UITableViewCell{
var cell = tbRight.dequeueReusableCell(withIdentifier: "tbrightTrace")
if cell == nil{
cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "tbrightTrace")
cell?.backgroundColor = UIColor.clear
}
let dict = arrTrace![(index as NSIndexPath).row]
cell?.textLabel?.numberOfLines = 0
cell?.textLabel?.lineBreakMode = NSLineBreakMode.byCharWrapping
cell?.textLabel?.frame = CGRect(x: 0, y: 0, width: cell!.textLabel!.frame.size.width, height: 40)
cell?.textLabel?.text = "\(dict["Key"]!)(\(dict["Time"]!))"
cell?.textLabel?.sizeToFit()
cell?.detailTextLabel?.numberOfLines = 0
cell?.detailTextLabel?.lineBreakMode = NSLineBreakMode.byCharWrapping
cell?.detailTextLabel?.frame = CGRect(x: 0, y: 0, width: cell!.detailTextLabel!.frame.size.width, height: 40)
cell?.detailTextLabel?.text = "from \(dict["OldValue"]!) to \(dict["NewValue"]!)"
if dict["Key"] as! String == "superview.frame"{
cell?.detailTextLabel?.text = "\(dict["Superview"]!)" + cell!.detailTextLabel!.text!
}
cell?.detailTextLabel?.sizeToFit()
return cell!
}
func handleAboutCell(_ index:IndexPath)->UITableViewCell{
var cell = tbRight.dequeueReusableCell(withIdentifier: "tbrightAbout")
if cell == nil{
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "tbrightAbout")
cell?.backgroundColor = UIColor.clear
}
cell?.textLabel?.numberOfLines = 0
cell?.textLabel?.lineBreakMode = NSLineBreakMode.byCharWrapping
cell?.textLabel?.frame = CGRect(x: 0, y: 0, width: cell!.textLabel!.frame.size.width, height: 40)
cell?.textLabel?.text = arrAbout![(index as NSIndexPath).row]
cell?.textLabel?.sizeToFit()
return cell!
}
func heightForGeneralCell(_ index:IndexPath,width:CGFloat) -> CGFloat{
if (index as NSIndexPath).row == 0{
let str = arrGeneral![0] as NSString
let rect = str.boundingRect(with: CGSize(width: width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 17)], context: nil)
return rect.size.height + 5
}
else{
return 44
}
}
func heightForSuperViewCell(_ index:IndexPath,width:CGFloat) -> CGFloat{
let view = arrSuperView![(index as NSIndexPath).row].obj as? UIView
var str,strDetail:String
if view == nil
{
str = "view has released"
strDetail = ""
}
else{
str = "\(type(of: view!))"
strDetail = "l:\(view!.frame.origin.x.format(".1f"))t:\(view!.frame.origin.y.format(".1f"))w:\(view!.frame.size.width.format(".1f"))h:\(view!.frame.size.height.format(".1f"))"
if view! is UILabel || view! is UITextField || view! is UITextView{
let text = view!.value(forKey: "text") as! String
strDetail = "\(strDetail) text(\((text as NSString).length)):\(text)"
}else if view! is UIButton{
let btn = view as! UIButton
if let title = btn.title(for: UIControlState()){
strDetail = "\(strDetail) text(\((title as NSString).length)):\(title)"
}
else{
strDetail = "\(strDetail) text(0):\" \""
}
}
}
let rect = (str as NSString).boundingRect(with: CGSize(width: width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 17)], context: nil)
let rectDetail = (strDetail as NSString).boundingRect(with: CGSize(width: width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 12)], context: nil)
let height = rect.size.height + rectDetail.size.height + 10
return height
}
func heightForSubViewCell(_ index:IndexPath,width:CGFloat) -> CGFloat{
let view = arrSubview![(index as NSIndexPath).row].obj as? UIView
var str,strDetail:String
if view == nil
{
str = "view has released"
strDetail = ""
}
else{
str = "\(type(of: view!))"
strDetail = "l:\(view!.frame.origin.x.format(".1f"))t:\(view!.frame.origin.y.format(".1f"))w:\(view!.frame.size.width.format(".1f"))h:\(view!.frame.size.height.format(".1f"))"
if view! is UILabel || view! is UITextField || view! is UITextView{
let text = view!.value(forKey: "text") as! String
strDetail = "\(strDetail) text(\((text as NSString).length)):\(text)"
}else if view! is UIButton{
let btn = view as! UIButton
if let title = btn.title(for: UIControlState()){
strDetail = "\(strDetail) text(\((title as NSString).length)):\(title)"
}
else{
strDetail = "\(strDetail) text(0):\" \""
}
}
}
let rect = (str as NSString).boundingRect(with: CGSize(width: width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 17)], context: nil)
let rectDetail = (strDetail as NSString).boundingRect(with: CGSize(width: width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 12)], context: nil)
return rect.size.height + rectDetail.size.height + 10
}
func heightForConstrainCell(_ index:IndexPath,width:CGFloat) -> CGFloat{
var str,strDetail:String
let dic = arrConstrains![(index as NSIndexPath).row]
str = "\(dic["Type"]!)(Priority:\(dic["Priority"] == nil ? "" : dic["Priority"]! as! String))"
let arrTemp = (dic["Value"] as! NSString).components(separatedBy: " ")
var arr = [String]()
for t in arrTemp{
arr.append(t)
}
strDetail = (arr as NSArray).componentsJoined(by: " ").replacingOccurrences(of: ">", with: "")
let rect = (str as NSString).boundingRect(with: CGSize(width: width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 17)], context: nil)
let rectDetail = (strDetail as NSString).boundingRect(with: CGSize(width: width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 12)], context: nil)
return rect.size.height + rectDetail.size.height + 10
}
func heightForTraceCell(_ index:IndexPath,width:CGFloat)->CGFloat{
var str,strDetail:String
let dic = arrTrace![(index as NSIndexPath).row]
str = "\(dic["Key"]!)(\(dic["Time"])!)"
strDetail = "from \(dic["OldValue"]!) to \(dic["NewValue"]!)"
if (dic["Key"] as! String) == "superview.frame"{
strDetail = (dic["Superview"]! as! String) + strDetail
}
let rect = (str as NSString).boundingRect(with: CGSize(width: width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 17)], context: nil)
let rectDetail = (strDetail as NSString).boundingRect(with: CGSize(width: width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 12)], context: nil)
return rect.size.height + rectDetail.size.height + 10
}
func heightForAboutCell(_ index:IndexPath,width:CGFloat)->CGFloat{
let str = arrAbout![(index as NSIndexPath).row]
let rect = (str as NSString).boundingRect(with: CGSize(width: width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 17)], context: nil)
return rect.size.height + 5
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit{
NotificationCenter.default.removeObserver(self)
}
}
| mit | 2257abdef1ed6463fa2ec7f7ce343ce4 | 50.71157 | 282 | 0.583977 | 4.740227 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/iOS/AudioKit/AudioKit.playground/Sources/AKPlaygroundView.swift | 2 | 4314 | //
// AKPlaygroundView.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2015 Aurelius Prochazka. All rights reserved.
//
import UIKit
public typealias Slider = UISlider
public typealias Label = UILabel
public typealias TextField = UITextField
public class AKPlaygroundView: UIView {
public var elementHeight: CGFloat = 30
public var yPosition: Int = 0
public var horizontalSpacing = 40
public var lastButton: UIButton?
public override init(frame frameRect: CGRect) {
super.init(frame: frameRect)
self.backgroundColor = UIColor.whiteColor()
setup()
}
public func setup() {
}
public func addLineBreak() {
lastButton = nil
}
public func addTitle(text: String) -> UILabel {
let newLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: 2 * elementHeight))
newLabel.text = text
newLabel.textAlignment = .Center
newLabel.frame.origin.y = 0
newLabel.font = UIFont.boldSystemFontOfSize(24)
self.addSubview(newLabel)
yPosition += horizontalSpacing
return newLabel
}
public func addButton(label: String, action: Selector) -> UIButton {
let newButton = UIButton(type: .Custom)
newButton.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: elementHeight)
newButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
newButton.backgroundColor = UIColor.blueColor()
newButton.setTitle(" \(label) ", forState: .Normal)
newButton.setNeedsDisplay()
// Line up multiple buttons in a row
if let button = lastButton {
newButton.frame.origin.x += button.frame.origin.x + button.frame.width + 10
yPosition -= horizontalSpacing
}
newButton.frame.origin.y = CGFloat(yPosition)
newButton.addTarget(self, action: action, forControlEvents: .TouchDown)
newButton.sizeToFit()
self.addSubview(newButton)
yPosition += horizontalSpacing
lastButton = newButton
return newButton
}
public func addLabel(text: String) -> UILabel {
lastButton = nil
let newLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: elementHeight))
newLabel.text = text
newLabel.font = UIFont.systemFontOfSize(18)
newLabel.frame.origin.y = CGFloat(yPosition)
self.addSubview(newLabel)
yPosition += horizontalSpacing
return newLabel
}
public func addTextField(action: Selector, text: String, value: Double = 0) -> UITextField {
lastButton = nil
let newLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: elementHeight))
newLabel.text = text
newLabel.font = UIFont.systemFontOfSize(18)
newLabel.frame.origin.y = CGFloat(yPosition)
self.addSubview(newLabel)
let newTextField = UITextField(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: 20))
newTextField.frame.origin.y = CGFloat(yPosition)
newTextField.text = "\(value)"
newTextField.textAlignment = .Right
newTextField.setNeedsDisplay()
newTextField.addTarget(self, action: action, forControlEvents: .AllEvents)
self.addSubview(newTextField)
yPosition += horizontalSpacing
return newTextField
}
public func addSlider(action: Selector, value: Double = 0, minimum: Double = 0, maximum: Double = 1) -> UISlider {
lastButton = nil
let newSlider = UISlider(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: 20))
newSlider.frame.origin.y = CGFloat(yPosition)
newSlider.minimumValue = Float(minimum)
newSlider.maximumValue = Float(maximum)
newSlider.value = Float(value)
newSlider.setNeedsDisplay()
newSlider.addTarget(self, action: action, forControlEvents: .ValueChanged)
self.addSubview(newSlider)
yPosition += horizontalSpacing
return newSlider
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 1904020e6eaa92d0a5aa91605d2dabaf | 34.360656 | 118 | 0.64395 | 4.735456 | false | false | false | false |
christophhagen/Signal-iOS | SignalMessaging/utils/Searcher.swift | 1 | 1615 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
// ObjC compatible searcher
@objc class AnySearcher: NSObject {
private let searcher: Searcher<AnyObject>
public init(indexer: @escaping (AnyObject) -> String ) {
searcher = Searcher(indexer: indexer)
super.init()
}
@objc(item:doesMatchQuery:)
public func matches(item: AnyObject, query: String) -> Bool {
return searcher.matches(item: item, query: query)
}
}
// A generic searching class, configurable with an indexing block
public class Searcher<T> {
private let indexer: (T) -> String
public init(indexer: @escaping (T) -> String) {
self.indexer = indexer
}
public func matches(item: T, query: String) -> Bool {
let itemString = normalize(string: indexer(item))
return stem(string: query).map { queryStem in
return itemString.contains(queryStem)
}.reduce(true) { $0 && $1 }
}
private func stem(string: String) -> [String] {
var normalized = normalize(string: string)
// Remove any phone number formatting from the search terms
let nonformattingScalars = normalized.unicodeScalars.lazy.filter {
!CharacterSet.punctuationCharacters.contains($0)
}
normalized = String(String.UnicodeScalarView(nonformattingScalars))
return normalized.components(separatedBy: .whitespacesAndNewlines)
}
private func normalize(string: String) -> String {
return string.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
}
}
| gpl-3.0 | b2efec0ab65fd9d913cd03ca0b1d3971 | 28.363636 | 82 | 0.663777 | 4.486111 | false | false | false | false |
Jerrywx/WeiBo | Headers/Swift Guide.playground/Pages/Advanced Operators(高级运算符).xcplaygroundpage/Contents.swift | 2 | 3808 | //: [Previous](@previous)
import Foundation
/*:
一、位运算符
****
位运算符可以操作数据结构中每个独立的比特位。
*/
/*:
1、按位取反运算符(~)
作用:按位取反运算符(~)可以对一个数值的全部比特位进行取反:
注意:按位取反运算符是一个前缀运算符, 需要直接放在运算的数之前, 并且他们之间不能添加空格。
*/
// 二进制 用 0b前缀
let initialBits:UInt8 = 0b11
print(initialBits) // 十进制 3 转二进制 0b11
let invertedBits = ~initialBits
print(invertedBits)
/*:
2、按位与运算符 (&)
3、按位或运算符 (|)
4、按位异或运算符 (^)
5、按位左移、右移运算符 (<<、>>)
*/
/*:
二、溢出运算符
****
*/
/*:
三、优先级和结合性
****
运算符的优先级使得一些运算符优先于其他运算符,高优先级的运算符会先被计算。
结合性定义了相同优先级的运算符是如何结合的,也就是说,是与左边结合为一组,还是与右边结合为一组。
*/
/*:
四、运算符函数
****
1、运算符重载:
类和结构体可以为现有运算符提供自定义的实现, 这通常被称为运算符重载。
*/
prefix operator +++
struct Vector2D {
var x = 0.0, y = 0.0
}
/// 重载双目运算符
extension Vector2D {
static func + (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
}
var v1: Vector2D = Vector2D(x: 20, y: 40)
var v2: Vector2D = Vector2D(x: 10, y: 20)
let v3 = v1 + v2
print(v3)
/*:
2、前缀和后缀运算符
****
类和结构体也能提供标准单目运算符的实现, 单目运算符只运行一个值。当运算符出现在值之前时,它是前缀的(例如: -a), 而当它出现在值之后时, 它就是后缀的(例如: b!)。
要实现前缀或者后缀运算符,需要在声明运算符函数的时候在 func 关键字之前指定 prefix 或者 postfix 修饰符:
*/
/// 重载单目运算符
extension Vector2D {
static prefix func -(vector:Vector2D) -> Vector2D {
return Vector2D(x: -vector.x, y: -vector.y)
}
}
print(-v3)
/*:
3、复合赋值运算符
复合赋值运算符将赋值运算符(=)与其他运算符进行结合。例如: (+=)
注意:
不能对默认的赋值运算符(=)进行重载, 只有组合赋值运算符可以被重载, 同样也无法对三木运算符进行重载。
*/
/// 重载复合运算符
extension Vector2D {
static func += (left: inout Vector2D, right:Vector2D) {
left = left + right
}
}
v1+=v2
print(v1)
/*:
4、等价运算符
自定义的类和结构体没有对等价运算符进行默认实现, 等价运算符通常称为"相等"运算符(==)与"不等"运算符(!=)。
*/
/// 重载等价运算符
extension Vector2D {
static func ==(left: Vector2D, right:Vector2D) -> Bool{
return (left.x == right.x) && (left.y == right.y)
}
static func !=(left: Vector2D, right:Vector2D) -> Bool {
return !(left == right)
}
}
/*:
五、自定义运算符
除了实现标准运算符, 在Swift 中还可以声明和实现自定义运算符。
新的运算符要使用 operator 关键字在全局作用域内进行定义, 同时还要指定 prefix、infix、postfix 修饰符
*/
/// 自定义运算符
extension Vector2D {
static prefix func +++(vector: inout Vector2D) -> Vector2D {
vector += vector
return vector
}
}
+++v2
print(v2)
/// 自定义中缀运算符的优先级
infix operator +-: AdditionPrecedence
extension Vector2D {
static func +- (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y - right.y)
}
}
let vv1 = Vector2D(x: 20, y: 20)
let vv2 = Vector2D(x: 10, y: 10)
let vv3 = vv1+-vv2
print(vv3)
//: [Next](@next)
| apache-2.0 | dd56e8f0eacb54be5ada15ad595475e3 | 12.036649 | 88 | 0.646586 | 2.119149 | false | false | false | false |
jday001/DataEntryToolbar | Source/DataEntryToolbar.swift | 1 | 13404 | //
// DataEntryToolbar.swift
//
// Created by Jeff Day on 1/19/15.
// Copyright (c) 2015 JDay Apps, LLC. All rights reserved.
//
import UIKit
/**
A subclass of `UIToolbar` intended for use as the input accessory view of a keyboard or picker, providing Next, Previous, & Done buttons to navigate up and down a dynamic tableView.
To set up:
- Set a DataEntryToolbar instance as the inputAccessoryView of textFields you want to control
- Add textFields to `tableTextFields` in cellForRowAtIndexPath, using the textField's cell's indexPath as a key
- If you want to be notified when a user taps one of the navigation buttons, implement the appropriate didTap... closures
- The look and feel of the toolbar and its buttons can be customized as you would with any toolbar (i.e. barStyle, barTintColor, or button tintColor properties)
*/
public class DataEntryToolbar: UIToolbar {
/// The direction of the next text field that should become active.
///
/// - Next: The following text field should become firstResponder.
/// - Previous: The previous text field should become firstResponder.
/// - Done: The current text field should resign firstResponder status.
public enum ToolbarTraversalDirection: Int {
case Next = 0, Previous, Done
}
// -----------------------------------------
// MARK: - Delegate Closures
// -----------------------------------------
public typealias ButtonTapped = () -> ()
public typealias ButtonTappedFromTextField = (UITextField?) -> ()
public var didTapPreviousButton: ButtonTapped?
public var didTapPreviousButtonFromTextField: ButtonTappedFromTextField?
public var didTapNextButton: ButtonTapped?
public var didTapNextButtonFromTextField: ButtonTappedFromTextField?
public var didTapDoneButton: ButtonTapped?
public var didTapDoneButtonFromTextField: ButtonTappedFromTextField?
// -----------------------------------------
// MARK: - Public Class Properties
// -----------------------------------------
/// A button for navigating backwards/upwards through textFields in `tableView`'s cells.
public var previousButton :UIBarButtonItem!
/// A button for navigating forwards/downwards through textFields in `tableView`'s cells.
public var nextButton :UIBarButtonItem!
/// A flexible space use to provide separation between previousButton/nextButton and doneButton.
public var space :UIBarButtonItem!
/// A button used to resign firstResponder status on the active textField contained in a `tableView`'s cell.
public var doneButton :UIBarButtonItem!
/// The UITableView object for which this toolbar is managing textField navigation.
public var tableView: UITableView?
/// A property holding the direction in which the user is navigating through textFields in `tableView`'s cells.
public var toolbarTraversalDirection: ToolbarTraversalDirection!
/// A dictionary containing textFields in `tableView`, identified by the containing cell's index path.
public var tableTextFields: [NSIndexPath: UITextField] = [:]
// -----------------------------------------
// MARK: - Initializers
// -----------------------------------------
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
public init(frame: CGRect, table: UITableView) {
self.tableView = table
super.init(frame: frame)
self.setup()
}
// -----------------------------------------
// MARK: - Private Class Methods
// -----------------------------------------
/// A method to create and setup bar button items, and add them to the toolbar.
private func setup() {
// setup the bar and buttons, with a flexible space between prev/next and done
self.barStyle = .Default
self.barTintColor = UIColor.darkGrayColor()
self.previousButton = UIBarButtonItem(title: "Prev", style: .Plain, target: self, action: "previousButtonTapped")
self.previousButton.tintColor = UIColor.whiteColor()
self.nextButton = UIBarButtonItem(title: "Next", style: .Plain, target: self, action: "nextButtonTapped")
self.nextButton.tintColor = UIColor.whiteColor()
self.doneButton = UIBarButtonItem(title: "Done", style: .Plain, target: self, action: "doneButtonTapped")
self.doneButton.tintColor = UIColor.greenColor()
self.space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
// add buttons to the toolbar
self.items = [self.previousButton, self.nextButton, self.space, self.doneButton]
}
/**
findPreviousValidIndexPath is a recursive function that steps backward through the tableView's rows and sections
until it finds a row with a textField in the `tableTextFields` dictionary.
If a valid textField is found, it is activated as first responder.
:param: indexPath The current index path being checked for a valid text field.
:returns: Either the index path of a valid UITextField or nil.
*/
private func findPreviousValidIndexPath(indexPath: NSIndexPath) -> NSIndexPath? {
// if the current indexPath row is the first of a section, need to go back a section
if indexPath.row > 0 {
// search the current section
let previousIndexPath: NSIndexPath = NSIndexPath(forRow: indexPath.row - 1, inSection: indexPath.section)
if let foundTextField: UITextField = self.tableTextFields[previousIndexPath] {
foundTextField.becomeFirstResponder()
return previousIndexPath
} else {
self.findPreviousValidIndexPath(previousIndexPath)
}
} else {
// need to go back a section
if indexPath.section > 0 {
let previousSection: Int = indexPath.section - 1
// make sure there is a section before this one to go back to
if let previousSectionRows = self.tableView?.numberOfRowsInSection(previousSection) {
if let previousIndexPath = NSIndexPath(forRow: previousSectionRows - 1, inSection: previousSection) {
// make sure the preceding section has rows
if previousSectionRows > 0 {
if let foundPrevPath: UITextField = self.tableTextFields[previousIndexPath] {
foundPrevPath.becomeFirstResponder()
return previousIndexPath
} else {
self.findPreviousValidIndexPath(previousIndexPath)
}
} else {
self.findPreviousValidIndexPath(previousIndexPath)
}
}
}
}
}
return nil
}
/**
findNextValidIndexPath is a recursive function that steps foward through the tableView's rows and sections
until it finds a row with a textField in the `tableTextFields` dictionary.
If a valid textField is found, it is activated as first responder.
:param: indexPath The current index path being checked for a valid text field.
:returns: Either the index path of a valid UITextField or nil.
*/
private func findNextValidIndexPath(indexPath: NSIndexPath) -> NSIndexPath? {
// if the current indexPath is the last of a section, need to go up a section
if let lastRowOfSectionIndex = self.tableView?.numberOfRowsInSection(indexPath.section) {
if indexPath.row < lastRowOfSectionIndex - 1 {
// search the current section
let nextIndexPath: NSIndexPath = NSIndexPath(forRow: indexPath.row + 1, inSection: indexPath.section)
if let foundTextField: UITextField = self.tableTextFields[nextIndexPath] {
foundTextField.becomeFirstResponder()
return nextIndexPath
} else {
self.findNextValidIndexPath(nextIndexPath)
}
} else {
// need to go up a section
if let lastTableSection = self.tableView?.numberOfSections() {
let nextTableSection = indexPath.section + 1
// make sure there is a section after this one
if nextTableSection < lastTableSection - 1 {
if let nextIndexPath = NSIndexPath(forRow: 0, inSection: nextTableSection) {
// make sure the next section has rows
if self.tableView?.numberOfRowsInSection(nextTableSection) > 0 {
if let foundTextField: UITextField = self.tableTextFields[nextIndexPath] {
foundTextField.becomeFirstResponder()
return nextIndexPath
} else {
self.findNextValidIndexPath(nextIndexPath)
}
} else {
self.findNextValidIndexPath(nextIndexPath)
}
}
}
}
}
}
return nil
}
/// Sets the buttonTraversalDirection to .Previous, activates the previous textField in `tableTextFields`, and calls the delegate's previousButtonTapped method for any custom behavior.
@objc private func previousButtonTapped() {
// set property for the direction a user is navigating
self.toolbarTraversalDirection = .Previous
// move back to the previous textField or resign firstResponder status if already at first textField
var lastActiveTextField: UITextField?
for (indexPath, textField) in self.tableTextFields {
// found the currently active textField -- dismiss it and look for the previous textField or just resign if we are at the beginning
if textField.isFirstResponder() {
lastActiveTextField = textField
textField.resignFirstResponder()
if let prevPath: NSIndexPath = findPreviousValidIndexPath(indexPath) {}
break
}
}
// call the closure method for any further customization
if let textFieldToReturn = lastActiveTextField {
self.didTapPreviousButtonFromTextField?(lastActiveTextField)
} else {
self.didTapPreviousButton?()
}
}
/// Sets the buttonTraversalDirection to .Next, activates the next textField in `tableTextFields`, and calls the delegate's nextButtonTapped method for any custom behavior.
@objc private func nextButtonTapped() {
// set property for the direction a user is navigating
self.toolbarTraversalDirection = .Next
// move forward to the next textfield or resign firstResponder status if already at last textField
var lastActiveTextField: UITextField?
for (indexPath, textField) in self.tableTextFields {
// found the currently active textField -- dismiss it and look for the next textField or just resign if we are at the end
if textField.isFirstResponder() {
lastActiveTextField = textField
textField.resignFirstResponder()
if let nextPath: NSIndexPath = findNextValidIndexPath(indexPath) {}
break
}
}
// call the closure method for any further customization
if let textFieldToReturn = lastActiveTextField {
self.didTapNextButtonFromTextField?(lastActiveTextField)
} else {
self.didTapNextButton?()
}
}
/// Sets the buttonTraversalDirection to .Done and calls the delegate's doneButtonTapped method.
@objc private func doneButtonTapped() {
// set property for the direction a user is navigating
self.toolbarTraversalDirection = .Done
// resign firstResponder status on the active textField
var lastActiveTextField: UITextField?
for (indexPath, textField) in self.tableTextFields {
// found the currently active textField -- dismiss it and look for the next textField or just resign if we are at the end
if textField.isFirstResponder() {
lastActiveTextField = textField
textField.resignFirstResponder()
break
}
}
// call the closure method for any further customization
if let textFieldToReturn = lastActiveTextField {
self.didTapNextButtonFromTextField?(lastActiveTextField)
} else {
self.didTapNextButton?()
}
}
} | mit | 42b21ebca280dad6bcaf5d2bc60b3ffd | 44.750853 | 188 | 0.60288 | 5.946761 | false | false | false | false |
LeeMinglu/LSWeiboSwift | LSWeiboSwift/LSWeiboSwift/Classes/View/Main/VisitorView/LSVisitorView.swift | 1 | 7339 | //
// LSVisitorView.swift
// LSWeiboSwift
//
// Created by 李明禄 on 2017/8/19.
// Copyright © 2017年 SocererGroup. All rights reserved.
//
import UIKit
class LSVisitorView: UIView {
//添加注册按钮
lazy var regigterBtn:UIButton = UIButton.cz_textButton(
"注册",
fontSize: 16,
normalColor: .orange,
highlightedColor: .black,
backgroundImageName: "common_button_white_disable")
//添加登陆按钮
lazy var loginBtn:UIButton = UIButton.cz_textButton(
"登录",
fontSize: 16,
normalColor: .orange,
highlightedColor: .black,
backgroundImageName: "common_button_white_disable")
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: -设置visitorInfo
var visitorInfo: [String: String]? {
didSet {
guard let imageName = visitorInfo?["imageName"],
let message = visitorInfo?["message"]
else {
return
}
tipLabel.text = message
if imageName == "" {
startAnimate()
return
}
iconView.image = UIImage(named: imageName)
houseView.isHidden = true
maskIconView.isHidden = true
}
}
//MARK: - 旋转动画
fileprivate func startAnimate() {
let animate = CABasicAnimation(keyPath: "transform.rotation")
animate.toValue = Double.pi
animate.duration = 20
animate.repeatCount = MAXFLOAT
//必须添加在动作之前,否则是不生效的
animate.isRemovedOnCompletion = false
iconView.layer.add(animate, forKey: nil)
}
//MARK:- 懒加载视图
//添加image
fileprivate lazy var iconView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon"))
//添加MaskIconImage
fileprivate lazy var maskIconView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon"))
//添加小房子
fileprivate lazy var houseView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house"))
//添加label
fileprivate lazy var tipLabel: UILabel = UILabel.cz_label(withText: "关注一些人看看有什么惊喜吧", fontSize: 14, color: .darkGray)
}
extension LSVisitorView {
func setupUI() {
self.backgroundColor = UIColor.cz_color(withRed: 237, green: 237, blue: 237)
//1. 添加视图
addSubview(iconView)
addSubview(maskIconView)
addSubview(houseView)
addSubview(tipLabel)
addSubview(regigterBtn)
addSubview(loginBtn)
tipLabel.textAlignment = .center
//sb使用autolayout 代码使用autoresize
//2. 取消autoresize
for v in subviews {
v.translatesAutoresizingMaskIntoConstraints = false
}
//3.使用苹果原生设置布局
//设置iconView
addConstraint(NSLayoutConstraint(
item: iconView,
attribute: .centerX,
relatedBy: .equal,
toItem: self,
attribute: .centerX,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(
item: iconView,
attribute: .centerY,
relatedBy: .equal,
toItem: self,
attribute: .centerY,
multiplier: 1.0,
constant: -60))
//设置houseView
addConstraint(NSLayoutConstraint(
item: houseView,
attribute: .centerX,
relatedBy: .equal,
toItem: iconView,
attribute: .centerX,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(
item: houseView,
attribute: .centerY,
relatedBy: .equal,
toItem: iconView,
attribute: .centerY,
multiplier: 1.0,
constant: 20))
//设置tipLabel
addConstraint(NSLayoutConstraint(
item: tipLabel,
attribute: .centerX,
relatedBy: .equal,
toItem: iconView,
attribute: .centerX,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(
item: tipLabel,
attribute: .top,
relatedBy: .equal,
toItem: iconView,
attribute: .bottom,
multiplier: 1.0,
constant: 20))
//在Label中显示内容换行
addConstraint(NSLayoutConstraint(
item: tipLabel,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 236))
//设置注册按钮
addConstraint(NSLayoutConstraint(
item: regigterBtn,
attribute: .left,
relatedBy: .equal,
toItem: tipLabel,
attribute: .left,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(
item: regigterBtn,
attribute: .top,
relatedBy: .equal,
toItem: tipLabel,
attribute: .bottom,
multiplier: 1.0,
constant: 10))
addConstraint(NSLayoutConstraint(
item: regigterBtn,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 100))
//设置登陆按钮
addConstraint(NSLayoutConstraint(
item: loginBtn,
attribute: .right,
relatedBy: .equal,
toItem: tipLabel,
attribute: .right,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(
item: loginBtn,
attribute: .top,
relatedBy: .equal,
toItem: tipLabel,
attribute: .bottom,
multiplier: 1.0,
constant: 10))
addConstraint(NSLayoutConstraint(
item: loginBtn,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 100))
//使用VFL布局maskIcon
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[maskIconView]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["maskIconView": maskIconView]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[maskIconView]-(0)-[regigterBtn]", options: .directionLeadingToTrailing, metrics: nil, views: ["maskIconView": maskIconView, "regigterBtn": regigterBtn]))
}
}
| apache-2.0 | 69f7d95f7c56133e23483f87ee5a6143 | 27.821138 | 233 | 0.535402 | 5.182749 | false | false | false | false |
Farteen/firefox-ios | Client/Frontend/Browser/URLBarView.swift | 3 | 27592 | /* 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 UIKit
import Shared
import SnapKit
private struct URLBarViewUX {
// The color shown behind the tabs count button, and underneath the (mostly transparent) status bar.
static let TextFieldBorderColor = UIColor.blackColor().colorWithAlphaComponent(0.05)
static let TextFieldActiveBorderColor = UIColor(rgb: 0x4A90E2)
static let TextFieldContentInset = UIOffsetMake(9, 5)
static let LocationLeftPadding = 5
static let LocationHeight = 28
static let LocationContentOffset: CGFloat = 8
static let TextFieldCornerRadius: CGFloat = 3
static let TextFieldBorderWidth: CGFloat = 1
// offset from edge of tabs button
static let URLBarCurveOffset: CGFloat = 14
// buffer so we dont see edges when animation overshoots with spring
static let URLBarCurveBounceBuffer: CGFloat = 8
static let TabsButtonRotationOffset: CGFloat = 1.5
static let TabsButtonHeight: CGFloat = 18.0
static let ToolbarButtonInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
static func backgroundColorWithAlpha(alpha: CGFloat) -> UIColor {
return UIConstants.AppBackgroundColor.colorWithAlphaComponent(alpha)
}
}
protocol URLBarDelegate: class {
func urlBarDidPressTabs(urlBar: URLBarView)
func urlBarDidPressReaderMode(urlBar: URLBarView)
/// :returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied
func urlBarDidLongPressReaderMode(urlBar: URLBarView) -> Bool
func urlBarDidPressStop(urlBar: URLBarView)
func urlBarDidPressReload(urlBar: URLBarView)
func urlBarDidBeginEditing(urlBar: URLBarView)
func urlBarDidEndEditing(urlBar: URLBarView)
func urlBarDidLongPressLocation(urlBar: URLBarView)
func urlBarLocationAccessibilityActions(urlBar: URLBarView) -> [UIAccessibilityCustomAction]?
func urlBarDidPressScrollToTop(urlBar: URLBarView)
func urlBar(urlBar: URLBarView, didEnterText text: String)
func urlBar(urlBar: URLBarView, didSubmitText text: String)
}
class URLBarView: UIView {
weak var delegate: URLBarDelegate?
weak var browserToolbarDelegate: BrowserToolbarDelegate?
var helper: BrowserToolbarHelper?
var toolbarIsShowing = false
var backButtonLeftConstraint: Constraint?
lazy var locationView: BrowserLocationView = {
var locationView = BrowserLocationView(frame: CGRectZero)
locationView.setTranslatesAutoresizingMaskIntoConstraints(false)
locationView.readerModeState = ReaderModeState.Unavailable
locationView.delegate = self
locationView.autocompleteDelegate = self
locationView.locationContentInset = URLBarViewUX.LocationContentOffset
locationView.borderColor = URLBarViewUX.TextFieldBorderColor.CGColor
locationView.cornerRadius = URLBarViewUX.TextFieldCornerRadius
locationView.borderWidth = URLBarViewUX.TextFieldBorderWidth
locationView.editingBorderColor = URLBarViewUX.TextFieldActiveBorderColor.CGColor
return locationView
}()
private lazy var locationContainer: UIView = {
var locationContainer = UIView()
locationContainer.setTranslatesAutoresizingMaskIntoConstraints(false)
return locationContainer
}()
private lazy var tabsButton: UIButton = {
var tabsButton = InsetButton()
tabsButton.setTranslatesAutoresizingMaskIntoConstraints(false)
tabsButton.setTitle("0", forState: UIControlState.Normal)
tabsButton.setTitleColor(URLBarViewUX.backgroundColorWithAlpha(1), forState: UIControlState.Normal)
tabsButton.titleLabel?.layer.backgroundColor = UIColor.whiteColor().CGColor
tabsButton.titleLabel?.layer.cornerRadius = 2
tabsButton.titleLabel?.font = UIConstants.DefaultSmallFontBold
tabsButton.titleLabel?.textAlignment = NSTextAlignment.Center
tabsButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
tabsButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
tabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility Label for the tabs button in the browser toolbar")
return tabsButton
}()
private lazy var progressBar: UIProgressView = {
var progressBar = UIProgressView()
progressBar.progressTintColor = UIColor(red:1, green:0.32, blue:0, alpha:1)
progressBar.alpha = 0
progressBar.hidden = true
return progressBar
}()
private lazy var cancelButton: UIButton = {
var cancelButton = InsetButton()
cancelButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
let cancelTitle = NSLocalizedString("Cancel", comment: "Button label to cancel entering a URL or search query")
cancelButton.setTitle(cancelTitle, forState: UIControlState.Normal)
cancelButton.titleLabel?.font = UIConstants.DefaultMediumFont
cancelButton.addTarget(self, action: "SELdidClickCancel", forControlEvents: UIControlEvents.TouchUpInside)
cancelButton.titleEdgeInsets = UIEdgeInsetsMake(10, 12, 10, 12)
cancelButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
cancelButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
return cancelButton
}()
private lazy var curveShape: CurveView = { return CurveView() }()
private lazy var scrollToTopButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: "SELtappedScrollToTopArea", forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
lazy var shareButton: UIButton = { return UIButton() }()
lazy var bookmarkButton: UIButton = { return UIButton() }()
lazy var forwardButton: UIButton = { return UIButton() }()
lazy var backButton: UIButton = { return UIButton() }()
lazy var stopReloadButton: UIButton = { return UIButton() }()
lazy var actionButtons: [UIButton] = {
return [self.shareButton, self.bookmarkButton, self.forwardButton, self.backButton, self.stopReloadButton]
}()
// Used to temporarily store the cloned button so we can respond to layout changes during animation
private weak var clonedTabsButton: InsetButton?
private var rightBarConstraint: Constraint?
private let defaultRightOffset: CGFloat = URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer
var isEditing: Bool {
return locationView.active
}
var canCancel: Bool {
return !cancelButton.hidden
}
var currentURL: NSURL? {
get {
return locationView.url
}
set(newURL) {
locationView.url = newURL
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
backgroundColor = URLBarViewUX.backgroundColorWithAlpha(0)
addSubview(curveShape);
addSubview(scrollToTopButton)
locationContainer.addSubview(locationView)
addSubview(locationContainer)
addSubview(progressBar)
addSubview(tabsButton)
addSubview(cancelButton)
addSubview(shareButton)
addSubview(bookmarkButton)
addSubview(forwardButton)
addSubview(backButton)
addSubview(stopReloadButton)
helper = BrowserToolbarHelper(toolbar: self)
setupConstraints()
// Make sure we hide any views that shouldn't be showing in non-editing mode
finishEditingAnimation(false)
}
private func setupConstraints() {
scrollToTopButton.snp_makeConstraints { make in
make.top.equalTo(self)
make.left.right.equalTo(self.locationContainer)
}
progressBar.snp_makeConstraints { make in
make.top.equalTo(self.snp_bottom)
make.width.equalTo(self)
}
locationView.snp_makeConstraints { make in
make.edges.equalTo(self.locationContainer).insets(EdgeInsetsMake(URLBarViewUX.TextFieldBorderWidth,
URLBarViewUX.TextFieldBorderWidth,
URLBarViewUX.TextFieldBorderWidth,
URLBarViewUX.TextFieldBorderWidth))
}
cancelButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
}
tabsButton.titleLabel?.snp_makeConstraints { make in
make.size.equalTo(URLBarViewUX.TabsButtonHeight)
}
curveShape.snp_makeConstraints { make in
make.top.left.bottom.equalTo(self)
self.rightBarConstraint = make.right.equalTo(self).constraint
self.rightBarConstraint?.updateOffset(defaultRightOffset)
}
}
private func updateToolbarConstraints() {
if toolbarIsShowing {
backButton.snp_remakeConstraints { (make) -> () in
self.backButtonLeftConstraint = make.left.equalTo(self).constraint
make.centerY.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
backButton.contentEdgeInsets = URLBarViewUX.ToolbarButtonInsets
forwardButton.snp_remakeConstraints { (make) -> () in
make.left.equalTo(self.backButton.snp_right)
make.centerY.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
forwardButton.contentEdgeInsets = URLBarViewUX.ToolbarButtonInsets
stopReloadButton.snp_remakeConstraints { (make) -> () in
make.left.equalTo(self.forwardButton.snp_right)
make.centerY.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
stopReloadButton.contentEdgeInsets = URLBarViewUX.ToolbarButtonInsets
shareButton.snp_remakeConstraints { (make) -> () in
make.right.equalTo(self.bookmarkButton.snp_left)
make.centerY.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
bookmarkButton.snp_remakeConstraints { (make) -> () in
make.right.equalTo(self.tabsButton.snp_left)
make.centerY.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
}
}
override func updateConstraints() {
updateToolbarConstraints()
tabsButton.snp_remakeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
make.width.height.equalTo(UIConstants.ToolbarHeight)
}
updateLayoutForEditing(editing: isEditing, animated: false)
super.updateConstraints()
}
// Ideally we'd split this implementation in two, one URLBarView with a toolbar and one without
// However, switching views dynamically at runtime is a difficult. For now, we just use one view
// that can show in either mode.
func setShowToolbar(shouldShow: Bool) {
toolbarIsShowing = shouldShow
setNeedsUpdateConstraints()
}
func updateURLBarText(text: String) {
delegate?.urlBarDidBeginEditing(self)
locationView.text = text
updateLayoutForEditing(editing: true)
delegate?.urlBar(self, didEnterText: text)
}
func updateAlphaForSubviews(alpha: CGFloat) {
self.tabsButton.alpha = alpha
self.locationContainer.alpha = alpha
self.backgroundColor = URLBarViewUX.backgroundColorWithAlpha(1 - alpha)
self.actionButtons.map { $0.alpha = alpha }
}
func updateTabCount(count: Int) {
// make a 'clone' of the tabs button
let newTabsButton = InsetButton()
self.clonedTabsButton = newTabsButton
newTabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
newTabsButton.setTitleColor(UIConstants.AppBackgroundColor, forState: UIControlState.Normal)
newTabsButton.titleLabel?.layer.backgroundColor = UIColor.whiteColor().CGColor
newTabsButton.titleLabel?.layer.cornerRadius = 2
newTabsButton.titleLabel?.font = UIConstants.DefaultSmallFontBold
newTabsButton.titleLabel?.textAlignment = NSTextAlignment.Center
newTabsButton.setTitle(count.description, forState: .Normal)
addSubview(newTabsButton)
newTabsButton.titleLabel?.snp_makeConstraints { make in
make.size.equalTo(URLBarViewUX.TabsButtonHeight)
}
newTabsButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
newTabsButton.frame = tabsButton.frame
// Instead of changing the anchorPoint of the CALayer, lets alter the rotation matrix math to be
// a rotation around a non-origin point
if let labelFrame = newTabsButton.titleLabel?.frame {
let halfTitleHeight = CGRectGetHeight(labelFrame) / 2
var newFlipTransform = CATransform3DIdentity
newFlipTransform = CATransform3DTranslate(newFlipTransform, 0, halfTitleHeight, 0)
newFlipTransform.m34 = -1.0 / 200.0 // add some perspective
newFlipTransform = CATransform3DRotate(newFlipTransform, CGFloat(-M_PI_2), 1.0, 0.0, 0.0)
newTabsButton.titleLabel?.layer.transform = newFlipTransform
var oldFlipTransform = CATransform3DIdentity
oldFlipTransform = CATransform3DTranslate(oldFlipTransform, 0, halfTitleHeight, 0)
oldFlipTransform.m34 = -1.0 / 200.0 // add some perspective
oldFlipTransform = CATransform3DRotate(oldFlipTransform, CGFloat(M_PI_2), 1.0, 0.0, 0.0)
UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { _ in
newTabsButton.titleLabel?.layer.transform = CATransform3DIdentity
self.tabsButton.titleLabel?.layer.transform = oldFlipTransform
self.tabsButton.titleLabel?.layer.opacity = 0
}, completion: { _ in
// remove the clone and setup the actual tab button
newTabsButton.removeFromSuperview()
self.tabsButton.titleLabel?.layer.opacity = 1
self.tabsButton.titleLabel?.layer.transform = CATransform3DIdentity
self.tabsButton.setTitle(count.description, forState: UIControlState.Normal)
self.tabsButton.accessibilityValue = count.description
self.tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility label for the tabs button in the (top) browser toolbar")
})
}
}
func updateProgressBar(progress: Float) {
if progress == 1.0 {
self.progressBar.setProgress(progress, animated: true)
UIView.animateWithDuration(1.5, animations: {
self.progressBar.alpha = 0.0
}, completion: { _ in
self.progressBar.setProgress(0.0, animated: false)
})
} else {
self.progressBar.alpha = 1.0
self.progressBar.setProgress(progress, animated: (progress > progressBar.progress))
}
}
func updateReaderModeState(state: ReaderModeState) {
locationView.readerModeState = state
}
func setAutocompleteSuggestion(suggestion: String?) {
locationView.editTextField.setAutocompleteSuggestion(suggestion)
}
func finishEditing() {
locationView.active = false
updateLayoutForEditing(editing: false)
delegate?.urlBarDidEndEditing(self)
}
func prepareEditingAnimation(editing: Bool) {
// Make sure everything is showing during the transition (we'll hide it afterwards).
self.progressBar.hidden = editing
self.tabsButton.hidden = false
self.cancelButton.hidden = false
self.forwardButton.hidden = !self.toolbarIsShowing
self.backButton.hidden = !self.toolbarIsShowing
self.stopReloadButton.hidden = !self.toolbarIsShowing
self.shareButton.hidden = !self.toolbarIsShowing
self.bookmarkButton.hidden = !self.toolbarIsShowing
// Update the location bar's size. If we're animating, we'll call layoutIfNeeded in the Animation
// and transition to this.
if editing {
// In editing mode, we always show the location view full width
self.locationContainer.snp_remakeConstraints { make in
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.cancelButton.snp_leading)
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self)
}
} else {
self.locationContainer.snp_remakeConstraints { make in
if self.toolbarIsShowing {
// If we are showing a toolbar, show the text field next to the forward button
make.left.equalTo(self.stopReloadButton.snp_right)
make.right.equalTo(self.shareButton.snp_left)
} else {
// Otherwise, left align the location view
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.tabsButton.snp_leading).offset(-14)
}
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self)
}
}
}
func transitionToEditing(editing: Bool) {
self.cancelButton.alpha = editing ? 1 : 0
self.shareButton.alpha = editing ? 0 : 1
self.bookmarkButton.alpha = editing ? 0 : 1
if editing {
self.cancelButton.transform = CGAffineTransformIdentity
let tabsButtonTransform = CGAffineTransformMakeTranslation(self.tabsButton.frame.width + URLBarViewUX.URLBarCurveOffset, 0)
self.tabsButton.transform = tabsButtonTransform
self.clonedTabsButton?.transform = tabsButtonTransform
self.rightBarConstraint?.updateOffset(URLBarViewUX.URLBarCurveOffset + URLBarViewUX.URLBarCurveBounceBuffer + tabsButton.frame.width)
if self.toolbarIsShowing {
self.backButtonLeftConstraint?.updateOffset(-3 * UIConstants.ToolbarHeight)
}
} else {
self.tabsButton.transform = CGAffineTransformIdentity
self.clonedTabsButton?.transform = CGAffineTransformIdentity
self.cancelButton.transform = CGAffineTransformMakeTranslation(self.cancelButton.frame.width, 0)
self.rightBarConstraint?.updateOffset(defaultRightOffset)
if self.toolbarIsShowing {
self.backButtonLeftConstraint?.updateOffset(0)
}
}
}
func finishEditingAnimation(editing: Bool) {
self.tabsButton.hidden = editing
self.cancelButton.hidden = !editing
self.forwardButton.hidden = !self.toolbarIsShowing || editing
self.backButton.hidden = !self.toolbarIsShowing || editing
self.shareButton.hidden = !self.toolbarIsShowing || editing
self.bookmarkButton.hidden = !self.toolbarIsShowing || editing
self.stopReloadButton.hidden = !self.toolbarIsShowing || editing
}
func updateLayoutForEditing(#editing: Bool, animated: Bool = true) {
prepareEditingAnimation(editing)
if animated {
self.layoutIfNeeded()
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: nil, animations: { _ in
self.transitionToEditing(editing)
self.layoutIfNeeded()
}, completion: { _ in
self.finishEditingAnimation(editing)
})
} else {
finishEditingAnimation(editing)
}
}
func SELdidClickAddTab() {
delegate?.urlBarDidPressTabs(self)
}
func SELdidClickCancel() {
locationView.cancel()
finishEditing()
}
func SELtappedScrollToTopArea() {
delegate?.urlBarDidPressScrollToTop(self)
}
}
extension URLBarView: BrowserToolbarProtocol {
func updateBackStatus(canGoBack: Bool) {
backButton.enabled = canGoBack
}
func updateForwardStatus(canGoForward: Bool) {
forwardButton.enabled = canGoForward
}
func updateBookmarkStatus(isBookmarked: Bool) {
bookmarkButton.selected = isBookmarked
}
func updateReloadStatus(isLoading: Bool) {
if isLoading {
stopReloadButton.setImage(helper?.ImageStop, forState: .Normal)
stopReloadButton.setImage(helper?.ImageStopPressed, forState: .Highlighted)
} else {
stopReloadButton.setImage(helper?.ImageReload, forState: .Normal)
stopReloadButton.setImage(helper?.ImageReloadPressed, forState: .Highlighted)
}
}
func updatePageStatus(#isWebPage: Bool) {
bookmarkButton.enabled = isWebPage
stopReloadButton.enabled = isWebPage
shareButton.enabled = isWebPage
}
override var accessibilityElements: [AnyObject]! {
get {
if canCancel {
return [locationView, cancelButton]
} else {
if toolbarIsShowing {
return [backButton, forwardButton, stopReloadButton, locationView, shareButton, bookmarkButton, tabsButton, progressBar]
} else {
return [locationView, tabsButton, progressBar]
}
}
}
set {
super.accessibilityElements = newValue
}
}
}
extension URLBarView: BrowserLocationViewDelegate {
func browserLocationViewDidLongPressReaderMode(browserLocationView: BrowserLocationView) -> Bool {
return delegate?.urlBarDidLongPressReaderMode(self) ?? false
}
func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidBeginEditing(self)
// locationView÷.editTextField.text = locationView.url?.absoluteString
// locationView.editTextField.becomeFirstResponder()
updateLayoutForEditing(editing: true)
}
func browserLocationViewDidLongPressLocation(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidLongPressLocation(self)
}
func browserLocationViewDidTapReload(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressReload(self)
}
func browserLocationViewDidTapStop(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressStop(self)
}
func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressReaderMode(self)
}
func browserLocationViewLocationAccessibilityActions(browserLocationView: BrowserLocationView) -> [UIAccessibilityCustomAction]? {
return delegate?.urlBarLocationAccessibilityActions(self)
}
}
extension URLBarView: AutocompleteTextFieldDelegate {
func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool {
delegate?.urlBar(self, didSubmitText: locationView.text)
return true
}
func autocompleteTextField(autocompleteTextField: AutocompleteTextField, didTextChange text: String) {
delegate?.urlBar(self, didEnterText: text)
}
func autocompleteTextFieldDidBeginEditing(autocompleteTextField: AutocompleteTextField) {
delegate?.urlBarDidBeginEditing(self)
autocompleteTextField.highlightAll()
}
func autocompleteTextFieldShouldClear(autocompleteTextField: AutocompleteTextField) -> Bool {
delegate?.urlBar(self, didEnterText: "")
return true
}
}
/* Code for drawing the urlbar curve */
// Curve's aspect ratio
private let ASPECT_RATIO = 0.729
// Width multipliers
private let W_M1 = 0.343
private let W_M2 = 0.514
private let W_M3 = 0.49
private let W_M4 = 0.545
private let W_M5 = 0.723
// Height multipliers
private let H_M1 = 0.25
private let H_M2 = 0.5
private let H_M3 = 0.72
private let H_M4 = 0.961
/* Code for drawing the urlbar curve */
private class CurveView: UIView {
private lazy var leftCurvePath: UIBezierPath = {
var leftArc = UIBezierPath(arcCenter: CGPoint(x: 5, y: 5), radius: CGFloat(5), startAngle: CGFloat(-M_PI), endAngle: CGFloat(-M_PI_2), clockwise: true)
leftArc.addLineToPoint(CGPoint(x: 0, y: 0))
leftArc.addLineToPoint(CGPoint(x: 0, y: 5))
leftArc.closePath()
return leftArc
}()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
self.opaque = false
self.contentMode = .Redraw
}
private func getWidthForHeight(height: Double) -> Double {
return height * ASPECT_RATIO
}
private func drawFromTop(path: UIBezierPath) {
let height: Double = Double(UIConstants.ToolbarHeight)
let width = getWidthForHeight(height)
var from = (Double(self.frame.width) - width * 2 - Double(URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer), Double(0))
path.moveToPoint(CGPoint(x: from.0, y: from.1))
path.addCurveToPoint(CGPoint(x: from.0 + width * W_M2, y: from.1 + height * H_M2),
controlPoint1: CGPoint(x: from.0 + width * W_M1, y: from.1),
controlPoint2: CGPoint(x: from.0 + width * W_M3, y: from.1 + height * H_M1))
path.addCurveToPoint(CGPoint(x: from.0 + width, y: from.1 + height),
controlPoint1: CGPoint(x: from.0 + width * W_M4, y: from.1 + height * H_M3),
controlPoint2: CGPoint(x: from.0 + width * W_M5, y: from.1 + height * H_M4))
}
private func getPath() -> UIBezierPath {
let path = UIBezierPath()
self.drawFromTop(path)
path.addLineToPoint(CGPoint(x: self.frame.width, y: UIConstants.ToolbarHeight))
path.addLineToPoint(CGPoint(x: self.frame.width, y: 0))
path.addLineToPoint(CGPoint(x: 0, y: 0))
path.closePath()
return path
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextClearRect(context, rect)
CGContextSetFillColorWithColor(context, URLBarViewUX.backgroundColorWithAlpha(1).CGColor)
getPath().fill()
leftCurvePath.fill()
CGContextDrawPath(context, kCGPathFill)
CGContextRestoreGState(context)
}
}
| mpl-2.0 | c6b3261e61094b4cf7b632ebbbe4b6de | 39.634757 | 177 | 0.678917 | 5.429162 | false | false | false | false |
airbnb/lottie-ios | Sources/Private/MainThread/NodeRenderSystem/Nodes/ModifierNodes/TrimPathNode.swift | 2 | 9405 | //
// TrimPathNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/23/19.
//
import Foundation
import QuartzCore
// MARK: - TrimPathProperties
final class TrimPathProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(trim: Trim) {
keypathName = trim.name
start = NodeProperty(provider: KeyframeInterpolator(keyframes: trim.start.keyframes))
end = NodeProperty(provider: KeyframeInterpolator(keyframes: trim.end.keyframes))
offset = NodeProperty(provider: KeyframeInterpolator(keyframes: trim.offset.keyframes))
type = trim.trimType
keypathProperties = [
"Start" : start,
"End" : end,
"Offset" : offset,
]
properties = Array(keypathProperties.values)
}
// MARK: Internal
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
let keypathName: String
let start: NodeProperty<LottieVector1D>
let end: NodeProperty<LottieVector1D>
let offset: NodeProperty<LottieVector1D>
let type: TrimType
}
// MARK: - TrimPathNode
final class TrimPathNode: AnimatorNode {
// MARK: Lifecycle
init(parentNode: AnimatorNode?, trim: Trim, upstreamPaths: [PathOutputNode]) {
outputNode = PassThroughOutputNode(parent: parentNode?.outputNode)
self.parentNode = parentNode
properties = TrimPathProperties(trim: trim)
self.upstreamPaths = upstreamPaths
}
// MARK: Internal
let properties: TrimPathProperties
let parentNode: AnimatorNode?
let outputNode: NodeOutput
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
var isEnabled = true
// MARK: Animator Node
var propertyMap: NodePropertyMap & KeypathSearchable {
properties
}
func forceUpstreamOutputUpdates() -> Bool {
hasLocalUpdates || hasUpstreamUpdates
}
func rebuildOutputs(frame: CGFloat) {
/// Make sure there is a trim.
let startValue = properties.start.value.cgFloatValue * 0.01
let endValue = properties.end.value.cgFloatValue * 0.01
let start = min(startValue, endValue)
let end = max(startValue, endValue)
let offset = properties.offset.value.cgFloatValue.truncatingRemainder(dividingBy: 360) / 360
/// No need to trim, it's a full path
if start == 0, end == 1 {
return
}
/// All paths are empty.
if start == end {
for pathContainer in upstreamPaths {
pathContainer.removePaths(updateFrame: frame)
}
return
}
if properties.type == .simultaneously {
/// Just trim each path
for pathContainer in upstreamPaths {
let pathObjects = pathContainer.removePaths(updateFrame: frame)
for path in pathObjects {
// We are treating each compount path as an individual path. Its subpaths are treated as a whole.
pathContainer.appendPath(
path.trim(fromPosition: start, toPosition: end, offset: offset, trimSimultaneously: false),
updateFrame: frame)
}
}
return
}
/// Individual path trimming.
/// Brace yourself for the below code.
/// Normalize lengths with offset.
var startPosition = (start + offset).truncatingRemainder(dividingBy: 1)
var endPosition = (end + offset).truncatingRemainder(dividingBy: 1)
if startPosition < 0 {
startPosition = 1 + startPosition
}
if endPosition < 0 {
endPosition = 1 + endPosition
}
if startPosition == 1 {
startPosition = 0
}
if endPosition == 0 {
endPosition = 1
}
/// First get the total length of all paths.
var totalLength: CGFloat = 0
upstreamPaths.forEach { totalLength = totalLength + $0.totalLength }
/// Now determine the start and end cut lengths
let startLength = startPosition * totalLength
let endLength = endPosition * totalLength
var pathStart: CGFloat = 0
/// Now loop through all path containers
for pathContainer in upstreamPaths {
let pathEnd = pathStart + pathContainer.totalLength
if
!startLength.isInRange(pathStart, pathEnd) &&
endLength.isInRange(pathStart, pathEnd)
{
// pathStart|=======E----------------------|pathEnd
// Cut path components, removing after end.
let pathCutLength = endLength - pathStart
let subpaths = pathContainer.removePaths(updateFrame: frame)
var subpathStart: CGFloat = 0
for path in subpaths {
let subpathEnd = subpathStart + path.length
if pathCutLength < subpathEnd {
/// This is the subpath that needs to be cut.
let cutLength = pathCutLength - subpathStart
let newPath = path.trim(fromPosition: 0, toPosition: cutLength / path.length, offset: 0, trimSimultaneously: false)
pathContainer.appendPath(newPath, updateFrame: frame)
break
} else {
/// Add to container and move on
pathContainer.appendPath(path, updateFrame: frame)
}
if pathCutLength == subpathEnd {
/// Right on the end. The next subpath is not included. Break.
break
}
subpathStart = subpathEnd
}
} else if
!endLength.isInRange(pathStart, pathEnd) &&
startLength.isInRange(pathStart, pathEnd)
{
// pathStart|-------S======================|pathEnd
//
// Cut path components, removing before beginning.
let pathCutLength = startLength - pathStart
// Clear paths from container
let subpaths = pathContainer.removePaths(updateFrame: frame)
var subpathStart: CGFloat = 0
for path in subpaths {
let subpathEnd = subpathStart + path.length
if subpathStart < pathCutLength, pathCutLength < subpathEnd {
/// This is the subpath that needs to be cut.
let cutLength = pathCutLength - subpathStart
let newPath = path.trim(fromPosition: cutLength / path.length, toPosition: 1, offset: 0, trimSimultaneously: false)
pathContainer.appendPath(newPath, updateFrame: frame)
} else if pathCutLength <= subpathStart {
pathContainer.appendPath(path, updateFrame: frame)
}
subpathStart = subpathEnd
}
} else if
endLength.isInRange(pathStart, pathEnd) &&
startLength.isInRange(pathStart, pathEnd)
{
// pathStart|-------S============E---------|endLength
// pathStart|=====E----------------S=======|endLength
// trim from path beginning to endLength.
// Cut path components, removing before beginnings.
let startCutLength = startLength - pathStart
let endCutLength = endLength - pathStart
// Clear paths from container
let subpaths = pathContainer.removePaths(updateFrame: frame)
var subpathStart: CGFloat = 0
for path in subpaths {
let subpathEnd = subpathStart + path.length
if
!startCutLength.isInRange(subpathStart, subpathEnd),
!endCutLength.isInRange(subpathStart, subpathEnd)
{
// The whole path is included. Add
// S|==============================|E
pathContainer.appendPath(path, updateFrame: frame)
} else if
startCutLength.isInRange(subpathStart, subpathEnd),
!endCutLength.isInRange(subpathStart, subpathEnd)
{
/// The start of the path needs to be trimmed
// |-------S======================|E
let cutLength = startCutLength - subpathStart
let newPath = path.trim(fromPosition: cutLength / path.length, toPosition: 1, offset: 0, trimSimultaneously: false)
pathContainer.appendPath(newPath, updateFrame: frame)
} else if
!startCutLength.isInRange(subpathStart, subpathEnd),
endCutLength.isInRange(subpathStart, subpathEnd)
{
// S|=======E----------------------|
let cutLength = endCutLength - subpathStart
let newPath = path.trim(fromPosition: 0, toPosition: cutLength / path.length, offset: 0, trimSimultaneously: false)
pathContainer.appendPath(newPath, updateFrame: frame)
break
} else if
startCutLength.isInRange(subpathStart, subpathEnd),
endCutLength.isInRange(subpathStart, subpathEnd)
{
// |-------S============E---------|
let cutFromLength = startCutLength - subpathStart
let cutToLength = endCutLength - subpathStart
let newPath = path.trim(
fromPosition: cutFromLength / path.length,
toPosition: cutToLength / path.length,
offset: 0,
trimSimultaneously: false)
pathContainer.appendPath(newPath, updateFrame: frame)
break
}
subpathStart = subpathEnd
}
} else if
(endLength <= pathStart && pathEnd <= startLength) ||
(startLength <= pathStart && endLength <= pathStart) ||
(pathEnd <= startLength && pathEnd <= endLength)
{
/// The Path needs to be cleared
pathContainer.removePaths(updateFrame: frame)
}
pathStart = pathEnd
}
}
// MARK: Fileprivate
fileprivate let upstreamPaths: [PathOutputNode]
}
| apache-2.0 | 27883171d116cb5af7c115e1385b61ca | 32.830935 | 127 | 0.62488 | 4.711924 | false | false | false | false |
trident10/TDMediaPicker | TDMediaPicker/Classes/View/CustomView/TDMediaVideoView.swift | 1 | 2809 | //
// TDMediaVideoView.swift
// Pods
//
// Created by Abhimanu Jindal on 27/07/17.
//
//
import UIKit
import Photos
protocol TDMediaVideoViewDelegate {
func videoViewDidStopPlay(_ view:TDMediaVideoView)
}
class TDMediaVideoView: UIView {
// MARK: - Variable(s)
private var avPlayerLayer: AVPlayerLayer?
private var avPlayer: AVPlayer?
private var asset: PHAsset?
var delegate: TDMediaVideoViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
print("Video Deinit")
}
// MARK: - Public Method(s)
func playVideo(){
self.isHidden = false
self.avPlayer?.play()
}
func stopVideo(){
self.isHidden = true
self.avPlayer?.pause()
self.avPlayer?.seek(to: kCMTimeZero)
}
func pause(){
self.isHidden = true
self.avPlayer?.pause()
}
func purgeVideoPlayer(_ completion: @escaping () -> Void){
if self.avPlayerLayer != nil{
self.purgeVideoLayer {
completion()
}
return
}
completion()
}
func setupVideoPlayer(_ asset: PHAsset, completion: @escaping () -> Void){
self.asset = asset
self.setupPlayer {
self.isHidden = true
completion()
}
}
// MARK: - Private Method(s)
private func setupPlayer(_ completion: @escaping () -> Void){
TDMediaUtil.fetchPlayerItem(self.asset!) { (playerItem) in
if playerItem != nil{
self.avPlayer = AVPlayer(playerItem: playerItem!)
NotificationCenter.default.addObserver(self, selector: #selector(self.playerItemDidPlayToEndTime), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
self.avPlayerLayer = AVPlayerLayer(player: self.avPlayer)
self.avPlayerLayer!.frame = self.bounds
self.avPlayerLayer?.videoGravity = AVLayerVideoGravity.resizeAspect
self.layer.addSublayer(self.avPlayerLayer!)
completion()
}
}
}
private func purgeVideoLayer(_ completion: @escaping () -> Void){
self.avPlayerLayer?.removeFromSuperlayer()
avPlayerLayer = nil
stopVideo()
avPlayer = nil
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
completion()
}
@objc private func playerItemDidPlayToEndTime(){
stopVideo()
self.delegate?.videoViewDidStopPlay(self)
}
}
| mit | 349532133dd11ee15e2f84e52e984082 | 26.009615 | 190 | 0.594518 | 4.954145 | false | false | false | false |
zwaldowski/ParksAndRecreation | Latest/String Views.playground/Sources/SimpleStringViews.swift | 1 | 3499 | import Foundation
public struct StringLinesView<Base: StringProtocol> where Base.Index == String.Index {
fileprivate let base: Base
fileprivate init(_ base: Base) {
self.base = base
}
}
extension StringLinesView: BidirectionalCollection {
public typealias Index = Base.Index
public var startIndex: Index {
return base.startIndex
}
public var endIndex: Index {
return base.endIndex
}
public func index(after i: Index) -> Index {
var i = i
formIndex(after: &i)
return i
}
public func formIndex(after i: inout Index) {
guard i != base.endIndex else { return }
var unused1 = base.startIndex, unused2 = base.startIndex
base.getLineStart(&unused1, end: &i, contentsEnd: &unused2, for: i ..< i)
}
public func index(before i: Index) -> Index {
var i = i
formIndex(before: &i)
return i
}
public func formIndex(before i: inout Index) {
guard i != base.startIndex else { return }
base.formIndex(before: &i)
var unused1 = base.startIndex, unused2 = base.startIndex
base.getLineStart(&i, end: &unused1, contentsEnd: &unused2, for: i ..< i)
}
public subscript(i: Index) -> Base.SubSequence {
guard i != base.endIndex else { preconditionFailure("Out of bounds") }
var start = base.startIndex, unused1 = base.startIndex, end = base.endIndex
base.getLineStart(&start, end: &unused1, contentsEnd: &end, for: i ..< i)
return base[start ..< end]
}
}
public struct StringParagraphsView<Base: StringProtocol> where Base.Index == String.Index {
fileprivate let base: Base
fileprivate init(_ base: Base) {
self.base = base
}
}
extension StringParagraphsView: BidirectionalCollection {
public typealias Index = Base.Index
public var startIndex: Index {
return base.startIndex
}
public var endIndex: Index {
return base.endIndex
}
public func index(after i: Index) -> Index {
var i = i
formIndex(after: &i)
return i
}
public func formIndex(after i: inout Index) {
guard i != base.endIndex else { return }
var unused1 = base.startIndex, unused2 = base.startIndex
base.getParagraphStart(&unused1, end: &i, contentsEnd: &unused2, for: i ..< i)
}
public func index(before i: Index) -> Index {
var i = i
formIndex(before: &i)
return i
}
public func formIndex(before i: inout Index) {
guard i != base.startIndex else { return }
base.formIndex(before: &i)
var unused1 = base.startIndex, unused2 = base.startIndex
base.getParagraphStart(&i, end: &unused1, contentsEnd: &unused2, for: i ..< i)
}
public subscript(i: Index) -> Base.SubSequence {
guard i != base.endIndex else { preconditionFailure("Out of bounds") }
var start = base.startIndex, unused1 = base.startIndex, end = base.endIndex
base.getParagraphStart(&start, end: &unused1, contentsEnd: &end, for: i ..< i)
return base[start ..< end]
}
}
extension StringProtocol where Index == String.Index {
public typealias LinesView = StringLinesView<Self>
public var lines: LinesView {
return LinesView(self)
}
public typealias ParagraphsView = StringParagraphsView<Self>
public var paragraphs: ParagraphsView {
return ParagraphsView(self)
}
}
| mit | 41e47e4ffce6ed55fac3d9633b521c68 | 26.124031 | 91 | 0.627608 | 4.190419 | false | false | false | false |
xiabob/ZhiHuDaily | ZhiHuDaily/ZhiHuDaily/Views/NewsDetail/NewsDetailBottomToolBar.swift | 1 | 8502 | //
// NewsDetailBottomToolBar.swift
// ZhiHuDaily
//
// Created by xiabob on 17/3/23.
// Copyright © 2017年 xiabob. All rights reserved.
//
import UIKit
protocol NewsDetailBottomToolBarDelegate: NSObjectProtocol {
func bottomToolBar(_ toolBar: NewsDetailBottomToolBar, didClickBackButton button: UIButton)
func bottomToolBar(_ toolBar: NewsDetailBottomToolBar, didClickNextButton button: UIButton)
func bottomToolBar(_ toolBar: NewsDetailBottomToolBar, didClickVoteButton button: UIButton)
func bottomToolBar(_ toolBar: NewsDetailBottomToolBar, didClickShareButton button: UIButton)
func bottomToolBar(_ toolBar: NewsDetailBottomToolBar, didClickCommentButton button: UIButton)
}
class NewsDetailBottomToolBar: UIView {
fileprivate lazy var backButton: UIButton = { [unowned self] in
let button = UIButton()
button.setImage(#imageLiteral(resourceName: "News_Navigation_Arrow"), for: .normal)
button.setImage(#imageLiteral(resourceName: "News_Navigation_Arrow_Highlight"), for: .highlighted)
button.addTarget(self, action: #selector(onBackButtonClicked), for: .touchUpInside)
return button
}()
fileprivate lazy var nextButton: UIButton = { [unowned self] in
let button = UIButton()
button.setImage(#imageLiteral(resourceName: "News_Navigation_Next"), for: .normal)
button.setImage(#imageLiteral(resourceName: "News_Navigation_Next_Highlight"), for: .highlighted)
button.setImage(#imageLiteral(resourceName: "News_Navigation_Unnext"), for: .disabled)
button.addTarget(self, action: #selector(onNextButtonClicked), for: .touchUpInside)
return button
}()
fileprivate lazy var voteButton: UIButton = { [unowned self] in
let button = UIButton()
button.setImage(#imageLiteral(resourceName: "News_Navigation_Vote"), for: .normal)
button.setImage(#imageLiteral(resourceName: "News_Navigation_Vote"), for: .highlighted)
button.addTarget(self, action: #selector(onVoteButtonClicked), for: .touchUpInside)
return button
}()
fileprivate lazy var voteLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 8)
label.textColor = UIColor.gray
label.textAlignment = .left
label.text = ""
return label
}()
fileprivate lazy var shareButton: UIButton = { [unowned self] in
let button = UIButton()
button.setImage(#imageLiteral(resourceName: "News_Navigation_Share"), for: .normal)
button.setImage(#imageLiteral(resourceName: "News_Navigation_Share_Highlight"), for: .highlighted)
button.addTarget(self, action: #selector(onShareButtonClicked), for: .touchUpInside)
return button
}()
fileprivate lazy var commentButton: UIButton = { [unowned self] in
let button = UIButton()
button.setImage(#imageLiteral(resourceName: "News_Navigation_Comment"), for: .normal)
button.setImage(#imageLiteral(resourceName: "News_Navigation_Comment_Highlight"), for: .highlighted)
button.addTarget(self, action: #selector(onCommentButtonClicked), for: .touchUpInside)
return button
}()
fileprivate lazy var commentLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 8)
label.textColor = UIColor.white
label.textAlignment = .center
label.text = "0"
return label
}()
fileprivate lazy var voteNumberView: UIImageView = {
let view = UIImageView(image: #imageLiteral(resourceName: "News_Number_Bg"))
view.sizeToFit()
return view
}()
fileprivate lazy var voteNumberLabel: ScrollNumberLabel = { [unowned self] in
let rect = CGRect(x: 0, y: 0, width: 40, height: 20)
let label = ScrollNumberLabel(frame: rect, originNumber: 0)
label.center = CGPoint(x: self.voteNumberView.xb_width/2, y: self.voteNumberView.xb_height/2 - 3)
label.textColor = UIColor.white
return label
}()
weak var delegate: NewsDetailBottomToolBarDelegate?
var extraModel: NewsExtraModel?
//MARK: - init
override init(frame: CGRect) {
super.init(frame: frame)
configViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - config views
fileprivate func configViews() {
backgroundColor = UIColor.white
layer.shadowOpacity = 1
layer.shadowOffset = CGSize(width: 0, height: -kXBBorderWidth)
layer.shadowColor = UIColor.black.withAlphaComponent(0.15).cgColor
layer.shadowRadius = kXBBorderWidth
let buttonWidth = kScreenWidth / 5
backButton.frame = CGRect(x: 0, y: 0, width: buttonWidth, height: xb_height)
addSubview(backButton)
nextButton.frame = CGRect(x: backButton.xb_right, y: 0, width: buttonWidth, height: xb_height)
addSubview(nextButton)
voteButton.frame = CGRect(x: nextButton.xb_right, y: 0, width: buttonWidth, height: xb_height)
addSubview(voteButton)
voteLabel.frame = CGRect(x: voteButton.xb_width/2+6, y: 10, width: 40, height: 12)
voteButton.addSubview(voteLabel)
shareButton.frame = CGRect(x: voteButton.xb_right, y: 0, width: buttonWidth, height: xb_height)
addSubview(shareButton)
commentButton.frame = CGRect(x: shareButton.xb_right, y: 0, width: buttonWidth, height: xb_height)
addSubview(commentButton)
commentLabel.frame = CGRect(x: commentButton.xb_width/2, y: 10, width: 20, height: 12)
commentButton.addSubview(commentLabel)
voteNumberView.addSubview(voteNumberLabel)
}
func refreshViews(with model: NewsExtraModel?, andNewsPosition position: NewsPositionInNewsList) {
extraModel = model
if position == .last || position == .alone {
nextButton.isEnabled = false
} else {
nextButton.isEnabled = true
}
let voteNumber = extraModel?.voteNumber ?? 0
voteLabel.text = voteNumber > 0 ? "\(voteNumber)" : ""
commentLabel.text = "\(extraModel?.allCommentNumber ?? 0)"
voteNumberLabel.change(toNewNumber: UInt(voteNumber))
if model?.hasVoted ?? false {
voteButton.setImage(#imageLiteral(resourceName: "News_Navigation_Voted"), for: .normal)
} else {
voteButton.setImage(#imageLiteral(resourceName: "News_Navigation_Vote"), for: .normal)
}
}
//MARK: - action
@objc fileprivate func onBackButtonClicked() {
delegate?.bottomToolBar(self, didClickBackButton: backButton)
}
@objc fileprivate func onNextButtonClicked() {
delegate?.bottomToolBar(self, didClickNextButton: nextButton)
}
@objc fileprivate func onVoteButtonClicked() {
voteNumberView.center = CGPoint(x: voteButton.xb_centerX, y: 0)
voteNumberView.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
voteNumberView.alpha = 0
addSubview(voteNumberView)
UIView.animate(withDuration: 0.25) {
self.voteNumberView.transform = CGAffineTransform.identity
self.voteNumberView.xb_centerY = -20
self.voteNumberView.alpha = 1
}
let vote = (extraModel?.hasVoted ?? false) ? (extraModel?.voteNumber ?? 0) - 1 : (extraModel?.voteNumber ?? 0) + 1
dispatchMain(after: 0.5) {
self.voteNumberLabel.change(toNewNumber: UInt(vote))
}
dispatchMain(after: 0.9) {
UIView.animate(withDuration: 0.25, animations: {
self.voteNumberView.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
self.voteNumberView.xb_centerY = 0
self.voteNumberView.alpha = 0
}, completion: { (finished) in
self.voteNumberView.removeFromSuperview()
self.delegate?.bottomToolBar(self, didClickVoteButton: self.voteButton)
})
}
}
@objc fileprivate func onShareButtonClicked() {
delegate?.bottomToolBar(self, didClickShareButton: shareButton)
}
@objc fileprivate func onCommentButtonClicked() {
delegate?.bottomToolBar(self, didClickCommentButton: commentButton)
}
}
| mit | 791e0bc25401b8c97d89be59ba3ad32e | 40.057971 | 122 | 0.653018 | 4.574273 | false | false | false | false |
eoger/firefox-ios | Client/Frontend/Settings/AppSettingsOptions.swift | 1 | 44219 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Account
import SwiftKeychainWrapper
import LocalAuthentication
// This file contains all of the settings available in the main settings screen of the app.
private var ShowDebugSettings: Bool = false
private var DebugSettingsClickCount: Int = 0
// For great debugging!
class HiddenSetting: Setting {
unowned let settings: SettingsTableViewController
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var hidden: Bool {
return !ShowDebugSettings
}
}
// Sync setting for connecting a Firefox Account. Shown when we don't have an account.
class ConnectSetting: WithoutAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var title: NSAttributedString? {
return NSAttributedString(string: Strings.FxASignInToSync, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override var accessibilityIdentifier: String? { return "SignInToSync" }
override func onClick(_ navigationController: UINavigationController?) {
let fxaParams = FxALaunchParams(query: ["entrypoint": "preferences"])
let viewController = FxAContentViewController(profile: profile, fxaOptions: fxaParams)
viewController.delegate = self
viewController.url = settings.profile.accountConfiguration.signInURL
navigationController?.pushViewController(viewController, animated: true)
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.imageView?.image = UIImage.templateImageNamed("FxA-Default")
cell.imageView?.tintColor = UIColor.theme.tableView.disabledRowText
cell.imageView?.layer.cornerRadius = (cell.imageView?.frame.size.width)! / 2
cell.imageView?.layer.masksToBounds = true
}
}
class SyncNowSetting: WithAccountSetting {
let imageView = UIImageView(frame: CGRect(width: 30, height: 30))
let syncIconWrapper = UIImage.createWithColor(CGSize(width: 30, height: 30), color: UIColor.clear)
let syncBlueIcon = UIImage(named: "FxA-Sync-Blue")?.createScaled(CGSize(width: 20, height: 20))
let syncIcon = UIImage(named: "FxA-Sync")?.createScaled(CGSize(width: 20, height: 20))
// Animation used to rotate the Sync icon 360 degrees while syncing is in progress.
let continuousRotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
override init(settings: SettingsTableViewController) {
super.init(settings: settings)
NotificationCenter.default.addObserver(self, selector: #selector(stopRotateSyncIcon), name: .ProfileDidFinishSyncing, object: nil)
}
fileprivate lazy var timestampFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}()
fileprivate var syncNowTitle: NSAttributedString {
if !DeviceInfo.hasConnectivity() {
return NSAttributedString(
string: Strings.FxANoInternetConnection,
attributes: [
NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.errorText,
NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultMediumFont
]
)
}
return NSAttributedString(
string: NSLocalizedString("Sync Now", comment: "Sync Firefox Account"),
attributes: [
NSAttributedStringKey.foregroundColor: self.enabled ? UIColor.theme.tableView.syncText : UIColor.theme.tableView.headerTextLight,
NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFont
]
)
}
fileprivate let syncingTitle = NSAttributedString(string: Strings.SyncingMessageWithEllipsis, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText, NSAttributedStringKey.font: UIFont.systemFont(ofSize: DynamicFontHelper.defaultHelper.DefaultStandardFontSize, weight: UIFont.Weight.regular)])
func startRotateSyncIcon() {
DispatchQueue.main.async {
self.imageView.layer.add(self.continuousRotateAnimation, forKey: "rotateKey")
}
}
@objc func stopRotateSyncIcon() {
DispatchQueue.main.async {
self.imageView.layer.removeAllAnimations()
}
}
override var accessoryType: UITableViewCellAccessoryType { return .none }
override var style: UITableViewCellStyle { return .value1 }
override var image: UIImage? {
guard let syncStatus = profile.syncManager.syncDisplayState else {
return syncIcon
}
switch syncStatus {
case .inProgress:
return syncBlueIcon
default:
return syncIcon
}
}
override var title: NSAttributedString? {
guard let syncStatus = profile.syncManager.syncDisplayState else {
return syncNowTitle
}
switch syncStatus {
case .bad(let message):
guard let message = message else { return syncNowTitle }
return NSAttributedString(string: message, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.errorText, NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFont])
case .warning(let message):
return NSAttributedString(string: message, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.warningText, NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFont])
case .inProgress:
return syncingTitle
default:
return syncNowTitle
}
}
override var status: NSAttributedString? {
guard let timestamp = profile.syncManager.lastSyncFinishTime else {
return nil
}
let formattedLabel = timestampFormatter.string(from: Date.fromTimestamp(timestamp))
let attributedString = NSMutableAttributedString(string: formattedLabel)
let attributes = [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)]
let range = NSRange(location: 0, length: attributedString.length)
attributedString.setAttributes(attributes, range: range)
return attributedString
}
override var enabled: Bool {
if !DeviceInfo.hasConnectivity() {
return false
}
return profile.hasSyncableAccount()
}
fileprivate lazy var troubleshootButton: UIButton = {
let troubleshootButton = UIButton(type: .roundedRect)
troubleshootButton.setTitle(Strings.FirefoxSyncTroubleshootTitle, for: .normal)
troubleshootButton.addTarget(self, action: #selector(self.troubleshoot), for: .touchUpInside)
troubleshootButton.tintColor = UIColor.theme.tableView.rowActionAccessory
troubleshootButton.titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultSmallFont
troubleshootButton.sizeToFit()
return troubleshootButton
}()
fileprivate lazy var warningIcon: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "AmberCaution"))
imageView.sizeToFit()
return imageView
}()
fileprivate lazy var errorIcon: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "RedCaution"))
imageView.sizeToFit()
return imageView
}()
fileprivate let syncSUMOURL = SupportUtils.URLForTopic("sync-status-ios")
@objc fileprivate func troubleshoot() {
let viewController = SettingsContentViewController()
viewController.url = syncSUMOURL
settings.navigationController?.pushViewController(viewController, animated: true)
}
override func onConfigureCell(_ cell: UITableViewCell) {
cell.textLabel?.attributedText = title
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = .byWordWrapping
if let syncStatus = profile.syncManager.syncDisplayState {
switch syncStatus {
case .bad(let message):
if let _ = message {
// add the red warning symbol
// add a link to the MANA page
cell.detailTextLabel?.attributedText = nil
cell.accessoryView = troubleshootButton
addIcon(errorIcon, toCell: cell)
} else {
cell.detailTextLabel?.attributedText = status
cell.accessoryView = nil
}
case .warning(_):
// add the amber warning symbol
// add a link to the MANA page
cell.detailTextLabel?.attributedText = nil
cell.accessoryView = troubleshootButton
addIcon(warningIcon, toCell: cell)
case .good:
cell.detailTextLabel?.attributedText = status
fallthrough
default:
cell.accessoryView = nil
}
} else {
cell.accessoryView = nil
}
cell.accessoryType = accessoryType
cell.isUserInteractionEnabled = !profile.syncManager.isSyncing && DeviceInfo.hasConnectivity()
// Animation that loops continously until stopped
continuousRotateAnimation.fromValue = 0.0
continuousRotateAnimation.toValue = CGFloat(Double.pi)
continuousRotateAnimation.isRemovedOnCompletion = true
continuousRotateAnimation.duration = 0.5
continuousRotateAnimation.repeatCount = .infinity
// To ensure sync icon is aligned properly with user's avatar, an image is created with proper
// dimensions and color, then the scaled sync icon is added as a subview.
imageView.contentMode = .center
imageView.image = image
cell.imageView?.subviews.forEach({ $0.removeFromSuperview() })
cell.imageView?.image = syncIconWrapper
cell.imageView?.addSubview(imageView)
if let syncStatus = profile.syncManager.syncDisplayState {
switch syncStatus {
case .inProgress:
self.startRotateSyncIcon()
default:
self.stopRotateSyncIcon()
}
}
}
fileprivate func addIcon(_ image: UIImageView, toCell cell: UITableViewCell) {
cell.contentView.addSubview(image)
cell.textLabel?.snp.updateConstraints { make in
make.leading.equalTo(image.snp.trailing).offset(5)
make.trailing.lessThanOrEqualTo(cell.contentView)
make.centerY.equalTo(cell.contentView)
}
image.snp.makeConstraints { make in
make.leading.equalTo(cell.contentView).offset(17)
make.top.equalTo(cell.textLabel!).offset(2)
}
}
override func onClick(_ navigationController: UINavigationController?) {
if !DeviceInfo.hasConnectivity() {
return
}
NotificationCenter.default.post(name: .UserInitiatedSyncManually, object: nil)
profile.syncManager.syncEverything(why: .syncNow)
}
}
// Sync setting that shows the current Firefox Account status.
class AccountStatusSetting: WithAccountSetting {
override init(settings: SettingsTableViewController) {
super.init(settings: settings)
NotificationCenter.default.addObserver(self, selector: #selector(updateAccount), name: .FirefoxAccountProfileChanged, object: nil)
}
@objc func updateAccount(notification: Notification) {
DispatchQueue.main.async {
self.settings.tableView.reloadData()
}
}
override var image: UIImage? {
if let image = profile.getAccount()?.fxaProfile?.avatar.image {
return image.createScaled(CGSize(width: 30, height: 30))
}
let image = UIImage(named: "placeholder-avatar")
return image?.createScaled(CGSize(width: 30, height: 30))
}
override var accessoryType: UITableViewCellAccessoryType {
if let account = profile.getAccount() {
switch account.actionNeeded {
case .needsVerification:
// We link to the resend verification email page.
return .disclosureIndicator
case .needsPassword:
// We link to the re-enter password page.
return .disclosureIndicator
case .none:
// We link to FxA web /settings.
return .disclosureIndicator
case .needsUpgrade:
// In future, we'll want to link to an upgrade page.
return .none
}
}
return .disclosureIndicator
}
override var title: NSAttributedString? {
if let account = profile.getAccount() {
if let displayName = account.fxaProfile?.displayName {
return NSAttributedString(string: displayName, attributes: [NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText])
}
if let email = account.fxaProfile?.email {
return NSAttributedString(string: email, attributes: [NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText])
}
return NSAttributedString(string: account.email, attributes: [NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText])
}
return nil
}
override var status: NSAttributedString? {
if let account = profile.getAccount() {
var string: String
switch account.actionNeeded {
case .none:
return nil
case .needsVerification:
string = Strings.FxAAccountVerifyEmail
break
case .needsPassword:
string = Strings.FxAAccountVerifyPassword
break
case .needsUpgrade:
string = Strings.FxAAccountUpgradeFirefox
break
}
let orange = UIColor.theme.tableView.warningText
let range = NSRange(location: 0, length: string.count)
let attrs = [NSAttributedStringKey.foregroundColor: orange]
let res = NSMutableAttributedString(string: string)
res.setAttributes(attrs, range: range)
return res
}
return nil
}
override func onClick(_ navigationController: UINavigationController?) {
let fxaParams = FxALaunchParams(query: ["entrypoint": "preferences"])
let viewController = FxAContentViewController(profile: profile, fxaOptions: fxaParams)
viewController.delegate = self
if let account = profile.getAccount() {
switch account.actionNeeded {
case .none:
let viewController = SyncContentSettingsViewController()
viewController.profile = profile
navigationController?.pushViewController(viewController, animated: true)
return
case .needsVerification:
var cs = URLComponents(url: account.configuration.settingsURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email))
if let url = try? cs?.asURL() {
viewController.url = url
}
case .needsPassword:
var cs = URLComponents(url: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email))
if let url = try? cs?.asURL() {
viewController.url = url
}
case .needsUpgrade:
// In future, we'll want to link to an upgrade page.
return
}
}
navigationController?.pushViewController(viewController, animated: true)
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if let imageView = cell.imageView {
imageView.subviews.forEach({ $0.removeFromSuperview() })
imageView.frame = CGRect(width: 30, height: 30)
imageView.layer.cornerRadius = (imageView.frame.height) / 2
imageView.layer.masksToBounds = true
imageView.image = image
}
}
}
// For great debugging!
class RequirePasswordDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount(), account.actionNeeded != FxAActionNeeded.needsPassword {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onClick(_ navigationController: UINavigationController?) {
profile.getAccount()?.makeSeparated()
settings.tableView.reloadData()
}
}
// For great debugging!
class RequireUpgradeDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount(), account.actionNeeded != FxAActionNeeded.needsUpgrade {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onClick(_ navigationController: UINavigationController?) {
profile.getAccount()?.makeDoghouse()
settings.tableView.reloadData()
}
}
// For great debugging!
class ForgetSyncAuthStateDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let _ = profile.getAccount() {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onClick(_ navigationController: UINavigationController?) {
profile.getAccount()?.syncAuthState.invalidate()
settings.tableView.reloadData()
}
}
class DeleteExportedDataSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onClick(_ navigationController: UINavigationController?) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let fileManager = FileManager.default
do {
let files = try fileManager.contentsOfDirectory(atPath: documentsPath)
for file in files {
if file.hasPrefix("browser.") || file.hasPrefix("logins.") {
try fileManager.removeItemInDirectory(documentsPath, named: file)
}
}
} catch {
print("Couldn't delete exported data: \(error).")
}
}
}
class ExportBrowserDataSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onClick(_ navigationController: UINavigationController?) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
do {
let log = Logger.syncLogger
try self.settings.profile.files.copyMatching(fromRelativeDirectory: "", toAbsoluteDirectory: documentsPath) { file in
log.debug("Matcher: \(file)")
return file.hasPrefix("browser.") || file.hasPrefix("logins.") || file.hasPrefix("metadata.")
}
} catch {
print("Couldn't export browser data: \(error).")
}
}
}
/*
FeatureSwitchSetting is a boolean switch for features that are enabled via a FeatureSwitch.
These are usually features behind a partial release and not features released to the entire population.
*/
class FeatureSwitchSetting: BoolSetting {
let featureSwitch: FeatureSwitch
let prefs: Prefs
init(prefs: Prefs, featureSwitch: FeatureSwitch, with title: NSAttributedString) {
self.featureSwitch = featureSwitch
self.prefs = prefs
super.init(prefs: prefs, defaultValue: featureSwitch.isMember(prefs), attributedTitleText: title)
}
override var hidden: Bool {
return !ShowDebugSettings
}
override func displayBool(_ control: UISwitch) {
control.isOn = featureSwitch.isMember(prefs)
}
override func writeBool(_ control: UISwitch) {
self.featureSwitch.setMembership(control.isOn, for: self.prefs)
}
}
class EnableBookmarkMergingSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Enable Bidirectional Bookmark Sync ", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onClick(_ navigationController: UINavigationController?) {
AppConstants.shouldMergeBookmarks = true
}
}
class ForceCrashSetting: HiddenSetting {
override var title: NSAttributedString? {
return NSAttributedString(string: "Debug: Force Crash", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onClick(_ navigationController: UINavigationController?) {
Sentry.shared.crash()
}
}
// Show the current version of Firefox
class VersionSetting: Setting {
unowned let settings: SettingsTableViewController
override var accessibilityIdentifier: String? { return "FxVersion" }
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var title: NSAttributedString? {
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
let buildNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String
return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.selectionStyle = .none
}
override func onClick(_ navigationController: UINavigationController?) {
DebugSettingsClickCount += 1
if DebugSettingsClickCount >= 5 {
DebugSettingsClickCount = 0
ShowDebugSettings = !ShowDebugSettings
settings.tableView.reloadData()
}
}
}
// Opens the the license page in a new tab
class LicenseAndAcknowledgementsSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override var url: URL? {
return URL(string: WebServer.sharedInstance.URLForResource("license", module: "about"))
}
override func onClick(_ navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens about:rights page in the content view controller
class YourRightsSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Your Rights", comment: "Your Rights settings section title"), attributes:
[NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override var url: URL? {
return URL(string: "https://www.mozilla.org/about/legal/terms/firefox/")
}
override func onClick(_ navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens the on-boarding screen again
class ShowIntroductionSetting: Setting {
let profile: Profile
override var accessibilityIdentifier: String? { return "ShowTour" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
navigationController?.dismiss(animated: true, completion: {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.browserViewController.presentIntroViewController(true)
}
})
}
}
class SendFeedbackSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Menu item in settings used to open input.mozilla.org where people can submit feedback"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override var url: URL? {
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
return URL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)")
}
override func onClick(_ navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
class SendAnonymousUsageDataSetting: BoolSetting {
init(prefs: Prefs, delegate: SettingsDelegate?) {
let statusText = NSMutableAttributedString()
statusText.append(NSAttributedString(string: Strings.SendUsageSettingMessage, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight]))
statusText.append(NSAttributedString(string: " "))
statusText.append(NSAttributedString(string: Strings.SendUsageSettingLink, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.general.highlightBlue]))
super.init(
prefs: prefs, prefKey: AppConstants.PrefSendUsageData, defaultValue: true,
attributedTitleText: NSAttributedString(string: Strings.SendUsageSettingTitle),
attributedStatusText: statusText,
settingDidChange: {
AdjustIntegration.setEnabled($0)
LeanPlumClient.shared.set(attributes: [LPAttributeKey.telemetryOptIn: $0])
LeanPlumClient.shared.set(enabled: $0)
}
)
}
override var url: URL? {
return SupportUtils.URLForTopic("adjust")
}
override func onClick(_ navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens the the SUMO page in a new tab
class OpenSupportPageSetting: Setting {
init(delegate: SettingsDelegate?) {
super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]),
delegate: delegate)
}
override func onClick(_ navigationController: UINavigationController?) {
navigationController?.dismiss(animated: true) {
if let url = URL(string: "https://support.mozilla.org/products/ios") {
self.delegate?.settingsOpenURLInNewTab(url)
}
}
}
}
// Opens the search settings pane
class SearchSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var style: UITableViewCellStyle { return .value1 }
override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) }
override var accessibilityIdentifier: String? { return "Search" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = SearchSettingsTableViewController()
viewController.model = profile.searchEngines
viewController.profile = profile
navigationController?.pushViewController(viewController, animated: true)
}
}
class LoginsSetting: Setting {
let profile: Profile
var tabManager: TabManager!
weak var navigationController: UINavigationController?
weak var settings: AppSettingsTableViewController?
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "Logins" }
init(settings: SettingsTableViewController, delegate: SettingsDelegate?) {
self.profile = settings.profile
self.tabManager = settings.tabManager
self.navigationController = settings.navigationController
self.settings = settings as? AppSettingsTableViewController
let loginsTitle = NSLocalizedString("Logins", comment: "Label used as an item in Settings. When touched, the user will be navigated to the Logins/Password manager.")
super.init(title: NSAttributedString(string: loginsTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]),
delegate: delegate)
}
func deselectRow () {
if let selectedRow = self.settings?.tableView.indexPathForSelectedRow {
self.settings?.tableView.deselectRow(at: selectedRow, animated: true)
}
}
override func onClick(_: UINavigationController?) {
guard let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() else {
settings?.navigateToLoginsList()
LeanPlumClient.shared.track(event: .openedLogins)
return
}
if authInfo.requiresValidation() {
AppAuthenticator.presentAuthenticationUsingInfo(authInfo,
touchIDReason: AuthenticationStrings.loginsTouchReason,
success: {
self.settings?.navigateToLoginsList()
LeanPlumClient.shared.track(event: .openedLogins)
},
cancel: {
self.deselectRow()
},
fallback: {
AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self.settings)
self.deselectRow()
})
} else {
settings?.navigateToLoginsList()
LeanPlumClient.shared.track(event: .openedLogins)
}
}
}
class TouchIDPasscodeSetting: Setting {
let profile: Profile
var tabManager: TabManager!
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "TouchIDPasscode" }
init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) {
self.profile = settings.profile
self.tabManager = settings.tabManager
let localAuthContext = LAContext()
let title: String
if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) {
if #available(iOS 11.0, *), localAuthContext.biometryType == .faceID {
title = AuthenticationStrings.faceIDPasscodeSetting
} else {
title = AuthenticationStrings.touchIDPasscodeSetting
}
} else {
title = AuthenticationStrings.passcode
}
super.init(title: NSAttributedString(string: title, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]),
delegate: delegate)
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = AuthenticationSettingsViewController()
viewController.profile = profile
navigationController?.pushViewController(viewController, animated: true)
}
}
@available(iOS 11, *)
class ContentBlockerSetting: Setting {
let profile: Profile
var tabManager: TabManager!
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "TrackingProtection" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
self.tabManager = settings.tabManager
super.init(title: NSAttributedString(string: Strings.SettingsTrackingProtectionSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = ContentBlockerSettingViewController(prefs: profile.prefs)
viewController.profile = profile
viewController.tabManager = tabManager
navigationController?.pushViewController(viewController, animated: true)
}
}
class ClearPrivateDataSetting: Setting {
let profile: Profile
var tabManager: TabManager!
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "ClearPrivateData" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
self.tabManager = settings.tabManager
let clearTitle = Strings.SettingsClearPrivateDataSectionName
super.init(title: NSAttributedString(string: clearTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = ClearPrivateDataTableViewController()
viewController.profile = profile
viewController.tabManager = tabManager
navigationController?.pushViewController(viewController, animated: true)
}
}
class PrivacyPolicySetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override var url: URL? {
return URL(string: "https://www.mozilla.org/privacy/firefox/")
}
override func onClick(_ navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
class ChinaSyncServiceSetting: WithoutAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .none }
var prefs: Prefs { return settings.profile.prefs }
let prefKey = "useChinaSyncService"
override var title: NSAttributedString? {
return NSAttributedString(string: "本地同步服务", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override var status: NSAttributedString? {
return NSAttributedString(string: "禁用后使用全球服务同步数据", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight])
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIColor.theme.tableView.controlTint
control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)
control.isOn = prefs.boolForKey(prefKey) ?? BrowserProfile.isChinaEdition
cell.accessoryView = control
cell.selectionStyle = .none
}
@objc func switchValueChanged(_ toggle: UISwitch) {
prefs.setObject(toggle.isOn, forKey: prefKey)
}
}
class StageSyncServiceDebugSetting: WithoutAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .none }
var prefs: Prefs { return settings.profile.prefs }
var prefKey: String = "useStageSyncService"
override var accessibilityIdentifier: String? { return "DebugStageSync" }
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let _ = profile.getAccount() {
return true
}
return false
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: use stage servers", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override var status: NSAttributedString? {
// Derive the configuration we display from the profile. Currently, this could be either a custom
// FxA server or FxA stage servers.
let isOn = prefs.boolForKey(prefKey) ?? false
let isCustomSync = prefs.boolForKey(PrefsKeys.KeyUseCustomSyncService) ?? false
var configurationURL = ProductionFirefoxAccountConfiguration().authEndpointURL
if isCustomSync {
configurationURL = CustomFirefoxAccountConfiguration(prefs: profile.prefs).authEndpointURL
} else if isOn {
configurationURL = StageFirefoxAccountConfiguration().authEndpointURL
}
return NSAttributedString(string: configurationURL.absoluteString, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight])
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIColor.theme.tableView.controlTint
control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)
control.isOn = prefs.boolForKey(prefKey) ?? false
cell.accessoryView = control
cell.selectionStyle = .none
}
@objc func switchValueChanged(_ toggle: UISwitch) {
prefs.setObject(toggle.isOn, forKey: prefKey)
settings.tableView.reloadData()
}
}
class HomePageSetting: Setting {
let profile: Profile
var tabManager: TabManager!
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "Homepage" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
self.tabManager = settings.tabManager
super.init(title: NSAttributedString(string: Strings.SettingsHomePageSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = HomePageSettingsViewController()
viewController.profile = profile
viewController.tabManager = tabManager
navigationController?.pushViewController(viewController, animated: true)
}
}
class NewTabPageSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "NewTab" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: Strings.SettingsNewTabSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = NewTabContentSettingsViewController(prefs: profile.prefs)
viewController.profile = profile
navigationController?.pushViewController(viewController, animated: true)
}
}
class OpenWithSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "OpenWith.Setting" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: Strings.SettingsOpenWithSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = OpenWithSettingsViewController(prefs: profile.prefs)
navigationController?.pushViewController(viewController, animated: true)
}
}
class AdvanceAccountSetting: HiddenSetting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "AdvanceAccount.Setting" }
override var title: NSAttributedString? {
return NSAttributedString(string: Strings.SettingsAdvanceAccountTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(settings: settings)
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = AdvanceAccountSettingViewController()
viewController.profile = profile
navigationController?.pushViewController(viewController, animated: true)
}
override var hidden: Bool {
return !ShowDebugSettings || profile.hasAccount()
}
}
class ThemeSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var style: UITableViewCellStyle { return .value1 }
override var accessibilityIdentifier: String? { return "DisplayThemeOption" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: Strings.SettingsDisplayThemeTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
navigationController?.pushViewController(ThemeSettingsController(), animated: true)
}
}
| mpl-2.0 | 876318cf9427ef26a8b95fb3ca7f5943 | 40.290654 | 327 | 0.695457 | 5.776804 | false | false | false | false |
benlangmuir/swift | test/Interop/SwiftToCxx/generics/generic-struct-in-cxx.swift | 1 | 21841 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -typecheck -module-name Generics -clang-header-expose-public-decls -emit-clang-header-path %t/generics.h
// RUN: %FileCheck %s < %t/generics.h
// RUN: %check-generic-interop-cxx-header-in-clang(%t/generics.h -Wno-reserved-identifier)
// Check that an instantiation compiles too.
// RUN: echo "constexpr int x = sizeof(Generics::GenericPair<int, int>);" >> %t/generics.h
// RUN: %check-generic-interop-cxx-header-in-clang(%t/generics.h -Wno-reserved-identifier)
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -enable-library-evolution -typecheck -module-name Generics -clang-header-expose-public-decls -emit-clang-header-path %t/generics.h
// RUN: %FileCheck %s < %t/generics.h
// RUN: %check-generic-interop-cxx-header-in-clang(%t/generics.h -Wno-reserved-identifier)
// FIXME: remove the need for -Wno-reserved-identifier
@frozen
public struct PairOfUInt64 {
public let x: UInt64
public let y: UInt64
public init(_ x: UInt64,
_ y: UInt64) {
self.x = x
self.y = y
}
}
class ClassWithT<T>: CustomStringConvertible {
var val: T
init(_ x: T) {
val = x
}
var description: String {
return "ClassWithT(\(val))"
}
}
@frozen
public struct GenericPair<T, T2> {
#if KNOWN_LAYOUT
var x_: ClassWithT<T>
var y_: ClassWithT<T2>
var x: T {
get {
return x_.val
} set {
x_ = ClassWithT<T>(newValue)
}
}
public var y: T2 {
get {
return y_.val
} set {
y_ = ClassWithT<T2>(newValue)
}
}
#if INDIRECT_KNOWN_LAYOUT
let val1, val2, val3, val4: Int
#endif
#else
var x: T
public var y: T2
#endif
init(x: T, y: T2) {
#if KNOWN_LAYOUT
self.x_ = ClassWithT<T>(x)
self.y_ = ClassWithT<T2>(y)
#if INDIRECT_KNOWN_LAYOUT
val1 = 0
val2 = 0
val3 = 0
val4 = 0
#endif
#else
self.x = x
self.y = y
#endif
}
public init(_ x: T, _ i: Int, _ y: T2) {
#if KNOWN_LAYOUT
self.x_ = ClassWithT<T>(x)
self.y_ = ClassWithT<T2>(y)
#if INDIRECT_KNOWN_LAYOUT
val1 = 0
val2 = 0
val3 = 0
val4 = 0
#endif
#else
self.x = x
self.y = y
#endif
print("GenericPair<T, T2>::init::\(x),\(y),\(i);")
}
public func method() {
let copyOfSelf = self
print("GenericPair<T, T2>::testme::\(x),\(copyOfSelf.y);")
}
public mutating func mutatingMethod(_ other: GenericPair<T2, T>) {
x = other.y
y = other.x
}
public func genericMethod<T>(_ x: T, _ y: T2) -> T {
print("GenericPair<T, T2>::genericMethod<T>::\(x),\(y);")
return x
}
public var computedProp: Int {
return 42
}
public var computedVar: T {
get {
print("GenericPair<T, T2>::computeVar::get")
return x
} set {
print("GenericPair<T, T2>::computeVar::set")
x = newValue
}
}
}
public func makeGenericPair<T, T1>(_ x: T, _ y: T1) -> GenericPair<T, T1> {
return GenericPair<T, T1>(x: x, y: y);
}
public func makeConcretePair(_ x: UInt16, _ y: UInt16) -> GenericPair<UInt16, UInt16> {
return GenericPair<UInt16, UInt16>(x: x, y: y)
}
public func takeGenericPair<T, T1>(_ x: GenericPair<T, T1>) {
print(x)
}
public func takeConcretePair(_ x: GenericPair<UInt16, UInt16>) {
print("CONCRETE pair of UInt16: ", x.x, x.y, ";")
}
public func passThroughGenericPair<T1, T>(_ x: GenericPair<T1, T>, _ y: T) -> GenericPair<T1, T> {
return GenericPair<T1, T>(x: x.x, y: y)
}
public typealias ConcreteUint32Pair = GenericPair<UInt16, UInt16>
public func passThroughConcretePair(_ x: ConcreteUint32Pair, y: UInt16) -> ConcreteUint32Pair {
return ConcreteUint32Pair(x: x.x, y: y)
}
public func inoutGenericPair<T1, T>(_ x: inout GenericPair<T1, T>, _ y: T1) {
x.x = y
}
public func inoutConcretePair(_ x: UInt16, _ y: inout GenericPair<UInt16, UInt16>) {
y.x = x
}
// CHECK: SWIFT_EXTERN void $s8Generics11GenericPairV1yq_vg(SWIFT_INDIRECT_RESULT void * _Nonnull, void * _Nonnull , SWIFT_CONTEXT const void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // _
// CHECK-NEXT: SWIFT_EXTERN void $s8Generics11GenericPairV1yq_vs(const void * _Nonnull value, void * _Nonnull , SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // _
// CHECK-NEXT: SWIFT_EXTERN void $s8Generics11GenericPairVyACyxq_Gx_Siq_tcfC(SWIFT_INDIRECT_RESULT void * _Nonnull, const void * _Nonnull x, ptrdiff_t i, const void * _Nonnull y, void * _Nonnull , void * _Nonnull ) SWIFT_NOEXCEPT SWIFT_CALL; // init(_:_:_:)
// CHECK-NEXT: SWIFT_EXTERN void $s8Generics11GenericPairV6methodyyF(void * _Nonnull , SWIFT_CONTEXT const void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // method()
// CHECK-NEXT: SWIFT_EXTERN void $s8Generics11GenericPairV14mutatingMethodyyACyq_xGF(const void * _Nonnull other, void * _Nonnull , SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // mutatingMethod(_:)
// CHECK-NEXT: SWIFT_EXTERN void $s8Generics11GenericPairV13genericMethodyqd__qd___q_tlF(SWIFT_INDIRECT_RESULT void * _Nonnull, const void * _Nonnull x, const void * _Nonnull y, void * _Nonnull , void * _Nonnull , SWIFT_CONTEXT const void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // genericMethod(_:_:)
// CHECK-NEXT: SWIFT_EXTERN ptrdiff_t $s8Generics11GenericPairV12computedPropSivg(void * _Nonnull , SWIFT_CONTEXT const void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // _
// CHECK-NEXT: SWIFT_EXTERN void $s8Generics11GenericPairV11computedVarxvg(SWIFT_INDIRECT_RESULT void * _Nonnull, void * _Nonnull , SWIFT_CONTEXT const void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // _
// CHECK-NEXT: SWIFT_EXTERN void $s8Generics11GenericPairV11computedVarxvs(const void * _Nonnull newValue, void * _Nonnull , SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // _
// CHECK: SWIFT_EXTERN void $s8Generics17inoutConcretePairyys6UInt16V_AA07GenericD0VyA2DGztF(uint16_t x, void * _Nonnull y) SWIFT_NOEXCEPT SWIFT_CALL; // inoutConcretePair(_:_:)
// CHECK-NEXT: SWIFT_EXTERN void $s8Generics16inoutGenericPairyyAA0cD0Vyxq_Gz_xtr0_lF(void * _Nonnull x, const void * _Nonnull y, void * _Nonnull , void * _Nonnull ) SWIFT_NOEXCEPT SWIFT_CALL; // inoutGenericPair(_:_:)
// CHECK-NEXT: // Stub struct to be used to pass/return values to/from Swift functions.
// CHECK-NEXT: struct swift_interop_returnStub_Generics_uint32_t_0_4 {
// CHECK-NEXT: uint32_t _1;
// CHECK-NEXT: };
// CHECK-EMPTY:
// CHECK-NEXT: static inline void swift_interop_returnDirect_Generics_uint32_t_0_4(char * _Nonnull result, struct swift_interop_returnStub_Generics_uint32_t_0_4 value) __attribute__((always_inline)) {
// CHECK-NEXT: memcpy(result + 0, &value._1, 4);
// CHECK-NEXT: }
// CHECK-EMPTY:
// CHECK-NEXT: SWIFT_EXTERN struct swift_interop_returnStub_Generics_uint32_t_0_4 $s8Generics16makeConcretePairyAA07GenericD0Vys6UInt16VAFGAF_AFtF(uint16_t x, uint16_t y) SWIFT_NOEXCEPT SWIFT_CALL; // makeConcretePair(_:_:)
// CHECK-NEXT: SWIFT_EXTERN void $s8Generics15makeGenericPairyAA0cD0Vyxq_Gx_q_tr0_lF(SWIFT_INDIRECT_RESULT void * _Nonnull, const void * _Nonnull x, const void * _Nonnull y, void * _Nonnull , void * _Nonnull ) SWIFT_NOEXCEPT SWIFT_CALL; // makeGenericPair(_:_:)
// CHECK-NEXT: // Stub struct to be used to pass/return values to/from Swift functions.
// CHECK-NEXT: struct swift_interop_passStub_Generics_uint32_t_0_4 {
// CHECK-NEXT: uint32_t _1;
// CHECK-NEXT: };
// CHECK-EMPTY:
// CHECK-NEXT: static inline struct swift_interop_passStub_Generics_uint32_t_0_4 swift_interop_passDirect_Generics_uint32_t_0_4(const char * _Nonnull value) __attribute__((always_inline)) {
// CHECK-NEXT: struct swift_interop_passStub_Generics_uint32_t_0_4 result;
// CHECK-NEXT: memcpy(&result._1, value + 0, 4);
// CHECK-NEXT: return result;
// CHECK-NEXT: }
// CHECK-EMPTY:
// CHECK-NEXT: SWIFT_EXTERN struct swift_interop_returnStub_Generics_uint32_t_0_4 $s8Generics23passThroughConcretePair_1yAA07GenericE0Vys6UInt16VAGGAH_AGtF(struct swift_interop_passStub_Generics_uint32_t_0_4 x, uint16_t y) SWIFT_NOEXCEPT SWIFT_CALL; // passThroughConcretePair(_:y:)
// CHECK-NEXT: SWIFT_EXTERN void $s8Generics22passThroughGenericPairyAA0dE0Vyxq_GAE_q_tr0_lF(SWIFT_INDIRECT_RESULT void * _Nonnull, const void * _Nonnull x, const void * _Nonnull y, void * _Nonnull , void * _Nonnull ) SWIFT_NOEXCEPT SWIFT_CALL; // passThroughGenericPair(_:_:)
// CHECK-NEXT: SWIFT_EXTERN void $s8Generics16takeConcretePairyyAA07GenericD0Vys6UInt16VAFGF(struct swift_interop_passStub_Generics_uint32_t_0_4 x) SWIFT_NOEXCEPT SWIFT_CALL; // takeConcretePair(_:)
// CHECK-NEXT: SWIFT_EXTERN void $s8Generics15takeGenericPairyyAA0cD0Vyxq_Gr0_lF(const void * _Nonnull x, void * _Nonnull , void * _Nonnull ) SWIFT_NOEXCEPT SWIFT_CALL; // takeGenericPair(_:)
// CHECK: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: class _impl_GenericPair;
// CHECK-EMPTY:
// CHECK-NEXT: static_assert(2 <= 3, "unsupported generic requirement list for metadata func");
// CHECK-NEXT: // Type metadata accessor for GenericPair
// CHECK-NEXT: SWIFT_EXTERN swift::_impl::MetadataResponseTy $s8Generics11GenericPairVMa(swift::_impl::MetadataRequestTy, void * _Nonnull, void * _Nonnull) SWIFT_NOEXCEPT SWIFT_CALL;
// CHECK: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: class GenericPair final {
// CHECK-NEXT: public:
// CHECK-NEXT: inline ~GenericPair() {
// CHECK-NEXT: auto metadata = _impl::$s8Generics11GenericPairVMa(0, swift::TypeMetadataTrait<T_0_0>::getTypeMetadata(), swift::TypeMetadataTrait<T_0_1>::getTypeMetadata());
// CHECK: swift::_impl::OpaqueStorage _storage;
// CHECK-NEXT: friend class _impl::_impl_GenericPair<T_0_0, T_0_1>;
// CHECK-NEXT: }
// CHECK: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: class _impl_GenericPair {
// CHECK-NEXT: public:
// CHECK-NEXT: static inline char * _Nonnull getOpaquePointer(GenericPair<T_0_0, T_0_1> &object) { return object._getOpaquePointer(); }
// CHECK-NEXT: static inline const char * _Nonnull getOpaquePointer(const GenericPair<T_0_0, T_0_1> &object) { return object._getOpaquePointer(); }
// CHECK-NEXT: template<class T>
// CHECK-NEXT: static inline GenericPair<T_0_0, T_0_1> returnNewValue(T callable) {
// CHECK-NEXT: auto result = GenericPair<T_0_0, T_0_1>::_make();
// CHECK-NEXT: callable(result._getOpaquePointer());
// CHECK-NEXT: return result;
// CHECK-NEXT: }
// CHECK: namespace swift {
// CHECK-NEXT: #pragma clang diagnostic push
// CHECK-NEXT: #pragma clang diagnostic ignored "-Wc++17-extensions"
// CHECK-NEXT: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: struct TypeMetadataTrait<Generics::GenericPair<T_0_0, T_0_1>> {
// CHECK-NEXT: static inline void * _Nonnull getTypeMetadata() {
// CHECK-NEXT: return Generics::_impl::$s8Generics11GenericPairVMa(0, swift::TypeMetadataTrait<T_0_0>::getTypeMetadata(), swift::TypeMetadataTrait<T_0_1>::getTypeMetadata())._0;
// CHECK-NEXT: }
// CHECK-NEXT: };
// CHECK-NEXT: namespace _impl{
// CHECK-NEXT: } // namespace
// CHECK-NEXT: #pragma clang diagnostic pop
// CHECK-NEXT: } // namespace swift
// CHECK: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: class GenericPair;
// CHECK-EMPTY:
// CHECK-NEXT: inline void inoutConcretePair(uint16_t x, GenericPair<uint16_t, uint16_t>& y) noexcept {
// CHECK-NEXT: return _impl::$s8Generics17inoutConcretePairyys6UInt16V_AA07GenericD0VyA2DGztF(x, _impl::_impl_GenericPair<uint16_t, uint16_t>::getOpaquePointer(y));
// CHECK-NEXT: }
// CHECK: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: inline void inoutGenericPair(GenericPair<T_0_0, T_0_1>& x, const T_0_0& y) noexcept {
// CHECK-NEXT: return _impl::$s8Generics16inoutGenericPairyyAA0cD0Vyxq_Gz_xtr0_lF(_impl::_impl_GenericPair<T_0_0, T_0_1>::getOpaquePointer(x), swift::_impl::getOpaquePointer(y), swift::TypeMetadataTrait<T_0_0>::getTypeMetadata(), swift::TypeMetadataTrait<T_0_1>::getTypeMetadata());
// CHECK-NEXT: }
// CHECK: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: inline GenericPair<T_0_0, T_0_1> makeGenericPair(const T_0_0& x, const T_0_1& y) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::_impl_GenericPair<T_0_0, T_0_1>::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s8Generics15makeGenericPairyAA0cD0Vyxq_Gx_q_tr0_lF(result, swift::_impl::getOpaquePointer(x), swift::_impl::getOpaquePointer(y), swift::TypeMetadataTrait<T_0_0>::getTypeMetadata(), swift::TypeMetadataTrait<T_0_1>::getTypeMetadata());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline GenericPair<uint16_t, uint16_t> passThroughConcretePair(const GenericPair<uint16_t, uint16_t>& x, uint16_t y) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::_impl_GenericPair<uint16_t, uint16_t>::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Generics_uint32_t_0_4(result, _impl::$s8Generics23passThroughConcretePair_1yAA07GenericE0Vys6UInt16VAGGAH_AGtF(_impl::swift_interop_passDirect_Generics_uint32_t_0_4(_impl::_impl_GenericPair<uint16_t, uint16_t>::getOpaquePointer(x)), y));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: inline GenericPair<T_0_0, T_0_1> passThroughGenericPair(const GenericPair<T_0_0, T_0_1>& x, const T_0_1& y) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::_impl_GenericPair<T_0_0, T_0_1>::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s8Generics22passThroughGenericPairyAA0dE0Vyxq_GAE_q_tr0_lF(result, _impl::_impl_GenericPair<T_0_0, T_0_1>::getOpaquePointer(x), swift::_impl::getOpaquePointer(y), swift::TypeMetadataTrait<T_0_0>::getTypeMetadata(), swift::TypeMetadataTrait<T_0_1>::getTypeMetadata());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline void takeConcretePair(const GenericPair<uint16_t, uint16_t>& x) noexcept {
// CHECK-NEXT: return _impl::$s8Generics16takeConcretePairyyAA07GenericD0Vys6UInt16VAFGF(_impl::swift_interop_passDirect_Generics_uint32_t_0_4(_impl::_impl_GenericPair<uint16_t, uint16_t>::getOpaquePointer(x)));
// CHECK-NEXT: }
// CHECK: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: inline void takeGenericPair(const GenericPair<T_0_0, T_0_1>& x) noexcept {
// CHECK-NEXT: return _impl::$s8Generics15takeGenericPairyyAA0cD0Vyxq_Gr0_lF(_impl::_impl_GenericPair<T_0_0, T_0_1>::getOpaquePointer(x), swift::TypeMetadataTrait<T_0_0>::getTypeMetadata(), swift::TypeMetadataTrait<T_0_1>::getTypeMetadata());
// CHECK-NEXT:}
// CHECK: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: inline T_0_1 GenericPair<T_0_0, T_0_1>::getY() const {
// CHECK-NEXT: if constexpr (std::is_base_of<::swift::_impl::RefCountedClass, T_0_1>::value) {
// CHECK-NEXT: void *returnValue;
// CHECK-NEXT: _impl::$s8Generics11GenericPairV1yq_vg(reinterpret_cast<void *>(&returnValue), swift::TypeMetadataTrait<GenericPair<T_0_0, T_0_1>>::getTypeMetadata(), _getOpaquePointer());
// CHECK-NEXT: return ::swift::_impl::implClassFor<T_0_1>::type::makeRetained(returnValue);
// CHECK-NEXT: } else if constexpr (::swift::_impl::isValueType<T_0_1>) {
// CHECK-NEXT: return ::swift::_impl::implClassFor<T_0_1>::type::returnNewValue([&](void * _Nonnull returnValue) {
// CHECK-NEXT: _impl::$s8Generics11GenericPairV1yq_vg(returnValue, swift::TypeMetadataTrait<GenericPair<T_0_0, T_0_1>>::getTypeMetadata(), _getOpaquePointer());
// CHECK-NEXT: });
// CHECK-NEXT: } else {
// CHECK-NEXT: T_0_1 returnValue;
// CHECK-NEXT: _impl::$s8Generics11GenericPairV1yq_vg(reinterpret_cast<void *>(&returnValue), swift::TypeMetadataTrait<GenericPair<T_0_0, T_0_1>>::getTypeMetadata(), _getOpaquePointer());
// CHECK-NEXT: return returnValue;
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: inline void GenericPair<T_0_0, T_0_1>::setY(const T_0_1& value) {
// CHECK-NEXT: return _impl::$s8Generics11GenericPairV1yq_vs(swift::_impl::getOpaquePointer(value), swift::TypeMetadataTrait<GenericPair<T_0_0, T_0_1>>::getTypeMetadata(), _getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: inline GenericPair<T_0_0, T_0_1> GenericPair<T_0_0, T_0_1>::init(const T_0_0& x, swift::Int i, const T_0_1& y) {
// CHECK-NEXT: return _impl::_impl_GenericPair<T_0_0, T_0_1>::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s8Generics11GenericPairVyACyxq_Gx_Siq_tcfC(result, swift::_impl::getOpaquePointer(x), i, swift::_impl::getOpaquePointer(y), swift::TypeMetadataTrait<T_0_0>::getTypeMetadata(), swift::TypeMetadataTrait<T_0_1>::getTypeMetadata());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: inline void GenericPair<T_0_0, T_0_1>::method() const {
// CHECK-NEXT: return _impl::$s8Generics11GenericPairV6methodyyF(swift::TypeMetadataTrait<GenericPair<T_0_0, T_0_1>>::getTypeMetadata(), _getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: inline void GenericPair<T_0_0, T_0_1>::mutatingMethod(const GenericPair<T_0_1, T_0_0>& other) {
// CHECK-NEXT: return _impl::$s8Generics11GenericPairV14mutatingMethodyyACyq_xGF(_impl::_impl_GenericPair<T_0_1, T_0_0>::getOpaquePointer(other), swift::TypeMetadataTrait<GenericPair<T_0_0, T_0_1>>::getTypeMetadata(), _getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: template<class T_1_0>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_1_0>
// CHECK-NEXT: inline T_1_0 GenericPair<T_0_0, T_0_1>::genericMethod(const T_1_0& x, const T_0_1& y) const {
// CHECK-NEXT: if constexpr (std::is_base_of<::swift::_impl::RefCountedClass, T_1_0>::value) {
// CHECK-NEXT: void *returnValue;
// CHECK-NEXT: _impl::$s8Generics11GenericPairV13genericMethodyqd__qd___q_tlF(reinterpret_cast<void *>(&returnValue), swift::_impl::getOpaquePointer(x), swift::_impl::getOpaquePointer(y), swift::TypeMetadataTrait<GenericPair<T_0_0, T_0_1>>::getTypeMetadata(), swift::TypeMetadataTrait<T_1_0>::getTypeMetadata(), _getOpaquePointer());
// CHECK-NEXT: return ::swift::_impl::implClassFor<T_1_0>::type::makeRetained(returnValue);
// CHECK-NEXT: } else if constexpr (::swift::_impl::isValueType<T_1_0>) {
// CHECK-NEXT: return ::swift::_impl::implClassFor<T_1_0>::type::returnNewValue([&](void * _Nonnull returnValue) {
// CHECK-NEXT: _impl::$s8Generics11GenericPairV13genericMethodyqd__qd___q_tlF(returnValue, swift::_impl::getOpaquePointer(x), swift::_impl::getOpaquePointer(y), swift::TypeMetadataTrait<GenericPair<T_0_0, T_0_1>>::getTypeMetadata(), swift::TypeMetadataTrait<T_1_0>::getTypeMetadata(), _getOpaquePointer());
// CHECK-NEXT: });
// CHECK-NEXT: } else {
// CHECK-NEXT: T_1_0 returnValue;
// CHECK-NEXT: _impl::$s8Generics11GenericPairV13genericMethodyqd__qd___q_tlF(reinterpret_cast<void *>(&returnValue), swift::_impl::getOpaquePointer(x), swift::_impl::getOpaquePointer(y), swift::TypeMetadataTrait<GenericPair<T_0_0, T_0_1>>::getTypeMetadata(), swift::TypeMetadataTrait<T_1_0>::getTypeMetadata(), _getOpaquePointer());
// CHECK-NEXT: return returnValue;
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: template<class T_0_0, class T_0_1>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T_0_0> && swift::isUsableInGenericContext<T_0_1>
// CHECK-NEXT: inline swift::Int GenericPair<T_0_0, T_0_1>::getComputedProp() const {
// CHECK-NEXT: return _impl::$s8Generics11GenericPairV12computedPropSivg(swift::TypeMetadataTrait<GenericPair<T_0_0, T_0_1>>::getTypeMetadata(), _getOpaquePointer());
// CHECK-NEXT: }
// CHECK: inline T_0_0 GenericPair<T_0_0, T_0_1>::getComputedVar()
// CHECK: _impl::$s8Generics11GenericPairV11computedVarxvg(reinterpret_cast<void *>(&returnValue), swift::TypeMetadataTrait<GenericPair<T_0_0, T_0_1>>::getTypeMetadata(), _getOpaquePointer());
// CHECK: inline void GenericPair<T_0_0, T_0_1>::setComputedVar(const T_0_0& newValue) {
// CHECK-NEXT: return _impl::$s8Generics11GenericPairV11computedVarxvs(swift::_impl::getOpaquePointer(newValue), swift::TypeMetadataTrait<GenericPair<T_0_0, T_0_1>>::getTypeMetadata(), _getOpaquePointer());
| apache-2.0 | 0f2b39c70d59760cfe93ca5926eb23bc | 59.168044 | 333 | 0.701754 | 3.077498 | false | false | false | false |
mozilla-mobile/firefox-ios | Tests/ClientTests/DownloadQueueTests.swift | 2 | 4506 | /* 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/. */
@testable import Client
import XCTest
class DownloadQueueTests: XCTestCase {
let didStartDownload = "downloadQueue(_:didStartDownload:)"
let didDownloadCombinedBytes = "downloadQueue(_:didDownloadCombinedBytes:combinedTotalBytesExpected:)"
let didCompleteWithError = "downloadQueue(_:didCompleteWithError:)"
let didFinishDownloadingTo = "downloadQueue(_:download:didFinishDownloadingTo:)"
var queue: DownloadQueue!
var download: MockDownload!
override func setUp() {
queue = DownloadQueue()
download = MockDownload()
super.setUp()
}
override func tearDown() {
super.tearDown()
queue = nil
download = nil
}
func testDownloadQueueIsEmpty() {
XCTAssertTrue(queue.isEmpty)
}
func testDownloadQueueIsNotEmpty() {
queue.downloads = [download]
XCTAssertTrue(!queue.isEmpty)
}
func testEnqueueDownloadShouldAppendDownloadAndTriggerResume() {
queue.enqueue(download)
XCTAssertTrue(download.downloadTriggered)
}
func testEnqueueDownloadShouldCallDownloadQueueDidStartDownload() {
let mockQueueDelegate = MockDownloadQueueDelegate()
queue.delegate = mockQueueDelegate
queue.enqueue(download)
XCTAssertEqual(mockQueueDelegate.methodCalled, didStartDownload)
}
func testCancelAllDownload() {
queue.downloads = [download]
queue.cancelAll()
XCTAssertTrue(download.downloadCanceled)
}
func testDidDownloadBytes() {
let mockQueueDelegate = MockDownloadQueueDelegate()
queue.delegate = mockQueueDelegate
queue.downloads = [download]
queue.download(download, didDownloadBytes: 0)
XCTAssertEqual(mockQueueDelegate.methodCalled, didDownloadCombinedBytes)
}
func testDidFinishDownloadingToWithOneElementsInQueue() {
let mockQueueDelegate = MockDownloadQueueDelegate()
queue.delegate = mockQueueDelegate
queue.downloads = [download]
queue.download(download, didFinishDownloadingTo: url)
XCTAssertEqual(mockQueueDelegate.methodCalled, didCompleteWithError)
}
func testDidFinishDownloadingToWithTwoElementsInQueue() {
let mockQueueDelegate = MockDownloadQueueDelegate()
queue.delegate = mockQueueDelegate
queue.downloads = [download, MockDownload()]
queue.download(download, didFinishDownloadingTo: url)
XCTAssertEqual(mockQueueDelegate.methodCalled, didFinishDownloadingTo)
}
func testDidFinishDownloadingToWithNoElementsInQueue() {
let mockQueueDelegate = MockDownloadQueueDelegate()
queue.delegate = mockQueueDelegate
queue.download(download, didFinishDownloadingTo: url)
XCTAssertEqual(mockQueueDelegate.methodCalled, "noneOfMethodWasCalled")
}
func testDidCompleteWithError() {
let mockQueueDelegate = MockDownloadQueueDelegate()
queue.delegate = mockQueueDelegate
queue.downloads = [download]
queue.download(download, didCompleteWithError: DownloadTestError.noError("OK"))
XCTAssertEqual(mockQueueDelegate.methodCalled, didCompleteWithError)
}
}
private enum DownloadTestError: Error {
case noError(String)
}
private let url = URL(string: "http://mozilla.org")!
class MockDownload: Download {
var downloadTriggered: Bool = false
var downloadCanceled: Bool = false
override func resume() {
downloadTriggered = true
}
override func cancel() {
downloadCanceled = true
}
}
class MockDownloadQueueDelegate: DownloadQueueDelegate {
var methodCalled: String = "noneOfMethodWasCalled"
func downloadQueue(_ downloadQueue: DownloadQueue, didStartDownload download: Download) {
methodCalled = #function
}
func downloadQueue(_ downloadQueue: DownloadQueue, didDownloadCombinedBytes combinedBytesDownloaded: Int64, combinedTotalBytesExpected: Int64?) {
methodCalled = #function
}
func downloadQueue(_ downloadQueue: DownloadQueue, download: Download, didFinishDownloadingTo location: URL) {
methodCalled = #function
}
func downloadQueue(_ downloadQueue: DownloadQueue, didCompleteWithError error: Error?) {
methodCalled = #function
}
}
| mpl-2.0 | 85978353dcb81b633c009c6255eae401 | 31.890511 | 149 | 0.715934 | 5.370679 | false | true | false | false |
niceb5y/DRSTm | DRST manager/AppDelegate.swift | 1 | 3287 | //
// AppDelegate.swift
// DRST manager
//
// Created by 김승호 on 2016. 7. 24..
// Copyright © 2016년 Seungho Kim. All rights reserved.
//
import UIKit
import DRSTKit
import WatchConnectivity
@UIApplicationMain
class AppDelegate:UIResponder, UIApplicationDelegate, WCSessionDelegate {
var window: UIWindow?
var session: WCSession?
let dk = DataKit()
override init() {
super.init()
if WCSession.isSupported() {
session = WCSession.default
session!.delegate = self
session!.activate()
}
}
@available(iOS 9.3, *)
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
}
/** Called when all delegate callbacks for the previously selected watch has occurred. The session can be re-activated for the now selected watch using activateSession. */
@available(iOS 9.3, *)
public func sessionDidDeactivate(_ session: WCSession) {
}
/** Called when the session can no longer be used to modify or add any new transfers and, all interactive messages will be cancelled, but delegate callbacks for background transfers can still occur. This will happen when the selected watch is being changed. */
@available(iOS 9.3, *)
public func sessionDidBecomeInactive(_ session: WCSession) {
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
let req = message["req"] as! String
if req == "?" {
let queue = DispatchQueue.global()
queue.async(execute: {() -> () in
let result:[String:AnyObject] = [
"current": self.dk.estimatedCurrentStamina(0) as AnyObject,
"max": self.dk.maxStamina(0) as AnyObject,
"timeLeft": self.dk.estimatedTimeLeftString(0) as AnyObject
]
replyHandler(result)
})
}
if req == "set" {
let value = Int(message["value"] as! String)
self.dk.setCurrentStamina(value!, atIndex: 0)
self.dk.date = Date()
let result:[String:AnyObject] = [
"success":true as AnyObject
]
replyHandler(result)
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
let query = url.query
if query == "method=edit" {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let editViewController = storyboard.instantiateViewController(withIdentifier: "EditViewController")
let nav = self.window?.rootViewController?.children[0] as! UINavigationController
nav.pushViewController(editViewController, animated: true)
}
return true
}
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
if shortcutItem.type == "com.niceb5y.drstm.edit" {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let editViewController = storyboard.instantiateViewController(withIdentifier: "EditViewController")
let nav = self.window?.rootViewController?.children[0] as! UINavigationController
nav.pushViewController(editViewController, animated: true)
}
}
}
| mit | 288cdc3b772ea8f1701cffba43283eca | 33.505263 | 262 | 0.718426 | 4.092385 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequestProtocol.swift | 13 | 3135 | // Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright 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 FBSDKCoreKit
/**
Protocol that represents a request to the Facebook Graph API.
An implementation of this protocol is intended to be either generic and be used for a lot of separate endpoints,
or encapsulate a request + response type for a single endpoint, for example `Profile`.
To send a request and receive a response - see `GraphRequestConnection`.
Nearly all Graph APIs require an access token.
Unless specified, the `AccessToken.current` is used. Therefore, most requests
will require login first (see `LoginManager` in `FacebookLogin.framework`).
A `start` function is provided for convenience for single requests.
*/
public protocol GraphRequestProtocol {
associatedtype Response: GraphResponseProtocol
/// The Graph API endpoint to use for the request, e.g. `"me"`.
var graphPath: String { get }
/// The request parameters.
var parameters: [String : Any]? { get }
/// The `AccessToken` used by the request to authenticate.
var accessToken: AccessToken? { get }
/// The `HTTPMethod` to use for the request, e.g. `.GET`/`.POST`/`.DELETE`.
var httpMethod: GraphRequestHTTPMethod { get }
/// Graph API Version to use. Default: `GraphAPIVersion.Default`.
var apiVersion: GraphAPIVersion { get }
}
extension GraphRequestProtocol {
/**
A convenience method that creates and starts a connection to the Graph API.
- parameter completion: Optional completion closure that is going to be called when the connection finishes or fails.
*/
public func start(_ completion: GraphRequestConnection.Completion<Self>? = nil) {
let connection = GraphRequestConnection()
connection.add(self, completion: completion)
connection.start()
}
}
/**
Represents HTTP methods that could be used to issue `GraphRequestProtocol`.
*/
public enum GraphRequestHTTPMethod: String {
/// `GET` graph request HTTP method.
case GET = "GET"
/// `POST` graph request HTTP method.
case POST = "POST"
/// `DELETE` graph request HTTP method.
case DELETE = "DELETE"
}
| mit | aad68d40ecb9e4a16444a238c90cd568 | 38.683544 | 120 | 0.745774 | 4.52381 | false | false | false | false |
Lorenzo45/AutoMute | AutoMute/SetupViewController.swift | 1 | 1740 | //
// SetupViewController.swift
// AutoMute
//
// Created by Lorenzo Gentile on 2015-08-30.
// Copyright © 2015 Lorenzo Gentile. All rights reserved.
//
import Cocoa
class SetupViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
@IBOutlet weak var tableView: NSTableView!
// MARK: NSTableViewDataSource
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return WifiManager.networks.count
}
func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? {
if tableColumn?.identifier == ColumnIds.network {
return WifiManager.networks[row][NetworkKeys.ssid]
} else if tableColumn?.identifier == ColumnIds.action {
if let action = WifiManager.networks[row][NetworkKeys.action] as? Int where action == -1 {
WifiManager.networks[row][NetworkKeys.action] = Action.DoNothing.rawValue
}
return WifiManager.networks[row][NetworkKeys.action]
}
return nil
}
func tableView(tableView: NSTableView, setObjectValue object: AnyObject?, forTableColumn tableColumn: NSTableColumn?, row: Int) {
if let selectedSegment = object as? Int where tableColumn?.identifier == ColumnIds.action {
WifiManager.updateActionForNetwork(selectedSegment, index: row)
}
}
// MARK: NSTableViewDelegate
func tableView(tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
return false
}
func tableView(tableView: NSTableView, shouldTrackCell cell: NSCell, forTableColumn tableColumn: NSTableColumn?, row: Int) -> Bool {
return true
}
}
| mit | f3cb47b875b556d03335df509ff88e4f | 36 | 136 | 0.682001 | 4.884831 | false | false | false | false |
practicalswift/swift | test/DebugInfo/letstring.swift | 41 | 1697 | // RUN: %target-swift-frontend %s -emit-ir -g -o %t.ll
// RUN: %FileCheck %s < %t.ll
// FIXME(TODO: JIRA): As i386 string is now big enough to be a by-address type,
// and due to the peculiarities of debug info ordering and limitations of CHECK-
// DAG and Posix regexes (without going crazy), temporarily disable for i386.
//
// REQUIRES: CPU=x86_64
class UIWindow {}
class AppDelegate {
var window: UIWindow?
// CHECK: define hidden {{.*}}i1 {{.*}}11AppDelegateC1f
func f() -> Bool {
// Test for -O0 shadow copies.
// CHECK: call void @llvm.dbg.declare({{.*}}, metadata ![[SELF:.*]], metadata !DIExpression())
// CHECK-NOT: call void @llvm.dbg.value
// CHECK: call void @llvm.dbg.declare({{.*}}, metadata ![[A:.*]], metadata !DIExpression())
let a = "let"
// CHECK-NOT: call void @llvm.dbg.value
// CHECK: call void @llvm.dbg.declare({{.*}}, metadata ![[B:.*]], metadata !DIExpression())
// CHECK-NOT: call void @llvm.dbg.value
// CHECK: ret
// CHECK-DAG: ![[SELF]] = !DILocalVariable(name: "self", arg: 1{{.*}} line: [[@LINE-10]],
// CHECK-DAG: ![[A]] = !DILocalVariable(name: "a",{{.*}} line: [[@LINE-6]],
// CHECK-DAG: ![[B]] = !DILocalVariable(name: "b",{{.*}} line: [[@LINE+1]],
var b = "var"
self.window = UIWindow()
return true
}
}
// End-to-end test:
// RUN: llc %t.ll -filetype=obj -o %t.o
// RUN: %llvm-dwarfdump %t.o | %FileCheck %s --check-prefix DWARF-CHECK
// DWARF-CHECK: DW_AT_name ("f")
//
// DWARF-CHECK: DW_TAG_formal_parameter
// DWARF-CHECK: DW_AT_name ("self")
//
// DWARF-CHECK: DW_TAG_variable
// DWARF-CHECK: DW_AT_name ("a")
//
// DWARF-CHECK: DW_TAG_variable
// DWARF-CHECK: DW_AT_name ("b")
| apache-2.0 | e0798fd6ac262ca46aeaa50f62bc9f5d | 36.711111 | 98 | 0.605186 | 3.154275 | false | false | false | false |
tejasranade/KinveyHealth | SportShop/ProductCell.swift | 1 | 1173 | //
// ProductCell.swift
// SportShop
//
// Created by Tejas on 1/30/17.
// Copyright © 2017 Kinvey. All rights reserved.
//
import Foundation
import UIKit
import Haneke
class ProductCell: UITableViewCell {
var product: Product?
@IBOutlet weak var name: UILabel!
@IBOutlet weak var price: UILabel!
@IBOutlet weak var shortDesc: UILabel!
@IBOutlet weak var productImage: UIImageView!
override func layoutSubviews() {
name.text = product?.name
price.text = product?.priceString
shortDesc.text = product?.shortDesc
//productImage.image = UIImage
if let src = product?.imageSource {
self.loadImage(src)
}
}
func loadImage (_ src: String) {
let url = URL(string: src)
self.productImage.hnk_setImage(from: url)
// DispatchQueue.global().async {
// let data = try? Data(contentsOf: url!)
//
// if let _ = data{
// DispatchQueue.main.async {
// self.productImage?.image = UIImage(data: data!)
// }
// }
// }
}
}
| apache-2.0 | 5b1e95a2fe3712359b15c38d8f775562 | 23.416667 | 69 | 0.554608 | 4.261818 | false | false | false | false |
Flinesoft/HandyUIKit | Frameworks/HandyUIKit/Extensions/UIImageExt.swift | 1 | 1012 | // Copyright © 2018 Flinesoft. All rights reserved.
import UIKit
extension UIImage {
/// Creates a grayscale version of the image.
///
/// - Returns: The grayscale image.
public func toGrayscale() -> UIImage? {
let imageRect = CGRect(x: 0, y: 0, width: size.width * scale, height: size.height * scale)
let colorSpace = CGColorSpaceCreateDeviceGray()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
let contextOptional = CGContext(
data: nil,
width: Int(size.width * scale),
height: Int(size.height * scale),
bitsPerComponent: 8,
bytesPerRow: 0,
space: colorSpace,
bitmapInfo: bitmapInfo.rawValue
)
guard let context = contextOptional else { return nil }
context.draw(cgImage!, in: imageRect)
guard let grayscaleCgImage = context.makeImage() else { return nil }
return UIImage(cgImage: grayscaleCgImage)
}
}
| mit | 729dcb86ce10eee02be211ac5774b743 | 33.862069 | 98 | 0.622156 | 4.637615 | false | false | false | false |
SwiftyMagic/Magic | Magic/Magic/Foundation/NSURLComponentsExtension.swift | 1 | 1453 | //
// NSURLComponentsExtension.swift
// Magic
//
// Created by Broccoli on 2016/9/22.
// Copyright © 2016年 broccoliii. All rights reserved.
//
import Foundation
// MARK: - Methods
public extension NSURLComponents {
func updateQueryParameter(key: String, value: String?) -> String {
var queryItems: [URLQueryItem] = (self.queryItems ?? [])
for (index, item) in queryItems.enumerated() {
if item.name.lowercased() == key.lowercased() {
if let v = value {
queryItems[index] = URLQueryItem(name: key, value: v)
} else {
queryItems.remove(at: index)
}
self.queryItems = queryItems.count > 0
? queryItems : nil
return self.string!
}
}
if let v = value {
queryItems.append(URLQueryItem(name: key, value: v))
self.queryItems = queryItems
return self.string!
}
return ""
}
func addOrUpdateQueryStringParameter(values: [String: String?]) -> String {
var newUrl = self.string ?? ""
for item in values {
newUrl = updateQueryParameter(key: item.0, value: item.1)
}
return newUrl
}
func removeQueryStringParameter(key: String) -> String {
return updateQueryParameter(key: key, value: nil)
}
}
| mit | e7825df05c26f5f22c4fe30b8a9b3fce | 28 | 79 | 0.54 | 4.707792 | false | false | false | false |
NghiaTranUIT/Hakuba | Source/MYTableViewCell.swift | 2 | 3292 | //
// MYTableViewCell.swift
// Hakuba
//
// Created by Le Van Nghia on 1/13/15.
// Copyright (c) 2015 Le Van Nghia. All rights reserved.
//
import UIKit
public class MYCellModel : MYViewModel {
let identifier: String
internal(set) var row: Int = 0
internal(set) var section: Int = 0
public var cellHeight: CGFloat = 44
public var cellSelectionEnabled = true
public var editable = false
public var calculatedHeight: CGFloat?
public var dynamicHeightEnabled: Bool = false {
didSet {
calculatedHeight = nil
}
}
public init(cellClass: AnyClass, height: CGFloat = 44, userData: AnyObject?, selectionHandler: MYSelectionHandler? = nil) {
self.identifier = String.my_className(cellClass)
self.cellHeight = height
super.init(userData: userData, selectionHandler: selectionHandler)
}
public func slide(_ animation: MYAnimation = .None) -> Self {
delegate?.reloadView(row, section: section, animation: animation)
return self
}
}
public class MYTableViewCell : UITableViewCell, MYBaseViewProtocol {
class var identifier: String { return String.my_className(self) }
var cellSelectionEnabled = true
private weak var delegate: MYBaseViewDelegate?
weak var cellModel: MYCellModel?
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
public func setup() {
}
public func configureCell(data: MYCellModel) {
cellModel = data
delegate = data
cellSelectionEnabled = data.cellSelectionEnabled
unhighlight(false)
}
public func emitSelectedEvent(view: MYBaseViewProtocol) {
delegate?.didSelect(view)
}
public func willAppear(data: MYCellModel) {
}
public func didDisappear(data: MYCellModel) {
}
}
// MARK - Hightlight
public extension MYTableViewCell {
// ignore the default handling
override func setHighlighted(highlighted: Bool, animated: Bool) {
}
override func setSelected(selected: Bool, animated: Bool) {
}
public func highlight(animated: Bool) {
super.setHighlighted(true, animated: animated)
}
public func unhighlight(animated: Bool) {
super.setHighlighted(false, animated: animated)
}
}
// MARK - Touch events
public extension MYTableViewCell {
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
if cellSelectionEnabled {
highlight(false)
}
}
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
super.touchesCancelled(touches, withEvent: event)
if cellSelectionEnabled {
unhighlight(false)
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesEnded(touches, withEvent: event)
if cellSelectionEnabled {
emitSelectedEvent(self)
}
}
} | mit | 04b4024da1ae1a31245fddac11167f0e | 27.387931 | 127 | 0.653098 | 4.729885 | false | false | false | false |
Valbrand/tibei | Sources/Tibei/connection/ConnectionID.swift | 1 | 626 | //
// ConnectionID.swift
// Pods
//
// Created by Daniel de Jesus Oliveira on 27/12/2016.
//
//
import Foundation
/**
A struct that's used to identify existing connections. An uuid is generated upon this struct's instantiation, and its hashValue is used for comparison.
*/
public struct ConnectionID: Hashable {
let id: UUID
/// :nodoc:
public var hashValue: Int {
return self.id.hashValue
}
init() {
self.id = UUID()
}
/// :nodoc:
public static func ==(lhs: ConnectionID, rhs: ConnectionID) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
| mit | 517ab5dceaeb4698784ab4807c2764f0 | 19.866667 | 152 | 0.619808 | 4.118421 | false | false | false | false |
Jintin/Swimat | Parser/SwiftParser.swift | 1 | 13641 | import Foundation
let operatorList: [Character: [String]] =
[
"+": ["+=<", "+=", "+++=", "+++", "+"],
"-": ["->", "-=", "-<<"],
"*": ["*=", "*"],
"/": ["/=", "/"],
"~": ["~=", "~~>", "~>"],
"%": ["%=", "%"],
"^": ["^="],
"&": ["&&=", "&&&", "&&", "&=", "&+", "&-", "&*", "&/", "&%"],
"<": ["<<<", "<<=", "<<", "<=", "<~~", "<~", "<--", "<-<", "<-", "<^>", "<|>", "<*>", "<||?", "<||", "<|?", "<|", "<"],
">": [">>>", ">>=", ">>-", ">>", ">=", ">->", ">"],
"|": ["|||", "||=", "||", "|=", "|"],
"!": ["!==", "!="],
"=": ["===", "==", "="],
".": ["...", "..<", "."],
"#": ["#>", "#"]
]
fileprivate let negativeCheckSigns: [Character] =
["+", "-", "*", "/", "&", "|", "^", "<", ">", ":", "(", "[", "{", "=", ",", ".", "?"]
fileprivate let negativeCheckKeys =
["case", "return", "if", "for", "while", "in"]
fileprivate let numbers: [Character] =
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
class SwiftParser {
let string: String
var retString = ""
var strIndex: String.Index
var indent = Indent()
var indentStack = [Indent]()
var newlineIndex: Int = 0
var isNextSwitch: Bool = false
var isNextEnum: Bool = false
var autoRemoveChar: Bool = false
init(string: String, preferences: Preferences? = nil) {
self.string = string
self.strIndex = string.startIndex
if let preferences = preferences {
// Use the preferences given (for example, when testing)
Indent.paraAlign = preferences.areParametersAligned
autoRemoveChar = preferences.areSemicolonsRemoved
} else {
// Fallback on user-defined preferences
Indent.paraAlign = Preferences.areParametersAligned
autoRemoveChar = Preferences.areSemicolonsRemoved
return
}
}
func format() throws -> String {
while strIndex < string.endIndex {
let char = string[strIndex]
strIndex = try check(char: char)
}
removeUnnecessaryChar()
return retString.trim()
}
func check(char: Character) throws -> String.Index {
switch char {
case "+", "*", "%", ">", "|", "=", "~", "^", "!", "&":
if let index = space(with: operatorList[char]!) {
return index
}
return add(char: char)
case ".":
if let index = add(with: operatorList[char]!) {
return index
}
return add(char: char)
case "-":
return checkMinus(char: char)
case "/":
return checkSlash(char: char)
case "<":
return try checkLess(char: char)
case "?":
return try checkQuestion(char: char)
case ":":
return checkColon(char: char)
case "#":
return checkHash(char: char)
case "\"":
return try checkQuote(char: char)
case "\n":
return checkLineBreak(char: char)
case " ", "\t":
return checkSpace(char: char)
case ",":
return checkComma(char: char)
case "{", "[", "(":
return checkUpperBlock(char: char)
case "}", "]", ")":
return checkLowerBlock(char: char)
default:
return checkDefault(char: char)
}
}
func checkMinus(char: Character) -> String.Index {
if let index = space(with: operatorList[char]!) {
return index
} else {
var noSpace = false
if !retString.isEmpty {
// check scientific notation
if strIndex != string.endIndex {
if retString.last == "e" && numbers.contains(string[string.index(after: strIndex)]) {
noSpace = true
}
}
// check negative
let last = retString.lastNonSpaceChar(retString.endIndex)
if last.isAZ() {
if negativeCheckKeys.contains(retString.lastWord()) {
noSpace = true
}
} else {
if negativeCheckSigns.contains(last) {
noSpace = true
}
}
}
if noSpace {
return add(char: char)
}
return space(with: "-")
}
}
func checkSlash(char: Character) -> String.Index {
if isNext(char: "/") {
return addLine()
} else if isNext(char: "*") {
return addToNext(strIndex, stopWord: "*/")
}
return space(with: operatorList[char]!)!
}
func checkLess(char: Character) throws -> String.Index {
if isNext(char: "#") {
return add(string: "<#")
}
if let result = try string.findGeneric(from: strIndex), !isNext(char: " ") {
retString += result.string
return result.index
}
return space(with: operatorList[char]!)!
}
func checkQuestion(char: Character) throws -> String.Index {
if isNext(char: "?") {
// MARK: check double optional or nil check
return add(string: "??")
} else if let ternary = string.findTernary(from: strIndex) {
retString.keepSpace()
retString += ternary.string
return ternary.index
} else {
return add(char: char)
}
}
func checkColon(char: Character) -> String.Index {
_ = checkInCase()
trimWithIndent()
retString += ": "
return string.nextNonSpaceIndex(string.index(after: strIndex))
}
func checkHash(char: Character) -> String.Index {
if isNext(string: "#if") {
indent.count += 1
return addLine() // MARK: bypass like '#if swift(>=3)'
} else if isNext(string: "#else") {
indent.count -= 1
trimWithIndent()
indent.count += 1
return addLine() // bypass like '#if swift(>=3)'
} else if isNext(string: "#endif") {
indent.count -= 1
trimWithIndent()
return addLine() // bypass like '#if swift(>=3)'
} else if isNext(char: "!") { // shebang
return addLine()
}
if let index = checkHashQuote(index: strIndex, count: 0) {
return index
}
if let index = add(with: operatorList[char]!) {
return index
}
return add(char: char)
}
func checkHashQuote(index: String.Index, count: Int) -> String.Index? {
switch string[index] {
case "#":
return checkHashQuote(index: string.index(after: index), count: count + 1)
case "\"":
return addToNext(strIndex, stopWord: "\"" + String(repeating: "#", count: count))
default:
return nil
}
}
func checkQuote(char: Character) throws -> String.Index {
if isNext(string: "\"\"\"") {
strIndex = add(string: "\"\"\"")
return addToNext(strIndex, stopWord: "\"\"\"")
}
let quote = try string.findQuote(from: strIndex)
retString += quote.string
return quote.index
}
func checkLineBreak(char: Character) -> String.Index {
removeUnnecessaryChar()
indent.line += 1
return checkLine(char)
}
func checkSpace(char: Character) -> String.Index {
if retString.lastWord() == "if" {
let leading = retString.count - newlineIndex
let newIndent = Indent(with: indent, offset: leading, type: IndentType(rawValue: "f"))
indentStack.append(indent)
indent = newIndent
}
retString.keepSpace()
return string.index(after: strIndex)
}
func checkComma(char: Character) -> String.Index {
trimWithIndent()
retString += ", "
return string.nextNonSpaceIndex(string.index(after: strIndex))
}
func checkUpperBlock(char: Character) -> String.Index {
if char == "{" && indent.block == .ifelse {
if let last = indentStack.popLast() {
indent = last
if indent.indentAdd {
indent.indentAdd = false
}
}
}
let offset = retString.count - newlineIndex
let newIndent = Indent(with: indent, offset: offset, type: IndentType(rawValue: char))
indentStack.append(indent)
indent = newIndent
if indent.block == .curly {
if isNextSwitch {
indent.inSwitch = true
isNextSwitch = false
}
if isNextEnum {
indent.inEnum = true
isNextEnum = false
}
indent.count -= 1
trimWithIndent()
indent.count += 1
if !retString.last.isUpperBlock() {
retString.keepSpace()
}
retString += "{ "
return string.nextNonSpaceIndex(string.index(after: strIndex))
} else {
if Indent.paraAlign && char == "(" && isNext(char: "\n") {
indent.count += 1
}
retString.append(char)
return string.nextNonSpaceIndex(string.index(after: strIndex))
}
}
func checkLowerBlock(char: Character) -> String.Index {
var addIndentBack = false
if let last = indentStack.popLast() {
indent = last
if indent.indentAdd {
indent.indentAdd = false
addIndentBack = true
}
} else {
indent = Indent()
}
if char == "}" {
if isNext(char: ".", skipBlank: true) {
trimWithIndent()
} else {
trimWithIndent(addExtra: false)
}
if addIndentBack {
indent.count += 1
}
retString.keepSpace()
let next = string.index(after: strIndex)
if next < string.endIndex && string[next].isAZ() {
retString += "} "
} else {
retString += "}"
}
return next
}
if addIndentBack {
indent.count += 1
}
trimWithIndent()
return add(char: char)
}
func removeUnnecessaryChar() {
if autoRemoveChar && retString.last == ";" {
retString = String(retString[..<retString.index(before: retString.endIndex)])
}
}
func checkInCase() -> Bool {
if indent.inCase {
indent.inCase = false
indent.leading -= 1
indent.isLeading = false
indent.count += 1
return true
}
return false
}
func checkLine(_ char: Character, checkLast: Bool = true) -> String.Index {
trim()
newlineIndex = retString.count - 1
if checkLast {
checkLineEndExtra()
} else {
indent.extra = 0
}
indent.indentAdd = false
indent.extraAdd = false
strIndex = add(char: char)
if !isNext(string: "//") {
if isBetween(words: ("if", "let"), ("guard", "let")) {
indent.extra = 1
} else if isPrevious(str: "case") {
indent.extra = 1
} else if isNext(word: "else") {
if retString.lastWord() != "}" {
indent.extra = 1
}
}
addIndent()
}
return string.nextNonSpaceIndex(strIndex)
}
func checkDefault(char: Character) -> String.Index {
strIndex = add(char: char)
while strIndex < string.endIndex {
let next = string[strIndex]
if next.isAZ() {
strIndex = add(char: next)
} else {
break
}
}
return strIndex
}
func checkLineChar(char: Character) -> Int? {
switch char {
case "+", "-", "*", "=", ".", "&", "|":
return 1
case ":":
if self.checkInCase() {
return 0
}
if !self.indent.inSwitch {
return 1
}
case ",":
if self.indent.inEnum {
return 0
}
if self.indent.line == 1 && (self.indent.block == .parentheses || self.indent.block == .square) {
self.indent.isLeading = true
}
if self.indent.block == .curly {
return 1
}
default:
break
}
return nil
}
func checkLineEndExtra() {
guard indent.block != .ifelse else {
return
}
if let result = checkLineChar(char: retString.last) {
indent.extra = result
return
}
if strIndex < string.endIndex {
let next = string.nextNonSpaceIndex(string.index(after: strIndex))
if next < string.endIndex {
if let result = checkLineChar(char: string[next]) {
indent.extra = result
} else if string[next] == "?" {
indent.extra = 1
} else {
indent.extra = 0
}
}
// MARK: check next if ? :
}
}
}
| mit | 187e6765213dd6db8f489c36bac38caa | 30.723256 | 127 | 0.464409 | 4.499011 | false | false | false | false |
jakob-stoeck/speechToText | SpeechToTextAction/GoogleCloudStorage.swift | 1 | 4841 | //
// GoogleCloudStorage.swift
// SpeechToText
//
// Created by jaksto on 5/14/19.
// Copyright © 2019 Jakob Stoeck. All rights reserved.
//
import Foundation
enum GoogleStorageError: Error {
case initFailed, uploadLocationMissing, noUploadResponse, uploadWithoutRange, maxRetries, wrongStatusCode(statusCode: Int)
}
extension GoogleStorageError: LocalizedError {
public var errorDescription: String? {
switch self {
case .wrongStatusCode(let statusCode):
return String.localizedStringWithFormat(NSLocalizedString("error.wrongStatusCode", value: "Wrong status code: %d", comment: ""), statusCode)
case .initFailed:
return NSLocalizedString("error.initFailed", value: "Initial upload failed", comment: "")
case .maxRetries:
return NSLocalizedString("error.maxRetries", value: "Upload failed after maximum retries", comment: "")
case .uploadLocationMissing:
return NSLocalizedString("error.uploadLocationMissing", value: "Upload failed due to missing URL", comment: "")
case .noUploadResponse:
return NSLocalizedString("error.noUploadResponse", value: "Upload failed", comment: "")
case .uploadWithoutRange:
return NSLocalizedString("error.uploadWithoutRange", value: "Resume upload failed", comment: "")
}
}
}
typealias HTTPCompletionHandler = (HTTPURLResponse?, GoogleStorageError?) -> Void
class Storage {
var session: URLSession
let host: String
let apiKey: String
init(host: String, apiKey: String) {
self.session = URLSession.shared
self.host = host
self.apiKey = apiKey
}
func upload(bucket: String, name: String, data: Data, completion: @escaping HTTPCompletionHandler) {
guard let url = URL.init(string: "https://\(host)/upload/storage/v1/b/\(bucket)/o?uploadType=resumable&name=\(name)&key=\(apiKey)") else {
return completion(nil, .uploadLocationMissing)
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("0", forHTTPHeaderField: "Content-Length")
request.setValue("\(data.count)", forHTTPHeaderField: "X-Upload-Content-Length")
request.setValue(Bundle.main.bundleIdentifier!, forHTTPHeaderField: "X-Ios-Bundle-Identifier")
session.dataTask(with: request) { respData, resp, err in
if err != nil {
// todo do something with the original error
return completion(nil, .initFailed)
}
guard let httpResp = resp as? HTTPURLResponse else {
return completion(nil, .initFailed)
}
if httpResp.statusCode != 200 {
return completion(nil, .wrongStatusCode(statusCode: httpResp.statusCode))
}
guard let location = httpResp.allHeaderFields["Location"] as? String, let url = URL.init(string: location) else {
return completion(nil, .uploadLocationMissing)
}
self.dataUpload(url: url, data: data, completion: completion)
}.resume()
}
func dataUpload(url: URL, data: Data, lastByte: Int = -1, retries: Int = 10, completion: @escaping HTTPCompletionHandler) {
let nextByte = lastByte+1
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.httpBody = data[nextByte...]
request.setValue(apiKey, forHTTPHeaderField: "X-Goog-Api-Key")
if nextByte > 0 {
// resuming download
request.setValue("\(nextByte)/\(data.count)", forHTTPHeaderField: "Range")
}
session.dataTask(with: request) { data, resp, err in
if err != nil {
return completion(nil, err as? GoogleStorageError)
}
guard let resp = resp as? HTTPURLResponse, let data = data else {
return completion(nil, .noUploadResponse)
}
switch resp.statusCode {
case 200, 201:
// file is complete
return completion(resp, nil)
case 308:
// file is incomplete, resume upload
guard let range = resp.allHeaderFields["Range"] as? String, let lastByte = Int(range.split(separator: "-")[1]) else {
return completion(nil, .uploadWithoutRange)
}
if retries > 0 {
self.dataUpload(url: url, data: data, lastByte: lastByte, retries: retries-1, completion: completion)
} else {
return completion(nil, .maxRetries)
}
default:
return completion(nil, .wrongStatusCode(statusCode: resp.statusCode))
}
}.resume()
}
}
| mit | 558b9a04c95d6e3639a44b90f5926c14 | 41.45614 | 152 | 0.611983 | 4.735812 | false | false | false | false |
jcsla/MusicoAudioPlayer | MusicoAudioPlayer/Classes/utils/URL+Offline.swift | 4 | 496 | //
// URL+Offline.swift
// AudioPlayer
//
// Created by Kevin DELANNOY on 03/04/16.
// Copyright © 2016 Kevin Delannoy. All rights reserved.
//
import Foundation
extension URL {
//swiftlint:disable variable_name
/// A boolean value indicating whether a resource should be considered available when internet connection is down
/// or not.
var ap_isOfflineURL: Bool {
return isFileURL || scheme == "ipod-library" || host == "localhost" || host == "127.0.0.1"
}
}
| mit | da3f8b3f878d881f6469c10b413cfc7f | 26.5 | 117 | 0.666667 | 3.897638 | false | false | false | false |
jasonpaulwong/SwiftGameCenter | GameKitHelper.swift | 1 | 6781 | //
// GameKitHelper.swift
// CatRaceStarter
//
// Created by Jason Wong on 11/11/14.
// Copyright (c) 2014 Raywenderlich. All rights reserved.
//
import GameKit
import Foundation
let PresentAuthenticationViewController : NSString = "present_authentication_view_controller"
let LocalPlayerIsAuthenticated : NSString = "local_player_authenticated"
/* For singleton pattern */
private let _GameKitHelperSharedInstace = GameKitHelper()
protocol GameKitHelperDelegate {
func matchStarted()
func matchEnded()
func match(match:GKMatch, didReceiveData data: NSData!, fromPlayer playerID: NSString!)
}
class GameKitHelper : NSObject, GKMatchmakerViewControllerDelegate, GKMatchDelegate {
var _enableGameCenter : Bool
var _matchStarted : Bool
var _match : GKMatch!
var _delegate : GameKitHelperDelegate?
var authenticationViewController: UIViewController?
var lastError : NSError?
var playersDict : NSMutableDictionary?
class var SharedGameKitHelper:GameKitHelper {
return _GameKitHelperSharedInstace
}
override init() {
self._enableGameCenter = true
self._matchStarted = false
super.init()
}
func authenticateLocalPlayer() {
var localPlayer = GKLocalPlayer.localPlayer()
if(localPlayer.authenticated) {
NSNotificationCenter.defaultCenter().postNotificationName(LocalPlayerIsAuthenticated, object:nil)
return
}
localPlayer.authenticateHandler = {(viewController : UIViewController!, error : NSError!) -> Void in
if(error != nil) {
self.setLastError(error)
}
if(viewController != nil) {
self.setAuthenticationViewController(viewController)
}
else if(GKLocalPlayer.localPlayer().authenticated) {
self._enableGameCenter = true
NSNotificationCenter.defaultCenter().postNotificationName(LocalPlayerIsAuthenticated, object: nil)
}
else {
self._enableGameCenter = false
}
}
}
func setAuthenticationViewController(authViewController:UIViewController!) {
if(authViewController != nil) {
authenticationViewController = authViewController
NSNotificationCenter.defaultCenter().postNotificationName(PresentAuthenticationViewController, object:self)
}
}
func setLastError(error: NSError) {
lastError = error.copy() as? NSError
if((lastError) != nil) {
NSLog("GamerKitHelp ERROR: \(lastError?.userInfo?.description)")
}
}
func findMatchWithMinPlayers(minPlayers:Int, maxPlayers:Int, viewController:UIViewController, delegate:GameKitHelperDelegate) {
if(!_enableGameCenter) {
return;
}
_matchStarted = false
self._match = nil
_delegate = delegate
viewController.dismissViewControllerAnimated(false, completion: nil)
let request = GKMatchRequest()
request.minPlayers = minPlayers
request.maxPlayers = maxPlayers
let mmvc = GKMatchmakerViewController(matchRequest: request)
mmvc.matchmakerDelegate = self
viewController.presentViewController(mmvc, animated: true, completion: nil)
}
func lookupPlayers() {
println("Looking up \(_match.playerIDs.count) players...")
GKPlayer.loadPlayersForIdentifiers(_match?.playerIDs) { (players, error) -> Void in
if error != nil {
println("Error retrieving player info: \(error.localizedDescription)")
self._matchStarted = false
self._delegate?.matchEnded()
}
else {
self.playersDict = NSMutableDictionary(capacity: players.count)
for player in players {
println("Found player: \(player.alias)")
self.playersDict?.setObject(player, forKey: player.playerID)
}
}
self.playersDict?.setObject(GKLocalPlayer.localPlayer(), forKey: GKLocalPlayer.localPlayer().playerID)
self._matchStarted = true
self._delegate?.matchStarted()
}
}
/* For protocol GKMatchmakerViewControllerDelegate */
func matchmakerViewControllerWasCancelled(viewController:GKMatchmakerViewController) {
viewController.dismissViewControllerAnimated(true, completion: nil)
}
func matchmakerViewController(viewController: GKMatchmakerViewController!, didFailWithError error:NSError!) {
viewController.dismissViewControllerAnimated(true, completion: nil)
NSLog("Error finding match: %@", error.localizedDescription)
}
func matchmakerViewController(viewController: GKMatchmakerViewController!,
didFindMatch match: GKMatch!) {
viewController.dismissViewControllerAnimated(true, completion: nil)
self._match = match
match.delegate = self
if(!_matchStarted && match.expectedPlayerCount==0) {
NSLog("Ready to start match")
self.lookupPlayers()
}
}
/* For protocol GKMatchDelegate */
func match(match: GKMatch!, didReceiveData data: NSData!, fromPlayer playerID: NSString!) {
if(_match != match) {
return
}
_delegate?.match(match, didReceiveData: data, fromPlayer: playerID)
}
func match(match: GKMatch!, player: String!, didChangeState state: GKPlayerConnectionState) {
if(_match != match) {
return
}
switch(state) {
case GKPlayerConnectionState.StateConnected:
if(!_matchStarted && match.expectedPlayerCount == 0) {
NSLog("Ready to start match!")
self.lookupPlayers()
}
case GKPlayerConnectionState.StateDisconnected:
NSLog("Player disconnected!")
_matchStarted = false
_delegate?.matchEnded()
default:
break
}
}
func match(match: GKMatch!, connectionWithPlayerFailed:String!, withError error:NSError!) {
if(_match != match) {
return
}
NSLog("Failed to connect to player with error: %@", error.localizedDescription)
_matchStarted = false
_delegate?.matchEnded()
}
func match(match: GKMatch!, didFailWithError error: NSError!) {
if(_match != match) {
return
}
NSLog("Match failed with error: %@", error.localizedDescription)
_matchStarted = false
_delegate?.matchEnded()
}
} | mit | a38180f976792960bee401b6826f4b48 | 32.91 | 131 | 0.626751 | 5.293521 | false | false | false | false |
e-fas/tabijimanOSS-iOS | tabijiman/AppDelegate.swift | 1 | 7297 | //
// AppDelegate.swift
// tabijiman
//
// Copyright (c) 2016 FUKUI Association of information & system industry
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UINavigationControllerDelegate, UINavigationBarDelegate {
var window: UIWindow?
func application( application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]? ) -> Bool {
// Override point for customization after application launch.
//スプラッシュ時間設定
sleep(1)
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "net.e-fas.app.tabijiman" 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("tabijiman", 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("SingleViewCoreData.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 | 35ad373f7ea2cd7e9210466bd49337ee | 54.549618 | 291 | 0.7242 | 5.627997 | false | false | false | false |
Valine/mr-inspiration | ProjectChartSwift/Mr. Inspiration/SongListViewController.swift | 2 | 7104 | //
// SongListViewController.swift
// Mr. Inspiration
//
// Created by Lukas Valine on 12/1/15.
// Copyright © 2015 Lukas Valine. All rights reserved.
//
import UIKit
class SongListViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIGestureRecognizerDelegate {
let model = SongListModel()
var rightButton: UIBarButtonItem?
var deleteButton: UIBarButtonItem?
let cellWidth: CGFloat = screenSize.width / 3 - 30 * 1.3
let cellHeight: CGFloat = screenSize.width / 3 - 30 * 1.3
var delegate: SongListViewControllerDelegate?
private let cellIdentifier = "songCell"
override func loadView() {
view = SongListView(frame: UIScreen.mainScreen().bounds, cellSize: CGSize(width: cellWidth, height: cellHeight))
}
override func viewDidLoad() { super.viewDidLoad()
let listView = self.view as! SongListView
listView.collectionView!.dataSource = self
listView.collectionView!.delegate = self
let longPress = UILongPressGestureRecognizer(target: self, action: "handleLongPress:")
longPress.minimumPressDuration = 0.5
longPress.delaysTouchesBegan = true
longPress.delegate = self
listView.collectionView!.addGestureRecognizer(longPress)
/// Add nav bar buttons
rightButton = UIBarButtonItem(title: "Edit", style: UIBarButtonItemStyle.Done, target: self, action: "editPressed:")
navigationItem.rightBarButtonItem = rightButton
deleteButton = UIBarButtonItem(title: "Delete", style: UIBarButtonItemStyle.Done, target: self, action: "deletePressed:")
deleteButton?.enabled = false
self.title = "Mr. Inspiration"
}
//-----------------------------------------------------------------
// MARK: Collection view data
//-----------------------------------------------------------------
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return model.songs.count + 1
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let listView = self.view as! SongListView
let cell: SongCellView = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! SongCellView
var name = "song"
if indexPath.item != 0 {
print(model.songs.count)
print(indexPath.item)
name = model.songs[indexPath.item * -1 + model.songs.count].name
}
cell.setupCell(name, indexPath: indexPath.item, mode: listView.mode, cellsSelected: listView.cellsSelected)
return cell
}
//-----------------------------------------------------------------
// MARK: Cell tapped
//-----------------------------------------------------------------
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let listView = self.view as! SongListView
if listView.mode == .EditOff {
if indexPath.item == 0 {
//// Present buildSongView
delegate?.addSongTapped()
} else {
//// Present songView
delegate?.songCellTapped(indexPath.item, model: model.songs[indexPath.item * -1 + model.songs.count])
}
} else {
if indexPath.item != 0 {
listView.toggleCellSelectedAtIndex(indexPath)
if listView.thereIsButtonSelected() {
deleteButton?.enabled = true
} else {
deleteButton?.enabled = false
}
}
}
}
//-----------------------------------------------------------------
// MARK: Cell long press || Edit tapped
//-----------------------------------------------------------------
func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) {
deleteButton?.enabled = false
if gestureReconizer.state == UIGestureRecognizerState.Began {
toggleEditMode()
}
}
func editPressed(sender: UIButton) {
deleteButton?.enabled = false
toggleEditMode()
}
func toggleEditMode() {
let listView = self.view as! SongListView
if listView.mode == .EditOff {
listView.enableEditMode()
rightButton?.title = "Done"
navigationItem.leftBarButtonItem = deleteButton
} else {
listView.disableEditMode()
rightButton?.title = "Edit"
navigationItem.leftBarButtonItem = nil
}
}
//-----------------------------------------------------------------
// MARK: Delete Tapped
//-----------------------------------------------------------------
func deletePressed(sender: UIButton) {
let listView = self.view as! SongListView
var deleteMessage = "Delete Song"
if listView.numberOfSongSelected() > 1 {
deleteMessage = "Delete " + String(listView.numberOfSongSelected()) + " Songs"
}
let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let deleteAction = UIAlertAction(title: deleteMessage, style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
var numberDeleted = 0
for i in listView.cellsSelected.enumerate() {
if i.element.boolValue {
self.model.deleteSongAtIndex(self.model.songs.count + (i.index - numberDeleted) * -1)
numberDeleted++
}
}
self.toggleEditMode()
})
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
(alert: UIAlertAction!) -> Void in
})
optionMenu.addAction(deleteAction)
optionMenu.addAction(cancelAction)
self.presentViewController(optionMenu, animated: true, completion: nil)
}
}
protocol SongListViewControllerDelegate {
func deletePressed(sender: UIButton)
func addSongTapped()
func songCellTapped(index: Int, model: Song)
}
| gpl-2.0 | 16169e5a00b7865fa49672f0928ee891 | 30.153509 | 144 | 0.519358 | 6.187282 | false | false | false | false |
kafejo/Tracker-Aggregator | TrackerAggregator/TrackerAggregator.swift | 1 | 9623 | //
// TrackerAggregator.swift
// TrackerAggregator
//
// Created by Ales Kocur on 25/08/2017.
// Copyright © 2017 All rights reserved.
//
import Foundation
// MARK: - Tracking types
protocol TrackerConfigurable: AnyObject {
/// This is called before anything is tracked to configure each tracker. This is being called on background thread!
func configure()
func reset()
var name: String { get }
}
extension TrackerConfigurable {
var name: String {
return String(describing: type(of: self))
}
func reset() {}
}
protocol AnalyticsAdapter: EventTrackable, PropertyTrackable, TrackerConfigurable {}
extension AnalyticsAdapter {
func shouldTrackEvent(_ event: TrackableEvent) -> Bool {
guard let rule = eventTrackingRule else {
return true
}
let isIncluded = rule.types.contains(where: { type(of: event) == $0 })
if (isIncluded && rule.rule == .allow) || (!isIncluded && rule.rule == .prohibit) {
return true
} else {
return false
}
}
}
// MARK: - Global Tracker
class GlobalTracker {
private static let shared = GlobalTracker()
private let trackingQueue = DispatchQueue(label: "com.global-tracker.tracking-queue", qos: DispatchQoS.background, attributes: .concurrent)
init() {}
private var wasConfigured: Bool = false
var postponedEvents: [TrackableEvent] = []
var postponedProperties: [TrackableProperty] = []
private var adapters: [AnalyticsAdapter] = []
private var log: ((String) -> Void) = { message in
print(message)
}
enum LoggingLevel {
case none, info, verbose
}
var loggingLevel: LoggingLevel = .none
func set(adapters: [AnalyticsAdapter]) {
self.adapters = adapters
}
func configureAdapters() {
trackingQueue.sync {
self.adapters.forEach { $0.configure() }
self.wasConfigured = true
self.postponedEvents.forEach { self.track(event: $0) }
self.postponedProperties.forEach { self.update(property: $0) }
self.postponedEvents.removeAll()
self.postponedProperties.removeAll()
}
}
func resetAdapters() {
trackingQueue.sync {
self.adapters.forEach { $0.reset() }
}
}
func track(event: TrackableEvent) {
if !self.wasConfigured {
self.postponedEvents.append(event)
// Should reschedule to be sent after configuration is complete
return
}
trackingQueue.sync {
self._track(event: event)
}
}
private func _track(event: TrackableEvent) {
func trackEvent(event: TrackableEvent, tracker: AnalyticsAdapter) {
if self.loggingLevel == .info {
log("-[\(tracker.name)]: EVENT TRIGGERED - '\(event.identifier.formatted)'")
} else if self.loggingLevel == .verbose {
if event.metadata.count > 0 {
let metadata = event.metadata.compactMap { "\($0.key): \($0.value)"}.joined(separator: "\n > ")
log("-[\(tracker.name)]: EVENT TRIGGERED - '\(event.identifier.formatted)' \n > \(metadata)")
} else {
log("-[\(tracker.name)]: EVENT TRIGGERED - '\(event.identifier.formatted)' (no meta)")
}
}
tracker.track(event: event)
}
adapters.forEach { tracker in
if let rule = tracker.eventTrackingRule {
let isIncluded = rule.types.contains(where: { type(of: event) == $0 })
if isIncluded && rule.rule == .allow {
trackEvent(event: event, tracker: tracker)
} else if !isIncluded && rule.rule == .prohibit {
trackEvent(event: event, tracker: tracker)
}
} else {
trackEvent(event: event, tracker: tracker)
}
}
}
func update(property: TrackableProperty) {
if !self.wasConfigured {
trackingQueue.async(flags: .barrier) {
self.postponedProperties.append(property)
}
return
}
trackingQueue.sync {
self._update(property: property)
}
}
private func _update(property: TrackableProperty) {
self.adapters.forEach { tracker in
let action = {
tracker.track(property: property)
if self.loggingLevel == .info {
self.log("-[\(tracker.name)]: '\(property.identifier)' UPDATED TO '\(property.trackedValue ?? "nil")'")
}
}
if let rule = tracker.propertyTrackingRule {
let isIncluded = rule.types.contains(where: { type(of: property) == $0 })
if isIncluded && rule.rule == .allow {
action()
} else if !isIncluded && rule.rule == .prohibit {
action()
}
} else {
action()
}
}
property.generateUpdateEvents().forEach(self._track)
}
lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .medium
return formatter
}()
// MARK: - Public API
/// Set adapters to track events to and configure them to start tracking
class func startTracking(adapters: [AnalyticsAdapter]) {
shared.set(adapters: adapters)
shared.configureAdapters()
}
class func log(logClosure: @escaping (String) -> Void) {
shared.log = logClosure
}
/// Reset trackers so them set new unregistered user
class func resetAdapters() {
shared.resetAdapters()
}
/// Track event
class func track(event: TrackableEvent) {
shared.track(event: event)
}
/// Update property
class func update(property: TrackableProperty) {
shared.update(property: property)
}
/// Default `.none`
class var loggingLevel: LoggingLevel {
get {
return shared.loggingLevel
}
set {
shared.loggingLevel = newValue
}
}
}
// Event triggering shortcut
extension TrackableEvent {
func trigger() {
GlobalTracker.track(event: self)
}
}
// Property update shortcut
extension TrackableProperty {
func update() {
GlobalTracker.update(property: self)
}
}
extension EventIdentifier {
func underscoredLowercased() -> String {
if let label = label {
return "\(object)_\(action)_\(label)".lowercased().replacingOccurrences(of: " ", with: "_")
} else {
return "\(object)_\(action)".lowercased().replacingOccurrences(of: " ", with: "_")
}
}
}
enum TrackingRule {
case allow, prohibit
}
// MARK: - Event tracking
protocol EventTrackable {
var eventTrackingRule: EventTrackingRule? { get }
func track(event: TrackableEvent)
}
extension EventTrackable {
var eventTrackingRule: EventTrackingRule? {
return nil
}
}
protocol EventIdentifiable {
var identifier: EventIdentifier { get }
}
protocol MetadataConvertible {
var metadata: [String: Any] { get }
}
extension MetadataConvertible {
var metadata: [String: Any] {
[:]
}
}
protocol TrackableEvent: MetadataConvertible, EventIdentifiable {}
struct EventIdentifier {
let object: String
let action: String
let label: String?
init(object: String, action: String, label: String? = nil) {
self.object = object
self.action = action
self.label = label
}
var formatted: String {
if let label = label {
return "\(object): \(action) - \(label)"
} else {
return "\(object): \(action)"
}
}
}
struct EventTrackingRule {
let rule: TrackingRule
let types: [TrackableEvent.Type]
init(_ rule: TrackingRule, types: [TrackableEvent.Type]) {
self.rule = rule
self.types = types
}
}
// MARK: - Property tracking
protocol TrackableValueType { }
extension String: TrackableValueType {}
extension Bool: TrackableValueType {}
extension Int: TrackableValueType {}
extension Double: TrackableValueType {}
protocol TrackableProperty {
var identifier: String { get }
var trackedValue: TrackableValueType? { get }
func generateUpdateEvents() -> [TrackableEvent]
}
extension TrackableProperty {
func generateUpdateEvents() -> [TrackableEvent] {
return []
}
}
protocol PropertyTrackable {
var propertyTrackingRule: PropertyTrackingRule? { get }
func track(property: TrackableProperty)
}
extension PropertyTrackable {
var propertyTrackingRule: PropertyTrackingRule? {
return nil
}
}
struct PropertyTrackingRule {
let rule: TrackingRule
let types: [TrackableProperty.Type]
init(_ rule: TrackingRule, types: [TrackableProperty.Type]) {
self.rule = rule
self.types = types
}
}
extension TrackableValueType {
var stringValue: String {
switch self {
case let string as String:
return string
case let int as Int:
return String(int)
case let bool as Bool:
return bool ? "true" : "false"
case let double as Double:
return String(double)
default:
return "unsupported_value"
}
}
}
| mit | 2430ddca3ce2aa208ed6ff787b090337 | 24.658667 | 143 | 0.585949 | 4.532266 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureKYC/Sources/FeatureKYCUI/KYCRouter.swift | 1 | 31693 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import BlockchainNamespace
import Combine
import DIKit
import Errors
import FeatureFormDomain
import FeatureKYCDomain
import Localization
import NetworkKit
import PlatformKit
import PlatformUIKit
import RxRelay
import RxSwift
import ToolKit
import UIComponentsKit
import UIKit
enum KYCEvent {
/// When a particular screen appears, we need to
/// look at the `NabuUser` object and determine if
/// there is data there for pre-populate the screen with.
case pageWillAppear(KYCPageType)
/// This will push on the next page in the KYC flow.
case nextPageFromPageType(KYCPageType, KYCPagePayload?)
/// Event emitted when the provided page type emits an error
case failurePageForPageType(KYCPageType, KYCPageError)
}
protocol KYCRouterDelegate: AnyObject {
func apply(model: KYCPageModel)
}
public enum UserAddressSearchResult {
case abandoned
case saved
}
public protocol AddressSearchFlowPresenterAPI {
func openSearchAddressFlow(
country: String,
state: String?
) -> AnyPublisher<UserAddressSearchResult, Never>
}
// swiftlint:disable type_body_length
/// Coordinates the KYC flow. This component can be used to start a new KYC flow, or if
/// the user drops off mid-KYC and decides to continue through it again, the coordinator
/// will handle recovering where they left off.
final class KYCRouter: KYCRouterAPI {
// MARK: - Public Properties
weak var delegate: KYCRouterDelegate?
// MARK: - Private Properties
private(set) var user: NabuUser?
private(set) var country: CountryData?
private(set) var states: [KYCState] = []
private var pager: KYCPagerAPI!
private weak var rootViewController: UIViewController?
private var navController: KYCOnboardingNavigationController?
private let disposables = CompositeDisposable()
private let disposeBag = DisposeBag()
private let pageFactory = KYCPageViewFactory()
private let appSettings: AppSettingsAPI
private let loadingViewPresenter: LoadingViewPresenting
private let app: AppProtocol
private var userTiersResponse: KYC.UserTiers?
private var kycSettings: KYCSettingsAPI
private let tiersService: KYCTiersServiceAPI
private let networkAdapter: NetworkAdapterAPI
private let analyticsRecorder: AnalyticsEventRecorderAPI
private let nabuUserService: NabuUserServiceAPI
private let requestBuilder: RequestBuilder
private let webViewServiceAPI: WebViewServiceAPI
private let kycStoppedRelay = PublishRelay<Void>()
private let kycFinishedRelay = PublishRelay<KYC.Tier>()
private var parentFlow: KYCParentFlow?
private var errorRecorder: ErrorRecording
private var alertPresenter: AlertViewPresenterAPI
private var addressSearchFlowPresenter: AddressSearchFlowPresenterAPI
/// KYC finsihed with `tier1` in-progress / approved
var tier1Finished: Observable<Void> {
kycFinishedRelay
.filter { $0 == .tier1 }
.mapToVoid()
}
/// KYC finsihed with `tier2` in-progress / approved
var tier2Finished: Observable<Void> {
kycFinishedRelay
.filter { $0 == .tier2 }
.mapToVoid()
}
var kycFinished: Observable<KYC.Tier> {
kycFinishedRelay.asObservable()
}
var kycStopped: Observable<Void> {
kycStoppedRelay.asObservable()
}
private var bag = Set<AnyCancellable>()
init(
app: AppProtocol = resolve(),
requestBuilder: RequestBuilder = resolve(tag: DIKitContext.retail),
webViewServiceAPI: WebViewServiceAPI = resolve(),
tiersService: KYCTiersServiceAPI = resolve(),
appSettings: AppSettingsAPI = resolve(),
analyticsRecorder: AnalyticsEventRecorderAPI = resolve(),
errorRecorder: ErrorRecording = resolve(),
alertPresenter: AlertViewPresenterAPI = resolve(),
addressSearchFlowPresenter: AddressSearchFlowPresenterAPI = resolve(),
nabuUserService: NabuUserServiceAPI = resolve(),
kycSettings: KYCSettingsAPI = resolve(),
loadingViewPresenter: LoadingViewPresenting = resolve(),
networkAdapter: NetworkAdapterAPI = resolve(tag: DIKitContext.retail)
) {
self.app = app
self.requestBuilder = requestBuilder
self.errorRecorder = errorRecorder
self.alertPresenter = alertPresenter
self.addressSearchFlowPresenter = addressSearchFlowPresenter
self.analyticsRecorder = analyticsRecorder
self.nabuUserService = nabuUserService
self.webViewServiceAPI = webViewServiceAPI
self.tiersService = tiersService
self.appSettings = appSettings
self.kycSettings = kycSettings
self.loadingViewPresenter = loadingViewPresenter
self.networkAdapter = networkAdapter
}
deinit {
disposables.dispose()
}
// MARK: Public
func start(parentFlow: KYCParentFlow) {
start(tier: .tier2, parentFlow: parentFlow, from: nil)
}
func start(tier: KYC.Tier, parentFlow: KYCParentFlow) {
start(tier: tier, parentFlow: parentFlow, from: nil)
}
// swiftlint:disable function_body_length
func start(
tier: KYC.Tier,
parentFlow: KYCParentFlow,
from viewController: UIViewController?
) {
self.parentFlow = parentFlow
guard let viewController = viewController ?? UIApplication.shared.topMostViewController else {
Logger.shared.warning("Cannot start KYC. rootViewController is nil.")
return
}
rootViewController = viewController
app.post(
event: blockchain.ux.kyc.event.did.start,
context: [
blockchain.ux.kyc.tier: {
switch tier {
case .tier0:
return blockchain.ux.kyc.tier.none[]
case .tier1:
return blockchain.ux.kyc.tier.silver[]
case .tier2:
return blockchain.ux.kyc.tier.gold[]
}
}()
]
)
switch tier {
case .tier0:
analyticsRecorder.record(event: AnalyticsEvents.KYC.kycTier0Start)
case .tier1:
analyticsRecorder.record(event: AnalyticsEvents.KYC.kycTier1Start)
case .tier2:
analyticsRecorder.record(event: AnalyticsEvents.KYC.kycTier2Start)
analyticsRecorder.record(
event: AnalyticsEvents.New.Onboarding.upgradeVerificationClicked(
origin: .init(parentFlow),
tier: tier.rawValue
)
)
}
let postTierObservable = post(tier: tier).asObservable()
.flatMap { [tiersService] tiersResponse in
Observable.zip(
Observable.just(tiersResponse),
tiersService
.checkSimplifiedDueDiligenceEligibility(for: tiersResponse.latestApprovedTier)
.asObservable(),
tiersService
.checkSimplifiedDueDiligenceVerification(
for: tiersResponse.latestApprovedTier,
pollUntilComplete: false
)
.asObservable()
)
}
let disposable = Observable
.zip(
nabuUserService.fetchUser().asObservable(),
postTierObservable
)
.subscribe(on: MainScheduler.asyncInstance)
.observe(on: MainScheduler.instance)
.hideLoaderOnDisposal(loader: loadingViewPresenter)
.subscribe(onNext: { [weak self] user, tiersTuple in
let (tiersResponse, isSDDEligible, isSDDVerified) = tiersTuple
self?.pager = KYCPager(tier: tier, tiersResponse: tiersResponse)
Logger.shared.debug("Got user with ID: \(user.personalDetails.identifier ?? "")")
guard let strongSelf = self else {
return
}
strongSelf.userTiersResponse = tiersResponse
strongSelf.user = user
// SDD Eligible users can buy but we only need to check for SDD during the buy flow.
// This is to avoid breaking Tier 2 upgrade paths (e.g., from Settings)
let shouldUseSDDFlags = tier < .tier2 && parentFlow == .simpleBuy
let shouldCheckForSDDEligibility = shouldUseSDDFlags ? isSDDEligible : false
let shouldCheckForSDDVerification = shouldUseSDDFlags ? isSDDVerified : false
let startingPage = KYCPageType.startingPage(
forUser: user,
requiredTier: tier,
tiersResponse: tiersResponse,
isSDDEligible: shouldCheckForSDDEligibility,
isSDDVerified: shouldCheckForSDDVerification,
hasQuestions: strongSelf.hasQuestions
)
if startingPage == .finish {
return strongSelf.finish()
}
if startingPage != .accountStatus {
/// If the starting page is accountStatus, they do not have any additional
/// pages to view, so we don't want to set `isCompletingKyc` to `true`.
strongSelf.kycSettings.isCompletingKyc = true
}
strongSelf.initializeNavigationStack(
viewController,
user: user,
tier: tier,
isSDDEligible: shouldCheckForSDDEligibility,
isSDDVerified: shouldCheckForSDDVerification
)
strongSelf.restoreToMostRecentPageIfNeeded(
tier: tier,
isSDDEligible: isSDDEligible,
isSDDVerified: shouldCheckForSDDVerification
)
}, onError: { [alertPresenter, errorRecorder] error in
Logger.shared.error("Failed to get user: \(String(describing: error))")
errorRecorder.error(error)
alertPresenter.notify(
content: .init(
title: LocalizationConstants.KYC.Errors.cannotFetchUserAlertTitle,
message: String(describing: error)
),
in: viewController
)
})
disposables.insertWithDiscardableResult(disposable)
}
// Called when the entire KYC process has been completed.
func finish() {
dismiss { [app, tiersService, kycFinishedRelay, disposeBag] in
tiersService.fetchTiers()
.asObservable()
.map(\.latestApprovedTier)
.catchAndReturn(.tier0)
.bindAndCatch(to: kycFinishedRelay)
.disposed(by: disposeBag)
NotificationCenter.default.post(
name: Constants.NotificationKeys.kycFinished,
object: nil
)
NotificationCenter.default.post(name: .kycStatusChanged, object: nil)
NotificationCenter.default.post(name: .kycFinished, object: nil)
app.post(event: blockchain.ux.kyc.event.did.finish)
app.post(event: blockchain.ux.kyc.event.status.did.change)
}
}
// Called when the KYC process is stopped before completing.
func stop() {
dismiss { [app, kycStoppedRelay] in
kycStoppedRelay.accept(())
NotificationCenter.default.post(
name: Constants.NotificationKeys.kycStopped,
object: nil
)
NotificationCenter.default.post(name: .kycStatusChanged, object: nil)
app.post(event: blockchain.ux.kyc.event.did.stop)
app.post(event: blockchain.ux.kyc.event.status.did.change)
}
}
private func dismiss(completion: @escaping () -> Void) {
guard let navController = navController else {
completion()
return
}
navController.dismiss(animated: true, completion: completion)
}
func handle(event: KYCEvent) {
switch event {
case .pageWillAppear(let type):
handlePageWillAppear(for: type)
app.state.set(blockchain.ux.kyc.current.state, to: type.tag[])
app.post(
event: blockchain.ux.kyc.event.did.enter.state[][type.descendant]!,
context: [blockchain.ux.kyc.current.state: type.tag[]]
)
case .failurePageForPageType(let type, let error):
handleFailurePage(for: error)
app.post(
event: blockchain.ux.kyc.event.did.fail.on.state[][type.descendant]!,
context: [blockchain.ux.kyc.current.state: type.tag[]]
)
case .nextPageFromPageType(let type, let payload):
handlePayloadFromPageType(type, payload)
app.post(
event: blockchain.ux.kyc.event.did.confirm.state[][type.descendant]!,
context: [blockchain.ux.kyc.current.state: type.tag[]]
)
let disposable = pager.nextPage(from: type, payload: payload)
.subscribe(on: MainScheduler.asyncInstance)
.observe(on: MainScheduler.instance)
.subscribe(onSuccess: { [weak self] nextPage in
guard let self = self else {
return
}
switch (self.parentFlow, nextPage) {
case (.simpleBuy, .accountStatus):
self.finish()
return
default:
break
}
let controller = self.pageFactory.createFrom(
pageType: nextPage,
in: self,
payload: payload
)
self.isNewAddressSearchEnabled { isNewAddressSearchEnabled in
if let informationController = controller as? KYCInformationController, nextPage == .accountStatus {
self.presentInformationController(informationController)
} else if isNewAddressSearchEnabled, nextPage == .address {
if let navController = self.navController {
navController.dismiss(animated: true) {
self.navController = nil
self.presentAddressSearchFlow()
}
} else {
self.presentAddressSearchFlow()
}
} else {
self.safePushInNavController(controller)
}
}
}, onError: { error in
Logger.shared.error("Error getting next page: \(String(describing: error))")
}, onCompleted: { [weak self] in
Logger.shared.info("No more next pages")
guard let strongSelf = self else {
return
}
strongSelf.kycSettings.isCompletingKyc = false
strongSelf.finish()
})
disposables.insertWithDiscardableResult(disposable)
}
}
private func isNewAddressSearchEnabled(onComplete: @escaping (Bool) -> Void) {
Task(priority: .userInitiated) { @MainActor in
let isNewAddressSearchEnabled: Bool? = try? await app.publisher(
for: blockchain.app.configuration.addresssearch.kyc.is.enabled,
as: Bool.self
)
.await()
.value
onComplete(isNewAddressSearchEnabled ?? false)
}
}
private func presentAddressSearchFlow() {
guard let countryCode = country?.code ?? user?.address?.countryCode else { return }
addressSearchFlowPresenter
.openSearchAddressFlow(
country: countryCode,
state: user?.address?.state
)
.receive(on: DispatchQueue.main)
.sink(receiveValue: { [weak self] addressResult in
switch addressResult {
case .saved:
self?.handle(event: .nextPageFromPageType(.address, nil))
case .abandoned:
self?.stop()
}
})
.store(in: &bag)
}
func presentInformationController(_ controller: KYCInformationController) {
/// Refresh the user's tiers to get their status.
/// Sometimes we receive an `INTERNAL_SERVER_ERROR` if we refresh this
/// immediately after submitting all KYC data. So, we apply a delay here.
tiersService.tiers
.asSingle()
.handleLoaderForLifecycle(loader: loadingViewPresenter)
.observe(on: MainScheduler.instance)
.subscribe(
onSuccess: { [weak self] response in
guard let self = self else { return }
let status = response.tierAccountStatus(for: .tier2)
controller.viewModel = KYCInformationViewModel.create(
for: status,
isReceivingAirdrop: false
)
controller.viewConfig = KYCInformationViewConfig.create(
for: status,
isReceivingAirdrop: false
)
controller.primaryButtonAction = { _ in
switch status {
case .approved:
self.finish()
case .pending:
break
case .failed, .expired:
if let blockchainSupportURL = URL(string: Constants.Url.blockchainSupport) {
UIApplication.shared.open(blockchainSupportURL)
}
case .none, .underReview:
return
}
}
self.safePushInNavController(controller)
}
)
.disposed(by: disposeBag)
}
var hasQuestions: Bool {
(try? app.state.get(blockchain.ux.kyc.extra.questions.form.is.empty)) == false
}
// MARK: View Restoration
/// Restores the user to the most recent page if they dropped off mid-flow while KYC'ing
private func restoreToMostRecentPageIfNeeded(tier: KYC.Tier, isSDDEligible: Bool, isSDDVerified: Bool) {
guard let currentUser = user else {
return
}
guard let response = userTiersResponse else { return }
let latestPage = kycSettings.latestKycPage
let startingPage = KYCPageType.startingPage(
forUser: currentUser,
requiredTier: tier,
tiersResponse: response,
isSDDEligible: isSDDEligible,
isSDDVerified: isSDDVerified,
hasQuestions: hasQuestions
)
if startingPage == .finish {
return
}
if startingPage == .accountStatus {
/// The `tier` on KYCPager cannot be `tier1` if the user's `startingPage` is `.accountStatus`.
/// If their `startingPage` is `.accountStatus`, they're done.
pager = KYCPager(tier: .tier2, tiersResponse: response)
}
guard let endPageForLastUsedTier = KYCPageType.pageType(
for: currentUser,
tiersResponse: response,
latestPage: latestPage
) else {
return
}
// If a user has moved to a new tier, they need to use the starting page for the new tier
let endPage = endPageForLastUsedTier.rawValue >= startingPage.rawValue ? endPageForLastUsedTier : startingPage
var currentPage = startingPage
while currentPage != endPage {
guard let nextPage = currentPage.nextPage(
forTier: tier,
user: user,
country: country,
tiersResponse: response
) else { return }
currentPage = nextPage
let nextController = pageFactory.createFrom(
pageType: currentPage,
in: self,
payload: createPagePayload(page: currentPage, user: currentUser)
)
safePushInNavController(nextController, animated: false)
}
}
private func createPagePayload(page: KYCPageType, user: NabuUser) -> KYCPagePayload? {
switch page {
case .confirmPhone:
return .phoneNumberUpdated(phoneNumber: user.mobile?.phone ?? "")
case .confirmEmail:
return .emailPendingVerification(email: user.email.address)
case .accountStatus:
guard let response = userTiersResponse else { return nil }
return .accountStatus(
status: response.tierAccountStatus(for: .tier2),
isReceivingAirdrop: false
)
case .enterEmail,
.welcome,
.country,
.states,
.profile,
.address,
.accountUsageForm,
.sddVerificationCheck,
.tier1ForcedTier2,
.enterPhone,
.verifyIdentity,
.resubmitIdentity,
.applicationComplete,
.finish:
return nil
}
}
private func initializeNavigationStack(
_ viewController: UIViewController,
user: NabuUser,
tier: KYC.Tier,
isSDDEligible: Bool,
isSDDVerified: Bool
) {
guard let response = userTiersResponse else { return }
let startingPage = KYCPageType.startingPage(
forUser: user,
requiredTier: tier,
tiersResponse: response,
isSDDEligible: isSDDEligible,
isSDDVerified: isSDDVerified,
hasQuestions: hasQuestions
)
if startingPage == .finish {
return
}
isNewAddressSearchEnabled { [weak self] isNewAddressSearchEnabled in
guard let self = self else { return }
var controller: KYCBaseViewController
if startingPage == .accountStatus {
controller = self.pageFactory.createFrom(
pageType: startingPage,
in: self,
payload: .accountStatus(
status: response.tierAccountStatus(for: .tier2),
isReceivingAirdrop: false
)
)
self.navController = self.presentInNavigationController(controller, in: viewController)
} else if isNewAddressSearchEnabled, startingPage == .address {
self.presentAddressSearchFlow()
} else {
controller = self.pageFactory.createFrom(
pageType: startingPage,
in: self
)
self.navController = self.presentInNavigationController(controller, in: viewController)
}
}
}
// MARK: Private Methods
private func handlePayloadFromPageType(_ pageType: KYCPageType, _ payload: KYCPagePayload?) {
guard let payload = payload else { return }
switch payload {
case .countrySelected(let country):
self.country = country
case .stateSelected(_, let states):
self.states = states
case .phoneNumberUpdated,
.emailPendingVerification,
.sddVerification,
.accountStatus:
// Not handled here
return
}
}
private func handleFailurePage(for error: KYCPageError) {
let informationViewController = KYCInformationController.make(with: self)
informationViewController.viewConfig = KYCInformationViewConfig(
titleColor: UIColor.gray5,
isPrimaryButtonEnabled: true,
imageTintColor: nil
)
switch error {
case .countryNotSupported(let country):
kycSettings.isCompletingKyc = false
informationViewController.viewModel = KYCInformationViewModel.createForUnsupportedCountry(country)
informationViewController.primaryButtonAction = { [unowned self] viewController in
viewController.presentingViewController?.presentingViewController?.dismiss(animated: true)
let interactor = KYCCountrySelectionInteractor()
let disposable = interactor.selected(
country: country,
shouldBeNotifiedWhenAvailable: true
)
self.disposables.insertWithDiscardableResult(disposable)
}
safePresentInNavigationController(informationViewController)
case .stateNotSupported(let state):
kycSettings.isCompletingKyc = false
informationViewController.viewModel = KYCInformationViewModel.createForUnsupportedState(state)
informationViewController.primaryButtonAction = { [unowned self] viewController in
viewController.presentingViewController?.presentingViewController?.dismiss(animated: true)
let interactor = KYCCountrySelectionInteractor()
let disposable = interactor.selected(
state: state,
shouldBeNotifiedWhenAvailable: true
)
self.disposables.insertWithDiscardableResult(disposable)
}
safePresentInNavigationController(informationViewController)
}
}
private func handlePageWillAppear(for type: KYCPageType) {
if type == .accountStatus || type == .applicationComplete {
kycSettings.latestKycPage = nil
} else {
kycSettings.latestKycPage = type
}
// Optionally apply page model
switch type {
case .tier1ForcedTier2,
.sddVerificationCheck,
.welcome,
.confirmEmail,
.country,
.states,
.accountStatus,
.accountUsageForm,
.applicationComplete,
.resubmitIdentity,
.finish:
break
case .enterEmail:
guard let current = user else { return }
delegate?.apply(model: .email(current))
case .profile:
guard let current = user else { return }
delegate?.apply(model: .personalDetails(current))
case .address:
guard let current = user else { return }
delegate?.apply(model: .address(current, country, states))
case .enterPhone, .confirmPhone:
guard let current = user else { return }
delegate?.apply(model: .phone(current))
case .verifyIdentity:
guard let countryCode = country?.code ?? user?.address?.countryCode else { return }
delegate?.apply(model: .verifyIdentity(countryCode: countryCode))
}
}
private func post(tier: KYC.Tier) -> AnyPublisher<KYC.UserTiers, NabuNetworkError> {
let body = KYCTierPostBody(selectedTier: tier)
let request = requestBuilder.post(
path: ["kyc", "tiers"],
body: try? JSONEncoder().encode(body),
authenticated: true
)!
return networkAdapter.perform(request: request)
}
private func safePushInNavController(
_ viewController: UIViewController,
animated: Bool = true
) {
if let navController = navController {
navController.pushViewController(viewController, animated: animated)
} else {
guard let rootViewController = rootViewController else {
return
}
navController = presentInNavigationController(viewController, in: rootViewController)
}
}
private func safePresentInNavigationController(
_ viewController: UIViewController
) {
if let navController = navController {
presentInNavigationController(viewController, in: navController)
} else {
guard let rootViewController = rootViewController else {
return
}
navController = presentInNavigationController(viewController, in: rootViewController)
}
}
@discardableResult private func presentInNavigationController(
_ viewController: UIViewController,
in presentingViewController: UIViewController
) -> KYCOnboardingNavigationController {
let navController = KYCOnboardingNavigationController.make()
navController.pushViewController(viewController, animated: false)
navController.modalTransitionStyle = .coverVertical
if let presentedViewController = presentingViewController.presentedViewController {
presentedViewController.dismiss(animated: true) {
presentingViewController.present(navController, animated: true)
}
} else {
presentingViewController.present(navController, animated: true)
}
return navController
}
}
extension KYCPageType {
/// The page type the user should be placed in given the information they have provided
fileprivate static func pageType(for user: NabuUser, tiersResponse: KYC.UserTiers, latestPage: KYCPageType? = nil) -> KYCPageType? {
// Note: latestPage is only used by tier 2 flow, for tier 1, we need to infer the page,
// because the user may need to select the country again.
let tier = user.tiers?.selected ?? .tier1
switch tier {
case .tier0:
return nil
case .tier1:
return tier1PageType(for: user)
case .tier2:
return tier1PageType(for: user) ?? tier2PageType(for: user, tiersResponse: tiersResponse, latestPage: latestPage)
}
}
private static func tier1PageType(for user: NabuUser) -> KYCPageType? {
guard user.email.verified else {
return .enterEmail
}
guard user.personalDetails.firstName != nil else {
return .country
}
guard user.address != nil else { return .country }
return nil
}
private static func tier2PageType(for user: NabuUser, tiersResponse: KYC.UserTiers, latestPage: KYCPageType? = nil) -> KYCPageType? {
if let latestPage = latestPage {
return latestPage
}
guard let mobile = user.mobile else { return .enterPhone }
guard mobile.verified else { return .confirmPhone }
if tiersResponse.canCompleteTier2 {
switch tiersResponse.canCompleteTier2 {
case true:
return user.needsDocumentResubmission == nil ? .verifyIdentity : .resubmitIdentity
case false:
return nil
}
}
guard tiersResponse.canCompleteTier2 == false else { return .verifyIdentity }
return nil
}
}
| lgpl-3.0 | 25f99eff7467ff42e14e06d0c6a46ed7 | 36.818616 | 137 | 0.58529 | 5.348861 | false | false | false | false |
guanix/swift-sodium | Sodium/Sodium.swift | 3 | 666 | //
// Sodium.swift
// Sodium
//
// Created by Frank Denis on 12/27/14.
// Copyright (c) 2014 Frank Denis. All rights reserved.
//
import Foundation
public class Sodium {
public var box = Box()
public var secretBox = SecretBox()
public var genericHash = GenericHash()
public var pwHash = PWHash()
public var randomBytes = RandomBytes()
public var shortHash = ShortHash()
public var sign = Sign()
public var utils = Utils()
public init?() {
struct Once {
static var once: dispatch_once_t = 0
}
dispatch_once(&Once.once) {
sodium_init()
()
}
}
}
| isc | d0e19dddd0a88feb671b75afdc149036 | 21.2 | 56 | 0.575075 | 3.784091 | false | false | false | false |
nextgenappsllc/NGAEssentials | NGAEssentials/Classes/UIViewExtension.swift | 1 | 16516 | //
// UIViewExtension.swift
// NGAFramework
//
// Created by Jose Castellanos on 3/13/16.
// Copyright © 2016 NextGen Apps LLC. All rights reserved.
//
import Foundation
public extension UIView {
//// adding subviews make the last one appear on top of the previous so these methods do not re add thus preserving the order
public func addSubviewIfNeeded(_ subview:UIView?) {
//// changed to direct descendant
if subview != nil && !subview!.isDirectDescendantOf(self) {addSubview(subview!)}
}
//// same as above but can add many
public func addSubviewsIfNeeded(_ subviews:UIView?...) {
for subview in subviews {addSubviewIfNeeded(subview)}
}
//// considering deprecating
func centerInView(_ view:UIView) {
self.frame = self.centeredFrameInBounds(view.bounds)
}
//// considering deprecating
func centeredFrameInBounds(_ superBounds:CGRect) -> CGRect {
var temp = self.frame
temp.origin.x = (superBounds.size.width - temp.size.width) / 2
temp.origin.y = (superBounds.size.height - temp.size.height) / 2
return temp
}
public func setSizeFromView(_ view:UIView, withXRatio xRatio:CGFloat, andYRatio yRatio:CGFloat) {
var newFrame = self.frame
newFrame.size = UIView.sizeFromSize(view.frame.size, withXRatio: xRatio, andYRatio: yRatio)
self.frame = newFrame
}
public func setWidthFromView(_ view:UIView, withXRatio xRatio:CGFloat) {
var newFrame = self.frame
newFrame.size.width = view.frame.size.width * xRatio
self.frame = newFrame
}
public func setHeightFromView(_ view:UIView, withYRatio yRatio:CGFloat) {
var newFrame = self.frame
newFrame.size.height = view.frame.size.height * yRatio
self.frame = newFrame
}
public class func sizeFromSize(_ superSize:CGSize, withXRatio xRatio:CGFloat, andYRatio yRatio:CGFloat) -> CGSize {
return CGSize(width: superSize.width * xRatio, height: superSize.height * yRatio)
}
//// considering deprecating
func applyInsetsToFrame(xInset:CGFloat, andYInset yInset:CGFloat, shouldApplyToAllSides:Bool) {
let multiplier:CGFloat = shouldApplyToAllSides ? 2 : 1
self.changeFrameOrigin(dX: xInset, dY: yInset)
self.changeFrameSize(dWidth: -xInset * multiplier, dHeight: -yInset * multiplier)
}
//// the two following functions advance their property by the values inputed
public func changeFrameOrigin(dX:CGFloat, dY:CGFloat) {
var temp = self.frame
temp.origin.x = temp.origin.x + dX
temp.origin.y = temp.origin.y + dY
self.frame = temp
}
public func changeFrameSize(dWidth:CGFloat, dHeight:CGFloat) {
var temp = self.frame
temp.size.width = temp.size.width + dWidth
temp.size.height = temp.size.height + dHeight
self.frame = temp
}
//// editing a views frame directly like view.frame.size.height = 20 is not allowed and is tedious so the following methods a for convenience making the previous example view.frameHeight = 20
public var frameOrigin:CGPoint {
get {
return self.frame.origin
}
set {
var temp = self.frame
temp.origin = newValue
self.frame = temp
}
}
public var frameSize:CGSize {
get {
return self.frame.size
}
set {
var temp = self.frame
temp.size = newValue
self.frame = temp
}
}
public var frameHeight:CGFloat {
get {
return self.frame.size.height
}
set {
var temp = self.frame
temp.size.height = newValue
self.frame = temp
}
}
public var frameWidth:CGFloat {
get {
return self.frame.size.width
}
set {
var temp = self.frame
temp.size.width = newValue
self.frame = temp
}
}
public var frameOriginY:CGFloat {
get {
return self.frame.origin.y
}
set {
var temp = self.frame
temp.origin.y = newValue
self.frame = temp
}
}
public var frameOriginX:CGFloat {
get {
return self.frame.origin.x
}
set {
var temp = self.frame
temp.origin.x = newValue
self.frame = temp
}
}
//// Top and Left just set position and are equivalent to the short hand above
public var top:CGFloat {
get {return frameOriginY}
set {frameOriginY = newValue}
}
public var left:CGFloat {
get {return frameOriginX}
set {frameOriginX = newValue}
}
//// Bottom and Right adjusts the size to make the bottom or right equal the value so a view with view.top = 10 and view.bottom = 30 will have a y orgigin of 10 and a height of 20
public var bottom:CGFloat {
get {return frameOriginY + frameHeight}
set {frameHeight = newValue - frameOriginY}
}
public var right:CGFloat {
get {return frameOriginX + frameWidth}
set {frameWidth = newValue - frameOriginX}
}
public func placeViewInView(view:UIView, andPosition position:NGARelativeViewPosition) {
self.placeViewInView(view: view, position: position, andPadding: 0)
}
public func placeViewAccordingToView(view:UIView, andPosition position:NGARelativeViewPosition) {
self.placeViewAccordingToView(view: view, position: position, andPadding: 0)
}
public func placeViewInView(view:UIView, position:NGARelativeViewPosition, andPadding padding:CGFloat) {
let otherViewFrame = view.bounds
placeViewRelativeToRect(rect: otherViewFrame, position: position, andPadding: padding)
}
public func placeViewAccordingToView(view:UIView, position:NGARelativeViewPosition, andPadding padding:CGFloat) {
let otherViewFrame = view.frame
placeViewRelativeToRect(rect: otherViewFrame, position: position, andPadding: padding)
}
public func placeViewRelativeToRect(rect:CGRect, position:NGARelativeViewPosition, andPadding padding:CGFloat) {
self.frame = self.rectForViewRelativeToRect(rect: rect, position: position, andPadding: padding)
}
func rectForViewInView(view:UIView, position:NGARelativeViewPosition, andPadding padding:CGFloat) -> CGRect{
let otherViewFrame = view.bounds
return self.rectForViewRelativeToRect(rect: otherViewFrame, position: position, andPadding: padding)
}
public func rectForViewAccordingToView(view:UIView, position:NGARelativeViewPosition, andPadding padding:CGFloat) -> CGRect{
let otherViewFrame = view.frame
return self.rectForViewRelativeToRect(rect: otherViewFrame, position: position, andPadding: padding)
}
public func rectForViewRelativeToRect(rect:CGRect, position:NGARelativeViewPosition, andPadding padding:CGFloat) -> CGRect {
var thisViewFrame = self.frame
switch position {
case NGARelativeViewPosition.aboveTop:
thisViewFrame.origin.y = rect.origin.y - thisViewFrame.size.height - padding
case NGARelativeViewPosition.belowBottom:
thisViewFrame.origin.y = rect.origin.y + rect.size.height + padding
case NGARelativeViewPosition.toTheLeft:
thisViewFrame.origin.x = rect.origin.x - thisViewFrame.size.width - padding
case NGARelativeViewPosition.toTheRight:
thisViewFrame.origin.x = rect.origin.x + rect.size.width + padding
case NGARelativeViewPosition.alignTop:
thisViewFrame.origin.y = rect.origin.y + padding
case NGARelativeViewPosition.alignBottom:
thisViewFrame.origin.y = rect.origin.y + rect.size.height - thisViewFrame.size.height + padding
case NGARelativeViewPosition.alignRight:
thisViewFrame.origin.x = rect.origin.x + rect.size.width - thisViewFrame.size.width + padding
case NGARelativeViewPosition.alignLeft:
thisViewFrame.origin.x = rect.origin.x + padding
case NGARelativeViewPosition.alignCenter, NGARelativeViewPosition.alignCenterY, NGARelativeViewPosition.alignCenterX:
let center = (NGARelativeViewPosition.alignCenter == position)
let centerX = (NGARelativeViewPosition.alignCenterX == position)
let centerY = (NGARelativeViewPosition.alignCenterY == position)
if center || centerX {
thisViewFrame.origin.x = rect.origin.x + (rect.size.width - thisViewFrame.size.width) / 2 + padding
}
if center || centerY {
thisViewFrame.origin.y = rect.origin.y + (rect.size.height - thisViewFrame.size.height) / 2 + padding
}
}
return thisViewFrame
}
public var longSide:CGFloat {
get {
var temp:CGFloat = 0
if self.frame.size.height > self.frame.size.width {
temp = self.frame.size.height
}
else {
temp = self.frame.size.width
}
return temp
}
set {
if frame.size.height > frame.size.width {
frame.size.height = newValue
}
else if frame.size.width > frame.size.height {
frame.size.width = newValue
}
else {
frame.size.height = newValue
frame.size.width = newValue
}
}
}
public var shortSide:CGFloat {
get {
var temp:CGFloat = 0
if self.frame.size.height > self.frame.size.width {
temp = self.frame.size.width
}
else {
temp = self.frame.size.height
}
return temp
}
set {
if frame.size.height > frame.size.width {
frame.size.width = newValue
}
else if frame.size.width > frame.size.height {
frame.size.height = newValue
}
else {
frame.size.height = newValue
frame.size.width = newValue
}
}
}
public func shiftRight(_ to:CGFloat) {left = to - frameWidth}
public func shiftBottom(_ to:CGFloat) {top = to - frameHeight}
public var aspectRatioWToH:CGFloat {get {return frame.size.aspectRatioWToH}}
public var aspectRatioHtoW:CGFloat {get {return frame.size.aspectRatioHtoW}}
public func fitViewInCiricleWithRadius(_ radius:CGFloat, xInset:CGFloat = 0, yInset:CGFloat = 0) {
frame.fitRectInCiricleWithRadius(radius, xInset: xInset, yInset: yInset)
}
public var topView:UIView? {
get{
var v = superview
while v != nil {
let s = v?.superview
if s.isNil || s is UIWindow {return v}
v = s
}
return v
}
}
public func isDirectDescendantOf(_ view:UIView) -> Bool {
return view.subviews.contains(self)
}
public func lowestSubviewBottom() -> CGFloat {
return subviews.collect(initialValue: 0, iteratorBlock: { (t, v) -> CGFloat in
let b = v.alpha == 0 ? t : v.bottom
return b > t ? b : t
})
}
//MARK: Layer
public var borderColor:UIColor? {get{if let temp = layer.borderColor{return UIColor(cgColor: temp)};return nil}set{layer.borderColor = newValue?.cgColor}}
public var borderWidth:CGFloat {get{return layer.borderWidth}set{layer.borderWidth = newValue}}
public func addBorderWith(width:CGFloat?, color:UIColor?) {
let w = width ?? 0
borderWidth = w
borderColor = color
}
public func removeBorder() {
addBorderWith(width: 0, color: UIColor.clear)
}
public var cornerRadius:CGFloat {get{return layer.cornerRadius}set{layer.cornerRadius = newValue}}
public var shadowRadius:CGFloat {get{return layer.shadowRadius}set{layer.shadowRadius = newValue}}
public var shadowOffset:CGSize {get{return layer.shadowOffset}set{layer.shadowOffset = newValue}}
public var shadowOpacity:CGFloat {get{return CGFloat(layer.shadowOpacity)}set{layer.shadowOpacity = Float(newValue)}}
public var shadowColor:UIColor? {get{if let temp = layer.shadowColor{return UIColor(cgColor: temp)};return nil}set{layer.shadowColor = newValue?.cgColor}}
public var shadowPath:UIBezierPath? {get{if let temp = layer.shadowPath{return UIBezierPath(cgPath: temp)};return nil}set{layer.shadowPath = newValue?.cgPath}}
public var roundedRectPath:UIBezierPath {get{return UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius)}}
public func addShadowWith(radius:CGFloat?, offset:CGSize?, opacity:CGFloat?, color:UIColor?, path:UIBezierPath?) {
let r = radius ?? 0 ; let off = offset ?? CGSize.zero ; let a = opacity ?? 0
shadowPath = path
shadowRadius = r
shadowOpacity = a
if self is UILabel {
layer.shadowColor = color?.cgColor ?? UIColor.clear.cgColor
layer.shadowOffset = off
} else {
shadowColor = color
shadowOffset = off
}
}
public func removeShadow() {
addShadowWith(radius: 0, offset: nil, opacity: 0, color: UIColor.clear, path: nil)
}
//MARK: Conversions
public func toImage(_ size:CGSize? = nil) -> UIImage? {
var temp:UIImage?
let s = size ?? bounds.size
autoreleasepool {
UIGraphicsBeginImageContext(s)
if let c = UIGraphicsGetCurrentContext() {
layer.draw(in: c)
temp = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
}
return temp
}
public func toPDF() -> Data? {
let data = NSMutableData()
//// default 8 1/2 x 11 is 612 x 792 and setting to CGRectZero will set it to default
UIGraphicsBeginPDFContextToData(data, bounds, nil)
UIGraphicsBeginPDFPage()
if let c = UIGraphicsGetCurrentContext() { layer.render(in: c) }
UIGraphicsEndPDFContext()
return data.copy() as? Data
}
public func toSquare(_ useSmallSide:Bool = true) {
let s = useSmallSide ? shortSide : longSide
frameSize = CGSize(width: s, height: s)
}
public func toCircle(_ useSmallSide:Bool = true) {
toSquare(useSmallSide)
cornerRadius = frameWidth / 2
}
public func setSizeWithWidth(_ w:CGFloat, aspectRatioHToW:CGFloat) {
frameSize = CGSize.makeFromWidth(w, aspectRatioHToW: aspectRatioHToW)
}
public func setSizeWithHeight(_ h:CGFloat, aspectRatioWToH:CGFloat) {
frameSize = CGSize.makeFromWidth(h, aspectRatioHToW: aspectRatioWToH)
}
}
//public protocol SetSubviewable {
// func setFramesForSubviews(propogate:Bool)
// func setFramesForSubviewsOnMainThread(propogate:Bool)
//}
//
//extension UIView:SetSubviewable {
// public func setFramesForSubviews(propogate:Bool = false) {
// print("Set frames for subviews in extension")
// if propogate {for subview in subviews {subview.setFramesForSubviews(propogate: propogate)}}
// }
// public func setFramesForSubviewsOnMainThread(propogate:Bool = false) {
// let voidBlock:VoidBlock = {
// self.setFramesForSubviews(propogate: propogate)
// }
// NGAExecute.performOnMainQueue(voidBlock)
// }
//
// public func frameBlock(propogate:Bool) -> VoidBlock {return {self.setFramesForSubviews(propogate: propogate)}}
//}
//// Going to encapsulate the enum in the UIView extension to something along the lines of Position so instead of NGARelativeViewPosition it would be UIView.Position
public enum NGARelativeViewPosition {
case aboveTop, belowBottom, toTheLeft, toTheRight, alignTop, alignBottom, alignRight, alignLeft, alignCenter, alignCenterX, alignCenterY
}
| mit | f8d84321f5401e8e9c92cfc0c16955eb | 36.27991 | 195 | 0.622464 | 4.514762 | false | false | false | false |
Smartvoxx/ios | Step07/Start/SmartvoxxOnWrist Extension/SlotController.swift | 2 | 6512 | //
// SlotControllerInterfaceController.swift
// Smartvoxx
//
// Created by Sebastien Arbogast on 26/09/2015.
// Copyright © 2015 Epseelon. All rights reserved.
//
import WatchKit
import Foundation
import WatchConnectivity
class SlotController: WKInterfaceController, WCSessionDelegate {
@IBOutlet var titleLabel: WKInterfaceLabel!
@IBOutlet var trackLabel: WKInterfaceLabel!
@IBOutlet var roomLabel: WKInterfaceLabel!
@IBOutlet var dateLabel: WKInterfaceLabel!
@IBOutlet var timesLabel: WKInterfaceLabel!
@IBOutlet var summaryLabel: WKInterfaceLabel!
@IBOutlet var speakersTable: WKInterfaceTable!
@IBOutlet var summarySeparator: WKInterfaceSeparator!
@IBOutlet var speakersSeparator: WKInterfaceSeparator!
@IBOutlet var favoriteImage: WKInterfaceImage!
var slot:Slot?
var speakers:[Speaker]?
var session:WCSession?
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
if let talkSlot = context as? TalkSlot {
self.slot = talkSlot
} else if let breakSlot = context as? BreakSlot {
self.slot = breakSlot
} else {
self.slot = nil
}
self.updateMenu()
startSession()
}
private func startSession() {
if WCSession.isSupported() {
session = WCSession.defaultSession()
session?.delegate = self
session?.activateSession()
}
}
override func willActivate() {
super.willActivate()
if let talkSlot = self.slot as? TalkSlot {
self.slot = talkSlot
self.titleLabel.setText(talkSlot.title!)
self.trackLabel.setHidden(false)
if let trackName = talkSlot.track?.name {
self.trackLabel.setText(trackName)
}
if let trackColor = talkSlot.track?.color {
self.trackLabel.setTextColor(UIColor(rgba: trackColor))
}
self.roomLabel.setText(talkSlot.roomName!)
self.dateLabel.setText(talkSlot.day!.capitalizedString)
self.timesLabel.setText("\(talkSlot.fromTime!) - \(talkSlot.toTime!)")
self.summaryLabel.setHidden(false)
self.summaryLabel.setText(talkSlot.summary!)
self.speakersTable.setHidden(false)
self.speakersTable.setNumberOfRows(talkSlot.speakers!.count, withRowType: "speaker")
self.speakers = talkSlot.speakers!.allObjects as? [Speaker]
for (index,speaker) in self.speakers!.enumerate() {
if let row = self.speakersTable.rowControllerAtIndex(index) as? SpeakerRowController {
row.nameLabel.setText(speaker.name!)
}
}
self.summarySeparator.setHidden(false)
self.speakersSeparator.setHidden(talkSlot.speakers!.count > 0)
} else if let breakSlot = self.slot as? BreakSlot {
self.slot = breakSlot
self.titleLabel.setText(breakSlot.nameEN!)
self.trackLabel.setHidden(true)
self.roomLabel.setText(breakSlot.roomName!)
self.dateLabel.setText(breakSlot.day!.capitalizedString)
self.timesLabel.setText("\(breakSlot.fromTime!) - \(breakSlot.toTime!)")
self.summaryLabel.setHidden(true)
self.speakersTable.setHidden(true)
self.summarySeparator.setHidden(true)
self.speakersSeparator.setHidden(true)
} else {
self.slot = nil
}
}
func updateMenu() {
self.clearAllMenuItems()
if let talkSlot = self.slot as? TalkSlot {
self.favoriteImage.setHidden(false)
if let favorite = talkSlot.favorite?.boolValue where favorite {
self.addMenuItemWithImageNamed("FavoriteOffMenu", title: NSLocalizedString("Remove from Favorites", comment: ""), action: "favoriteMenuSelected")
self.favoriteImage.setImageNamed("FavoriteOn")
} else {
self.addMenuItemWithImageNamed("FavoriteOnMenu", title: NSLocalizedString("Add to Favorites", comment: ""), action: "favoriteMenuSelected")
self.favoriteImage.setImageNamed("FavoriteOff")
}
self.addMenuItemWithItemIcon(WKMenuItemIcon.Decline, title: NSLocalizedString("Cancel", comment: ""), action: "cancelMenuSelected")
} else {
self.favoriteImage.setHidden(true)
}
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
override func contextForSegueWithIdentifier(segueIdentifier: String, inTable table: WKInterfaceTable, rowIndex: Int) -> AnyObject? {
if let speakers = self.speakers {
return speakers[rowIndex]
} else {
return nil
}
}
@IBAction func favoriteMenuSelected() {
if let talkSlot = self.slot as? TalkSlot {
DataController.sharedInstance.swapFavoriteStatusForTalkSlot(talkSlot, callback: { (talkSlot:TalkSlot) -> Void in
self.slot = talkSlot
self.updateMenu()
self.scheduleNotification()
})
}
}
@IBAction func cancelMenuSelected() {
}
private func scheduleNotification() {
if let talkSlot = self.slot as? TalkSlot {
let talkSlotMessage = [
"title":talkSlot.title!,
"room":talkSlot.roomName!,
"talkId":talkSlot.talkId!,
"track":talkSlot.track!.name!,
"favorite":talkSlot.favorite!,
"fromTimeMillis":talkSlot.fromTimeMillis!,
"fromTime":talkSlot.fromTime!,
"toTime":talkSlot.toTime!
]
if WCSession.isSupported() {
if let session = self.session where session.reachable {
session.sendMessage(["talkSlot" : talkSlotMessage as NSDictionary], replyHandler: { (reply:[String : AnyObject]) -> Void in
}, errorHandler: { (error:NSError) -> Void in
print(error)
})
} else {
session?.transferUserInfo(["talkSlot" : talkSlotMessage as NSDictionary])
}
}
}
}
}
| gpl-2.0 | e98595dff7a4c4a22d88d71117f24cf9 | 38.222892 | 161 | 0.601137 | 4.99693 | false | false | false | false |
googlemaps/ios-on-demand-rides-deliveries-samples | swift/consumer_swiftui/App/Views/ControlPanelView.swift | 1 | 4065 | /*
* Copyright 2022 Google LLC. All rights reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import SwiftUI
/// A control panel view containing buttons that control trip status.
struct ControlPanelView: View {
/// The name for add intermediate destination icon.
private static let addIntermediateDestinationIcon = "plus"
/// The `ModelData` containing the primary state of the application.
@EnvironmentObject var modelData: ModelData
private let tapButtonAction: () -> Void
private let tapAddIntermediateDestinationAction: () -> Void
init(
tapButtonAction: @escaping () -> Void, tapAddIntermediateDestinationAction: @escaping () -> Void
) {
self.tapButtonAction = tapButtonAction
self.tapAddIntermediateDestinationAction = tapAddIntermediateDestinationAction
}
var body: some View {
VStack(alignment: .center) {
HStack(alignment: .center) {
VStack(alignment: .leading) {
Group { Text(modelData.staticLabel) + Text(modelData.tripInfoLabel).bold() }
.frame(width: Style.frameWidth, height: Style.mediumFrameHeight, alignment: .topLeading)
if modelData.timeToWaypoint != 0 && modelData.remainingDistanceInMeters != 0 {
Text(
String.init(
format: "%.1f min · %.1f mi", modelData.timeToWaypoint,
modelData.remainingDistanceInMeters)
)
.foregroundColor(Style.textColor)
.font(Font.body.bold())
.font(.system(size: Style.mediumFontSize))
.frame(width: Style.frameWidth, height: Style.mediumFrameHeight, alignment: .topLeading)
}
if modelData.tripID != "" {
Text(Strings.tripIDText + modelData.tripID)
.font(.system(size: Style.smallFontSize)).foregroundColor(Style.textColor)
.frame(
width: Style.frameWidth, height: Style.mediumFrameHeight, alignment: .topLeading)
}
if modelData.vehicleID != "" {
Text(Strings.vehicleIDText + modelData.vehicleID)
.font(.system(size: Style.smallFontSize))
.foregroundColor(Style.textColor)
.frame(
width: Style.frameWidth, height: Style.mediumFrameHeight, alignment: .topLeading)
}
}
if modelData.customerState == .selectingDropoff {
Button(action: tapAddIntermediateDestinationAction) {
Image(systemName: ControlPanelView.addIntermediateDestinationIcon).foregroundColor(
Style.buttonBackgroundColor)
}.frame(height: Style.mediumFrameHeight, alignment: .topLeading)
}
}
Button(action: tapButtonAction) {
Text(modelData.controlButtonLabel)
}
.buttonStyle(StyledButton())
.frame(
alignment: .init(horizontal: .center, vertical: .center))
}
}
}
/// The customized button style which includes the tap animation.
private struct StyledButton: ButtonStyle {
@EnvironmentObject var modelData: ModelData
func makeBody(configuration: Configuration) -> some View {
configuration
.label
.foregroundColor(.white)
.frame(width: Style.frameWidth, height: Style.mediumFrameHeight)
.background(
configuration.isPressed
? Color.gray : modelData.buttonColor
)
.cornerRadius(.infinity)
}
}
struct ControlPanelView_Previews: PreviewProvider {
static var previews: some View {
ControlPanelView(tapButtonAction: {}, tapAddIntermediateDestinationAction: {})
}
}
| apache-2.0 | df8f2c43f563b782a701a5292642430e | 38.076923 | 100 | 0.672244 | 4.66055 | false | false | false | false |
hlian/syncopate | Syncopate/HomeViewController.swift | 1 | 7517 | import ObjectiveC
import UIKit
class HomeToSongAnimationController : NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
let duration : NSTimeInterval = 0.5
let damping : CGFloat = 0.5
let songView : UIView
var maximizing = true
var originalFrame : CGRect?
var originalSuperview : UIView?
init(songView: UIView) {
self.songView = songView
}
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
func animateTransition(ctx: UIViewControllerContextTransitioning) {
let songVC = songViewControllerOf(ctx) as! SongViewController
let homeVC = homeViewControllerOf(ctx)
let containerView = ctx.containerView()!
if (maximizing) {
containerView.insertSubview(songVC.view, aboveSubview: homeVC.view)
songVC.view.frame = ctx.containerView()!.convertRect(originalFrame!, fromView: originalSuperview!)
springlyAnimate({
songVC.view.frame = containerView.bounds
songVC.topInset = homeVC.topLayoutGuide.length
}, completionBlock: { (finished) -> Void in
assert(!ctx.transitionWasCancelled())
if (!finished) {
self.animateTransition(ctx)
return
}
ctx.completeTransition(true)
})
} else {
let originalSuperview = self.originalSuperview!
containerView.insertSubview(homeVC.view, belowSubview: songVC.view)
springlyAnimate({
songVC.view.frame = ctx.containerView()!.convertRect(self.originalFrame!, fromView: originalSuperview)
songVC.topInset = 0
}, completionBlock: { (finished) -> Void in
assert(!ctx.transitionWasCancelled())
if (!finished) {
self.animateTransition(ctx)
return
}
ctx.completeTransition(true)
songVC.view.frame = self.originalFrame!
originalSuperview.addSubview(songVC.view)
})
}
}
func springlyAnimate(animationBlock: () -> Void, completionBlock: (Bool) -> Void) {
UIView.animateWithDuration(
duration,
delay: 0,
usingSpringWithDamping: damping,
initialSpringVelocity: 0,
options: [UIViewAnimationOptions.CurveLinear, UIViewAnimationOptions.BeginFromCurrentState],
animations: animationBlock,
completion: completionBlock)
}
func animationControllerForPresentedController(
presented: UIViewController,
presentingController presenting: UIViewController,
sourceController source: UIViewController)-> UIViewControllerAnimatedTransitioning? {
// The song view controller is weird! Its view is already in the hierarchy; it as a VC
// is already a child of the home VC.
willPresent()
return self
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
willDismiss()
return self
}
func willPresent() {
maximizing = true
originalFrame = songView.frame
originalSuperview = songView.superview!
}
func willDismiss() {
maximizing = false
}
private func songViewControllerOf(ctx: UIViewControllerContextTransitioning) -> UIViewController {
let key = (maximizing ? UITransitionContextToViewControllerKey : UITransitionContextFromViewControllerKey)
let vc = ctx.viewControllerForKey(key)!
return vc
}
private func homeViewControllerOf(ctx: UIViewControllerContextTransitioning) -> UIViewController {
let key = (!maximizing ? UITransitionContextToViewControllerKey : UITransitionContextFromViewControllerKey)
let vc = ctx.viewControllerForKey(key)!
return vc
}
}
class HomeViewController: UIViewController, UINavigationControllerDelegate {
let songHeight = 100
let fauns = NSMutableOrderedSet()
var animationControllerKey: Void?
var preparedSongs = false
dynamic var modalFaun : SongViewController?
func addFaun(songFaun: SongViewController) {
assert(!fauns.containsObject(songFaun), "addFaun: already contains")
fauns.addObject(songFaun)
view.addSubview(songFaun.view)
songFaun.didMoveToParentViewController(self)
songFaun.modalPresentationStyle = UIModalPresentationStyle.Custom
let ac = HomeToSongAnimationController(songView: songFaun.view)
songFaun.transitioningDelegate = ac
objc_setAssociatedObject(songFaun, &animationControllerKey, ac, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
override func loadView() {
UILabel.appearance().font = UIFont(name: "Times", size: 16)
let scrollView = UIScrollView()
scrollView.alwaysBounceVertical = true
scrollView.backgroundColor = UIColor(white: 0.95, alpha: 1)
title = "Syncopate"
view = scrollView
navigationController!.delegate = self
prepareModal()
}
override func viewWillAppear(animated: Bool) {
if !preparedSongs {
prepareSongs()
preparedSongs = true
}
}
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if (operation == UINavigationControllerOperation.Push) {
let ac = toVC.transitioningDelegate as! HomeToSongAnimationController
ac.willPresent()
return ac
} else {
let ac = fromVC.transitioningDelegate as! HomeToSongAnimationController
ac.willDismiss()
return ac
}
}
func prepareSongs() {
let onTap = {
[unowned self] (controller: SongViewController, presenting: Bool) -> Void in
if (self.modalFaun == nil && presenting) {
self.modalFaun = controller
} else if (self.modalFaun! == controller && !presenting) {
self.modalFaun = nil
}
}
let song1 = SongViewController(
song: Song(url: NSURL(string: "https://a.tumblr.com/tumblr_mndqjdrkkq1s1b8mno1_r1.mp3")!),
onTap: onTap
)
let song2 = SongViewController(
song: Song(url: NSURL(string: "https://a.tumblr.com/tumblr_naqik7VOSl1te74f8o1.mp3")!),
onTap: onTap
)
song1.view.frame = CGRectMake(10, CGFloat(10), view.bounds.size.width - 20, CGFloat(songHeight))
song2.view.frame = CGRectMake(10, CGFloat(songHeight + 20), view.bounds.size.width - 20, CGFloat(songHeight))
addFaun(song1)
addFaun(song2)
}
// MARK: transitioning
func prepareModal() {
rac_valuesForKeyPath("modalFaun", observer: self).subscribeNext { [weak self] x in
if let faun = x as? SongViewController {
self!.navigationController!.pushViewController(faun, animated: true)
} else {
self!.navigationController!.popToViewController(self!, animated: true)
}
}
}
}
| gpl-2.0 | 3ddafde7ee97d3c2b49db0a57be0e4ff | 36.585 | 281 | 0.645337 | 5.365453 | false | false | false | false |
maxkonovalov/MKRingProgressView | Example/ActivityRingsExample/Icon.swift | 1 | 1565 | //
// Icon.swift
// MKRingProgressViewExample
//
// Created by Max Konovalov on 25/05/2018.
// Copyright © 2018 Max Konovalov. All rights reserved.
//
import UIKit
func generateAppIcon(scale: CGFloat = 1.0) -> UIImage {
let size = CGSize(width: 512, height: 512)
let rect = CGRect(origin: .zero, size: size)
let icon = UIView(frame: rect)
icon.backgroundColor = #colorLiteral(red: 0.1176470588, green: 0.1176470588, blue: 0.1254901961, alpha: 1)
let group = RingProgressGroupView(frame: icon.bounds.insetBy(dx: 33, dy: 33))
group.ringWidth = 50
group.ringSpacing = 10
group.ring1StartColor = #colorLiteral(red: 0.8823529412, green: 0, blue: 0.07843137255, alpha: 1)
group.ring1EndColor = #colorLiteral(red: 1, green: 0.1960784314, blue: 0.5294117647, alpha: 1)
group.ring2StartColor = #colorLiteral(red: 0.2156862745, green: 0.862745098, blue: 0, alpha: 1)
group.ring2EndColor = #colorLiteral(red: 0.7176470588, green: 1, blue: 0, alpha: 1)
group.ring3StartColor = #colorLiteral(red: 0, green: 0.7294117647, blue: 0.8823529412, alpha: 1)
group.ring3EndColor = #colorLiteral(red: 0, green: 0.9803921569, blue: 0.8156862745, alpha: 1)
group.ring1.progress = 1.0
group.ring2.progress = 1.0
group.ring3.progress = 1.0
icon.addSubview(group)
UIGraphicsBeginImageContextWithOptions(size, true, scale)
icon.drawHierarchy(in: rect, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
| mit | 0e4624c4181f95518f23588b81753238 | 40.157895 | 110 | 0.702046 | 3.407407 | false | false | false | false |
fs/ios-base-swift | Swift-Base/Tools/Storage/StorageFetchRequest.swift | 1 | 1040 | //
// StorageFetchRequest.swift
// Tools
//
// Created by Almaz Ibragimov on 24.02.2018.
// Copyright © 2018 Flatstack. All rights reserved.
//
import Foundation
public struct StorageFetchRequest<Object: StorageObject> {
// MARK: - Instance Properties
public var sortDescriptors: [NSSortDescriptor]
public var predicate: NSPredicate?
// MARK: -
public var returnsObjectsAsFaults: Bool = true
public var includesSubentities: Bool = true
public var includesPendingChanges: Bool = true
public var includesPropertyValues: Bool = true
public var shouldRefreshRefetchedObjects: Bool = false
public var fetchOffset: Int = 0
public var fetchLimit: Int = 0
public var fetchBatchSize: Int = 0
public var relationshipsForPrefetching: [String]?
// MARK: - Initializers
public init(sortDescriptors: [NSSortDescriptor], predicate: NSPredicate?) {
self.sortDescriptors = sortDescriptors
self.predicate = predicate
}
}
| mit | 69fce1691210fe52bc484cc7f177b393 | 24.975 | 79 | 0.684312 | 5.043689 | false | false | false | false |
SpiciedCrab/MGRxKitchen | MGRxKitchen/Classes/RxMogoIntergration/RxMogo+ScrollView+Spore.swift | 1 | 7352 | //
// RxMogo+ScrollView+Spore.swift
// MGRxKitchen
//
// Created by Harly on 2017/11/9.
//
import Foundation
import RxCocoa
import RxSwift
import NSObject_Rx
// MARK: - Common Definitions
public typealias ErrorActionType = ((RxMGError) -> Void)
/// 你想要的错误状态
///
/// - toast: 只是个toast
/// - onView: 弹到view上
/// - custom: 当然你还可以自定义自己玩
public enum MixErrorStatus {
case toast
case onView
case custom(action : ErrorActionType)
}
// MARK: - 基础款搅拌器
/// 超级搅拌器基础款
public class MGRxListWithApiMixer {
/// 下一个节点
var nextLink: MGRxListWithApiMixer?
required public init() { }
/// 把View和ViewModel之间的绑定做一下啦
///
/// - Parameters:
/// - view: 一只普通的view
/// - viewModel: viewModel
public func mixView(view: UIView,
togetherWith viewModel: HaveRequestRx) {
guard let next = nextLink else { return }
next.mixView(view: view, togetherWith: viewModel)
}
/// 创建一个搅拌器组合
///
/// - Parameters:
/// - errorShownType: 错误弹出方式
/// - mixerReformer: 自定义搅拌器组合啦
/// - Returns: 你要的超级搅拌器组合款
public class func createMixChain(errorType errorShownType: MixErrorStatus = .onView,
mixerReformer: (([MGRxListWithApiMixer.Type]) -> [MGRxListWithApiMixer.Type])? = nil)
-> MGRxListWithApiMixer {
var chainTypes: [MGRxListWithApiMixer.Type]!
if let reformer = mixerReformer {
chainTypes = reformer(defaultMixerInChain(errorType: errorShownType))
} else {
chainTypes = defaultMixerInChain(errorType: errorShownType)
}
var mixer = MGRxListWithApiMixer()
for mixerType in chainTypes {
let existingLink = mixer
switch errorShownType {
case .custom(let action):
if mixerType == CustErrorRequestMixer.self
{
mixer = CustErrorRequestMixer(action: action)
}
else
{
mixer = mixerType.init()
}
default:
mixer = mixerType.init()
}
mixer.nextLink = existingLink
}
return mixer
}
/// 定制好的搅拌器组合
///
/// - Parameter errorShownType: error形态
/// - Returns: 搅拌器组合集合
/// 常规款 : Error过滤 -> TableView过滤 -> 普通View过滤
class func defaultMixerInChain(errorType errorShownType: MixErrorStatus = .onView) -> [MGRxListWithApiMixer.Type] {
switch errorShownType {
case .toast:
return [DefaultRequestMixer.self,
PageRequestMixer.self,
ToastErrorRequestMixer.self]
case .onView:
return [DefaultRequestMixer.self,
PageRequestMixer.self,
ShowErrorRequestMixer.self]
case .custom:
return [DefaultRequestMixer.self,
PageRequestMixer.self,
CustErrorRequestMixer.self]
}
}
}
// MARK: - 附加的搅拌器款
/// 常规View搅拌器
/// 处理了View的loading
public class DefaultRequestMixer: MGRxListWithApiMixer {
override public func mixView(view: UIView,
togetherWith viewModel: HaveRequestRx) {
viewModel.loadingActivity
.asObservable()
.bind(to: view.rx.isLoading)
.disposed(by: view.rx.disposeBag)
}
}
/// ErrorView搅拌器
/// 弹一个error窗在view上
public class ShowErrorRequestMixer: MGRxListWithApiMixer {
override public func mixView(view: UIView,
togetherWith viewModel: HaveRequestRx) {
guard let filterErrorViewModel = viewModel as? NeedHandleRequestError else {
super.mixView(view: view, togetherWith: viewModel)
return
}
filterErrorViewModel.errorProvider
.distinctRubbish()
.delay(0.2, scheduler: MainScheduler.instance)
.map { ( $0, MGRxKichenConfiguration.shared.emptyImage) }
.bind(to: view.rx.emptyErrorViewOnMe)
.disposed(by: view.rx.disposeBag)
super.mixView(view: view, togetherWith: viewModel)
}
}
/// Error Toast搅拌器
/// 弹一个toast窗在view上
public class ToastErrorRequestMixer: MGRxListWithApiMixer {
override public func mixView(view: UIView,
togetherWith viewModel: HaveRequestRx) {
guard let filterErrorViewModel = viewModel as? NeedHandleRequestError else {
super.mixView(view: view, togetherWith: viewModel)
return
}
filterErrorViewModel.errorProvider
.distinctRubbish()
.bind(to: view.rx.toastErrorOnMe)
.disposed(by: view.rx.disposeBag)
super.mixView(view: view, togetherWith: viewModel)
}
}
/// 自定义Error搅拌器
/// 送你个Error
public class CustErrorRequestMixer: MGRxListWithApiMixer {
var errorAction: ErrorActionType!
convenience public init(action : @escaping ErrorActionType) {
self.init()
errorAction = action
}
required override public init() {
super.init()
}
override public func mixView(view: UIView,
togetherWith viewModel: HaveRequestRx) {
guard let filterErrorViewModel = viewModel as? NeedHandleRequestError else {
super.mixView(view: view, togetherWith: viewModel)
return
}
filterErrorViewModel.errorProvider
.distinctRubbish()
.subscribe(onNext: {[weak self] (error) in
guard let strongSelf = self else { return }
strongSelf.errorAction(error)
})
.disposed(by: view.rx.disposeBag)
super.mixView(view: view, togetherWith: viewModel)
}
}
/// Page 搅拌器
/// 处理了一系列上下啦绑定
public class PageRequestMixer: MGRxListWithApiMixer {
override public func mixView(view: UIView,
togetherWith viewModel: HaveRequestRx) {
guard let pageViewModel = viewModel as? PageBase ,
let listView = view as? UIScrollView else {
super.mixView(view: view, togetherWith: viewModel)
return
}
listView.rx
.pullDownRefreshing
.bind(to: pageViewModel.firstPage)
.disposed(by:listView.rx.disposeBag)
listView.rx
.pullUpRefreshing
.bind(to: pageViewModel.nextPage)
.disposed(by: listView.rx.disposeBag)
pageViewModel.finalPageReached
.bind(to: listView.rx.makTouchLastPage)
.disposed(by: view.rx.disposeBag)
viewModel.loadingActivity
.asObservable()
.bind(to: listView.rx.makMeStopRefreshing)
.disposed(by: view.rx.disposeBag)
}
}
| mit | e1a74bd323f897c5ca1e6f017081e09f | 28.485232 | 122 | 0.581568 | 4.300308 | false | false | false | false |
think-dev/MadridBUS | MadridBUS/Source/UI/Commons/LineSchemeGraphicNode.swift | 1 | 5987 | import UIKit
protocol LineSchemeGraphicNodeDelegate: class {
func didTap(node: LineSchemeGraphicNode)
}
class LineSchemeGraphicNode: UIView {
var node: LineSchemeNodeModel
weak var delegate: LineSchemeGraphicNodeDelegate?
var isSelected: Bool = false
internal var dotShape = CAShapeLayer()
internal var lineShape = CAShapeLayer()
internal var dotRadius: CGFloat
internal var nameLabel = UILabel()
internal var thickness: CGFloat = 0.0
internal var theme: LineSchemeTheme
internal var labelWrapper = UIView()
init(with node: LineSchemeNodeModel, dotRadius: CGFloat, theme: LineSchemeTheme) {
self.node = node
self.dotRadius = dotRadius
self.theme = theme
super.init(frame: .zero)
backgroundColor = .clear
clipsToBounds = true
layer.masksToBounds = true
nameLabel.translatesAutoresizingMaskIntoConstraints = false
nameLabel.numberOfLines = 0
nameLabel.lineBreakMode = .byWordWrapping
nameLabel.backgroundColor = .clear
labelWrapper.addSubview(nameLabel)
NSLayoutConstraint(item: nameLabel, attribute: .leading, relatedBy: .equal, toItem: labelWrapper, attribute: .leading, multiplier: 1.0, constant: 4.0).isActive = true
NSLayoutConstraint(item: nameLabel, attribute: .trailing, relatedBy: .equal, toItem: labelWrapper, attribute: .trailing, multiplier: 1.0, constant: -4.0).isActive = true
NSLayoutConstraint(item: nameLabel, attribute: .top, relatedBy: .equal, toItem: labelWrapper, attribute: .top, multiplier: 1.0, constant: 4.0).isActive = true
NSLayoutConstraint(item: nameLabel, attribute: .bottom, relatedBy: .equal, toItem: labelWrapper, attribute: .bottom, multiplier: 1.0, constant: -4.0).isActive = true
labelWrapper.translatesAutoresizingMaskIntoConstraints = false
labelWrapper.clipsToBounds = true
labelWrapper.layer.masksToBounds = true
addSubview(labelWrapper)
switch theme.orientation {
case .vertical:
nameLabel.textAlignment = .left
NSLayoutConstraint(item: labelWrapper, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: dotRadius * 3).isActive = true
NSLayoutConstraint(item: labelWrapper, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: labelWrapper, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: labelWrapper, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
case .horizontal:
nameLabel.textAlignment = .center
NSLayoutConstraint(item: labelWrapper, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: labelWrapper, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: labelWrapper, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: dotRadius * 2).isActive = true
NSLayoutConstraint(item: labelWrapper, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
}
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapSelf))
tapGesture.numberOfTapsRequired = 1
addGestureRecognizer(tapGesture)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func didTapSelf() {
if isSelected {
labelWrapper.backgroundColor = theme.normalBackgroundColor
nameLabel.textColor = theme.normalTitleColor
nameLabel.font = theme.normalTitleFont
dotShape.strokeColor = theme.normalForegroundColor.cgColor
isSelected = false
delegate?.didTap(node: self)
} else {
labelWrapper.backgroundColor = theme.highlightedBackgroundColor
nameLabel.textColor = theme.highlightedTitleColor
nameLabel.font = theme.highlightedTitleFont
dotShape.strokeColor = theme.highlightedForegroundColor.cgColor
isSelected = true
delegate?.didTap(node: self)
}
}
func reset() {
labelWrapper.backgroundColor = theme.normalBackgroundColor
nameLabel.textColor = theme.normalTitleColor
nameLabel.font = theme.normalTitleFont
dotShape.strokeColor = theme.normalForegroundColor.cgColor
isSelected = false
}
override func layoutSubviews() {
super.layoutSubviews()
labelWrapper.layer.cornerRadius = 4.0
}
override func draw(_ rect: CGRect) {
super.draw(rect)
thickness = dotRadius * 0.6
var dotCenter = CGPoint()
switch theme.orientation {
case .vertical: dotCenter = CGPoint(x: dotRadius * 2, y: rect.midY)
case .horizontal: dotCenter = CGPoint(x: rect.midX, y: dotRadius + thickness)
}
let circlePath = UIBezierPath(arcCenter: dotCenter, radius: dotRadius, startAngle: 0, endAngle: CGFloat(2.0) * CGFloat(M_PI), clockwise: true)
dotShape = CAShapeLayer()
dotShape.path = circlePath.cgPath
dotShape.fillColor = UIColor.white.cgColor
dotShape.strokeColor = theme.normalForegroundColor.cgColor
dotShape.lineWidth = thickness
layer.addSublayer(dotShape)
}
}
| mit | 66d462357d0ab7a99827efc99e7ebcb2 | 44.356061 | 183 | 0.664774 | 4.956126 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.