-
-
diff --git a/kplayer/exswift/ExSwift.swift b/kplayer/exswift/ExSwift.swift
deleted file mode 100644
index 82c5dc0..0000000
--- a/kplayer/exswift/ExSwift.swift
+++ /dev/null
@@ -1,282 +0,0 @@
-//
-// ExSwift.swift
-// ExSwift
-//
-// Created by pNre on 07/06/14.
-// Copyright (c) 2014 pNre. All rights reserved.
-//
-
-import Foundation
-
-infix operator =~ {}
-infix operator |~ {}
-infix operator .. {}
-infix operator <=> {}
-
-public typealias Ex = ExSwift
-
-public class ExSwift {
-
- /**
- Creates a wrapper that, executes function only after being called n times.
-
- :param: n No. of times the wrapper has to be called before function is invoked
- :param: function Function to wrap
- :returns: Wrapper function
- */
- public class func after (n: Int, function: (P...) -> T) -> ((P...) -> T?) {
-
- typealias Function = [P] -> T
-
- var times = n
-
- return {
- (params: P...) -> T? in
-
- // Workaround for the now illegal (T...) type.
- let adaptedFunction = unsafeBitCast(function, Function.self)
-
- if times-- <= 0 {
- return adaptedFunction(params)
- }
-
- return nil
- }
-
- }
-
- /**
- Creates a wrapper that, executes function only after being called n times
-
- :param: n No. of times the wrapper has to be called before function is invoked
- :param: function Function to wrap
- :returns: Wrapper function
- */
- public class func after (n: Int, function: Void -> T) -> (Void -> T?) {
- func callAfter (args: Any?...) -> T {
- return function()
- }
-
- let f = ExSwift.after(n, function: callAfter)
-
- return { f([nil]) }
- }
-
- /**
- Creates a wrapper function that invokes function once.
- Repeated calls to the wrapper function will return the value of the first call.
-
- :param: function Function to wrap
- :returns: Wrapper function
- */
- public class func once (function: (P...) -> T) -> ((P...) -> T) {
-
- typealias Function = [P] -> T
-
- var returnValue: T? = nil
-
- return { (params: P...) -> T in
-
- if returnValue != nil {
- return returnValue!
- }
-
- let adaptedFunction = unsafeBitCast(function, Function.self)
- returnValue = adaptedFunction(params)
-
- return returnValue!
-
- }
-
- }
-
- /**
- Creates a wrapper function that invokes function once.
- Repeated calls to the wrapper function will return the value of the first call.
-
- :param: function Function to wrap
- :returns: Wrapper function
- */
- public class func once (function: Void -> T) -> (Void -> T) {
- let f = ExSwift.once {
- (params: Any?...) -> T in
- return function()
- }
-
- return { f([nil]) }
- }
-
- /**
- Creates a wrapper that, when called, invokes function with any additional
- partial arguments prepended to those provided to the new function.
-
- :param: function Function to wrap
- :param: parameters Arguments to prepend
- :returns: Wrapper function
- */
- public class func partial (function: (P...) -> T, _ parameters: P...) -> ((P...) -> T) {
- typealias Function = [P] -> T
-
- return { (params: P...) -> T in
- let adaptedFunction = unsafeBitCast(function, Function.self)
- return adaptedFunction(parameters + params)
- }
- }
-
- /**
- Creates a wrapper (without any parameter) that, when called, invokes function
- automatically passing parameters as arguments.
-
- :param: function Function to wrap
- :param: parameters Arguments to pass to function
- :returns: Wrapper function
- */
- public class func bind
(function: (P...) -> T, _ parameters: P...) -> (Void -> T) {
- typealias Function = [P] -> T
-
- return { Void -> T in
- let adaptedFunction = unsafeBitCast(function, Function.self)
- return adaptedFunction(parameters)
- }
- }
-
- /**
- Creates a wrapper for function that caches the result of function's invocations.
-
- :param: function Function with one parameter to cache
- :returns: Wrapper function
- */
- public class func cached (function: P -> R) -> (P -> R) {
- var cache = [P:R]()
-
- return { (param: P) -> R in
- let key = param
-
- if let cachedValue = cache[key] {
- return cachedValue
- } else {
- let value = function(param)
- cache[key] = value
- return value
- }
- }
- }
-
- /**
- Creates a wrapper for function that caches the result of function's invocations.
-
- :param: function Function to cache
- :param: hash Parameters based hashing function that computes the key used to store each result in the cache
- :returns: Wrapper function
- */
- public class func cached (function: (P...) -> R, hash: ((P...) -> P)) -> ((P...) -> R) {
- typealias Function = [P] -> R
- typealias Hash = [P] -> P
-
- var cache = [P:R]()
-
- return { (params: P...) -> R in
- let adaptedFunction = unsafeBitCast(function, Function.self)
- let adaptedHash = unsafeBitCast(hash, Hash.self)
-
- let key = adaptedHash(params)
-
- if let cachedValue = cache[key] {
- return cachedValue
- } else {
- let value = adaptedFunction(params)
- cache[key] = value
- return value
- }
- }
- }
-
- /**
- Creates a wrapper for function that caches the result of function's invocations.
-
- :param: function Function to cache
- :returns: Wrapper function
- */
- public class func cached (function: (P...) -> R) -> ((P...) -> R) {
- return cached(function, hash: { (params: P...) -> P in return params[0] })
- }
-
- /**
- Utility method to return an NSRegularExpression object given a pattern.
-
- :param: pattern Regex pattern
- :param: ignoreCase If true the NSRegularExpression is created with the NSRegularExpressionOptions.CaseInsensitive flag
- :returns: NSRegularExpression object
- */
- internal class func regex (pattern: String, ignoreCase: Bool = false) -> NSRegularExpression? {
-
- var options = NSRegularExpressionOptions.DotMatchesLineSeparators.rawValue
-
- if ignoreCase {
- options = NSRegularExpressionOptions.CaseInsensitive.rawValue | options
- }
-
- var error: NSError? = nil
- let regex = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: options), error: &error)
-
- return (error == nil) ? regex : nil
-
- }
-
-}
-
-func <=> (lhs: T, rhs: T) -> Int {
- if lhs < rhs {
- return -1
- } else if lhs > rhs {
- return 1
- } else {
- return 0
- }
-}
-
-/**
-* Internal methods
-*/
-extension ExSwift {
-
- /**
- * Converts, if possible, and flattens an object from its Objective-C
- * representation to the Swift one.
- * @param object Object to convert
- * @returns Flattenend array of converted values
- */
- internal class func bridgeObjCObject (object: S) -> [T] {
- var result = [T]()
- let reflection = reflect(object)
-
- // object has an Objective-C type
- if let obj = object as? T {
- // object has type T
- result.append(obj)
- } else if reflection.disposition == .ObjCObject {
-
- var bridgedValue: T!?
-
- // If it is an NSArray, flattening will produce the expected result
- if let array = object as? NSArray {
- result += array.flatten()
- } else if let bridged = reflection.value as? T {
- result.append(bridged)
- }
- } else if reflection.disposition == .IndexContainer {
- // object is a native Swift array
-
- // recursively convert each item
- (0.. Float {
- return fabsf(self)
- }
-
- /**
- Squared root.
-
- :returns: sqrtf(self)
- */
- func sqrt () -> Float {
- return sqrtf(self)
- }
-
- /**
- Rounds self to the largest integer <= self.
-
- :returns: floorf(self)
- */
- func floor () -> Float {
- return floorf(self)
- }
-
- /**
- Rounds self to the smallest integer >= self.
-
- :returns: ceilf(self)
- */
- func ceil () -> Float {
- return ceilf(self)
- }
-
- /**
- Rounds self to the nearest integer.
-
- :returns: roundf(self)
- */
- func round () -> Float {
- return roundf(self)
- }
-
- /**
- Clamps self to a specified range.
-
- :param: min Lower bound
- :param: max Upper bound
- :returns: Clamped value
- */
- func clamp (min: Float, _ max: Float) -> Float {
- return Swift.max(min, Swift.min(max, self))
- }
-
- /**
- Random float between min and max (inclusive).
-
- :param: min
- :param: max
- :returns: Random number
- */
- static func random(min: Float = 0, max: Float) -> Float {
- let diff = max - min;
- let rand = Float(arc4random() % (UInt32(RAND_MAX) + 1))
- return ((rand / Float(RAND_MAX)) * diff) + min;
- }
-
-}
-
diff --git a/kplayer/exswift/Int.swift b/kplayer/exswift/Int.swift
deleted file mode 100644
index 26d3ddd..0000000
--- a/kplayer/exswift/Int.swift
+++ /dev/null
@@ -1,256 +0,0 @@
-//
-// Int.swift
-// ExSwift
-//
-// Created by pNre on 03/06/14.
-// Copyright (c) 2014 pNre. All rights reserved.
-//
-
-import Foundation
-
-public extension Int {
-
- /**
- Calls function self times.
-
- :param: function Function to call
- */
- func times (function: Void -> T) {
- (0.. Void) {
- (0.. (function: (Int) -> T) {
- (0.. Bool {
- return (self % 2) == 0
- }
-
- /**
- Checks if a number is odd.
-
- :returns: true if self is odd
- */
- func isOdd () -> Bool {
- return !isEven()
- }
-
- /**
- Iterates function, passing in integer values from self up to and including limit.
-
- :param: limit Last value to pass
- :param: function Function to invoke
- */
- func upTo (limit: Int, function: (Int) -> ()) {
- if limit < self {
- return
- }
-
- (self...limit).each(function)
- }
-
- /**
- Iterates function, passing in integer values from self down to and including limit.
-
- :param: limit Last value to pass
- :param: function Function to invoke
- */
- func downTo (limit: Int, function: (Int) -> ()) {
- if limit > self {
- return
- }
-
- Array(limit...self).reverse().each(function)
- }
-
- /**
- Clamps self to a specified range.
-
- :param: range Clamping range
- :returns: Clamped value
- */
- func clamp (range: Range) -> Int {
- return clamp(range.startIndex, range.endIndex - 1)
- }
-
- /**
- Clamps self to a specified range.
-
- :param: min Lower bound
- :param: max Upper bound
- :returns: Clamped value
- */
- func clamp (min: Int, _ max: Int) -> Int {
- return Swift.max(min, Swift.min(max, self))
- }
-
- /**
- Checks if self is included a specified range.
-
- :param: range Range
- :param: strict If true, "<" is used for comparison
- :returns: true if in range
- */
- func isIn (range: Range, strict: Bool = false) -> Bool {
- if strict {
- return range.startIndex < self && self < range.endIndex - 1
- }
-
- return range.startIndex <= self && self <= range.endIndex - 1
- }
-
- /**
- Checks if self is included in a closed interval.
-
- :param: interval Interval to check
- :returns: true if in the interval
- */
- func isIn (interval: ClosedInterval) -> Bool {
- return interval.contains(self)
- }
-
- /**
- Checks if self is included in an half open interval.
-
- :param: interval Interval to check
- :returns: true if in the interval
- */
- func isIn (interval: HalfOpenInterval) -> Bool {
- return interval.contains(self)
- }
-
- /**
- Returns an [Int] containing the digits in self.
-
- :return: Array of digits
- */
- func digits () -> [Int] {
- var result = [Int]()
-
- for char in String(self) {
- let string = String(char)
- if let toInt = string.toInt() {
- result.append(toInt)
- }
- }
-
- return result
- }
-
- /**
- Absolute value.
-
- :returns: abs(self)
- */
- func abs () -> Int {
- return Swift.abs(self)
- }
-
- /**
- Greatest common divisor of self and n.
-
- :param: n
- :returns: GCD
- */
- func gcd (n: Int) -> Int {
- return n == 0 ? self : n.gcd(self % n)
- }
-
- /**
- Least common multiple of self and n
-
- :param: n
- :returns: LCM
- */
- func lcm (n: Int) -> Int {
- return (self * n).abs() / gcd(n)
- }
-
- /**
- Computes the factorial of self
-
- :returns: Factorial
- */
- func factorial () -> Int {
- return self == 0 ? 1 : self * (self - 1).factorial()
- }
-
- /**
- Random integer between min and max (inclusive).
-
- :param: min Minimum value to return
- :param: max Maximum value to return
- :returns: Random integer
- */
- static func random(min: Int = 0, max: Int) -> Int {
- return Int(arc4random_uniform(UInt32((max - min) + 1))) + min
- }
-
-}
-
-/**
- NSTimeInterval conversion extensions
-*/
-public extension Int {
-
- var years: NSTimeInterval {
- return 365 * self.days
- }
-
- var year: NSTimeInterval {
- return self.years
- }
-
- var days: NSTimeInterval {
- return 24 * self.hours
- }
-
- var day: NSTimeInterval {
- return self.days
- }
-
- var hours: NSTimeInterval {
- return 60 * self.minutes
- }
-
- var hour: NSTimeInterval {
- return self.hours
- }
-
- var minutes: NSTimeInterval {
- return 60 * self.seconds
- }
-
- var minute: NSTimeInterval {
- return self.minutes
- }
-
- var seconds: NSTimeInterval {
- return NSTimeInterval(self)
- }
-
- var second: NSTimeInterval {
- return self.seconds
- }
-
-}
diff --git a/kplayer/exswift/NSArray.swift b/kplayer/exswift/NSArray.swift
deleted file mode 100644
index d2c3a9e..0000000
--- a/kplayer/exswift/NSArray.swift
+++ /dev/null
@@ -1,64 +0,0 @@
-//
-// NSArray.swift
-// ExSwift
-//
-// Created by pNre on 10/06/14.
-// Copyright (c) 2014 pNre. All rights reserved.
-//
-
-import Foundation
-
-public extension NSArray {
-
- /**
- Converts an NSArray object to an OutType[] array containing the items in the NSArray of type OutType.
-
- :returns: Array of Swift objects
- */
- func cast () -> [OutType] {
- var result = [OutType]()
-
- for item : AnyObject in self {
- result += Ex.bridgeObjCObject(item) as [OutType]
- }
-
- return result
- }
-
- /**
- Flattens a multidimensional NSArray to an OutType[] array
- containing the items in the NSArray that can be bridged from their ObjC type to OutType.
-
- :returns: Flattened array
- */
- func flatten () -> [OutType] {
- var result = [OutType]()
- let reflection = reflect(self)
-
- for i in 0.. [AnyObject] {
- var result = [AnyObject]()
-
- for item in self {
- if let array = item as? NSArray {
- result += array.flattenAny()
- } else {
- result.append(item)
- }
- }
-
- return result
- }
-
-}
diff --git a/kplayer/exswift/NSDate.swift b/kplayer/exswift/NSDate.swift
deleted file mode 100644
index 50d758e..0000000
--- a/kplayer/exswift/NSDate.swift
+++ /dev/null
@@ -1,318 +0,0 @@
-//
-// File.swift
-// ExSwift
-//
-// Created by Piergiuseppe Longo on 23/11/14.
-// Copyright (c) 2014 pNre. All rights reserved.
-//
-
-import Foundation
-
-public extension NSDate {
-
- // MARK: NSDate Manipulation
-
- /**
- Returns a new NSDate object representing the date calculated by adding the amount specified to self date
-
- :param: seconds number of seconds to add
- :param: minutes number of minutes to add
- :param: hours number of hours to add
- :param: days number of days to add
- :param: weeks number of weeks to add
- :param: months number of months to add
- :param: years number of years to add
- :returns: the NSDate computed
- */
- public func add(seconds: Int = 0, minutes: Int = 0, hours: Int = 0, days: Int = 0, weeks: Int = 0, months: Int = 0, years: Int = 0) -> NSDate {
- var calendar = NSCalendar.currentCalendar()
-
- let version = floor(NSFoundationVersionNumber)
-
- if version <= NSFoundationVersionNumber10_9_2 {
- var component = NSDateComponents()
- component.setValue(seconds, forComponent: .CalendarUnitSecond)
-
- var date : NSDate! = calendar.dateByAddingComponents(component, toDate: self, options: nil)!
- component = NSDateComponents()
- component.setValue(minutes, forComponent: .CalendarUnitMinute)
- date = calendar.dateByAddingComponents(component, toDate: date, options: nil)!
-
- component = NSDateComponents()
- component.setValue(hours, forComponent: .CalendarUnitHour)
- date = calendar.dateByAddingComponents(component, toDate: date, options: nil)!
-
- component = NSDateComponents()
- component.setValue(days, forComponent: .CalendarUnitDay)
- date = calendar.dateByAddingComponents(component, toDate: date, options: nil)!
-
- component = NSDateComponents()
- component.setValue(weeks, forComponent: .CalendarUnitWeekOfMonth)
- date = calendar.dateByAddingComponents(component, toDate: date, options: nil)!
-
- component = NSDateComponents()
- component.setValue(months, forComponent: .CalendarUnitMonth)
- date = calendar.dateByAddingComponents(component, toDate: date, options: nil)!
-
- component = NSDateComponents()
- component.setValue(years, forComponent: .CalendarUnitYear)
- date = calendar.dateByAddingComponents(component, toDate: date, options: nil)!
- return date
- }
-
- var date : NSDate! = calendar.dateByAddingUnit(.CalendarUnitSecond, value: seconds, toDate: self, options: nil)
- date = calendar.dateByAddingUnit(.CalendarUnitMinute, value: minutes, toDate: date, options: nil)
- date = calendar.dateByAddingUnit(.CalendarUnitDay, value: days, toDate: date, options: nil)
- date = calendar.dateByAddingUnit(.CalendarUnitHour, value: hours, toDate: date, options: nil)
- date = calendar.dateByAddingUnit(.CalendarUnitWeekOfMonth, value: weeks, toDate: date, options: nil)
- date = calendar.dateByAddingUnit(.CalendarUnitMonth, value: months, toDate: date, options: nil)
- date = calendar.dateByAddingUnit(.CalendarUnitYear, value: years, toDate: date, options: nil)
- return date
- }
-
- /**
- Returns a new NSDate object representing the date calculated by adding an amount of seconds to self date
-
- :param: seconds number of seconds to add
- :returns: the NSDate computed
- */
- public func addSeconds (seconds: Int) -> NSDate {
- return add(seconds: seconds)
- }
-
- /**
- Returns a new NSDate object representing the date calculated by adding an amount of minutes to self date
-
- :param: minutes number of minutes to add
- :returns: the NSDate computed
- */
- public func addMinutes (minutes: Int) -> NSDate {
- return add(minutes: minutes)
- }
-
- /**
- Returns a new NSDate object representing the date calculated by adding an amount of hours to self date
-
- :param: hours number of hours to add
- :returns: the NSDate computed
- */
- public func addHours(hours: Int) -> NSDate {
- return add(hours: hours)
- }
-
- /**
- Returns a new NSDate object representing the date calculated by adding an amount of days to self date
-
- :param: days number of days to add
- :returns: the NSDate computed
- */
- public func addDays(days: Int) -> NSDate {
- return add(days: days)
- }
-
- /**
- Returns a new NSDate object representing the date calculated by adding an amount of weeks to self date
-
- :param: weeks number of weeks to add
- :returns: the NSDate computed
- */
- public func addWeeks(weeks: Int) -> NSDate {
- return add(weeks: weeks)
- }
-
-
- /**
- Returns a new NSDate object representing the date calculated by adding an amount of months to self date
-
- :param: months number of months to add
- :returns: the NSDate computed
- */
-
- public func addMonths(months: Int) -> NSDate {
- return add(months: months)
- }
-
- /**
- Returns a new NSDate object representing the date calculated by adding an amount of years to self date
-
- :param: years number of year to add
- :returns: the NSDate computed
- */
- public func addYears(years: Int) -> NSDate {
- return add(years: years)
- }
-
- // MARK: Date comparison
-
- /**
- Checks if self is after input NSDate
-
- :param: date NSDate to compare
- :returns: True if self is after the input NSDate, false otherwise
- */
- public func isAfter(date: NSDate) -> Bool{
- return (self.compare(date) == NSComparisonResult.OrderedDescending)
- }
-
- /**
- Checks if self is before input NSDate
-
- :param: date NSDate to compare
- :returns: True if self is before the input NSDate, false otherwise
- */
- public func isBefore(date: NSDate) -> Bool{
- return (self.compare(date) == NSComparisonResult.OrderedAscending)
- }
-
-
- // MARK: Getter
-
- /**
- Date year
- */
- public var year : Int {
- get {
- return getComponent(.CalendarUnitYear)
- }
- }
-
- /**
- Date month
- */
- public var month : Int {
- get {
- return getComponent(.CalendarUnitMonth)
- }
- }
-
- /**
- Date weekday
- */
- public var weekday : Int {
- get {
- return getComponent(.CalendarUnitWeekday)
- }
- }
-
- /**
- Date weekMonth
- */
- public var weekMonth : Int {
- get {
- return getComponent(.CalendarUnitWeekOfMonth)
- }
- }
-
-
- /**
- Date days
- */
- public var days : Int {
- get {
- return getComponent(.CalendarUnitDay)
- }
- }
-
- /**
- Date hours
- */
- public var hours : Int {
-
- get {
- return getComponent(.CalendarUnitHour)
- }
- }
-
- /**
- Date minuts
- */
- public var minutes : Int {
- get {
- return getComponent(.CalendarUnitMinute)
- }
- }
-
- /**
- Date seconds
- */
- public var seconds : Int {
- get {
- return getComponent(.CalendarUnitSecond)
- }
- }
-
- /**
- Returns the value of the NSDate component
-
- :param: component NSCalendarUnit
- :returns: the value of the component
- */
-
- public func getComponent (component : NSCalendarUnit) -> Int {
- let calendar = NSCalendar.currentCalendar()
- let components = calendar.components(component, fromDate: self)
-
- return components.valueForComponent(component)
- }
-}
-
-extension NSDate: Strideable {
- public func distanceTo(other: NSDate) -> NSTimeInterval {
- return other - self
- }
-
- public func advancedBy(n: NSTimeInterval) -> Self {
- return self.dynamicType(timeIntervalSinceReferenceDate: self.timeIntervalSinceReferenceDate + n)
- }
-}
-// MARK: Arithmetic
-
-func +(date: NSDate, timeInterval: Int) -> NSDate {
- return date + NSTimeInterval(timeInterval)
-}
-
-func -(date: NSDate, timeInterval: Int) -> NSDate {
- return date - NSTimeInterval(timeInterval)
-}
-
-func +=(inout date: NSDate, timeInterval: Int) {
- date = date + timeInterval
-}
-
-func -=(inout date: NSDate, timeInterval: Int) {
- date = date - timeInterval
-}
-
-func +(date: NSDate, timeInterval: Double) -> NSDate {
- return date.dateByAddingTimeInterval(NSTimeInterval(timeInterval))
-}
-
-func -(date: NSDate, timeInterval: Double) -> NSDate {
- return date.dateByAddingTimeInterval(NSTimeInterval(-timeInterval))
-}
-
-func +=(inout date: NSDate, timeInterval: Double) {
- date = date + timeInterval
-}
-
-func -=(inout date: NSDate, timeInterval: Double) {
- date = date - timeInterval
-}
-
-func -(date: NSDate, otherDate: NSDate) -> NSTimeInterval {
- return date.timeIntervalSinceDate(otherDate)
-}
-
-extension NSDate: Equatable {
-}
-
-public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
- return lhs.compare(rhs) == NSComparisonResult.OrderedSame
-}
-
-extension NSDate: Comparable {
-}
-
-public func <(lhs: NSDate, rhs: NSDate) -> Bool {
- return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
-}
diff --git a/kplayer/exswift/Range.swift b/kplayer/exswift/Range.swift
deleted file mode 100644
index 051368d..0000000
--- a/kplayer/exswift/Range.swift
+++ /dev/null
@@ -1,80 +0,0 @@
-//
-// Range.swift
-// ExSwift
-//
-// Created by pNre on 04/06/14.
-// Copyright (c) 2014 pNre. All rights reserved.
-//
-
-import Foundation
-
-internal extension Range {
-
- /**
- For each element in the range invokes function.
-
- :param: function Function to call
- */
- func times (function: () -> ()) {
- each { (current: T) -> () in
- function()
- }
- }
-
- /**
- For each element in the range invokes function passing the element as argument.
-
- :param: function Function to invoke
- */
- func times (function: (T) -> ()) {
- each (function)
- }
-
- /**
- For each element in the range invokes function passing the element as argument.
-
- :param: function Function to invoke
- */
- func each (function: (T) -> ()) {
- for i in self {
- function(i)
- }
- }
-
- /**
- Returns each element of the range in an array
-
- :returns: Each element of the range in an array
- */
- func toArray () -> [T] {
- var result: [T] = []
- for i in self {
- result.append(i)
- }
- return result
- }
-
- /**
- Range of Int with random bounds between from and to (inclusive).
-
- :param: from Lower bound
- :param: to Upper bound
- :returns: Random range
- */
- static func random (from: Int, to: Int) -> Range {
- let lowerBound = Int.random(min: from, max: to)
- let upperBound = Int.random(min: lowerBound, max: to)
-
- return lowerBound...upperBound
- }
-
-}
-
-/**
-* Operator == to compare 2 ranges first, second by start & end indexes. If first.startIndex is equal to
-* second.startIndex and first.endIndex is equal to second.endIndex the ranges are considered equal.
-*/
-public func == (first: Range, second: Range) -> Bool {
- return first.startIndex == second.startIndex &&
- first.endIndex == second.endIndex
-}
diff --git a/kplayer/exswift/Sequence.swift b/kplayer/exswift/Sequence.swift
deleted file mode 100644
index 6aa19b3..0000000
--- a/kplayer/exswift/Sequence.swift
+++ /dev/null
@@ -1,244 +0,0 @@
-//
-// Sequence.swift
-// ExSwift
-//
-// Created by Colin Eberhardt on 24/06/2014.
-// Copyright (c) 2014 pNre. All rights reserved.
-//
-
-import Foundation
-
-internal extension SequenceOf {
-
- /**
- First element of the sequence.
-
- :returns: First element of the sequence if present
- */
- var first: T? {
- var generator = self.generate()
- return generator.next()
- }
-
- /**
- Checks if call returns true for any element of self.
-
- :param: call Function to call for each element
- :returns: True if call returns true for any element of self
- */
- func any (call: (T) -> Bool) -> Bool {
- var generator = self.generate()
- while let nextItem = generator.next() {
- if call(nextItem) {
- return true
- }
- }
- return false
- }
-
- /**
- Object at the specified index if exists.
-
- :param: index
- :returns: Object at index in sequence, nil if index is out of bounds
- */
- func get (index: Int) -> T? {
- var generator = self.generate()
- for _ in 0..<(index - 1) {
- generator.next()
- }
- return generator.next()
- }
-
- /**
- Objects in the specified range.
-
- :param: range
- :returns: Subsequence in range
- */
- func get (range: Range) -> SequenceOf {
- return self.skip(range.startIndex).take(range.endIndex - range.startIndex)
- }
-
- /**
- Index of the first occurrence of item, if found.
-
- :param: item The item to search for
- :returns: Index of the matched item or nil
- */
- func indexOf (item: U) -> Int? {
- var index = 0
- for current in self {
- if let equatable = current as? U {
- if equatable == item {
- return index
- }
- }
- index++
- }
- return nil
- }
-
- /**
- Subsequence from n to the end of the sequence.
-
- :param: n Number of elements to skip
- :returns: Sequence from n to the end
- */
- func skip (n: Int) -> SequenceOf {
- var generator = self.generate()
- for _ in 0.. Bool) -> SequenceOf {
- return SequenceOf(lazy(self).filter(include))
- }
-
- /**
- Opposite of filter.
-
- :param: exclude Function invoked to test elements for exlcusion from the sequence
- :returns: Filtered sequence
- */
- func reject (exclude: (T -> Bool)) -> SequenceOf {
- return self.filter {
- return !exclude($0)
- }
- }
-
- /**
- Skips the elements in the sequence up until the condition returns false.
-
- :param: condition A function which returns a boolean if an element satisfies a given condition or not
- :returns: Elements of the sequence starting with the element which does not meet the condition
- */
- func skipWhile(condition:(T) -> Bool) -> SequenceOf {
- var generator = self.generate()
- var checkingGenerator = self.generate()
-
- var keepSkipping = true
-
- while keepSkipping {
- var nextItem = checkingGenerator.next()
- keepSkipping = nextItem != nil ? condition(nextItem!) : false
-
- if keepSkipping {
- generator.next()
- }
- }
- return SequenceOf(generator)
- }
-
- /**
- Checks if self contains the item object.
-
- :param: item The item to search for
- :returns: true if self contains item
- */
- func contains (item: T) -> Bool {
- var generator = self.generate()
- while let nextItem = generator.next() {
- if nextItem as! T == item {
- return true
- }
- }
- return false
- }
-
- /**
- Returns the first n elements from self.
-
- :param: n Number of elements to take
- :returns: First n elements
- */
- func take (n: Int) -> SequenceOf {
- return SequenceOf(TakeSequence(self, n))
- }
-
- /**
- Returns the elements of the sequence up until an element does not meet the condition.
-
- :param: condition A function which returns a boolean if an element satisfies a given condition or not.
- :returns: Elements of the sequence up until an element does not meet the condition
- */
- func takeWhile (condition:(T?) -> Bool) -> SequenceOf {
- return SequenceOf(TakeWhileSequence(self, condition))
- }
-
- /**
- Returns each element of the sequence in an array
-
- :returns: Each element of the sequence in an array
- */
- func toArray () -> [T] {
- var result: [T] = []
- for item in self {
- result.append(item)
- }
- return result
- }
-}
-
-/**
- A sequence adapter that implements the 'take' functionality
-*/
-public struct TakeSequence: SequenceType {
- private let sequence: S
- private let n: Int
-
- public init(_ sequence: S, _ n: Int) {
- self.sequence = sequence
- self.n = n
- }
-
- public func generate() -> GeneratorOf {
- var count = 0
- var generator = self.sequence.generate()
- return GeneratorOf {
- count++
- if count > self.n {
- return nil
- } else {
- return generator.next()
- }
- }
- }
-}
-
-/**
- a sequence adapter that implements the 'takeWhile' functionality
-*/
-public struct TakeWhileSequence: SequenceType {
- private let sequence: S
- private let condition: (S.Generator.Element?) -> Bool
-
- public init(_ sequence:S, _ condition:(S.Generator.Element?) -> Bool) {
- self.sequence = sequence
- self.condition = condition
- }
-
- public func generate() -> GeneratorOf {
- var generator = self.sequence.generate()
- var endConditionMet = false
- return GeneratorOf {
- let next: S.Generator.Element? = generator.next()
- if !endConditionMet {
- endConditionMet = !self.condition(next)
- }
- if endConditionMet {
- return nil
- } else {
- return next
- }
- }
- }
-}
diff --git a/kplayer/exswift/String.swift b/kplayer/exswift/String.swift
deleted file mode 100644
index 95ff794..0000000
--- a/kplayer/exswift/String.swift
+++ /dev/null
@@ -1,403 +0,0 @@
-//
-// String.swift
-// ExSwift
-//
-// Created by pNre on 03/06/14.
-// Copyright (c) 2014 pNre. All rights reserved.
-//
-
-import Foundation
-
-public extension String {
-
- /**
- String length
- */
- var length: Int { return count(self) }
-
- /**
- self.capitalizedString shorthand
- */
- var capitalized: String { return capitalizedString }
-
- /**
- Returns the substring in the given range
-
- :param: range
- :returns: Substring in range
- */
- subscript (range: Range) -> String? {
- if range.startIndex < 0 || range.endIndex > self.length {
- return nil
- }
-
- let range = Range(start: advance(startIndex, range.startIndex), end: advance(startIndex, range.endIndex))
-
- return self[range]
- }
-
- /**
- Equivalent to at. Takes a list of indexes and returns an Array
- containing the elements at the given indexes in self.
-
- :param: firstIndex
- :param: secondIndex
- :param: restOfIndexes
- :returns: Charaters at the specified indexes (converted to String)
- */
- subscript (firstIndex: Int, secondIndex: Int, restOfIndexes: Int...) -> [String] {
- return at([firstIndex, secondIndex] + restOfIndexes)
- }
-
- /**
- Gets the character at the specified index as String.
- If index is negative it is assumed to be relative to the end of the String.
-
- :param: index Position of the character to get
- :returns: Character as String or nil if the index is out of bounds
- */
- subscript (index: Int) -> String? {
- if let char = Array(self).get(index) {
- return String(char)
- }
-
- return nil
- }
-
- /**
- Takes a list of indexes and returns an Array containing the elements at the given indexes in self.
-
- :param: indexes Positions of the elements to get
- :returns: Array of characters (as String)
- */
- func at (indexes: Int...) -> [String] {
- return indexes.map { self[$0]! }
- }
-
- /**
- Takes a list of indexes and returns an Array containing the elements at the given indexes in self.
-
- :param: indexes Positions of the elements to get
- :returns: Array of characters (as String)
- */
- func at (indexes: [Int]) -> [String] {
- return indexes.map { self[$0]! }
- }
-
- /**
- Returns an array of strings, each of which is a substring of self formed by splitting it on separator.
-
- :param: separator Character used to split the string
- :returns: Array of substrings
- */
- func explode (separator: Character) -> [String] {
- return split(self, isSeparator: { (element: Character) -> Bool in
- return element == separator
- })
- }
-
- /**
- Finds any match in self for pattern.
-
- :param: pattern Pattern to match
- :param: ignoreCase true for case insensitive matching
- :returns: Matches found (as [NSTextCheckingResult])
- */
- func matches (pattern: String, ignoreCase: Bool = false) -> [NSTextCheckingResult]? {
-
- if let regex = ExSwift.regex(pattern, ignoreCase: ignoreCase) {
- // Using map to prevent a possible bug in the compiler
- return regex.matchesInString(self, options: nil, range: NSMakeRange(0, length)).map { $0 as! NSTextCheckingResult }
- }
-
- return nil
- }
-
- /**
- Check is string with this pattern included in string
-
- :param: pattern Pattern to match
- :param: ignoreCase true for case insensitive matching
- :returns: true if contains match, otherwise false
- */
- func containsMatch (pattern: String, ignoreCase: Bool = false) -> Bool? {
- if let regex = ExSwift.regex(pattern, ignoreCase: ignoreCase) {
- let range = NSMakeRange(0, count(self))
- return regex.firstMatchInString(self, options: .allZeros, range: range) != nil
- }
-
- return nil
- }
-
- /**
- Replace all pattern matches with another string
-
- :param: pattern Pattern to match
- :param: replacementString string to replace matches
- :param: ignoreCase true for case insensitive matching
- :returns: true if contains match, otherwise false
- */
- func replaceMatches (pattern: String, withString replacementString: String, ignoreCase: Bool = false) -> String? {
- if let regex = ExSwift.regex(pattern, ignoreCase: ignoreCase) {
- let range = NSMakeRange(0, count(self))
- return regex.stringByReplacingMatchesInString(self, options: .allZeros, range: range, withTemplate: replacementString)
- }
-
- return nil
- }
-
- /**
- Inserts a substring at the given index in self.
-
- :param: index Where the new string is inserted
- :param: string String to insert
- :returns: String formed from self inserting string at index
- */
- func insert (var index: Int, _ string: String) -> String {
- // Edge cases, prepend and append
- if index > length {
- return self + string
- } else if index < 0 {
- return string + self
- }
-
- return self[0.. String {
- if let range = rangeOfCharacterFromSet(set.invertedSet) {
- return self[range.startIndex.. String {
- return trimmedLeft(characterSet: set)
- }
-
- /**
- Strips the specified characters from the end of self.
-
- :returns: Stripped string
- */
- func trimmedRight (characterSet set: NSCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()) -> String {
- if let range = rangeOfCharacterFromSet(set.invertedSet, options: NSStringCompareOptions.BackwardsSearch) {
- return self[startIndex.. String {
- return trimmedRight(characterSet: set)
- }
-
- /**
- Strips whitespaces from both the beginning and the end of self.
-
- :returns: Stripped string
- */
- func trimmed () -> String {
- return trimmedLeft().trimmedRight()
- }
-
- /**
- Costructs a string using random chars from a given set.
-
- :param: length String length. If < 1, it's randomly selected in the range 0..16
- :param: charset Chars to use in the random string
- :returns: Random string
- */
- static func random (var length len: Int = 0, charset: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") -> String {
-
- if len < 1 {
- len = Int.random(max: 16)
- }
-
- var result = String()
- let max = charset.length - 1
-
- len.times {
- result += charset[Int.random(min: 0, max: max)]!
- }
-
- return result
-
- }
-
-
- /**
- Parses a string containing a double numerical value into an optional double if the string is a well formed number.
-
- :returns: A double parsed from the string or nil if it cannot be parsed.
- */
- func toDouble() -> Double? {
-
- let scanner = NSScanner(string: self)
- var double: Double = 0
-
- if scanner.scanDouble(&double) {
- return double
- }
-
- return nil
-
- }
-
- /**
- Parses a string containing a float numerical value into an optional float if the string is a well formed number.
-
- :returns: A float parsed from the string or nil if it cannot be parsed.
- */
- func toFloat() -> Float? {
-
- let scanner = NSScanner(string: self)
- var float: Float = 0
-
- if scanner.scanFloat(&float) {
- return float
- }
-
- return nil
-
- }
-
- /**
- Parses a string containing a non-negative integer value into an optional UInt if the string is a well formed number.
-
- :returns: A UInt parsed from the string or nil if it cannot be parsed.
- */
- func toUInt() -> UInt? {
- if let val = self.trimmed().toInt() {
- if val < 0 {
- return nil
- }
- return UInt(val)
- }
-
- return nil
- }
-
-
- /**
- Parses a string containing a boolean value (true or false) into an optional Bool if the string is a well formed.
-
- :returns: A Bool parsed from the string or nil if it cannot be parsed as a boolean.
- */
- func toBool() -> Bool? {
- let text = self.trimmed().lowercaseString
- if text == "true" || text == "false" || text == "yes" || text == "no" {
- return (text as NSString).boolValue
- }
-
- return nil
- }
-
- /**
- Parses a string containing a date into an optional NSDate if the string is a well formed.
- The default format is yyyy-MM-dd, but can be overriden.
-
- :returns: A NSDate parsed from the string or nil if it cannot be parsed as a date.
- */
- func toDate(format : String? = "yyyy-MM-dd") -> NSDate? {
- let text = self.trimmed().lowercaseString
- var dateFmt = NSDateFormatter()
- dateFmt.timeZone = NSTimeZone.defaultTimeZone()
- if let fmt = format {
- dateFmt.dateFormat = fmt
- }
- return dateFmt.dateFromString(text)
- }
-
- /**
- Parses a string containing a date and time into an optional NSDate if the string is a well formed.
- The default format is yyyy-MM-dd hh-mm-ss, but can be overriden.
-
- :returns: A NSDate parsed from the string or nil if it cannot be parsed as a date.
- */
- func toDateTime(format : String? = "yyyy-MM-dd hh-mm-ss") -> NSDate? {
- return toDate(format: format)
- }
-
-}
-
-/**
- Repeats the string first n times
-*/
-public func * (first: String, n: Int) -> String {
-
- var result = String()
-
- n.times {
- result += first
- }
-
- return result
-
-}
-
-// Pattern matching using a regular expression
-public func =~ (string: String, pattern: String) -> Bool {
-
- let regex = ExSwift.regex(pattern, ignoreCase: false)!
- let matches = regex.numberOfMatchesInString(string, options: nil, range: NSMakeRange(0, string.length))
-
- return matches > 0
-
-}
-
-// Pattern matching using a regular expression
-public func =~ (string: String, regex: NSRegularExpression) -> Bool {
-
- let matches = regex.numberOfMatchesInString(string, options: nil, range: NSMakeRange(0, string.length))
-
- return matches > 0
-
-}
-
-// This version also allowes to specify case sentitivity
-public func =~ (string: String, options: (pattern: String, ignoreCase: Bool)) -> Bool {
-
- if let matches = ExSwift.regex(options.pattern, ignoreCase: options.ignoreCase)?.numberOfMatchesInString(string, options: nil, range: NSMakeRange(0, string.length)) {
- return matches > 0
- }
-
- return false
-
-}
-
-// Match against all the alements in an array of String
-public func =~ (strings: [String], pattern: String) -> Bool {
-
- let regex = ExSwift.regex(pattern, ignoreCase: false)!
-
- return strings.all { $0 =~ regex }
-
-}
-
-public func =~ (strings: [String], options: (pattern: String, ignoreCase: Bool)) -> Bool {
-
- return strings.all { $0 =~ options }
-
-}
-
-// Match against any element in an array of String
-public func |~ (strings: [String], pattern: String) -> Bool {
-
- let regex = ExSwift.regex(pattern, ignoreCase: false)!
-
- return strings.any { $0 =~ regex }
-
-}
-
-public func |~ (strings: [String], options: (pattern: String, ignoreCase: Bool)) -> Bool {
-
- return strings.any { $0 =~ options }
-
-}
diff --git a/kplayer/master/MasterViewController.swift b/kplayer/master/MasterViewController.swift
index 6490769..899ebaa 100644
--- a/kplayer/master/MasterViewController.swift
+++ b/kplayer/master/MasterViewController.swift
@@ -25,7 +25,8 @@ class MasterViewController: UITableViewController {
}
func addItem(item: MediaItem) {
- let path = item.root + item.path
+ let path = item.rootSlash + item.path
+ print(path)
var folder = itemsMap[path]
if folder == nil {
@@ -34,7 +35,7 @@ class MasterViewController: UITableViewController {
items.append(folder!)
}
- item.index = count(folder!.children)
+ item.index = folder!.children.count
folder!.children.append(item)
item.parent = folder
}
@@ -58,45 +59,29 @@ class MasterViewController: UITableViewController {
// let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
// self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
- let controllers = split.viewControllers
- self.detailViewController = controllers[controllers.count - 1].topViewController as? DetailViewController
+ self.detailViewController = split.findChildController(DetailViewController.self)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
- println("Memory Warning")
+ print("Memory Warning")
// Dispose of any resources that can be recreated.
}
- override func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
- let pc = MediaPhotoController()
-
- var i = [MediaItem]()
-
- for it in items[indexPath.row].children {
- for c in it.children {
- i.append(c)
- }
- }
-
- pc.items = i
- pc.completionHandler = {
- self.dismissViewControllerAnimated(true, completion: nil);
- }
- let navController = UINavigationController(rootViewController: pc) // Creating a navigation controller with pc at the root of the navigation stack.
-
- presentViewController(navController, animated: false, completion: nil)
- }
-
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
- println("\(indexPath.row)")
+ print("\(indexPath.row)")
let selectedItem = items[indexPath.row]
+ if (selectedItem.type == ItemType.DETAILS) {
+ performSegueWithIdentifier("showDetail", sender: self)
+ return
+ }
+
if (selectedItem.type == ItemType.FOLDER) {
if (!selectedItem.children.isEmpty) {
- if selectedItem.children[0].type != ItemType.FOLDER {
+ if selectedItem.children[0].type == ItemType.VIDEO {
performSegueWithIdentifier("showDetail", sender: self)
return
}
@@ -104,14 +89,13 @@ class MasterViewController: UITableViewController {
}
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
-// Imagine it's called MyCustomTableVC
let vc = mainStoryboard.instantiateViewControllerWithIdentifier("mastertable") as! MasterViewController
if (selectedItem.type == ItemType.FOLDER) {
vc.navigationItem.title = selectedItem.name;
if !selectedItem.loaded {
- let dir = selectedItem.root + "/" + selectedItem.path
+ let dir = selectedItem.encodedDir!
let weiter: NetworkManager.Weiter = {
(g) in
@@ -124,13 +108,14 @@ class MasterViewController: UITableViewController {
var all: [MediaItem]?
for f in selectedItem.children {
+ print(f.path)
if f.type == ItemType.FOLDER && f.path != "" {
self.navigationController!.pushViewController(vc, animated: true)
return
}
if f.type == ItemType.FOLDER && f.path == "" {
all = f.children
- break
+ // break
}
}
@@ -150,43 +135,114 @@ class MasterViewController: UITableViewController {
let p = selectedItem.parent!
if p.type == ItemType.VIDEOROOT {
- NetworkManager.sharedInstance.loadDirs(dir, completionHandler: weiter)
+ // NetworkManager.sharedInstance.loadDirs(dir, completionHandler: weiter)
}
- else {
- NetworkManager.sharedInstance.loadPicDirs(dir, completionHandler: weiter)
+ else if p.type == ItemType.DETAILS {
+ // NetworkManager.sharedInstance.loadPicDirs(dir, completionHandler: weiter)
}
+ else if p.type == ItemType.FOLDER {
+ }
} else {
vc.items = selectedItem.children
navigationController!.pushViewController(vc, animated: true)
+ return
}
}
- if (selectedItem.type == ItemType.ROOT) || (selectedItem.type == ItemType.VIDEOROOT) {
- NetworkManager.sharedInstance.listDirs(selectedItem.root, completionHandler: {
- (i) in
+ if (selectedItem.type == ItemType.ROOT) || (selectedItem.type == ItemType.VIDEOROOT) || (selectedItem.type == ItemType.FOLDER) {
+ print (selectedItem.path)
+ NetworkManager.sharedInstance.listDirs(selectedItem.encodedDir!, completionHandler: {
+ (i, leaf) in
+ let newFolder = MediaItem(name: ".", path: selectedItem.path, root: selectedItem.root, type: ItemType.FOLDER)
for item in i {
+
+ if item.type != ItemType.FOLDER {
+ item.parent = newFolder
+ newFolder.children.append(item)
+ }
+
item.parent = selectedItem
+ selectedItem.children.append(item)
+ }
+
+ if newFolder.children.count > 0 {
+ newFolder.parent = selectedItem
+ selectedItem.children.append(newFolder)
+ }
+
+ if leaf {
+ selectedItem.type = ItemType.DETAILS
+
+
+ let weiter: NetworkManager.Weiter = {
+ (g) in
+
+ vc.items.removeAll()
+ vc.itemsMap.removeAll()
+
+ for f in g {
+ vc.addItem(f)
+ }
+ selectedItem.children = vc.items
+ selectedItem.loaded = true
+
+ var all: [MediaItem]?
+
+ for f in selectedItem.children {
+ print(f.path)
+ if f.type == ItemType.FOLDER && f.path == "" {
+ all = f.children
+ break
+ }
+ }
+
+ if all != nil {
+ selectedItem.children = all!
+ selectedItem.loaded = false
+
+ for f in all! {
+ f.loaded = false
+ f.parent = selectedItem
+ }
+ }
+
+ self.performSegueWithIdentifier("showDetail", sender: self)
+ return
+ }
+
+ let p = selectedItem.superRoot()
+ let dir = selectedItem.encodedDir!
+
+ if p.type == ItemType.VIDEOROOT {
+ NetworkManager.sharedInstance.loadDirs(dir, completionHandler: weiter)
+ }
+ else {
+ NetworkManager.sharedInstance.loadPicDirs(dir, completionHandler: weiter)
+ }
+
+ // self.performSegueWithIdentifier("showDetail", sender: self)
+ return
}
vc.items = i
vc.tableView.reloadData()
+ vc.navigationItem.title = selectedItem.name;
+ self.navigationController!.pushViewController(vc, animated: true)
})
- vc.navigationItem.title = selectedItem.name;
- navigationController!.pushViewController(vc, animated: true)
}
}
- override func shouldPerformSegueWithIdentifier(identifier: String!, sender: AnyObject?) -> Bool {
+ override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
return false;
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
- if let indexPath = self.tableView.indexPathForSelectedRow() {
+ if let indexPath = self.tableView.indexPathForSelectedRow {
let item = items[indexPath.row]
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = item
@@ -201,7 +257,7 @@ class MasterViewController: UITableViewController {
controller.defaultItemSize = CGSize(width: 300, height: 300)
}
- item.children.sort({
+ item.children.sortInPlace({
$0.sortName < $1.sortName
})
@@ -210,8 +266,6 @@ class MasterViewController: UITableViewController {
i.index = j++
}
-// controller.collectionView.reloadData()
-
NetworkManager.sharedInstance.loadItems(item)
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
@@ -226,11 +280,11 @@ class MasterViewController: UITableViewController {
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- return count(items)
+ return items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
+ let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
self.configureCell(cell, atIndexPath: indexPath)
@@ -249,19 +303,14 @@ class MasterViewController: UITableViewController {
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = items[indexPath.row]
- if (object.path.length == 0) {
- cell.textLabel!.text = "."
+ if (object.path.characters.count == 0) {
+ cell.textLabel!.text = "." + object.name
}
else {
cell.textLabel!.text = object.path
}
-// if !object.children.isEmpty && object.children[0].type == ItemType.VIDEO {
-// cell.accessoryType = UITableViewCellAccessoryType.DetailDisclosureButton
-// }
-// else {
cell.accessoryType = UITableViewCellAccessoryType.None
-// }
}
diff --git a/kplayer/photo/MediaPhotoController.swift b/kplayer/photo/MediaPhotoController.swift
index 02dd5ca..2f87e5c 100644
--- a/kplayer/photo/MediaPhotoController.swift
+++ b/kplayer/photo/MediaPhotoController.swift
@@ -18,6 +18,10 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView
var imageCache = NSCache()
var total = 0
+ var slide = 0
+
+ var timer: NSTimer?
+
lazy var backgroundOperationQueue: NSOperationQueue = {
var queue = NSOperationQueue()
queue.name = "Thumb queue"
@@ -42,7 +46,8 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView
imageCache.totalCostLimit = 1024 * 1024 * 50
let backButton = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: Selector("back"))
- navigationItem.leftBarButtonItems = [backButton]
+ let slideButton = UIBarButtonItem(barButtonSystemItem: .FastForward, target: self, action: Selector("slideShow"))
+ navigationItem.leftBarButtonItems = [backButton, slideButton]
let playButton = UIBarButtonItem(barButtonSystemItem: .Play, target: self, action: Selector("play"))
let shotButton = UIBarButtonItem(barButtonSystemItem: .Camera, target: self, action: Selector("shot"))
@@ -72,22 +77,21 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView
let bytesPerPixel = CGImageGetBitsPerPixel(imageRef) / 8;
let cost = CGImageGetWidth(imageRef) * CGImageGetHeight(imageRef) * bytesPerPixel;
self.total += d.length
- println("preload image loaded \(i.thumbUrlAbsolute) cost \(cost) total\(self.total)")
+ print("preload image loaded \(i.thumbUrlAbsolute) cost \(cost) total\(self.total)")
self.imageCache.setObject(img, forKey: i.thumbUrlAbsolute, cost: d.length)
}
}
}, index: j)
op1.qualityOfService = NSQualityOfService.Background
backgroundOperationQueue.addOperation(op1)
- }
- else {
- println("## Invalid URL: \(i.thumbUrlAbsolute)")
+ } else {
+ print("## Invalid URL: \(i.thumbUrlAbsolute)")
}
}
}
override func didReceiveMemoryWarning() {
- println("warning")
+ print("warning")
imageCache.removeAllObjects()
super.didReceiveMemoryWarning()
@@ -100,10 +104,10 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView
imageUrl = imageUrl.stringByReplacingOccurrencesOfString("?preview=true", withString: "")
let url = NetworkManager.sharedInstance.baseurl + "/service/linkfavpic" + imageUrl
- println(url)
+ print(url)
Alamofire.request(.GET, url).responseString {
- (_, _, string, _) in
- println("ok")
+ (_, _, string) in
+ print("ok")
}
}
@@ -111,69 +115,96 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView
completionHandler!()
}
+ func slideShow() {
+ if (++slide > 2) {
+ slide = 0
+ }
+
+ if timer == nil {
+ showItem()
+ }
+ }
+
+ func showItem() {
+ var nextItem = photoAlbumView.centerPageIndex + 1
+
+ if (nextItem >= (items).count) {
+ nextItem = 0
+ }
+
+ photoAlbumView.moveToPageAtIndex(nextItem, animated: false);
+ photoScrubberView.setSelectedPhotoIndex(nextItem, animated: true)
+
+ if (slide > 0) {
+ timer = NSTimer.scheduledTimerWithTimeInterval(Double(slide) / 2.0, target: self, selector: Selector("showItem"), userInfo: nil, repeats: false)
+ } else {
+ timer = nil
+ }
+ }
+
func play() {
let currentItem = items[photoAlbumView.centerPageIndex]
if (currentItem.type == ItemType.PICS) {
let items = currentItem
- let len = count(items.root)
+ let len = items.root.characters.count
let url = NetworkManager.sharedInstance.baseurl + "/service/listfiles" + items.root + "/" + items.path + "/" + items.name
- println(items)
- println(url)
+ print(items)
+ print(url)
- Alamofire.request(.GET, url).responseSwiftyJSON({
- (request, response, json, error) in
+ Alamofire.request(.GET, url).responseJSON {
+ (request, response, result) in
var im = [MediaItem]()
var hashes = Dictionary()
- for (a, c) in json {
- // let (a,b) = j #
- let s = c.object as! NSString
+ if let json = result.value {
- if s.hasSuffix(".jpg") {
- let l = s.length
- let name = (s as NSString).lastPathComponent
- var pathlen = l - len - count(name)
+ for s in json as! [String] {
+ if s.hasSuffix(".jpg") {
+ let l = s.length
+ let name = NSURL(fileURLWithPath: s as! String).lastPathComponent!
+ var pathlen = l - len - name.length
// if (pathlen > 1000) {
- println(pathlen)
- println(name)
- println(s)
+ print(pathlen)
+ print(name)
+ print(s)
// }
- if (pathlen < 2) {
- pathlen = 2
- }
+ if (pathlen < 2) {
+ pathlen = 2
+ }
- let path = (s as NSString).substringWithRange(NSMakeRange(len + 1, pathlen - 2))
+ let path = (s as NSString).substringWithRange(NSMakeRange(len + 1, pathlen - 2))
- let folderName = path.lastPathComponent
- let fl = count(path)
- let pfl = fl - count(folderName)
+ let folderName = NSURL(fileURLWithPath: path).lastPathComponent!
+ let fl = path.length
+ let pfl = fl - folderName.length
- println("\(folderName) \(pfl)")
- let fpath = (s as NSString).substringWithRange(NSMakeRange(0, pfl))
+ print("\(folderName) \(pfl)")
+ let fpath = (s as NSString).substringWithRange(NSMakeRange(0, pfl))
- let i = MediaItem(name: folderName, path: fpath, root: items.root, type: ItemType.PICS)
- i.thumbUrl = "\(s)?preview=true"
- if !name.hasPrefix(".") {
- im.append(i)
+ let i = MediaItem(name: folderName, path: fpath, root: items.root, type: ItemType.PICS)
+ i.thumbUrl = "\(s)?preview=true"
+ if !name.hasPrefix(".") {
+ im.append(i)
+ }
}
}
- }
- let pc = MediaPhotoController()
+ let pc = MediaPhotoController()
- pc.items = im
- pc.completionHandler = {
- self.dismissViewControllerAnimated(true, completion: nil);
- }
- let navController = UINavigationController(rootViewController: pc) // Creating a navigation controller with pc at the root of the navigation stack.
+ pc.items = im
+ pc.completionHandler = {
+ self.dismissViewControllerAnimated(true, completion: nil);
+ }
+ let navController = UINavigationController(rootViewController: pc) // Creating a navigation controller with pc at the root of the navigation stack.
- self.presentViewController(navController, animated: false, completion: nil)
- })
+ self.presentViewController(navController, animated: false, completion: nil)
+ }
+ }
return
}
@@ -215,12 +246,12 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView
self.title = "loading"
// self.photoAlbumView.loadingImage = UIImage(named: "Kirschkeks-256x256.png")
- println("\(count(items))")
+ print("\(items.count)")
}
func photoAlbumScrollView(photoAlbumScrollView: NIPhotoAlbumScrollView!, photoAtIndex: Int, photoSize: UnsafeMutablePointer,
isLoading: UnsafeMutablePointer, originalPhotoDimensions: UnsafeMutablePointer) -> UIImage! {
- let c = count(items)
+ let c = items.count
// println("Index: \(photoAtIndex) of \(c)")
let newItem = items[photoAtIndex]
let u1 = NSURL(string: newItem.imageUrlAbsolute)
@@ -243,11 +274,11 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView
if !ok {
r.cancel()
- requests.remove(r)
+ requests.removeAtIndex(requests.indexOf(r)!)
}
}
- image = imageCache.objectForKey(URL.absoluteString!) as? UIImage
+ image = imageCache.objectForKey(URL.absoluteString) as? UIImage
if let i = image {
size = NIPhotoScrollViewPhotoSizeThumbnail
@@ -295,14 +326,14 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView
return image
} else {
- println("## Invalid URL: \(newItem.imageUrlAbsolute)")
+ print("## Invalid URL: \(newItem.imageUrlAbsolute)")
return nil
}
}
func numberOfPagesInPagingScrollView(pagingScrollView: NIPagingScrollView) -> Int {
- let c = count(items)
+ let c = items.count
return c
}
@@ -322,7 +353,7 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView
}
func numberOfPhotosInScrubberView(photoScrubberView: NIPhotoScrubberView!) -> Int {
- let c = count(items)
+ let c = items.count
return c
}
@@ -336,7 +367,7 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView
return nil
}
- let c = count(items)
+ let c = items.count
let newItem = items[thumbnailIndex]
var image: UIImage?
@@ -364,9 +395,8 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView
}, index: thumbnailIndex)
op3.qualityOfService = NSQualityOfService.UserInitiated
operationQueue.addOperation(op3)
- }
- else {
- println("## Invalid URL: \(newItem.thumbUrlAbsolute)")
+ } else {
+ print("## Invalid URL: \(newItem.thumbUrlAbsolute)")
}
}
diff --git a/kplayer/util/ImageLoadOperation.swift b/kplayer/util/ImageLoadOperation.swift
index a6333b8..9062b40 100644
--- a/kplayer/util/ImageLoadOperation.swift
+++ b/kplayer/util/ImageLoadOperation.swift
@@ -8,7 +8,7 @@ import Alamofire
import Darwin
class ImageLoadOperation: NSOperation {
- public typealias Succeeder = (UIImage) -> ()
+ internal typealias Succeeder = (UIImage) -> ()
let imageURL: NSURL
let succeeder: Succeeder
@@ -39,17 +39,12 @@ class ImageLoadOperation: NSOperation {
request = Alamofire.request(.GET, imageURL)
}
- request!.validate().responseImage() {
- (request, _, image, error) in
-
- if error == nil {
- self.ready1 = true
- // if request.URLString.isEqual(self.imageURL) {
-// dispatch_async(dispatch_get_main_queue()) {
- self.succeeder(image!)
- // }
-
- // }
+ request!.validate().response { (request, response, data, error) in
+ if let e = error {
+ print(e)
+ }
+ else if let d = data {
+ self.succeeder(UIImage(data: d, scale: 1)!)
}
}
diff --git a/kplayer/util/LayoutTools.swift b/kplayer/util/LayoutTools.swift
index 6c746a8..e2718ce 100644
--- a/kplayer/util/LayoutTools.swift
+++ b/kplayer/util/LayoutTools.swift
@@ -18,7 +18,7 @@ public extension UIView {
for value in views.values {
let vv: UIView = value
addSubview(vv)
- vv.setTranslatesAutoresizingMaskIntoConstraints(false)
+ vv.translatesAutoresizingMaskIntoConstraints = false
}
while index < constraints.count {
@@ -30,11 +30,11 @@ public extension UIView {
options: constraints[index] as! NSLayoutFormatOptions,
metrics: nil,
views: views)
- addConstraints(constr as [AnyObject])
+ addConstraints(constr as! [NSLayoutConstraint])
} else {
let constr: NSArray = NSLayoutConstraint.constraintsWithVisualFormat(c as! String,
- options: NSLayoutFormatOptions(0), metrics: nil, views: views)
- addConstraints(constr as [AnyObject])
+ options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
+ addConstraints(constr as! [NSLayoutConstraint])
}
}
index++
@@ -43,9 +43,9 @@ public extension UIView {
func recursiveSearchForViewWithName(classname: String) -> UIView? {
for v in subviews {
- let sv = v as! UIView
- var result = sv.recursiveSearchForViewWithName(classname)
- let cn = toString(v.dynamicType)
+ let sv = v
+ let result = sv.recursiveSearchForViewWithName(classname)
+ let cn = String(v.dynamicType)
if cn == classname {
return v as? UIView
diff --git a/kplayer/util/NetData.swift b/kplayer/util/NetData.swift
index ead4f24..8de6cf1 100644
--- a/kplayer/util/NetData.swift
+++ b/kplayer/util/NetData.swift
@@ -42,12 +42,12 @@ class NetData
self.filename = filename
}
init(pngImage: UIImage, filename: String) {
- data = UIImagePNGRepresentation(pngImage)
+ data = UIImagePNGRepresentation(pngImage)!
self.mimeType = MimeType.ImagePng
self.filename = filename
}
init(jpegImage: UIImage, compressionQuanlity: CGFloat, filename: String) {
- data = UIImageJPEGRepresentation(jpegImage, compressionQuanlity)
+ data = UIImageJPEGRepresentation(jpegImage, compressionQuanlity)!
self.mimeType = MimeType.ImageJpeg
self.filename = filename
}
diff --git a/kplayer/util/UploadOperation.swift b/kplayer/util/UploadOperation.swift
index 83ce3f2..d72978c 100644
--- a/kplayer/util/UploadOperation.swift
+++ b/kplayer/util/UploadOperation.swift
@@ -28,8 +28,8 @@ class UploadOperation: NSOperation {
"name": path
]
- let urlRequest = urlRequestWithComponents(baseUrl, parameters)
- let request = Alamofire.upload(urlRequest)
+ let urlRequest = urlRequestWithComponents(baseUrl, parameters: parameters)
+// let request = Alamofire.upload(urlRequest)
// success: todo set url to item
diff --git a/kplayer/util/ViewControllerExtensions.swift b/kplayer/util/ViewControllerExtensions.swift
new file mode 100644
index 0000000..ba344a4
--- /dev/null
+++ b/kplayer/util/ViewControllerExtensions.swift
@@ -0,0 +1,67 @@
+//
+// Created by Marco Schmickler on 25.01.15.
+// Copyright (c) 2015 Marco Schmickler. All rights reserved.
+//
+
+import Foundation
+import UIKit
+
+public extension UIView {
+ func removeAllSubViews() {
+ for subView: UIView in subviews {
+ subView.removeFromSuperview();
+ }
+ }
+}
+
+public extension UIViewController {
+
+ func findControllerInHierachy(_: T.Type) -> T? {
+ var currentVC = self
+ while let parentVC = currentVC.parentViewController {
+ print("comparing \(parentVC) to \(T.description())")
+ if let result = parentVC as? T {
+ // (XXX)
+ return result
+ }
+ currentVC = parentVC
+ }
+ return nil
+ }
+
+ func findChildController(my: T.Type) -> T? {
+ for child in childViewControllers {
+ if let result = child as? T {
+ // (XXX)
+ return result
+ }
+ if let childControl = child as? UIViewController {
+ if let found = childControl.findChildController(my) {
+ return found;
+ }
+ }
+ }
+ return nil
+ }
+
+ func removeAllConstraints(otherView: UIView) {
+ var cons = [NSLayoutConstraint]()
+ for con:NSLayoutConstraint in self.view.constraints {
+ if (con.firstItem as? UIView == otherView || con.secondItem as? UIView == otherView) {
+ cons.append(con)
+ }
+ }
+
+ view.removeConstraints(cons)
+ otherView.removeConstraints(otherView.constraints);
+
+ otherView.translatesAutoresizingMaskIntoConstraints = true;
+ }
+
+ func embedChildViewController(vc: UIViewController, inView: UIView) {
+ vc.view.frame = inView.bounds;
+ addChildViewController(vc);
+ inView.removeAllSubViews();
+ inView.addSubview(vc.view);
+ }
+}
\ No newline at end of file
diff --git a/kplayer/util/alamoimage.swift b/kplayer/util/alamoimage.swift
index 757e246..d9110f5 100644
--- a/kplayer/util/alamoimage.swift
+++ b/kplayer/util/alamoimage.swift
@@ -7,24 +7,26 @@ import Foundation
import Alamofire
extension Alamofire.Request {
- class func imageResponseSerializer() -> Serializer {
- return { request, response, data in
- if data == nil || data!.length == 0 {
- return (nil, nil)
- }
- if let i = UIImage(data: data!) {
-// let image = i.hnk_decompressedImage()
- return (i, nil)
- }
- return (nil, nil)
- }
- }
-
- func responseImage(completionHandler: (NSURLRequest, NSHTTPURLResponse?, UIImage?, NSError?) -> Void) -> Self {
- return response(serializer: Request.imageResponseSerializer(), completionHandler: { (request, response, image, error) in
- completionHandler(request, response, image as? UIImage, error)
- })
- }
+// class func imageResponseSerializer() -> Serializer {
+// return { request, response, data in
+// if data == nil || data!.length == 0 {
+// return (nil, nil)
+// }
+//
+// if let i = UIImage(data: data!) {
+//// let image = i.hnk_decompressedImage()
+//
+// return (i, nil)
+// }
+// return (nil, nil)
+// }
+// }
+//
+// func responseImage(completionHandler: (NSURLRequest, NSHTTPURLResponse?, UIImage?, NSError?) -> Void) -> Self {
+// return response(serializer: Request.imageResponseSerializer(), completionHandler: { (request, response, image, error) in
+// completionHandler(request, response, image as? UIImage, error)
+// })
+// }
}
\ No newline at end of file
diff --git a/kplayer/util/alamojson.swift b/kplayer/util/alamojson.swift
deleted file mode 100644
index d88e440..0000000
--- a/kplayer/util/alamojson.swift
+++ /dev/null
@@ -1,48 +0,0 @@
-//
-// AlamofireSwiftyJSON.swift
-// AlamofireSwiftyJSON
-//
-// Created by Pinglin Tang on 14-9-22.
-// Copyright (c) 2014 SwiftyJSON. All rights reserved.
-//
-
-import Foundation
-import Alamofire
-import SwiftyJSON
-
-// MARK: - Request for Swift JSON
-
-extension Request {
-/**
-Adds a handler to be called once the request has finished.
-:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the SwiftyJSON enum, if one could be created from the URL response and data, and any error produced while creating the SwiftyJSON enum.
-:returns: The request.
-*/
- public func responseSwiftyJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, SwiftyJSON.JSON, NSError?) -> Void) -> Self {
- return responseSwiftyJSON(queue: nil, options: NSJSONReadingOptions.AllowFragments, completionHandler: completionHandler)
- }
-/**
-Adds a handler to be called once the request has finished.
-:param: queue The queue on which the completion handler is dispatched.
-:param: options The JSON serialization reading options. `.AllowFragments` by default.
-:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the SwiftyJSON enum, if one could be created from the URL response and data, and any error produced while creating the SwiftyJSON enum.
-:returns: The request.
-*/
- public func responseSwiftyJSON(queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, JSON, NSError?) -> Void) -> Self {
- return response(queue: queue, serializer: Request.JSONResponseSerializer(options: options), completionHandler: {
- (request, response, object, error) -> Void in
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
- var responseJSON: JSON
- if error != nil || object == nil {
- responseJSON = JSON.nullJSON
- } else {
- responseJSON = SwiftyJSON.JSON(object!)
- }
- dispatch_async(queue ?? dispatch_get_main_queue(), {
- completionHandler(self.request, self.response, responseJSON, error)
- })
- })
- })
- }
-}
-
diff --git a/kplayer/util/stringutil.swift b/kplayer/util/stringutil.swift
new file mode 100644
index 0000000..2e1aa68
--- /dev/null
+++ b/kplayer/util/stringutil.swift
@@ -0,0 +1,16 @@
+//
+// Created by Marco Schmickler on 15.07.15.
+// Copyright (c) 2015 Marco Schmickler. All rights reserved.
+//
+
+import Foundation
+
+public extension String {
+ func beginsWith (str: String) -> Bool {
+ return hasPrefix(str)
+ }
+
+ func endsWith (str: String) -> Bool {
+ return hasSuffix(str)
+ }
+}
\ No newline at end of file
diff --git a/kplayerTests/Info.plist b/kplayerTests/Info.plist
index 0074743..ba72822 100644
--- a/kplayerTests/Info.plist
+++ b/kplayerTests/Info.plist
@@ -7,7 +7,7 @@
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIdentifier
- schmickler.$(PRODUCT_NAME:rfc1034identifier)
+ $(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
diff --git a/kplayerTests/kplayerTests.swift b/kplayerTests/kplayerTests.swift
index a19d59e..9839bf6 100644
--- a/kplayerTests/kplayerTests.swift
+++ b/kplayerTests/kplayerTests.swift
@@ -21,9 +21,14 @@ class kplayerTests: XCTestCase {
super.tearDown()
}
- func testExample() {
+ func testMyExample() {
+ // http://linkstation.local/tomcat/media/service/listpicdirs/srv/samba/ren/series/sg
+
+ print("hello")
+
+ let i = 12
// This is an example of a functional test case.
- XCTAssert(true, "Pass")
+ XCTAssert(i == 1, "Pass")
}
func testPerformanceExample() {