repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
getconnect/connect-swift
Pod/Classes/QueryResults.swift
1
2416
// // QueryResults.swift // ConnectSwift // // Created by Chad Edrupt on 2/12/2015. // Copyright © 2015 Connect. All rights reserved. // import Foundation import SwiftyJSON public typealias QueryCallback = (QueryResults) -> Void public typealias IntervalQueryCallback = (IntervalQueryResults) -> Void public struct Metadata { let groups: [String] let interval: String? let timezone: String? init(json: JSON) { groups = json["groups"].arrayValue.map { $0.string! } interval = json["interval"].string timezone = json["timezone"].string } } public typealias QueryResultItem = [String: AnyObject] public struct QueryResults { public let query: Query public let metadata: Metadata public let results: [QueryResultItem] public let resultsJSON: JSON public let cacheKey: String? init(json: JSON, query: Query, cacheKey: String? = nil) { metadata = Metadata(json: json["metadata"]) results = json["results"].arrayValue.map { $0.dictionaryObject! } resultsJSON = json["results"] self.query = query self.cacheKey = cacheKey } } public struct ResultItemInterval { public let start: NSDate public let end: NSDate init(json: JSON) { let startDate = json["start"].stringValue let endDate = json["end"].stringValue start = NSDateFormatter.iso8601Formatter.dateFromString(startDate)! end = NSDateFormatter.iso8601Formatter.dateFromString(endDate)! } } public struct IntervalQueryResultItem { public let interval: ResultItemInterval public let results: [QueryResultItem] public let resultJSON: JSON init(json: JSON) { interval = ResultItemInterval(json: json["interval"]) results = json["results"].arrayValue.map { $0.dictionaryObject! } resultJSON = json["results"] } } public struct IntervalQueryResults { public let query: Query public let metadata: Metadata public let results: [IntervalQueryResultItem] public let resultJSON: JSON public let cacheKey: String? init(json: JSON, query: Query, cacheKey: String? = nil) { metadata = Metadata(json: json["metadata"]) results = json["results"].arrayValue.map { IntervalQueryResultItem(json: $0) } resultJSON = json["results"] self.query = query self.cacheKey = cacheKey } }
mit
87a638fc206aa69e796ae28c48fd2aa9
28.096386
86
0.667495
4.406934
false
false
false
false
gribozavr/swift
test/SILGen/foreach.swift
1
21823
// RUN: %target-swift-emit-silgen -module-name foreach %s | %FileCheck %s ////////////////// // Declarations // ////////////////// class C {} @_silgen_name("loopBodyEnd") func loopBodyEnd() -> () @_silgen_name("condition") func condition() -> Bool @_silgen_name("loopContinueEnd") func loopContinueEnd() -> () @_silgen_name("loopBreakEnd") func loopBreakEnd() -> () @_silgen_name("funcEnd") func funcEnd() -> () struct TrivialStruct { var value: Int32 } struct NonTrivialStruct { var value: C } struct GenericStruct<T> { var value: T var value2: C } protocol P {} protocol ClassP : class {} protocol GenericCollection : Collection { } /////////// // Tests // /////////// //===----------------------------------------------------------------------===// // Trivial Struct //===----------------------------------------------------------------------===// // CHECK-LABEL: sil hidden [ossa] @$s7foreach13trivialStructyySaySiGF : $@convention(thin) (@guaranteed Array<Int>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @guaranteed $Array<Int>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<Int>> }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: switch_enum [[IND_VAR:%.*]] : $Optional<Int>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[VAR:%.*]] : $Int): // CHECK: [[LOOP_END_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_END_FUNC]]() // CHECK: br [[LOOP_DEST]] // // CHECK: [[NONE_BB]]: // CHECK: destroy_value [[ITERATOR_BOX]] // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: } // end sil function '$s7foreach13trivialStructyySaySiGF' func trivialStruct(_ xx: [Int]) { for x in xx { loopBodyEnd() } funcEnd() } // TODO: Write this test func trivialStructContinue(_ xx: [Int]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } // TODO: Write this test func trivialStructBreak(_ xx: [Int]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden [ossa] @$s7foreach26trivialStructContinueBreakyySaySiGF : $@convention(thin) (@guaranteed Array<Int>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @guaranteed $Array<Int>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<Int>> }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[BORROWED_ARRAY_STACK:%.*]] = alloc_stack $Array<Int> // CHECK: store [[ARRAY_COPY:%.*]] to [init] [[BORROWED_ARRAY_STACK]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = witness_method $Array<Int>, #Sequence.makeIterator!1 : <Self where Self : Sequence> (__owned Self) -> () -> Self.Iterator : $@convention(witness_method: Sequence) <τ_0_0 where τ_0_0 : Sequence> (@in τ_0_0) -> @out τ_0_0.Iterator // CHECK: apply [[MAKE_ITERATOR_FUNC]]<[Int]>([[PROJECT_ITERATOR_BOX]], [[BORROWED_ARRAY_STACK]]) // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[GET_ELT_STACK:%.*]] = alloc_stack $Optional<Int> // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*IndexingIterator<Array<Int>> // CHECK: [[FUNC_REF:%.*]] = witness_method $IndexingIterator<Array<Int>>, #IteratorProtocol.next!1 : <Self where Self : IteratorProtocol> (inout Self) -> () -> Self.Element? : $@convention(witness_method: IteratorProtocol) <τ_0_0 where τ_0_0 : IteratorProtocol> (@inout τ_0_0) -> @out Optional<τ_0_0.Element> // CHECK: apply [[FUNC_REF]]<IndexingIterator<Array<Int>>>([[GET_ELT_STACK]], [[WRITE]]) // CHECK: [[IND_VAR:%.*]] = load [trivial] [[GET_ELT_STACK]] // CHECK: switch_enum [[IND_VAR]] : $Optional<Int>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[VAR:%.*]] : $Int): // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: br [[LOOP_DEST]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: destroy_value [[ITERATOR_BOX]] : ${ var IndexingIterator<Array<Int>> } // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: } // end sil function '$s7foreach26trivialStructContinueBreakyySaySiGF' func trivialStructContinueBreak(_ xx: [Int]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Existential //===----------------------------------------------------------------------===// func existential(_ xx: [P]) { for x in xx { loopBodyEnd() } funcEnd() } func existentialContinue(_ xx: [P]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func existentialBreak(_ xx: [P]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden [ossa] @$s7foreach24existentialContinueBreakyySayAA1P_pGF : $@convention(thin) (@guaranteed Array<P>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @guaranteed $Array<P>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<P>> }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[BORROWED_ARRAY_STACK:%.*]] = alloc_stack $Array<P> // CHECK: store [[ARRAY_COPY:%.*]] to [init] [[BORROWED_ARRAY_STACK]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = witness_method $Array<P>, #Sequence.makeIterator!1 : <Self where Self : Sequence> (__owned Self) -> () -> Self.Iterator : $@convention(witness_method: Sequence) <τ_0_0 where τ_0_0 : Sequence> (@in τ_0_0) -> @out τ_0_0.Iterator // CHECK: apply [[MAKE_ITERATOR_FUNC]]<[P]>([[PROJECT_ITERATOR_BOX]], [[BORROWED_ARRAY_STACK]]) // CHECK: [[ELT_STACK:%.*]] = alloc_stack $Optional<P> // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*IndexingIterator<Array<P>> // CHECK: [[FUNC_REF:%.*]] = witness_method $IndexingIterator<Array<P>>, #IteratorProtocol.next!1 : <Self where Self : IteratorProtocol> (inout Self) -> () -> Self.Element? : $@convention(witness_method: IteratorProtocol) <τ_0_0 where τ_0_0 : IteratorProtocol> (@inout τ_0_0) -> @out Optional<τ_0_0.Element> // CHECK: apply [[FUNC_REF]]<IndexingIterator<Array<P>>>([[ELT_STACK]], [[WRITE]]) // CHECK: switch_enum_addr [[ELT_STACK]] : $*Optional<P>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]: // CHECK: [[T0:%.*]] = alloc_stack $P, let, name "x" // CHECK: [[ELT_STACK_TAKE:%.*]] = unchecked_take_enum_data_addr [[ELT_STACK]] : $*Optional<P>, #Optional.some!enumelt.1 // CHECK: copy_addr [take] [[ELT_STACK_TAKE]] to [initialization] [[T0]] // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: dealloc_stack [[ELT_STACK]] // CHECK: destroy_value [[ITERATOR_BOX]] : ${ var IndexingIterator<Array<P>> } // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: } // end sil function '$s7foreach24existentialContinueBreakyySayAA1P_pGF' func existentialContinueBreak(_ xx: [P]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Class Constrainted Existential //===----------------------------------------------------------------------===// func existentialClass(_ xx: [ClassP]) { for x in xx { loopBodyEnd() } funcEnd() } func existentialClassContinue(_ xx: [ClassP]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func existentialClassBreak(_ xx: [ClassP]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } func existentialClassContinueBreak(_ xx: [ClassP]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Generic Struct //===----------------------------------------------------------------------===// func genericStruct<T>(_ xx: [GenericStruct<T>]) { for x in xx { loopBodyEnd() } funcEnd() } func genericStructContinue<T>(_ xx: [GenericStruct<T>]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func genericStructBreak<T>(_ xx: [GenericStruct<T>]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden [ossa] @$s7foreach26genericStructContinueBreakyySayAA07GenericC0VyxGGlF : $@convention(thin) <T> (@guaranteed Array<GenericStruct<T>>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @guaranteed $Array<GenericStruct<T>>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box $<τ_0_0> { var IndexingIterator<Array<GenericStruct<τ_0_0>>> } <T>, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[BORROWED_ARRAY_STACK:%.*]] = alloc_stack $Array<GenericStruct<T>> // CHECK: store [[ARRAY_COPY:%.*]] to [init] [[BORROWED_ARRAY_STACK]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = witness_method $Array<GenericStruct<T>>, #Sequence.makeIterator!1 : <Self where Self : Sequence> (__owned Self) -> () -> Self.Iterator : $@convention(witness_method: Sequence) <τ_0_0 where τ_0_0 : Sequence> (@in τ_0_0) -> @out τ_0_0.Iterator // CHECK: apply [[MAKE_ITERATOR_FUNC]]<[GenericStruct<T>]>([[PROJECT_ITERATOR_BOX]], [[BORROWED_ARRAY_STACK]]) // CHECK: [[ELT_STACK:%.*]] = alloc_stack $Optional<GenericStruct<T>> // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*IndexingIterator<Array<GenericStruct<T>>> // CHECK: [[FUNC_REF:%.*]] = witness_method $IndexingIterator<Array<GenericStruct<T>>>, #IteratorProtocol.next!1 : <Self where Self : IteratorProtocol> (inout Self) -> () -> Self.Element? : $@convention(witness_method: IteratorProtocol) <τ_0_0 where τ_0_0 : IteratorProtocol> (@inout τ_0_0) -> @out Optional<τ_0_0.Element> // CHECK: apply [[FUNC_REF]]<IndexingIterator<Array<GenericStruct<T>>>>([[ELT_STACK]], [[WRITE]]) // CHECK: switch_enum_addr [[ELT_STACK]] : $*Optional<GenericStruct<T>>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]: // CHECK: [[T0:%.*]] = alloc_stack $GenericStruct<T>, let, name "x" // CHECK: [[ELT_STACK_TAKE:%.*]] = unchecked_take_enum_data_addr [[ELT_STACK]] : $*Optional<GenericStruct<T>>, #Optional.some!enumelt.1 // CHECK: copy_addr [take] [[ELT_STACK_TAKE]] to [initialization] [[T0]] // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: dealloc_stack [[ELT_STACK]] // CHECK: destroy_value [[ITERATOR_BOX]] // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: } // end sil function '$s7foreach26genericStructContinueBreakyySayAA07GenericC0VyxGGlF' func genericStructContinueBreak<T>(_ xx: [GenericStruct<T>]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Fully Generic Collection //===----------------------------------------------------------------------===// func genericCollection<T : Collection>(_ xx: T) { for x in xx { loopBodyEnd() } funcEnd() } func genericCollectionContinue<T : Collection>(_ xx: T) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func genericCollectionBreak<T : Collection>(_ xx: T) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden [ossa] @$s7foreach30genericCollectionContinueBreakyyxSlRzlF : $@convention(thin) <T where T : Collection> (@in_guaranteed T) -> () { // CHECK: bb0([[COLLECTION:%.*]] : $*T): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : Collection> { var τ_0_0.Iterator } <T>, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = witness_method $T, #Sequence.makeIterator!1 // CHECK: apply [[MAKE_ITERATOR_FUNC]]<T>([[PROJECT_ITERATOR_BOX]], [[COLLECTION_COPY:%.*]]) // CHECK: [[ELT_STACK:%.*]] = alloc_stack $Optional<T.Element> // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*T.Iterator // CHECK: [[GET_NEXT_FUNC:%.*]] = witness_method $T.Iterator, #IteratorProtocol.next!1 : <Self where Self : IteratorProtocol> (inout Self) -> () -> Self.Element? : $@convention(witness_method: IteratorProtocol) <τ_0_0 where τ_0_0 : IteratorProtocol> (@inout τ_0_0) -> @out Optional<τ_0_0.Element> // CHECK: apply [[GET_NEXT_FUNC]]<T.Iterator>([[ELT_STACK]], [[WRITE]]) // CHECK: switch_enum_addr [[ELT_STACK]] : $*Optional<T.Element>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]: // CHECK: [[T0:%.*]] = alloc_stack $T.Element, let, name "x" // CHECK: [[ELT_STACK_TAKE:%.*]] = unchecked_take_enum_data_addr [[ELT_STACK]] : $*Optional<T.Element>, #Optional.some!enumelt.1 // CHECK: copy_addr [take] [[ELT_STACK_TAKE]] to [initialization] [[T0]] // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: dealloc_stack [[ELT_STACK]] // CHECK: destroy_value [[ITERATOR_BOX]] // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: } // end sil function '$s7foreach30genericCollectionContinueBreakyyxSlRzlF' func genericCollectionContinueBreak<T : Collection>(_ xx: T) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Pattern Match Tests //===----------------------------------------------------------------------===// // CHECK-LABEL: sil hidden [ossa] @$s7foreach13tupleElementsyySayAA1CC_ADtGF func tupleElements(_ xx: [(C, C)]) { // CHECK: bb{{.*}}([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: ([[A:%.*]], [[B:%.*]]) = destructure_tuple [[PAYLOAD]] // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for (a, b) in xx {} // CHECK: bb{{.*}}([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: ([[A:%.*]], [[B:%.*]]) = destructure_tuple [[PAYLOAD]] // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for (a, _) in xx {} // CHECK: bb{{.*}}([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: ([[A:%.*]], [[B:%.*]]) = destructure_tuple [[PAYLOAD]] // CHECK: destroy_value [[A]] // CHECK: destroy_value [[B]] for (_, b) in xx {} // CHECK: bb{{.*}}([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: ([[A:%.*]], [[B:%.*]]) = destructure_tuple [[PAYLOAD]] // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for (_, _) in xx {} // CHECK: bb{{.*}}([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: ([[A:%.*]], [[B:%.*]]) = destructure_tuple [[PAYLOAD]] // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for _ in xx {} } // Make sure that when we have an unused value, we properly iterate over the // loop rather than run through the loop once. // // CHECK-LABEL: sil hidden [ossa] @$s7foreach16unusedArgPatternyySaySiGF : $@convention(thin) (@guaranteed Array<Int>) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Array<Int>): // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: switch_enum [[OPT_VAL:%.*]] : $Optional<Int>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[VAL:%.*]] : $Int): // CHECK: [[LOOP_END_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_END_FUNC]] func unusedArgPattern(_ xx: [Int]) { for _ in xx { loopBodyEnd() } } // Test for SR-11269. Make sure that the sil contains the needed upcast. // // CHECK-LABEL: sil hidden [ossa] @$s7foreach25genericFuncWithConversion4listySayxG_tAA1CCRbzlF // CHECK: bb2([[ITER_VAL:%.*]] : @owned $T): // CHECK: [[ITER_VAL_UPCAST:%.*]] = upcast [[ITER_VAL]] : $T to $C func genericFuncWithConversion<T: C>(list : [T]) { for item: C in list { print(item) } }
apache-2.0
2928c4fe64bc19c46781291f196a51f6
35.016529
324
0.566131
3.337418
false
false
false
false
nissivm/DemoShopPayPal
DemoShop-PayPal/View Controllers/ShoppingCart_VC.swift
1
18511
// // ShoppingCart_VC.swift // DemoShop-PayPal // // Copyright © 2016 Nissi Vieira Miranda. All rights reserved. // import UIKit protocol ShoppingCart_VC_Delegate: class { func shoppingCartItemsListChanged(cartItems: [ShoppingCartItem]) } class ShoppingCart_VC: UIViewController, UITableViewDataSource, UITableViewDelegate, ShoppingCartItemCellDelegate, PayPalPaymentDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var valueToPayLabel: UILabel! @IBOutlet weak var freeShippingBlueRect: UIView! @IBOutlet weak var pacBlueRect: UIView! @IBOutlet weak var sedexBlueRect: UIView! @IBOutlet weak var shopName: UILabel! @IBOutlet weak var shoppingCartImage: UIImageView! @IBOutlet weak var headerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var optionsSatckViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var valueToPayViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var buttonsSatckViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var shippingOptionsStackView: UIStackView! @IBOutlet weak var checkoutButton: UIButton! @IBOutlet weak var keepShoppingButton: UIButton! weak var delegate: ShoppingCart_VC_Delegate? let auxiliar = Auxiliar() let backend = Backend() let shippingMethods = ShippingMethods() var multiplier: CGFloat = 1 var payPalConfiguration: PayPalConfiguration! // Received from Products_VC: var shoppingCartItems: [ShoppingCartItem]! var valueToPay: CGFloat = 0 var shippingValue: CGFloat = 0 override func viewDidLoad() { super.viewDidLoad() payPalConfiguration = PayPalConfiguration() payPalConfiguration.acceptCreditCards = false payPalConfiguration.payPalShippingAddressOption = .PayPal if Device.IS_IPHONE_6 { multiplier = Constants.multiplier6 adjustForBiggerScreen() } else if Device.IS_IPHONE_6_PLUS { multiplier = Constants.multiplier6plus adjustForBiggerScreen() } else { calculateTableViewHeightConstraint() } valueToPay = totalPurchaseItemsValue() let value: NSString = NSString(format: "%.02f", valueToPay) valueToPayLabel.text = "Total: $\(value)" } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) PayPalMobile.preconnectWithEnvironment(PayPalEnvironmentSandbox) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } //-------------------------------------------------------------------------// // MARK: IBActions //-------------------------------------------------------------------------// @IBAction func shippingMethodButtonTapped(sender: UIButton) { let idx = sender.tag - 10 resetShippingMethod(idx) } @IBAction func checkoutButtonTapped(sender: UIButton) { guard Reachability.connectedToNetwork() else { Auxiliar.presentAlertControllerWithTitle("No Internet Connection", andMessage: "Make sure your device is connected to the internet.", forViewController: self) return } let payment = PayPalPayment() payment.items = createPayPalItems() payment.paymentDetails = getPaymentDetails() payment.amount = Auxiliar.formatPrice(valueToPay) payment.currencyCode = "BRL" payment.shortDescription = "Purchase of fashion items" payment.intent = .Sale payment.shippingAddress = nil if let paymentViewController = PayPalPaymentViewController(payment: payment, configuration: payPalConfiguration, delegate: self) { presentViewController(paymentViewController, animated: true, completion: nil) } } @IBAction func keepShoppingButtonTapped(sender: UIButton) { navigationController!.popViewControllerAnimated(true) } //-------------------------------------------------------------------------// // MARK: PayPal payment components //-------------------------------------------------------------------------// func createPayPalItems() -> [PayPalItem] { var payPalItems = [PayPalItem]() for cartItem in shoppingCartItems { let payPalItem = PayPalItem(name: cartItem.itemForSale.itemName, withQuantity: UInt(cartItem.amount), withPrice: Auxiliar.formatPrice(cartItem.itemForSale.itemPrice), withCurrency: "BRL", withSku: cartItem.itemForSale.itemId) payPalItems.append(payPalItem) } return payPalItems } func getPaymentDetails() -> PayPalPaymentDetails { let subTotal = totalPurchaseItemsValue() return PayPalPaymentDetails(subtotal: Auxiliar.formatPrice(subTotal), withShipping: Auxiliar.formatPrice(shippingValue), withTax: Auxiliar.formatPrice(0)) } //-------------------------------------------------------------------------// // MARK: UITableViewDataSource //-------------------------------------------------------------------------// func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return shoppingCartItems.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ShoppingCartItemCell", forIndexPath: indexPath) as! ShoppingCartItemCell cell.delegate = self cell.setupCellWithItem(shoppingCartItems[indexPath.row]) return cell } //-------------------------------------------------------------------------// // MARK: UITableViewDelegate //-------------------------------------------------------------------------// func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var starterCellHeight: CGFloat = 110 if Device.IS_IPHONE_6 { starterCellHeight = 100 } if Device.IS_IPHONE_6_PLUS { starterCellHeight = 90 } return starterCellHeight * multiplier } //-------------------------------------------------------------------------// // MARK: ShoppingCartItemCellDelegate //-------------------------------------------------------------------------// func amountForItemChanged(clickedItemId: String, newAmount: Int) { var totalPurchase = totalPurchaseItemsValue() let shippingValue = valueToPay - totalPurchase let idx = findOutCartItemIndex(clickedItemId) let item = shoppingCartItems[idx] item.amount = newAmount shoppingCartItems[idx] = item totalPurchase = totalPurchaseItemsValue() valueToPay = totalPurchase + shippingValue let value: NSString = NSString(format: "%.02f", valueToPay) valueToPayLabel.text = "Total: $\(value)" delegate!.shoppingCartItemsListChanged(shoppingCartItems) } func removeItem(clickedItemId: String) { var totalPurchase = totalPurchaseItemsValue() let shippingValue = valueToPay - totalPurchase let idx = findOutCartItemIndex(clickedItemId) shoppingCartItems.removeAtIndex(idx) delegate!.shoppingCartItemsListChanged(shoppingCartItems) if shoppingCartItems.count == 0 { navigationController!.popViewControllerAnimated(true) } else { tableView.beginUpdates() let indexPaths = [NSIndexPath(forRow: idx, inSection: 0)] tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Left) tableView.endUpdates() totalPurchase = totalPurchaseItemsValue() valueToPay = totalPurchase + shippingValue let value: NSString = NSString(format: "%.02f", valueToPay) valueToPayLabel.text = "Total: $\(value)" calculateTableViewHeightConstraint() } } //-------------------------------------------------------------------------// // MARK: PayPalPaymentDelegate //-------------------------------------------------------------------------// func payPalPaymentViewController(paymentViewController: PayPalPaymentViewController, didCompletePayment completedPayment: PayPalPayment) { dismissViewControllerAnimated(true, completion: nil) verifyPayment(completedPayment) } func payPalPaymentDidCancel(paymentViewController: PayPalPaymentViewController) { dismissViewControllerAnimated(true, completion: nil) } //-------------------------------------------------------------------------// // MARK: Verify payment in backend //-------------------------------------------------------------------------// func verifyPayment(completedPayment: PayPalPayment) { let response = completedPayment.confirmation["response"] as! [String : String] let state = response["state"] if state == "approved" { let paymentId = response["id"] let purchaseAmount = CGFloat(completedPayment.amount) let purchaseCurrency = completedPayment.currencyCode let postDic: [String : AnyObject] = ["paymentId" : paymentId!, "purchaseAmount" : purchaseAmount, "purchaseCurrency" : purchaseCurrency] Auxiliar.showLoadingHUDWithText("Verifing payment...", forView: self.view) Backend.verifyPayment(postDic, completion: { [unowned self](status, message) -> Void in Auxiliar.hideLoadingHUDInView(self.view) if status == "Success" { self.promptUserForSuccessfulPayment(status, message: message) } else { Auxiliar.presentAlertControllerWithTitle("Error", andMessage: "An error occurred with the payment.", forViewController: self) } }) } else { Auxiliar.presentAlertControllerWithTitle("Error", andMessage: "Your payment was not approved.", forViewController: self) } } //-------------------------------------------------------------------------// // MARK: Prompt user for successful payment //-------------------------------------------------------------------------// func promptUserForSuccessfulPayment(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) let saveAction = UIAlertAction(title: "Ok", style: .Default) { [unowned self](action: UIAlertAction!) -> Void in self.shoppingCartItems.removeAll() self.delegate!.shoppingCartItemsListChanged(self.shoppingCartItems) self.navigationController!.popToRootViewControllerAnimated(true) } alert.addAction(saveAction) dispatch_async(dispatch_get_main_queue()) { self.presentViewController(alert, animated: true, completion: nil) } } //-------------------------------------------------------------------------// // MARK: Auxiliar functions //-------------------------------------------------------------------------// func findOutCartItemIndex(clickedItemId: String) -> Int { var idx = 0 for (index, item) in shoppingCartItems.enumerate() { if item.itemForSale.itemId == clickedItemId { idx = index break } } return idx } func resetShippingMethod(idx: Int) { let totalPurchase = totalPurchaseItemsValue() let methods = shippingMethods.availableShippingMethods() let method = methods[idx] shippingValue = method.amount valueToPay = totalPurchase + shippingValue let value: NSString = NSString(format: "%.02f", valueToPay) valueToPayLabel.text = "Total: $\(value)" // Adjust UI: freeShippingBlueRect.alpha = 0.4 pacBlueRect.alpha = 0.4 sedexBlueRect.alpha = 0.4 switch idx { case 0: freeShippingBlueRect.alpha = 1 case 1: pacBlueRect.alpha = 1 case 2: sedexBlueRect.alpha = 1 default: print("Unknown") } } func totalPurchaseItemsValue() -> CGFloat { var totalValue: CGFloat = 0 for item in shoppingCartItems { let unityPrice = item.itemForSale.itemPrice let total = unityPrice * CGFloat(item.amount) totalValue += total } return totalValue } func getChoosenShippingMethod() -> ShippingMethod { let methods = shippingMethods.availableShippingMethods() var idx = 0 if pacBlueRect.alpha == 1 { idx = 1 } else if sedexBlueRect.alpha == 1 { idx = 2 } return methods[idx] } //-------------------------------------------------------------------------// // MARK: Ajust for bigger screen //-------------------------------------------------------------------------// func adjustForBiggerScreen() { for constraint in shopName.constraints { constraint.constant *= multiplier } for constraint in shoppingCartImage.constraints { constraint.constant *= multiplier } for subview in shippingOptionsStackView.subviews { for (index, subV) in subview.subviews.enumerate() { if index > 0 { for constraint in subV.constraints { constraint.constant *= multiplier } if index == 1 { let fontSize = 14 * multiplier let label = subV as! UILabel label.font = UIFont(name: "HelveticaNeue", size: fontSize) } if index == 2 { let fontSize = 12 * multiplier let label = subV as! UILabel label.font = UIFont(name: "HelveticaNeue", size: fontSize) } if index == 3 { let fontSize = 15 * multiplier let label = subV as! UILabel label.font = UIFont(name: "HelveticaNeue", size: fontSize) } } } } for constraint in valueToPayLabel.constraints { constraint.constant *= multiplier } headerHeightConstraint.constant *= multiplier optionsSatckViewHeightConstraint.constant *= multiplier valueToPayViewHeightConstraint.constant *= multiplier buttonsSatckViewHeightConstraint.constant *= multiplier calculateTableViewHeightConstraint() var fontSize = 25.0 * multiplier shopName.font = UIFont(name: "HelveticaNeue-Light", size: fontSize) fontSize = 17.0 * multiplier checkoutButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Light", size: fontSize) keepShoppingButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Light", size: fontSize) fontSize = 15.0 * multiplier valueToPayLabel.font = UIFont(name: "HelveticaNeue", size: fontSize) } //-------------------------------------------------------------------------// // MARK: Calculate TableView Height Constraint //-------------------------------------------------------------------------// func calculateTableViewHeightConstraint() { let space = self.view.frame.size.height - (headerHeightConstraint.constant + optionsSatckViewHeightConstraint.constant + valueToPayViewHeightConstraint.constant + buttonsSatckViewHeightConstraint.constant) var starterCellHeight: CGFloat = 110 if Device.IS_IPHONE_6 { starterCellHeight = 100 } if Device.IS_IPHONE_6_PLUS { starterCellHeight = 90 } let cellsTotalHeight = (starterCellHeight * multiplier) * CGFloat(shoppingCartItems.count) let tvHeight = cellsTotalHeight < space ? cellsTotalHeight : space tableViewHeightConstraint.constant = tvHeight } //-------------------------------------------------------------------------// // MARK: Memory Warning //-------------------------------------------------------------------------// override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
5b0f2933a4c689f884ce87b7b8664e87
33.277778
136
0.518531
6.306644
false
false
false
false
RMizin/PigeonMessenger-project
FalconMessenger/ChatsControllers/UserInfoPhoneNumberTableViewCell.swift
1
7245
// // UserInfoPhoneNumberTableViewCell.swift // Pigeon-project // // Created by Roman Mizin on 2/2/18. // Copyright © 2018 Roman Mizin. All rights reserved. // import UIKit import ContactsUI import ARSLineProgress extension UIViewController: CNContactViewControllerDelegate { fileprivate func checkContactsAuthorizationStatus() -> Bool { let contactsAuthorityCheck = CNContactStore.authorizationStatus(for: CNEntityType.contacts) switch contactsAuthorityCheck { case .denied, .notDetermined, .restricted: basicErrorAlertWith(title: "No access", message: contactsAccessDeniedMessage, controller: self) return false case .authorized: return true @unknown default: fatalError() } } func addPhoneNumber(phone : String , name: String, surname: String) { let contactsAccessStatus = checkContactsAuthorizationStatus() guard contactsAccessStatus == true else { return } let phone = CNLabeledValue(label: CNLabelPhoneNumberiPhone, value: CNPhoneNumber(stringValue :phone )) let contact = CNMutableContact() contact.givenName = name contact.familyName = surname contact.phoneNumbers = [phone] let destination = CreateContactTableViewController(style: .grouped) destination.contact = contact navigationController?.pushViewController(destination, animated: true) } } class UserInfoPhoneNumberTableViewCell: UITableViewCell { weak var userInfoTableViewController: UserInfoTableViewController? let copyNumberImage = UIImage(named: "copyNumber")?.withRenderingMode(.alwaysTemplate) let copy: UIButton = { let copy = UIButton(type: .system) copy.translatesAutoresizingMaskIntoConstraints = false copy.imageView?.contentMode = .scaleAspectFit return copy }() let add: UIButton = { let add = UIButton(type: .system ) add.translatesAutoresizingMaskIntoConstraints = false add.imageView?.contentMode = .scaleAspectFit add.setTitle("Add to contacts", for: .normal) return add }() let phoneLabel: UILabel = { let phoneLabel = UILabel() phoneLabel.sizeToFit() phoneLabel.numberOfLines = 0 phoneLabel.translatesAutoresizingMaskIntoConstraints = false return phoneLabel }() let contactStatus: UILabel = { let contactStatus = UILabel() contactStatus.sizeToFit() contactStatus.font = UIFont.systemFont(ofSize: 12) contactStatus.text = "This user not in your contacts" contactStatus.textColor = ThemeManager.currentTheme().generalSubtitleColor contactStatus.translatesAutoresizingMaskIntoConstraints = false return contactStatus }() let bio: UILabel = { let bio = UILabel() bio.sizeToFit() bio.numberOfLines = 0 bio.translatesAutoresizingMaskIntoConstraints = false return bio }() var bioTopAnchor: NSLayoutConstraint! var addHeightConstraint: NSLayoutConstraint! var phoneTopConstraint: NSLayoutConstraint! var contactStatusHeightConstraint: NSLayoutConstraint! override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .default, reuseIdentifier: reuseIdentifier) selectionStyle = .none addSubview(copy) addSubview(add) addSubview(contactStatus) addSubview(phoneLabel) addSubview(bio) contactStatus.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true if #available(iOS 11.0, *) { contactStatus.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 15).isActive = true } else { contactStatus.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true } contactStatus.widthAnchor.constraint(equalToConstant: 180).isActive = true contactStatusHeightConstraint = contactStatus.heightAnchor.constraint(equalToConstant: 40) contactStatusHeightConstraint.isActive = true phoneTopConstraint = phoneLabel.topAnchor.constraint(equalTo: contactStatus.bottomAnchor, constant: 0) phoneTopConstraint.isActive = true if #available(iOS 11.0, *) { phoneLabel.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 15).isActive = true } else { phoneLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true } phoneLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true phoneLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true if #available(iOS 11.0, *) { copy.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -15).isActive = true add.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -15).isActive = true } else { copy.rightAnchor.constraint(equalTo: rightAnchor, constant: -15).isActive = true add.rightAnchor.constraint(equalTo: rightAnchor, constant: -15).isActive = true } add.widthAnchor.constraint(equalToConstant: 110).isActive = true addHeightConstraint = add.heightAnchor.constraint(equalToConstant: 20) addHeightConstraint.isActive = true add.centerYAnchor.constraint(equalTo: contactStatus.centerYAnchor, constant: 0).isActive = true copy.widthAnchor.constraint(equalToConstant: 20).isActive = true copy.heightAnchor.constraint(equalToConstant: 20).isActive = true copy.bottomAnchor.constraint(equalTo: phoneLabel.bottomAnchor, constant: 0).isActive = true add.addTarget(self, action: #selector(handleAddNewContact), for: .touchUpInside) copy.addTarget(self, action: #selector(handleCopy), for: .touchUpInside) copy.setImage(copyNumberImage, for: .normal) bioTopAnchor = bio.topAnchor.constraint(equalTo: phoneLabel.bottomAnchor, constant: 20) bioTopAnchor.isActive = true if #available(iOS 11.0, *) { bio.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 15).isActive = true bio.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -15).isActive = true } else { bio.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true bio.rightAnchor.constraint(equalTo: rightAnchor, constant: -15).isActive = true } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() copy.imageView?.image = nil } @objc func handleAddNewContact() { let name = userInfoTableViewController?.user?.name?.components(separatedBy: " ").first ?? "" var surname = userInfoTableViewController?.user?.name?.components(separatedBy: " ").last ?? "" if name == surname { surname = "" } userInfoTableViewController?.addPhoneNumber(phone: phoneLabelText(), name: name, surname: surname) } @objc func handleCopy() { UIPasteboard.general.string = phoneLabelText() ARSLineProgress.showSuccess() } func phoneLabelText() -> String { guard let mutStr = phoneLabel.attributedText?.mutableCopy() as? NSMutableAttributedString else { return "" } let range = (mutStr.string as NSString).range(of: "mobile\n") mutStr.deleteCharacters(in: range) return mutStr.string } }
gpl-3.0
003ac7e9242796803e39262d3e86092f
35.585859
112
0.73026
4.911186
false
false
false
false
wftllc/hahastream
Haha Stream/HahaService/HahaService.swift
1
4245
import Foundation import Moya enum HahaService { case getDeviceKey(deviceUUID: String) case activateDevice(deviceKey: String) case deactivateDevice() case getDeviceActivationStatus() case getGamesNoDate(sport: String); case getNFLGames(week: NFLWeek?) case getGames(sport: String, year: Int, month: Int, day: Int); case getGame(sport: String, uuid: String) // case getGamesByDate(sport: String, year: Int, month: Int, day: Int); case getSports; case getChannels; case getChannelStreams(channelId: String); case getStreams(sport: String, gameId: String); case getStreamURLForItem(itemId: String, streamId: String, sport: String?); // case getStreamForChannel(channelId: String); case scrapeVCSChannels; } extension HahaService: TargetType { var headers: [String : String]? { let device = UIDevice.current /* To get App version: NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]; To get Build version: NSString *buildVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]; */ let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "Unknown" let buildVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "Unknown" let headers = [ //TODO: load these from os sources as appropriate "X-App" : "TvOS App (\(device.name))", "X-App-Version": "\(appVersion)b\(buildVersion)", "X-Device-Name": device.model, "X-Device-System": device.systemName, "X-Device-CPU": "ARM/x86/x64", "X-Id": "\(device.identifierForVendor!.uuidString)-b", "X-Device-Version": device.systemVersion, ] print("Headers: \(headers)") return headers } var baseURL: URL { return URL(string: "https://hehestreams.com/api/v1")! } var path: String { switch self { case .getDeviceKey(_): return "devices/register" case .activateDevice(_): return "devices/activate" case .deactivateDevice(): return "devices/deactivate" case .getDeviceActivationStatus(): return "devices/check" case .getSports: return "users/services"; case .getGame(let sport, let uuid): return "/\(sport.urlEscaped)/games/\(uuid.urlEscaped)"; case .getGames(let sport, _, _, _): return "/\(sport.urlEscaped)/games"; case .getGamesNoDate(let sport): return "/\(sport.urlEscaped)/games" case .getNFLGames(_): return "/nfl/games" case .getChannelStreams(let uuid): return "/channels/\(uuid.urlEscaped)/streams"; case .getStreams(let sport, let uuid): return "/\(sport.urlEscaped)/games/\(uuid.urlEscaped)/streams"; case .getStreamURLForItem(let itemId, let streamId, let sport): if let sport = sport { return "/\(sport.urlEscaped)/games/\(itemId.urlEscaped)/streams/\(streamId.urlEscaped)"; } else { //channel return "/channels/\(itemId.urlEscaped)/streams/\(streamId.urlEscaped)"; } case .getChannels: return "/channels"; case .scrapeVCSChannels: return "vcs" } } var method: Moya.Method { switch self { default: return .get; } } var parameters: [String: Any] { switch self { case .getDeviceKey(let deviceUUID): return [ "uiud": deviceUUID ] case .activateDevice(let deviceKey): return [ "code": deviceKey ] case .getGames(_, let year, let month, let day): return [ "date": String(format: "%2d-%02d-%1d", month, day, year) ] case .getNFLGames(let nflWeek): guard let nflWeek = nflWeek else { return [:] } //pre-week# or reg-week# //season=2016&week=pre-2 let prefix = nflWeek.type == .preSeason ? "pre" : "reg" return [ "season": nflWeek.year, "week": "\(prefix)-\(nflWeek.week)" ] default: return [:]; } } var parameterEncoding: ParameterEncoding { return URLEncoding.default; } var task: Task { return .requestParameters(parameters: self.parameters, encoding: self.parameterEncoding) } var sampleData: Data { switch self { default: return "".utf8Encoded; } } } // MARK: - Helpers private extension String { var urlEscaped: String { return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } var utf8Encoded: Data { return self.data(using: .utf8)! } }
mit
622d863ec698c01456113f1bf2814a99
27.682432
127
0.690931
3.387869
false
false
false
false
wvteijlingen/Spine
Spine/Errors.swift
1
3939
// // Errors.swift // Spine // // Created by Ward van Teijlingen on 07-04-15. // Copyright (c) 2015 Ward van Teijlingen. All rights reserved. // import Foundation /// An error returned from the server. public struct APIError: Error, Equatable { public var id: String? public var status: String? public var code: String? public var title: String? public var detail: String? public var sourcePointer: String? public var sourceParameter: String? public var meta: [String: Any]? init(id: String?, status: String?, code: String?, title: String?, detail: String?, sourcePointer: String?, sourceParameter: String?, meta: [String: Any]?) { self.id = id self.status = status self.code = code self.title = title self.detail = detail self.sourcePointer = sourcePointer self.sourceParameter = sourceParameter self.meta = meta } } public func ==(lhs: APIError, rhs: APIError) -> Bool { return lhs.code == rhs.code } /// An error that occured in Spine. public enum SpineError: Error, Equatable { case unknownError /// The next page of a collection is not available. case nextPageNotAvailable /// The previous page of a collection is not available. case previousPageNotAvailable /// The requested resource is not found. case resourceNotFound /// An error occured during (de)serializing. case serializerError(SerializerError) /// A error response was received from the API. case serverError(statusCode: Int, apiErrors: [APIError]?) /// A network error occured. case networkError(NSError) } public enum SerializerError: Error, Equatable { case unknownError /// The given JSON is not a dictionary (hash). case invalidDocumentStructure /// None of 'data', 'errors', or 'meta' is present in the top level. case topLevelEntryMissing /// Top level 'data' and 'errors' coexist in the same document. case topLevelDataAndErrorsCoexist /// The given JSON is not a dictionary (hash). case invalidResourceStructure /// 'Type' field is missing from resource JSON. case resourceTypeMissing /// The given resource type has not been registered to Spine. case resourceTypeUnregistered(ResourceType) /// 'ID' field is missing from resource JSON. case resourceIDMissing /// Error occurred in NSJSONSerialization case jsonSerializationError(NSError) } public func ==(lhs: SpineError, rhs: SpineError) -> Bool { switch (lhs, rhs) { case (.unknownError, .unknownError): return true case (.nextPageNotAvailable, .nextPageNotAvailable): return true case (.previousPageNotAvailable, .previousPageNotAvailable): return true case (.resourceNotFound, .resourceNotFound): return true case (let .serializerError(lhsError), let .serializerError(rhsError)): return lhsError == rhsError case (let .serverError(lhsStatusCode, lhsApiErrors), let .serverError(rhsStatusCode, rhsApiErrors)): if lhsStatusCode != rhsStatusCode { return false } if lhsApiErrors == nil && rhsApiErrors == nil { return true } if let lhsErrors = lhsApiErrors, let rhsErrors = rhsApiErrors { return lhsErrors == rhsErrors } return false case (let .networkError(lhsError), let .networkError(rhsError)): return lhsError == rhsError default: return false } } public func ==(lhs: SerializerError, rhs: SerializerError) -> Bool { switch (lhs, rhs) { case (.unknownError, .unknownError): return true case (.invalidDocumentStructure, .invalidDocumentStructure): return true case (.topLevelEntryMissing, .topLevelEntryMissing): return true case (.topLevelDataAndErrorsCoexist, .topLevelDataAndErrorsCoexist): return true case (.invalidResourceStructure, .invalidResourceStructure): return true case (.resourceTypeMissing, .resourceTypeMissing): return true case (.resourceIDMissing, .resourceIDMissing): return true case (let .jsonSerializationError(lhsError), let .jsonSerializationError(rhsError)): return lhsError == rhsError default: return false } }
mit
afc83ae997da833a804bca8f75277899
27.751825
157
0.741051
3.827988
false
false
false
false
sammyd/iOS8-SplitView
MultiLevelSplit/AppDelegate.swift
1
1820
// // AppDelegate.swift // MultiLevelSplit // // Copyright 2015 Sam Davies // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? let studentData = loadStudentDataModel() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() // Faff around to get hold of the master VC let masterContainer = splitViewController.viewControllers.first! as! UINavigationController if let masterVC = masterContainer.topViewController as? MasterViewController { switch studentData! { case let .Node(name, children): masterVC.children = children masterVC.title = name default: println("error") } } return true } }
apache-2.0
3ef6c70507fd1c83d7ec262a339e3321
33.339623
138
0.752747
5.185185
false
false
false
false
webim/webim-client-sdk-ios
WebimClientLibrary/Backend/Items/FAQStructureItem.swift
1
4158
// // FAQStructureItem.swift // WebimClientLibrary // // Created by Nikita Kaberov on 07.02.19. // Copyright © 2019 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** - author: Nikita Kaberov - copyright: 2019 Webim */ final class FAQStructureItem { // MARK: - Constants // Raw values equal to field names received in responses from server. private enum JSONField: String { case id = "id" case type = "type" case childs = "childs" case title = "title" } // MARK: - Properties private var id: String? private var title: String? private var type: RootType? private var children = [FAQStructureItem]() // MARK: - Initialization init(jsonDictionary: [String: Any?]) { if let title = jsonDictionary[JSONField.title.rawValue] as? String { self.title = title } if let type = jsonDictionary[JSONField.type.rawValue] as? String { self.type = toRootType(type: type) } if type == .item { if let id = jsonDictionary[JSONField.id.rawValue] as? String { self.id = id } } else { if let id = jsonDictionary[JSONField.id.rawValue] as? Int { self.id = String(id) } } if let childs = jsonDictionary[JSONField.childs.rawValue] as? [Any] { for child in childs { if let childValue = child as? [String: Any?] { let childItem = FAQStructureItem(jsonDictionary: childValue) children.append(childItem) } } } } private func toRootType(type: String) -> RootType? { switch type { case "item": return .item case "category": return .category default: return nil } } } extension FAQStructureItem: FAQStructure { func getID() -> String { guard let id = id else { WebimInternalLogger.shared.log(entry: "ID is nil in FAQStructureItem.\(#function)") return String() } return id } func getType() -> RootType { guard let type = type else { WebimInternalLogger.shared.log(entry: "Type is nil in FAQStructureItem.\(#function)") return .unknown } return type } func getChildren() -> [FAQStructure] { return children } func getTitle() -> String { guard let title = title else { WebimInternalLogger.shared.log(entry: "Title is nil in FAQStructureItem.\(#function)") return String() } return title } } // MARK: - Equatable extension FAQStructureItem: Equatable { // MARK: - Methods static func == (lhs: FAQStructureItem, rhs: FAQStructureItem) -> Bool { if lhs.id == rhs.id { return true } return false } }
mit
d04a1361ba90a9a6dcd57567724cf940
28.48227
98
0.593216
4.42705
false
false
false
false
yashigani/WebKitPlus
Sources/WebKitPlus/UIAlertController+Init.swift
1
1851
import UIKit extension UIAlertController { public convenience init?(for challenge: URLAuthenticationChallenge, completion: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { let space = challenge.protectionSpace guard space.isUserCredential else { return nil } self.init(title: "\(space.`protocol`!)://\(space.host):\(space.port)", message: space.realm, preferredStyle: .alert) self.addTextField { $0.placeholder = localizedString(for: "user") } self.addTextField { $0.placeholder = localizedString(for: "password") $0.isSecureTextEntry = true } self.addAction(UIAlertAction(title: localizedString(for: "Cancel"), style: .cancel) { _ in completion(.cancelAuthenticationChallenge, nil) }) self.addAction(UIAlertAction(title: localizedString(for: "OK"), style: .default) { [weak self] _ in let textFields = self!.textFields! let credential = URLCredential(user: textFields[0].text!, password: textFields[1].text!, persistence: .forSession) completion(.useCredential, credential) }) } public convenience init?(error: NSError) { if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled { return nil } // Ignore WebKitErrorFrameLoadInterruptedByPolicyChange if error.domain == "WebKitErrorDomain" && error.code == 102 { return nil } let title = error.userInfo[NSURLErrorFailingURLStringErrorKey] as? String let message = error.localizedDescription self.init(title: title, message: message, preferredStyle: .alert) self.addAction(UIAlertAction(title: localizedString(for: "OK"), style: .default) { _ in }) } }
mit
33e9d51517cd97f2163492d4a3e379ad
44.146341
158
0.642355
5.002703
false
false
false
false
VladasZ/iOSTools
Sources/iOS/Views/BannerAlertView/BannerAlertView.swift
1
2368
// // BannerAlertView.swift // iOSTools // // Created by Vladas Zakrevskis on 11/22/17. // Copyright © 2017 VladasZ. All rights reserved. // #if os(iOS) import UIKit public class BannerAlertView : UIView { @IBOutlet private var messageLabel: UILabel! private static weak var currentBanner: BannerAlertView? private static weak var currentView: UIView? public static var color: UIColor = UIColor.white public static var textColor: UIColor = UIColor.black public static var font: UIFont = UIFont.systemFont(ofSize: 15) public static var height: CGFloat = 50 public static var customise: ((BannerAlertView) -> ())? public static func show(_ message: String, inView view: UIView) { if let currentBanner = currentBanner, currentView === view { currentBanner.messageLabel.text = message return } guard let banner = UINib(nibName: "BannerAlertView", bundle: Bundle(for: self)).instantiate(withOwner: nil, options: nil)[0] as? BannerAlertView else { return } banner.backgroundColor = color banner.messageLabel.textColor = textColor banner.messageLabel.text = message customise?(banner) banner.frame = CGRect(x: 0, y: -height, width: view.frame.width, height: height) view.addSubview(banner) currentBanner = banner currentView = view UIView.animate(withDuration: 0.211) { banner.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: height) } } public static func dismiss() { guard let banner = currentBanner, let view = currentView else { return } UIView.animate(withDuration: 0.211, animations: { banner.frame = CGRect(x: 0, y: -height, width: view.frame.width, height: height) }, completion: { _ in banner.removeFromSuperview() currentBanner = nil currentView = nil }) } } #endif
mit
b062b93b2e48aac95000caab49f385d5
30.144737
159
0.537389
5.101293
false
false
false
false
michael-lehew/swift-corelibs-foundation
Foundation/NSPathUtilities.swift
1
23793
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) || CYGWIN import Glibc #endif public func NSTemporaryDirectory() -> String { #if os(OSX) || os(iOS) var buf = [Int8](repeating: 0, count: 100) let r = confstr(_CS_DARWIN_USER_TEMP_DIR, &buf, buf.count) if r != 0 && r < buf.count { return String(cString: buf, encoding: .utf8)! } #endif if let tmpdir = ProcessInfo.processInfo.environment["TMPDIR"] { if !tmpdir.hasSuffix("/") { return tmpdir + "/" } else { return tmpdir } } return "/tmp/" } internal extension String { internal var _startOfLastPathComponent : String.CharacterView.Index { precondition(!hasSuffix("/") && length > 1) let characterView = characters let startPos = characterView.startIndex let endPos = characterView.endIndex var curPos = endPos // Find the beginning of the component while curPos > startPos { let prevPos = characterView.index(before: curPos) if characterView[prevPos] == "/" { break } curPos = prevPos } return curPos } internal var _startOfPathExtension : String.CharacterView.Index? { precondition(!hasSuffix("/")) let characterView = self.characters let endPos = characterView.endIndex var curPos = endPos let lastCompStartPos = _startOfLastPathComponent // Find the beginning of the extension while curPos > lastCompStartPos { let prevPos = characterView.index(before: curPos) let char = characterView[prevPos] if char == "/" { return nil } else if char == "." { if lastCompStartPos == prevPos { return nil } else { return curPos } } curPos = prevPos } return nil } internal var absolutePath: Bool { return hasPrefix("~") || hasPrefix("/") } internal func _stringByAppendingPathComponent(_ str: String, doneAppending : Bool = true) -> String { if str.length == 0 { return self } if self == "" { return "/" + str } if self == "/" { return self + str } return self + "/" + str } internal func _stringByFixingSlashes(compress : Bool = true, stripTrailing: Bool = true) -> String { var result = self if compress { result.withMutableCharacters { characterView in let startPos = characterView.startIndex var endPos = characterView.endIndex var curPos = startPos while curPos < endPos { if characterView[curPos] == "/" { var afterLastSlashPos = curPos while afterLastSlashPos < endPos && characterView[afterLastSlashPos] == "/" { afterLastSlashPos = characterView.index(after: afterLastSlashPos) } if afterLastSlashPos != characterView.index(after: curPos) { characterView.replaceSubrange(curPos ..< afterLastSlashPos, with: ["/"]) endPos = characterView.endIndex } curPos = afterLastSlashPos } else { curPos = characterView.index(after: curPos) } } } } if stripTrailing && result.length > 1 && result.hasSuffix("/") { result.remove(at: result.characters.index(before: result.characters.endIndex)) } return result } internal func _stringByRemovingPrefix(_ prefix: String) -> String { guard hasPrefix(prefix) else { return self } var temp = self temp.removeSubrange(startIndex..<prefix.endIndex) return temp } internal func _tryToRemovePathPrefix(_ prefix: String) -> String? { guard self != prefix else { return nil } let temp = _stringByRemovingPrefix(prefix) if FileManager.default.fileExists(atPath: temp) { return temp } return nil } } public extension NSString { public var absolutePath: Bool { return hasPrefix("~") || hasPrefix("/") } public static func pathWithComponents(_ components: [String]) -> String { var result = "" for comp in components.prefix(components.count - 1) { result = result._stringByAppendingPathComponent(comp._stringByFixingSlashes(), doneAppending: false) } if let last = components.last { result = result._stringByAppendingPathComponent(last._stringByFixingSlashes(), doneAppending: true) } return result } public var pathComponents : [String] { return _pathComponents(self._swiftObject)! } public var lastPathComponent : String { let fixedSelf = _stringByFixingSlashes() if fixedSelf.length <= 1 { return fixedSelf } return String(fixedSelf.characters.suffix(from: fixedSelf._startOfLastPathComponent)) } public var deletingLastPathComponent : String { let fixedSelf = _stringByFixingSlashes() if fixedSelf == "/" { return fixedSelf } switch fixedSelf._startOfLastPathComponent { // relative path, single component case fixedSelf.startIndex: return "" // absolute path, single component case fixedSelf.index(after: fixedSelf.startIndex): return "/" // all common cases case let startOfLast: return String(fixedSelf.characters.prefix(upTo: fixedSelf.index(before: startOfLast))) } } internal func _stringByFixingSlashes(compress : Bool = true, stripTrailing: Bool = true) -> String { if _swiftObject == "/" { return _swiftObject } var result = _swiftObject if compress { result.withMutableCharacters { characterView in let startPos = characterView.startIndex var endPos = characterView.endIndex var curPos = startPos while curPos < endPos { if characterView[curPos] == "/" { var afterLastSlashPos = curPos while afterLastSlashPos < endPos && characterView[afterLastSlashPos] == "/" { afterLastSlashPos = characterView.index(after: afterLastSlashPos) } if afterLastSlashPos != characterView.index(after: curPos) { characterView.replaceSubrange(curPos ..< afterLastSlashPos, with: ["/"]) endPos = characterView.endIndex } curPos = afterLastSlashPos } else { curPos = characterView.index(after: curPos) } } } } if stripTrailing && result.hasSuffix("/") { result.remove(at: result.characters.index(before: result.characters.endIndex)) } return result } internal func _stringByAppendingPathComponent(_ str: String, doneAppending : Bool = true) -> String { if str.length == 0 { return _swiftObject } if self == "" { return "/" + str } if self == "/" { return _swiftObject + str } return _swiftObject + "/" + str } public func appendingPathComponent(_ str: String) -> String { return _stringByAppendingPathComponent(str) } public var pathExtension : String { let fixedSelf = _stringByFixingSlashes() if fixedSelf.length <= 1 { return "" } if let extensionPos = fixedSelf._startOfPathExtension { return String(fixedSelf.characters.suffix(from: extensionPos)) } else { return "" } } public var deletingPathExtension: String { let fixedSelf = _stringByFixingSlashes() if fixedSelf.length <= 1 { return fixedSelf } if let extensionPos = (fixedSelf._startOfPathExtension) { return String(fixedSelf.characters.prefix(upTo: fixedSelf.characters.index(before: extensionPos))) } else { return fixedSelf } } public func appendingPathExtension(_ str: String) -> String? { if str.hasPrefix("/") || self == "" || self == "/" { print("Cannot append extension \(str) to path \(self)") return nil } let result = _swiftObject._stringByFixingSlashes(compress: false, stripTrailing: true) + "." + str return result._stringByFixingSlashes() } public var expandingTildeInPath: String { guard hasPrefix("~") else { return _swiftObject } let endOfUserName = _swiftObject.characters.index(of: "/") ?? _swiftObject.endIndex let startOfUserName = _swiftObject.characters.index(after: _swiftObject.characters.startIndex) let userName = String(_swiftObject.characters[startOfUserName..<endOfUserName]) let optUserName: String? = userName.isEmpty ? nil : userName guard let homeDir = NSHomeDirectoryForUser(optUserName) else { return _swiftObject._stringByFixingSlashes(compress: false, stripTrailing: true) } var result = _swiftObject result.replaceSubrange(_swiftObject.startIndex..<endOfUserName, with: homeDir) result = result._stringByFixingSlashes(compress: false, stripTrailing: true) return result } public var standardizingPath: String { let expanded = expandingTildeInPath var resolved = expanded._bridgeToObjectiveC().resolvingSymlinksInPath let automount = "/var/automount" resolved = resolved._tryToRemovePathPrefix(automount) ?? resolved return resolved } public var resolvingSymlinksInPath: String { var components = pathComponents guard !components.isEmpty else { return _swiftObject } // TODO: pathComponents keeps final path separator if any. Check that logic. if components.last == "/" { components.removeLast() } let isAbsolutePath = components.first == "/" var resolvedPath = components.removeFirst() for component in components { switch component { case "", ".": break case ".." where isAbsolutePath: resolvedPath = resolvedPath._bridgeToObjectiveC().deletingLastPathComponent default: resolvedPath = resolvedPath._bridgeToObjectiveC().appendingPathComponent(component) if let destination = FileManager.default._tryToResolveTrailingSymlinkInPath(resolvedPath) { resolvedPath = destination } } } let privatePrefix = "/private" resolvedPath = resolvedPath._tryToRemovePathPrefix(privatePrefix) ?? resolvedPath return resolvedPath } public func stringsByAppendingPaths(_ paths: [String]) -> [String] { if self == "" { return paths } return paths.map(appendingPathComponent) } /// - Experiment: This is a draft API currently under consideration for official import into Foundation /// - Note: Since this API is under consideration it may be either removed or revised in the near future public func completePath(into outputName: inout String?, caseSensitive flag: Bool, matchesInto outputArray: inout [String], filterTypes: [String]?) -> Int { let path = _swiftObject guard !path.isEmpty else { return 0 } let url = URL(fileURLWithPath: path) let searchAllFilesInDirectory = _stringIsPathToDirectory(path) let namePrefix = searchAllFilesInDirectory ? "" : url.lastPathComponent let checkFileName = _getFileNamePredicate(namePrefix, caseSensitive: flag) let checkExtension = _getExtensionPredicate(filterTypes, caseSensitive: flag) let resolvedURL: URL = url.resolvingSymlinksInPath() let urlWhereToSearch: URL = searchAllFilesInDirectory ? resolvedURL : resolvedURL.deletingLastPathComponent() var matches = _getNamesAtURL(urlWhereToSearch, prependWith: "", namePredicate: checkFileName, typePredicate: checkExtension) if matches.count == 1 { let theOnlyFoundItem = URL(fileURLWithPath: matches[0], relativeTo: urlWhereToSearch) if theOnlyFoundItem.hasDirectoryPath { matches = _getNamesAtURL(theOnlyFoundItem, prependWith: matches[0], namePredicate: { _ in true }, typePredicate: checkExtension) } } let commonPath = searchAllFilesInDirectory ? path : _ensureLastPathSeparator(deletingLastPathComponent) if searchAllFilesInDirectory { outputName = "/" } else { if let lcp = _longestCommonPrefix(matches, caseSensitive: flag) { outputName = (commonPath + lcp) } } outputArray = matches.map({ (commonPath + $0) }) return matches.count } internal func _stringIsPathToDirectory(_ path: String) -> Bool { if !path.hasSuffix("/") { return false } var isDirectory = false let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) return exists && isDirectory } internal typealias _FileNamePredicate = (String?) -> Bool internal func _getNamesAtURL(_ filePathURL: URL, prependWith: String, namePredicate: _FileNamePredicate, typePredicate: _FileNamePredicate) -> [String] { var result: [String] = [] if let enumerator = FileManager.default.enumerator(at: filePathURL, includingPropertiesForKeys: nil, options: .skipsSubdirectoryDescendants, errorHandler: nil) { for item in enumerator.lazy.map({ $0 as! URL }) { let itemName = item.lastPathComponent let matchByName = namePredicate(itemName) let matchByExtension = typePredicate(item.pathExtension) if matchByName && matchByExtension { if prependWith.isEmpty { result.append(itemName) } else { result.append(prependWith._bridgeToObjectiveC().appendingPathComponent(itemName)) } } } } return result } fileprivate func _getExtensionPredicate(_ extensions: [String]?, caseSensitive: Bool) -> _FileNamePredicate { guard let exts = extensions else { return { _ in true } } if caseSensitive { let set = Set(exts) return { $0 != nil && set.contains($0!) } } else { let set = Set(exts.map { $0.lowercased() }) return { $0 != nil && set.contains($0!.lowercased()) } } } fileprivate func _getFileNamePredicate(_ prefix: String, caseSensitive: Bool) -> _FileNamePredicate { guard !prefix.isEmpty else { return { _ in true } } if caseSensitive { return { $0 != nil && $0!.hasPrefix(prefix) } } else { return { $0 != nil && $0!._bridgeToObjectiveC().range(of: prefix, options: .caseInsensitive).location == 0 } } } internal func _longestCommonPrefix(_ strings: [String], caseSensitive: Bool) -> String? { guard strings.count > 0 else { return nil } guard strings.count > 1 else { return strings.first } var sequences = strings.map({ $0.characters.makeIterator() }) var prefix: [Character] = [] loop: while true { var char: Character? = nil for (idx, s) in sequences.enumerated() { var seq = s guard let c = seq.next() else { break loop } if char != nil { let lhs = caseSensitive ? char : String(char!).lowercased().characters.first! let rhs = caseSensitive ? c : String(c).lowercased().characters.first! if lhs != rhs { break loop } } else { char = c } sequences[idx] = seq } prefix.append(char!) } return String(prefix) } internal func _ensureLastPathSeparator(_ path: String) -> String { if path.hasSuffix("/") || path.isEmpty { return path } return path + "/" } public var fileSystemRepresentation : UnsafePointer<Int8> { NSUnimplemented() } public func getFileSystemRepresentation(_ cname: UnsafeMutablePointer<Int8>, maxLength max: Int) -> Bool { guard self.length > 0 else { return false } return CFStringGetFileSystemRepresentation(self._cfObject, cname, max) } } extension FileManager { public enum SearchPathDirectory: UInt { case applicationDirectory // supported applications (Applications) case demoApplicationDirectory // unsupported applications, demonstration versions (Demos) case developerApplicationDirectory // developer applications (Developer/Applications). DEPRECATED - there is no one single Developer directory. case adminApplicationDirectory // system and network administration applications (Administration) case libraryDirectory // various documentation, support, and configuration files, resources (Library) case developerDirectory // developer resources (Developer) DEPRECATED - there is no one single Developer directory. case userDirectory // user home directories (Users) case documentationDirectory // documentation (Documentation) case documentDirectory // documents (Documents) case coreServiceDirectory // location of CoreServices directory (System/Library/CoreServices) case autosavedInformationDirectory // location of autosaved documents (Documents/Autosaved) case desktopDirectory // location of user's desktop case cachesDirectory // location of discardable cache files (Library/Caches) case applicationSupportDirectory // location of application support files (plug-ins, etc) (Library/Application Support) case downloadsDirectory // location of the user's "Downloads" directory case inputMethodsDirectory // input methods (Library/Input Methods) case moviesDirectory // location of user's Movies directory (~/Movies) case musicDirectory // location of user's Music directory (~/Music) case picturesDirectory // location of user's Pictures directory (~/Pictures) case printerDescriptionDirectory // location of system's PPDs directory (Library/Printers/PPDs) case sharedPublicDirectory // location of user's Public sharing directory (~/Public) case preferencePanesDirectory // location of the PreferencePanes directory for use with System Preferences (Library/PreferencePanes) case applicationScriptsDirectory // location of the user scripts folder for the calling application (~/Library/Application Scripts/code-signing-id) case itemReplacementDirectory // For use with NSFileManager's URLForDirectory:inDomain:appropriateForURL:create:error: case allApplicationsDirectory // all directories where applications can occur case allLibrariesDirectory // all directories where resources can occur case trashDirectory // location of Trash directory } public struct SearchPathDomainMask: OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let userDomainMask = SearchPathDomainMask(rawValue: 1) // user's home directory --- place to install user's personal items (~) public static let localDomainMask = SearchPathDomainMask(rawValue: 2) // local to the current machine --- place to install items available to everyone on this machine (/Library) public static let networkDomainMask = SearchPathDomainMask(rawValue: 4) // publically available location in the local area network --- place to install items available on the network (/Network) public static let systemDomainMask = SearchPathDomainMask(rawValue: 8) // provided by Apple, unmodifiable (/System) public static let allDomainsMask = SearchPathDomainMask(rawValue: 0x0ffff) // all domains: all of the above and future items } } public func NSSearchPathForDirectoriesInDomains(_ directory: FileManager.SearchPathDirectory, _ domainMask: FileManager.SearchPathDomainMask, _ expandTilde: Bool) -> [String] { NSUnimplemented() } public func NSHomeDirectory() -> String { return NSHomeDirectoryForUser(nil)! } public func NSHomeDirectoryForUser(_ user: String?) -> String? { let userName = user?._cfObject guard let homeDir = CFCopyHomeDirectoryURLForUser(userName)?.takeRetainedValue() else { return nil } let url: URL = homeDir._swiftObject return url.path } public func NSUserName() -> String { let userName = CFCopyUserName().takeRetainedValue() return userName._swiftObject } internal func _NSCreateTemporaryFile(_ filePath: String) throws -> (Int32, String) { let template = "." + filePath + ".tmp.XXXXXX" let maxLength = Int(PATH_MAX) + 1 var buf = [Int8](repeating: 0, count: maxLength) let _ = template._nsObject.getFileSystemRepresentation(&buf, maxLength: maxLength) let fd = mkstemp(&buf) if fd == -1 { throw _NSErrorWithErrno(errno, reading: false, path: filePath) } let pathResult = FileManager.default.string(withFileSystemRepresentation: buf, length: Int(strlen(buf))) return (fd, pathResult) } internal func _NSCleanupTemporaryFile(_ auxFilePath: String, _ filePath: String) throws { if rename(auxFilePath, filePath) != 0 { do { try FileManager.default.removeItem(atPath: auxFilePath) } catch _ { } throw _NSErrorWithErrno(errno, reading: false, path: filePath) } }
apache-2.0
fc3aa8312e3cc94397c8295767b1879f
37.375806
201
0.593914
5.524263
false
false
false
false
mrchenhao/Cheater
Cheater/Cheater/StubRequest.swift
1
780
// // StuRequest.swift // Cheater // // Created by ChenHao on 16/3/26. // Copyright © 2016年 HarriesChen. All rights reserved. // import Foundation class StubRequest { var method: String var url: String var response: StubResponse = StubResponse() init(method: String, url: String) { self.method = method self.url = url } func setHeader(key: String, value: String) { response.headers[key] = value } func matchRequest(request: requestProtocol) -> Bool { if matchMethod(request) { return true } return false } func matchMethod(request: requestProtocol) -> Bool { if self.method == request.method { return true } return false } }
mit
bbe46829e67354b3e94cb052d000cdfc
18.425
57
0.589447
3.964286
false
false
false
false
ishaan1995/susi_iOS
Susi/MainViewController.swift
1
23356
// // MainViewController.swift // Susi // // Created by Chashmeet Singh on 2017-03-13. // Copyright © 2017 FOSSAsia. All rights reserved. // import UIKit import Material import Popover import ALTextInputBar import CoreLocation class MainViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, ALTextInputBarDelegate, CLLocationManagerDelegate, UIImagePickerControllerDelegate { let cellId = "cellId", userDefaultsWallpaperKey = "wallpaper" var messages: [Message] = [] fileprivate var popover: Popover! private var popoverOptions: [PopoverOption] = [ .type(.down), .blackOverlayColor(UIColor(white: 0.0, alpha: 0.6)), .arrowSize(CGSize(width: 12.0, height: 10.0)) ] let popoverText = ["Settings", "Wallpaper", "Share", "Logout"] // Search Button Configure let searchButton: IconButton = { let ib = IconButton() ib.image = Icon.cm.search ib.tintColor = .white return ib }() // Settings Button Configure lazy var settingsButton: IconButton = { let image = Icon.cm.moreVertical let ib = IconButton() ib.image = image ib.addTarget(self, action: #selector(showSettingsView), for: .touchUpInside) ib.tintColor = .white return ib }() // Location Manager var locationManager = CLLocationManager() // Image Picker Controller var imagePicker = UIImagePickerController() let blackView = UIView() // Youtube Player lazy var youtubePlayer: YouTubePlayerView = { let frame = CGRect(x: 0, y: 0, width: self.view.frame.width - 16, height: self.view.frame.height * 1 / 3) let player = YouTubePlayerView(frame: frame) return player }() override func viewDidLoad() { super.viewDidLoad() setupTitle() setupView() setupCollectionView() setupInputComponents() // Dismiss keyboard when touched anywhere in CV view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.resignResponders))) subscribeToKeyboardNotifications() // Configure Location Manager configureLocationManager() } func subscribeToKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func handleKeyboardNotification(notification: NSNotification) { if let userInfo = notification.userInfo { let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue let isKeyboardShowing = notification.name == NSNotification.Name.UIKeyboardWillShow bottomConstraint?.constant = isKeyboardShowing ? -keyboardFrame!.height : 0 UIView.animate(withDuration: 0, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.view.layoutIfNeeded() }, completion: { (_) in if isKeyboardShowing { self.scrollToLast() } }) } } // Resign responders func resignResponders() { self.view.endEditing(true) } // Configures Location Manager func configureLocationManager() { locationManager.delegate = self if CLLocationManager.authorizationStatus() == .notDetermined || CLLocationManager.authorizationStatus() == .denied { self.locationManager.requestWhenInUseAuthorization() } locationManager.distanceFilter = kCLDistanceFilterNone locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.startUpdatingLocation() } // Setup Navigation Bar func setupTitle() { navigationItem.title = " Susi" navigationItem.titleLabel.textAlignment = .left navigationItem.titleLabel.textColor = .white navigationItem.rightViews = [searchButton, settingsButton] } // Setup View func setupView() { self.view.backgroundColor = UIColor.rgb(red: 236, green: 229, blue: 221) } // Setup Settings View func showSettingsView() { let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: Int(self.view.frame.width / 2), height: (popoverText.count * 44))) tableView.delegate = self tableView.dataSource = self tableView.isScrollEnabled = false self.popover = Popover(options: self.popoverOptions) self.popover.show(tableView, fromView: settingsButton) } // Shows Youtube Player func addYotubePlayer(_ videoID: String) { if let window = UIApplication.shared.keyWindow { blackView.frame = window.frame self.view.addSubview(blackView) blackView.backgroundColor = UIColor(white: 0, alpha: 0.5) blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss))) self.blackView.addSubview(self.youtubePlayer) let centerX = UIScreen.main.bounds.size.width / 2 let centerY = UIScreen.main.bounds.size.height / 3 self.youtubePlayer.center = CGPoint(x: centerX, y: centerY) self.youtubePlayer.loadVideoID(videoID) blackView.alpha = 0 youtubePlayer.alpha = 0 UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { self.blackView.alpha = 1 self.youtubePlayer.alpha = 1 }, completion: nil) } } func handleDismiss() { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { self.blackView.removeFromSuperview() }, completion: nil) } // Setup Collection View func setupCollectionView() { // Check if user defaults have an image, set background as image if let userDefaultData = getWallpaperFromUserDefaults() { if let imageData = userDefaultData as? Data { // Check if object saved in user defaults if of type Data setBackgroundImage(image: UIImage(data : imageData)) } } collectionView?.backgroundColor = .clear collectionView?.delegate = self collectionView?.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height - 45) collectionView?.register(ChatMessageCell.self, forCellWithReuseIdentifier: cellId) } // Number of items override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //print("Number of messages: \(messages.count)") return messages.count } // Configure Cell override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var message = messages[indexPath.row] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ChatMessageCell cell.message = message if let messageText = message.body { // Incoming message let size = CGSize(width: 250, height: 1000) let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin) let estimatedFrame = NSString(string: messageText).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 18)], context: nil) if message.isBot { cell.bubbleImageView.image = ChatMessageCell.grayBubbleImage cell.bubbleImageView.tintColor = .white cell.messageTextView.textColor = UIColor.black // Check if Map Type if message.responseType == Message.ResponseTypes.map { cell.messageTextView.frame = CGRect(x: 16, y: 0, width: estimatedFrame.width + 16, height: estimatedFrame.height + 30) cell.textBubbleView.frame = CGRect(x: 4, y: -4, width: estimatedFrame.width + 16 + 8 + 16, height: estimatedFrame.height + 20 + 6 + 250) let frame = CGRect(x: 16, y: estimatedFrame.height + 30 + 4, width: estimatedFrame.width + 16 - 4, height: 250 - 24) cell.addMapView(frame) } else if message.responseType == Message.ResponseTypes.websearch { let params = [ Client.WebsearchKeys.Query: message.query!, Client.WebsearchKeys.Format: "json" ] Client.sharedInstance.websearch(params as [String : AnyObject], { (results, success, error) in DispatchQueue.main.async { if success { cell.message?.websearchData = results message.websearchData = results cell.messageTextView.frame = CGRect(x: 16, y: 0, width: estimatedFrame.width + 16, height: estimatedFrame.height + 30) cell.textBubbleView.frame = CGRect(x: 4, y: -4, width: estimatedFrame.width + 16 + 8 + 16, height: estimatedFrame.height + 20 + 6 + 64) let frame = CGRect(x: 16, y: estimatedFrame.height + 20, width: estimatedFrame.width + 16 - 4, height: 60 - 8) cell.addLinkPreview(frame) } else { print(error) } } }) } else { cell.messageTextView.frame = CGRect(x: 16, y: 0, width: estimatedFrame.width + 16, height: estimatedFrame.height + 30) cell.textBubbleView.frame = CGRect(x: 4, y: -4, width: estimatedFrame.width + 16 + 8 + 16, height: estimatedFrame.height + 20 + 6) cell.mapView.removeFromSuperview() cell.websearchContentView.removeFromSuperview() } } else { //outgoing message cell.messageTextView.frame = CGRect(x: view.frame.width - estimatedFrame.width - 16 - 16, y: 0, width: estimatedFrame.width + 16, height: estimatedFrame.height + 20) cell.textBubbleView.frame = CGRect(x:view.frame.width - estimatedFrame.width - 16 - 8 - 16, y: -4, width: estimatedFrame.width + 16 + 8 + 10, height: estimatedFrame.height + 20 + 6) cell.bubbleImageView.image = ChatMessageCell.blueBubbleImage cell.bubbleImageView.tintColor = UIColor.rgb(red: 220, green: 248, blue: 198) cell.messageTextView.textColor = .black cell.mapView.removeFromSuperview() } } return cell } // Calculate Bubble Height func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let message = messages[indexPath.row] if let messageText = message.body { let size = CGSize(width: 250, height: 1000) let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin) let estimatedFrame = NSString(string: messageText).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 18)], context: nil) if message.responseType == Message.ResponseTypes.map { return CGSize(width: view.frame.width, height: estimatedFrame.height + 20 + 250) } else if message.responseType == Message.ResponseTypes.websearch { return CGSize(width: view.frame.width, height: estimatedFrame.height + 20 + 64) } return CGSize(width: view.frame.width, height: estimatedFrame.height + 20) } return CGSize(width: view.frame.width, height: 100) } // Set Edge Insets func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0) } // Setup Message Container let messageInputContainerView: UIView = { let view = UIView() view.backgroundColor = UIColor.white return view }() // Setup Input Text Field lazy var inputTextField: ALTextInputBar = { let textField = ALTextInputBar() textField.textView.placeholder = "Ask Susi Something..." textField.textView.font = UIFont.systemFont(ofSize: 17) textField.backgroundColor = .clear textField.textView.maxNumberOfLines = 2 textField.delegate = self return textField }() // Setup Send Button lazy var sendButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Send", for: .normal) let titleColor = UIColor(red: 0, green: 137/255, blue: 249/255, alpha: 1) button.setTitleColor(titleColor, for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16) button.addTarget(self, action: #selector(handleSend), for: .touchUpInside) return button }() // Send Button Action func handleSend() { if let text = inputTextField.text { if text.contains("play") || text.contains("Play") { let query = text.replacingOccurrences(of: "play ", with: "").replacingOccurrences(of: "Play", with: "") Client.sharedInstance.searchYotubeVideos(query) { (result, _, _) in DispatchQueue.main.async { if let result = result { self.addYotubePlayer(result) } } } } else { var params: [String : AnyObject] = [ Client.WebsearchKeys.Query: inputTextField.text! as AnyObject, Client.ChatKeys.TimeZoneOffset: "-530" as AnyObject, Client.ChatKeys.Language: Locale.current.languageCode as AnyObject ] if let location = locationManager.location { params[Client.ChatKeys.Latitude] = location.coordinate.latitude as AnyObject params[Client.ChatKeys.Longitude] = location.coordinate.longitude as AnyObject } Client.sharedInstance.queryResponse(params) { (results, success, _) in DispatchQueue.main.async { if success { self.messages.append(results!) } self.collectionView?.reloadData() self.scrollToLast() } } } } saveMessage() } var bottomConstraint: NSLayoutConstraint? // Setup Input Components private func setupInputComponents() { view.addSubview(messageInputContainerView) view.addConstraintsWithFormat(format: "H:|[v0]|", views: messageInputContainerView) view.addConstraintsWithFormat(format: "V:[v0(48)]", views: messageInputContainerView) bottomConstraint = NSLayoutConstraint(item: messageInputContainerView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0) view.addConstraint(bottomConstraint!) let topBorderView = UIView() topBorderView.backgroundColor = UIColor(white: 0.5, alpha: 0.5) messageInputContainerView.addSubview(inputTextField) messageInputContainerView.addSubview(sendButton) messageInputContainerView.addSubview(topBorderView) messageInputContainerView.addConstraintsWithFormat(format: "H:|-8-[v0][v1(60)]|", views: inputTextField, sendButton) messageInputContainerView.addConstraintsWithFormat(format: "V:|[v0]|", views: inputTextField) messageInputContainerView.addConstraintsWithFormat(format: "V:|[v0]|", views: sendButton) messageInputContainerView.addConstraintsWithFormat(format: "H:|[v0]|", views: topBorderView) messageInputContainerView.addConstraintsWithFormat(format: "V:|[v0(0.5)]", views: topBorderView) } // Temporarily save message to object func saveMessage() { let message = Message(inputTextField.text!) messages.append(message) collectionView?.reloadData() self.scrollToLast() inputTextField.text = "" } // Scroll to last message func scrollToLast() { if messages.count > 0 { let lastItem = self.messages.count - 1 let indexPath = IndexPath(item: lastItem, section: 0) self.collectionView?.scrollToItem(at: indexPath, at: .top, animated: true) } } // Check if chat field empty func textViewDidChange(textView: ALTextView) { if let message = inputTextField.text, message.isEmpty { sendButton.isUserInteractionEnabled = false } else { sendButton.isUserInteractionEnabled = true } } // Show image picker to set/reset wallpaper func showImagePicker() { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum) { imagePicker.allowsEditing = false imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum self.present(imagePicker, animated: true, completion: nil) } else { // Show error dialog if no photo is available in photo album let errorDialog = UIAlertController(title: ControllerConstants.errorDialogTitle, message: ControllerConstants.errorDialogMessage, preferredStyle: UIAlertControllerStyle.alert) errorDialog.addAction(UIAlertAction(title: ControllerConstants.dialogCancelAction, style: .cancel, handler: { (_: UIAlertAction!) in errorDialog.dismiss(animated: true, completion: nil) })) self.present(errorDialog, animated: true, completion: nil) } } // Set chat background image func setBackgroundImage(image: UIImage!) { let bgView = UIImageView() bgView.contentMode = .scaleAspectFill bgView.image = image self.collectionView?.backgroundView = bgView } // Clear chat background image func clearBackgroundImage() { self.collectionView?.backgroundView = nil } // Save image selected by user to user defaults func saveWallpaperInUserDefaults(image: UIImage!) { let imageData = UIImageJPEGRepresentation(image!, 1.0) let defaults = UserDefaults.standard defaults.set(imageData, forKey: userDefaultsWallpaperKey) } // Check if user defaults have an image data saved else return nil/Any func getWallpaperFromUserDefaults() -> Any? { let defaults = UserDefaults.standard return defaults.object(forKey: userDefaultsWallpaperKey) } // Remove wallpaper from user defaults func removeWallpaperFromUserDefaults() { let defaults = UserDefaults.standard defaults.removeObject(forKey: userDefaultsWallpaperKey) clearBackgroundImage() } // Callback when image is selected from gallery func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { dismiss(animated: true, completion: nil) let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage if let image = chosenImage { setBackgroundImage(image: image) saveWallpaperInUserDefaults(image: image) } } // Callback if cancel selected from picker func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } // Show wallpaper options to set wallpaper or clear wallpaper func showWallpaperOptions() { let imageDialog = UIAlertController(title: ControllerConstants.wallpaperOptionsTitle, message: nil, preferredStyle: UIAlertControllerStyle.alert) imageDialog.addAction(UIAlertAction(title: ControllerConstants.wallpaperOptionsPickAction, style: .default, handler: { (_: UIAlertAction!) in imageDialog.dismiss(animated: true, completion: nil) self.showImagePicker() })) imageDialog.addAction(UIAlertAction(title: ControllerConstants.wallpaperOptionsNoWallpaperAction, style: .default, handler: { (_: UIAlertAction!) in imageDialog.dismiss(animated: true, completion: nil) self.removeWallpaperFromUserDefaults() })) imageDialog.addAction(UIAlertAction(title: ControllerConstants.dialogCancelAction, style: .cancel, handler: { (_: UIAlertAction!) in imageDialog.dismiss(animated: true, completion: nil) })) self.present(imageDialog, animated: true, completion: nil) } } extension MainViewController: UITableViewDelegate { // Enum for menu options in main chat screen enum MenuOptions: Int { case setttings = 0 case wallpaper = 1 case share = 2 case logout = 3 } // Handles item click func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.popover.dismiss() let index = indexPath.row switch index { case MenuOptions.setttings.rawValue: let settingsController = SettingsViewController(collectionViewLayout: UICollectionViewFlowLayout()) self.navigationController?.pushViewController(settingsController, animated: true) break case MenuOptions.wallpaper.rawValue: showWallpaperOptions() break case MenuOptions.logout.rawValue: logoutUser() break default: break } } func logoutUser() { Client.sharedInstance.logoutUser { (success, error) in DispatchQueue.main.async { if success { self.dismiss(animated: true, completion: nil) } else { print(error) } } } } } extension MainViewController: UITableViewDataSource { // Number of options in popover func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return popoverText.count } // Configure setting cell func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: nil) let item = self.popoverText[indexPath.row] cell.textLabel?.text = item cell.imageView?.image = UIImage(named: item.lowercased()) return cell } }
apache-2.0
5c1ed01ed858e3f19a030e4536a6dd67
39.197935
197
0.636309
5.217828
false
false
false
false
naokits/my-programming-marathon
RxSwiftDemo/Carthage/Checkouts/RxSwift/RxExample/RxDataSourceStarterKit/Differentiator.swift
6
18438
// // Differentiator.swift // RxExample // // Created by Krunoslav Zaher on 6/27/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation public enum DifferentiatorError : ErrorType , CustomDebugStringConvertible { case DuplicateItem(item: Any) } extension DifferentiatorError { public var debugDescription: String { switch self { case let .DuplicateItem(item): return "Duplicate item \(item)" } } } enum EditEvent : CustomDebugStringConvertible { case Inserted // can't be found in old sections case Deleted // Was in old, not in new, in it's place is something "not new" :(, otherwise it's Updated case Moved // same item, but was on different index, and needs explicit move case MovedAutomatically // don't need to specify any changes for those rows case Untouched } extension EditEvent { var debugDescription: String { get { switch self { case .Inserted: return "Inserted" case .Deleted: return "Deleted" case .Moved: return "Moved" case .MovedAutomatically: return "MovedAutomatically" case .Untouched: return "Untouched" } } } } struct SectionAdditionalInfo : CustomDebugStringConvertible { var event: EditEvent var indexAfterDelete: Int? } extension SectionAdditionalInfo { var debugDescription: String { get { return "\(event), \(indexAfterDelete)" } } } struct ItemAdditionalInfo : CustomDebugStringConvertible { var event: EditEvent var indexAfterDelete: Int? } extension ItemAdditionalInfo { var debugDescription: String { get { return "\(event) \(indexAfterDelete)" } } } func indexSections<S: SectionModelType where S: Hashable, S.Item: Hashable>(sections: [S]) throws -> [S : Int] { var indexedSections: [S : Int] = [:] for (i, section) in sections.enumerate() { guard indexedSections[section] == nil else { #if DEBUG precondition(indexedSections[section] == nil, "Section \(section) has already been indexed at \(indexedSections[section]!)") #endif throw DifferentiatorError.DuplicateItem(item: section) } indexedSections[section] = i } return indexedSections } func indexSectionItems<S: SectionModelType where S: Hashable, S.Item: Hashable>(sections: [S]) throws -> [S.Item : (Int, Int)] { var totalItems = 0 for i in 0 ..< sections.count { totalItems += sections[i].items.count } // let's make sure it's enough var indexedItems: [S.Item : (Int, Int)] = Dictionary(minimumCapacity: totalItems * 3) for i in 0 ..< sections.count { for (j, item) in sections[i].items.enumerate() { guard indexedItems[item] == nil else { #if DEBUG precondition(indexedItems[item] == nil, "Item \(item) has already been indexed at \(indexedItems[item]!)" ) #endif throw DifferentiatorError.DuplicateItem(item: item) } indexedItems[item] = (i, j) } } return indexedItems } /* I've uncovered this case during random stress testing of logic. This is the hardest generic update case that causes two passes, first delete, and then move/insert [ NumberSection(model: "1", items: [1111]), NumberSection(model: "2", items: [2222]), ] [ NumberSection(model: "2", items: [0]), NumberSection(model: "1", items: []), ] If update is in the form * Move section from 2 to 1 * Delete Items at paths 0 - 0, 1 - 0 * Insert Items at paths 0 - 0 or * Move section from 2 to 1 * Delete Items at paths 0 - 0 * Reload Items at paths 1 - 0 or * Move section from 2 to 1 * Delete Items at paths 0 - 0 * Reload Items at paths 0 - 0 it crashes table view. No matter what change is performed, it fails for me. If anyone knows how to make this work for one Changeset, PR is welcome. */ // If you are considering working out your own algorithm, these are tricky // transition cases that you can use. // case 1 /* from = [ NumberSection(model: "section 4", items: [10, 11, 12]), NumberSection(model: "section 9", items: [25, 26, 27]), ] to = [ HashableSectionModel(model: "section 9", items: [11, 26, 27]), HashableSectionModel(model: "section 4", items: [10, 12]) ] */ // case 2 /* from = [ HashableSectionModel(model: "section 10", items: [26]), HashableSectionModel(model: "section 7", items: [5, 29]), HashableSectionModel(model: "section 1", items: [14]), HashableSectionModel(model: "section 5", items: [16]), HashableSectionModel(model: "section 4", items: []), HashableSectionModel(model: "section 8", items: [3, 15, 19, 23]), HashableSectionModel(model: "section 3", items: [20]) ] to = [ HashableSectionModel(model: "section 10", items: [26]), HashableSectionModel(model: "section 1", items: [14]), HashableSectionModel(model: "section 9", items: [3]), HashableSectionModel(model: "section 5", items: [16, 8]), HashableSectionModel(model: "section 8", items: [15, 19, 23]), HashableSectionModel(model: "section 3", items: [20]), HashableSectionModel(model: "Section 2", items: [7]) ] */ // case 3 /* from = [ HashableSectionModel(model: "section 4", items: [5]), HashableSectionModel(model: "section 6", items: [20, 14]), HashableSectionModel(model: "section 9", items: []), HashableSectionModel(model: "section 2", items: [2, 26]), HashableSectionModel(model: "section 8", items: [23]), HashableSectionModel(model: "section 10", items: [8, 18, 13]), HashableSectionModel(model: "section 1", items: [28, 25, 6, 11, 10, 29, 24, 7, 19]) ] to = [ HashableSectionModel(model: "section 4", items: [5]), HashableSectionModel(model: "section 6", items: [20, 14]), HashableSectionModel(model: "section 9", items: [16]), HashableSectionModel(model: "section 7", items: [17, 15, 4]), HashableSectionModel(model: "section 2", items: [2, 26, 23]), HashableSectionModel(model: "section 8", items: []), HashableSectionModel(model: "section 10", items: [8, 18, 13]), HashableSectionModel(model: "section 1", items: [28, 25, 6, 11, 10, 29, 24, 7, 19]) ] */ // Generates differential changes suitable for sectioned view consumption. // It will not only detect changes between two states, but it will also try to compress those changes into // almost minimal set of changes. // // I know, I know, it's ugly :( Totally agree, but this is the only general way I could find that works 100%, and // avoids UITableView quirks. // // Please take into consideration that I was also convinced about 20 times that I've found a simple general // solution, but then UITableView falls apart under stress testing :( // // Sincerely, if somebody else would present me this 250 lines of code, I would call him a mad man. I would think // that there has to be a simpler solution. Well, after 3 days, I'm not convinced any more :) // // Maybe it can be made somewhat simpler, but don't think it can be made much simpler. // // The algorithm could take anywhere from 1 to 3 table view transactions to finish the updates. // // * stage 1 - remove deleted sections and items // * stage 2 - move sections into place // * stage 3 - fix moved and new items // // There maybe exists a better division, but time will tell. // func differencesForSectionedView<S: SectionModelType where S: Hashable, S.Item: Hashable>( initialSections: [S], finalSections: [S] ) throws -> [Changeset<S>] { typealias I = S.Item var deletes = Changeset<S>() var newAndMovedSections = Changeset<S>() var newAndMovedItems = Changeset<S>() var initialSectionInfos = [SectionAdditionalInfo](count: initialSections.count, repeatedValue: SectionAdditionalInfo(event: .Untouched, indexAfterDelete: nil)) var finalSectionInfos = [SectionAdditionalInfo](count: finalSections.count, repeatedValue: SectionAdditionalInfo(event: .Untouched, indexAfterDelete: nil)) var initialSectionIndexes: [S : Int] = [:] var finalSectionIndexes: [S : Int] = [:] let defaultItemInfo = ItemAdditionalInfo(event: .Untouched, indexAfterDelete: nil) var initialItemInfos = initialSections.map { s in return [ItemAdditionalInfo](count: s.items.count, repeatedValue: defaultItemInfo) } var finalItemInfos = finalSections.map { s in return [ItemAdditionalInfo](count: s.items.count, repeatedValue: defaultItemInfo) } initialSectionIndexes = try indexSections(initialSections) finalSectionIndexes = try indexSections(finalSections) var initialItemIndexes: [I: (Int, Int)] = try indexSectionItems(initialSections) var finalItemIndexes: [I: (Int, Int)] = try indexSectionItems(finalSections) // mark deleted sections { // 1rst stage var sectionIndexAfterDelete = 0 for (i, initialSection) in initialSections.enumerate() { if finalSectionIndexes[initialSection] == nil { initialSectionInfos[i].event = .Deleted deletes.deletedSections.append(i) } else { initialSectionInfos[i].indexAfterDelete = sectionIndexAfterDelete sectionIndexAfterDelete += 1 } } deletes.deletedSections = deletes.deletedSections.reverse() // } var untouchedOldIndex: Int? = 0 let findNextUntouchedOldIndex = { (initialSearchIndex: Int?) -> Int? in var i = initialSearchIndex while i != nil && i < initialSections.count { if initialSectionInfos[i!].event == .Untouched { return i } i = i! + 1 } return nil } // inserted and moved sections { // this should fix all sections and move them into correct places // 2nd stage for (i, finalSection) in finalSections.enumerate() { untouchedOldIndex = findNextUntouchedOldIndex(untouchedOldIndex) // oh, it did exist if let oldSectionIndex = initialSectionIndexes[finalSection] { let moveType = oldSectionIndex != untouchedOldIndex ? EditEvent.Moved : EditEvent.MovedAutomatically finalSectionInfos[i].event = moveType initialSectionInfos[oldSectionIndex].event = moveType if moveType == .Moved { let moveCommand = (from: initialSectionInfos[oldSectionIndex].indexAfterDelete!, to: i) newAndMovedSections.movedSections.append(moveCommand) } } else { finalSectionInfos[i].event = .Inserted newAndMovedSections.insertedSections.append(i) } } // } // mark deleted items { // 1rst stage again (I know, I know ...) for (i, initialSection) in initialSections.enumerate() { let event = initialSectionInfos[i].event // Deleted section will take care of deleting child items. // In case of moving an item from deleted section, tableview will // crash anyway, so this is not limiting anything. if event == .Deleted { continue } var indexAfterDelete = 0 for (j, initialItem) in initialSection.items.enumerate() { if let finalItemIndex = finalItemIndexes[initialItem] { let targetSectionEvent = finalSectionInfos[finalItemIndex.0].event // In case there is move of item from existing section into new section // that is also considered a "delete" if targetSectionEvent == .Inserted { initialItemInfos[i][j].event = .Deleted deletes.deletedItems.append(ItemPath(sectionIndex: i, itemIndex: j)) continue } initialItemInfos[i][j].indexAfterDelete = indexAfterDelete indexAfterDelete += 1 } else { initialItemInfos[i][j].event = .Deleted deletes.deletedItems.append(ItemPath(sectionIndex: i, itemIndex: j)) } } } // } deletes.deletedItems = deletes.deletedItems.reverse() // mark new and moved items { // 3rd stage for (i, _) in finalSections.enumerate() { let finalSection = finalSections[i] let originalSection: Int? = initialSectionIndexes[finalSection] var untouchedOldIndex: Int? = 0 let findNextUntouchedOldIndex = { (initialSearchIndex: Int?) -> Int? in var i2 = initialSearchIndex while originalSection != nil && i2 != nil && i2! < initialItemInfos[originalSection!].count { if initialItemInfos[originalSection!][i2!].event == .Untouched { return i2 } i2 = i2! + 1 } return nil } let sectionEvent = finalSectionInfos[i].event // new and deleted sections cause reload automatically if sectionEvent != .Moved && sectionEvent != .MovedAutomatically { continue } for (j, finalItem) in finalSection.items.enumerate() { let currentItemEvent = finalItemInfos[i][j].event precondition(currentItemEvent == .Untouched) untouchedOldIndex = findNextUntouchedOldIndex(untouchedOldIndex) // ok, so it was moved from somewhere if let originalIndex = initialItemIndexes[finalItem] { // In case trying to move from deleted section, abort, otherwise it will crash table view if initialSectionInfos[originalIndex.0].event == .Deleted { finalItemInfos[i][j].event = .Inserted newAndMovedItems.insertedItems.append(ItemPath(sectionIndex: i, itemIndex: j)) } // original section can't be inserted else if initialSectionInfos[originalIndex.0].event == .Inserted { fatalError("New section in initial sections, that is wrong") } // what's left is moved section else { precondition(initialSectionInfos[originalIndex.0].event == .Moved || initialSectionInfos[originalIndex.0].event == .MovedAutomatically) let eventType = originalIndex.0 == (originalSection ?? -1) && originalIndex.1 == (untouchedOldIndex ?? -1) ? EditEvent.MovedAutomatically : EditEvent.Moved // print("\(finalItem) \(eventType) \(originalIndex), \(originalSection) \(untouchedOldIndex)") initialItemInfos[originalIndex.0][originalIndex.1].event = eventType finalItemInfos[i][j].event = eventType if eventType == .Moved { let finalSectionIndex = finalSectionIndexes[initialSections[originalIndex.0]]! let moveFromItemWithIndex = initialItemInfos[originalIndex.0][originalIndex.1].indexAfterDelete! let moveCommand = ( from: ItemPath(sectionIndex: finalSectionIndex, itemIndex: moveFromItemWithIndex), to: ItemPath(sectionIndex: i, itemIndex: j) ) newAndMovedItems.movedItems.append(moveCommand) } } } // if it wasn't moved from anywhere, it's inserted else { finalItemInfos[i][j].event = .Inserted newAndMovedItems.insertedItems.append(ItemPath(sectionIndex: i, itemIndex: j)) } } } // } var result: [Changeset<S>] = [] if deletes.deletedItems.count > 0 || deletes.deletedSections.count > 0 { deletes.finalSections = [] for (i, s) in initialSections.enumerate() { if initialSectionInfos[i].event == .Deleted { continue } var items: [I] = [] for (j, item) in s.items.enumerate() { if initialItemInfos[i][j].event != .Deleted { items.append(item) } } deletes.finalSections.append(S(original: s, items: items)) } result.append(deletes) } if newAndMovedSections.insertedSections.count > 0 || newAndMovedSections.movedSections.count > 0 || newAndMovedSections.updatedSections.count != 0 { // sections should be in place, but items should be original without deleted ones newAndMovedSections.finalSections = [] for (i, s) in finalSections.enumerate() { let event = finalSectionInfos[i].event if event == .Inserted { // it's already set up newAndMovedSections.finalSections.append(s) } else if event == .Moved || event == .MovedAutomatically { let originalSectionIndex = initialSectionIndexes[s]! let originalSection = initialSections[originalSectionIndex] var items: [I] = [] for (j, item) in originalSection.items.enumerate() { if initialItemInfos[originalSectionIndex][j].event != .Deleted { items.append(item) } } newAndMovedSections.finalSections.append(S(original: s, items: items)) } else { fatalError("This is weird, this shouldn't happen") } } result.append(newAndMovedSections) } newAndMovedItems.finalSections = finalSections result.append(newAndMovedItems) return result }
mit
dc10dc9201d8e622393227a095a201c5
35.222004
164
0.598742
4.715345
false
false
false
false
Kev1nChen/TicText
TicText-iOS/TicTextTests/TTExpirationPickerControllerTests.swift
1
17059
// // TTExpirationPickerControllerTests.swift // TicText // // Created by Terrence K on 3/16/15. // Copyright (c) 2015 Kevin Yufei Chen. All rights reserved. // import UIKit import XCTest class TTExpirationPickerControllerTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } func testInitWithExpirationTimeZero() { // Arrange/Act let pickerController = TTExpirationPickerController(expirationTime: 0) // Assert XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(0), 0, "bad selected hour") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(1), 0, "bad selected minute") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(2), 0, "bad selected second") XCTAssertEqual(pickerController.expirationTime, 0, "bad expiration time") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire instantly.", "bad previewLabel") } func testInitWithExpirationTimeSecondsOnly() { // Arrange/Act let pickerController = TTExpirationPickerController(expirationTime: 43) // Assert XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(0), 0, "bad selected hour") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(1), 0, "bad selected minute") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(2), 43, "bad selected second") XCTAssertEqual(pickerController.expirationTime, 43, "bad expiration time") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 43 seconds.", "bad previewLabel") } func testInitWithExpirationTimeMinutesOnly() { // Arrange/Act let pickerController = TTExpirationPickerController(expirationTime: 27 * 60) // Assert XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(0), 0, "bad selected hour") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(1), 27, "bad selected minute") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(2), 0, "bad selected second") XCTAssertEqual(pickerController.expirationTime, 27 * 60, "bad expiration time") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 27 minutes.", "bad previewLabel") } func testInitWithExpirationTimeHoursOnly() { // Arrange/Act let pickerController = TTExpirationPickerController(expirationTime: 17 * 60 * 60) // Assert XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(0), 17, "bad selected hour") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(1), 0, "bad selected minute") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(2), 0, "bad selected second") XCTAssertEqual(pickerController.expirationTime, 17 * 60 * 60, "bad expiration time") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 17 hours.", "bad previewLabel") } func testInitWithExpirationTimeSecondsMinutes() { // Arrange/Act let pickerController = TTExpirationPickerController(expirationTime: 45 * 60 + 49) // Assert XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(0), 0, "bad selected hour") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(1), 45, "bad selected minute") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(2), 49, "bad selected second") XCTAssertEqual(pickerController.expirationTime, 45 * 60 + 49, "bad expiration time") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 45 minutes and 49 seconds.", "bad previewLabel") } func testInitWithExpirationTimeHoursMinutes() { // Arrange/Act let pickerController = TTExpirationPickerController(expirationTime: 23 * 60 * 60 + 49 * 60) // Assert XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(0), 23, "bad selected hour") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(1), 49, "bad selected minute") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(2), 0, "bad selected second") XCTAssertEqual(pickerController.expirationTime, 23 * 60 * 60 + 49 * 60, "bad expiration time") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 23 hours and 49 minutes.", "bad previewLabel") } func testInitWithExpirationTimeHoursSeconds() { // Arrange/Act let pickerController = TTExpirationPickerController(expirationTime: 23 * 60 * 60 + 37) // Assert XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(0), 23, "bad selected hour") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(1), 0, "bad selected minute") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(2), 37, "bad selected second") XCTAssertEqual(pickerController.expirationTime, 23 * 60 * 60 + 37, "bad expiration time") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 23 hours and 37 seconds.", "bad previewLabel") } func testInitWithExpirationTimeMax() { // Arrange/Act let pickerController = TTExpirationPickerController(expirationTime: 23 * 60 * 60 + 59 * 60 + 59) // Assert XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(0), 23, "bad selected hour") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(1), 59, "bad selected minute") XCTAssertEqual(pickerController.pickerView.selectedRowInComponent(2), 59, "bad selected second") //XCTAssertEqual(pickerController.expirationTime, 23 * 60 * 60 + 59 * 60 + 59, "bad expiration time") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 23 hours, 59 minutes, and 59 seconds.", "bad previewLabel") } func testPresent() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 0) // Pre-Condition XCTAssertNil(pickerController.backgroundView, "backgroundView already exists?") // Act pickerController.present() // Assert XCTAssertNotNil(pickerController.backgroundView, "backgroundView not created") // Clean-up pickerController.dismiss() } func testSelectRowSecondsZeroOnly() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 43) // Act pickerController.pickerView(pickerController.pickerView, didSelectRow: 0, inComponent: 2) // Assert XCTAssertEqual(pickerController.expirationTime, 0, "bad expirationTime") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire instantly.", "bad previewLabel") } func testSelectRowSecondsNonZeroOnly() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 0) // Act pickerController.pickerView(pickerController.pickerView, didSelectRow: 43, inComponent: 2) // Assert XCTAssertEqual(pickerController.expirationTime, 43, "bad expirationTime") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 43 seconds.", "bad previewLabel") } func testSelectRowSecondsMaxValueOnly() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 0) // Act pickerController.pickerView(pickerController.pickerView, didSelectRow: 59, inComponent: 2) // Assert XCTAssertEqual(pickerController.expirationTime, 59, "bad expirationTime") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 59 seconds.", "bad previewLabel") } func testSelectRowMinutesZeroOnly() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 22 * 60) // Act pickerController.pickerView(pickerController.pickerView, didSelectRow: 0, inComponent: 1) // Assert XCTAssertEqual(pickerController.expirationTime, 0, "bad expirationTime") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire instantly.", "bad previewLabel") } func testSelectRowMinutesNonZeroOnly() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 0) // Act pickerController.pickerView(pickerController.pickerView, didSelectRow: 22, inComponent: 1) // Assert XCTAssertEqual(pickerController.expirationTime, 22 * 60, "bad expirationTime") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 22 minutes.", "bad previewLabel") } func testSelectRowMinutesMaxValueOnly() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 0) // Act pickerController.pickerView(pickerController.pickerView, didSelectRow: 22, inComponent: 1) // Assert XCTAssertEqual(pickerController.expirationTime, 22 * 60, "bad expirationTime") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 22 minutes.", "bad previewLabel") } func testSelectRowHoursZeroOnly() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 24 * 60 * 60) // Act pickerController.pickerView(pickerController.pickerView, didSelectRow: 0, inComponent: 0) // Assert XCTAssertEqual(pickerController.expirationTime, 0, "bad expirationTime") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire instantly.", "bad previewLabel") } func testSelectRowHoursNonZeroOnly() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 0) // Act pickerController.pickerView(pickerController.pickerView, didSelectRow: 17, inComponent: 0) // Assert XCTAssertEqual(pickerController.expirationTime, 17 * 60 * 60, "bad expirationTime") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 17 hours.", "bad previewLabel") } func testSelectRowHoursMaxValueOnly() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 0) // Act pickerController.pickerView(pickerController.pickerView, didSelectRow: 23, inComponent: 0) // Assert XCTAssertEqual(pickerController.expirationTime, 23 * 60 * 60, "bad expirationTime") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 23 hours.", "bad previewLabel") } func testSelectRowMinutesSecondsComposite() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 0) // Act pickerController.pickerView(pickerController.pickerView, didSelectRow: 17, inComponent: 1) pickerController.pickerView(pickerController.pickerView, didSelectRow: 43, inComponent: 2) // Assert XCTAssertEqual(pickerController.expirationTime, 17 * 60 + 43, "bad expirationTime") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 17 minutes and 43 seconds.", "bad previewLabel") } func testSelectRowHoursSecondsComposite() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 0) // Act pickerController.pickerView(pickerController.pickerView, didSelectRow: 6, inComponent: 0) pickerController.pickerView(pickerController.pickerView, didSelectRow: 27, inComponent: 2) // Assert XCTAssertEqual(pickerController.expirationTime, 6 * 60 * 60 + 27, "bad expirationTime") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 6 hours and 27 seconds.", "bad previewLabel") } func testSelectRowHoursMinutesComposite() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 0) // Act pickerController.pickerView(pickerController.pickerView, didSelectRow: 5, inComponent: 0) pickerController.pickerView(pickerController.pickerView, didSelectRow: 22, inComponent: 1) // Assert XCTAssertEqual(pickerController.expirationTime, 5 * 60 * 60 + 22 * 60, "bad expirationTime") XCTAssertEqual(pickerController.previewLabel.text!, "Your Tic will expire in 5 hours and 22 minutes.", "bad previewLabel") } func testNumberOfComponentsZero() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 0) // Act pickerController.expirationUnits = [] // Assert XCTAssertEqual(pickerController.numberOfComponentsInPickerView(pickerController.pickerView), 0, "non-zero # of components") } func testNumberOfComponentsThree() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 0) // Act pickerController.expirationUnits = [TTExpirationUnit(), TTExpirationUnit(), TTExpirationUnit()] // Assert XCTAssertEqual(pickerController.numberOfComponentsInPickerView(pickerController.pickerView), 3, "wrong # of components") } func testNumberOfRowsZero() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 0) let zeroRowUnit = TTExpirationUnit() zeroRowUnit.singularTitle = "zeroRowUnit" zeroRowUnit.pluralTitle = "zeroRowUnits" zeroRowUnit.minValue = 0 zeroRowUnit.maxValue = -1 zeroRowUnit.minimumDisplayWidth = 2 zeroRowUnit.currentValue = 0 // Act pickerController.expirationUnits = [zeroRowUnit] // Assert XCTAssertEqual(pickerController.pickerView(pickerController.pickerView, numberOfRowsInComponent: 0), 0, "wrong # of components") } func testNumberOfRowsSameMinValueMaxValue() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 0) let sameMinMaxValueUnit = TTExpirationUnit() sameMinMaxValueUnit.singularTitle = "zeroRowUnit" sameMinMaxValueUnit.pluralTitle = "zeroRowUnits" sameMinMaxValueUnit.minValue = 23 sameMinMaxValueUnit.maxValue = 23 sameMinMaxValueUnit.minimumDisplayWidth = 2 sameMinMaxValueUnit.currentValue = 0 // Act pickerController.expirationUnits = [sameMinMaxValueUnit] // Assert XCTAssertEqual(pickerController.pickerView(pickerController.pickerView, numberOfRowsInComponent: 0), 1, "wrong # of components") } func testNumberOfRowsZeroMinValue() { // Arrange let pickerController = TTExpirationPickerController(expirationTime: 0) let zeroMinValueUnit = TTExpirationUnit() zeroMinValueUnit.singularTitle = "zeroRowUnit" zeroMinValueUnit.pluralTitle = "zeroRowUnits" zeroMinValueUnit.minValue = 0 zeroMinValueUnit.maxValue = 33 zeroMinValueUnit.minimumDisplayWidth = 2 zeroMinValueUnit.currentValue = 0 // Act pickerController.expirationUnits = [zeroMinValueUnit] // Assert XCTAssertEqual(pickerController.pickerView(pickerController.pickerView, numberOfRowsInComponent: 0), 34, "wrong # of components") } func testNumberOfRowsNonZeroMinValue() { let pickerController = TTExpirationPickerController(expirationTime: 0) let nonZeroMinValueUnit = TTExpirationUnit() nonZeroMinValueUnit.singularTitle = "zeroRowUnit" nonZeroMinValueUnit.pluralTitle = "zeroRowUnits" nonZeroMinValueUnit.minValue = 21 nonZeroMinValueUnit.maxValue = 44 nonZeroMinValueUnit.minimumDisplayWidth = 2 nonZeroMinValueUnit.currentValue = 0 // Act pickerController.expirationUnits = [nonZeroMinValueUnit] // Assert XCTAssertEqual(pickerController.pickerView(pickerController.pickerView, numberOfRowsInComponent: 0), 24, "wrong # of components") } }
gpl-2.0
b56c2c5fd4b63793542f6e9a8a7fde73
43.54047
144
0.687438
5.542235
false
true
false
false
dcunited001/SpectraNu
Spectra-OSX/SpectraTasks/main.swift
1
5296
// // main.swift // SpectraTasks // // Created by David Conner on 2/22/16. // Copyright © 2016 Spectra. All rights reserved. // import Foundation // .. hey, it works. and it's better than handcoding this stuff // configure arguments for the SpectraTasks target in xcode schemas let projectPath = Process.arguments[1] // filename is relative to Spectra-OSX func updateSpectraEnums(filepath: String, enums: [String: [String: UInt]]) { let xsdEnums = enums.reduce("") { (memo, enumDef) in return memo + simpleTypeForEnum(enumDef.0, members: enumDef.1) } let spectraEnumSchema = xsdSchema("SpectraEnums", targetNamespace: "SpectraEnums", content: xsdEnums) do { try spectraEnumSchema.writeToFile(filepath, atomically: false, encoding: NSUTF8StringEncoding) } catch let ex as NSError { print(ex.localizedDescription) print("k pasta") } } // NOTE: i didn't want to add another dependency to my project // - and my xml reader doesn't write. and i don't feel like using NSXML ish // - wtf no multiline strings? func xsdSchema(xlmns: String, targetNamespace: String, content: String) -> String { return "<?xml version=\"1.0\"?>\n<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" " + "targetNamespace=\"\(targetNamespace)\" " + "xmlns=\"\(xlmns)\" elementFormDefault=\"qualified\">\n\n" + content + "\n\n</xs:schema>" } func xsSimpleType(name:String, content: String, mtlEnum: Bool = false) -> String { let mtlEnumAttr = mtlEnum ? " mtl-enum=\"true\"" : "" return " <xs:simpleType name=\"\(name)\"\(mtlEnumAttr)>\n\(content) </xs:simpleType>\n\n" } func xsMtlEnum(members: [String: UInt]) -> String { let content = members.reduce("\n") { (memo, member) in return "\(memo) <xs:enumeration id=\"\(member.1)\" value=\"\(member.0)\"/>\n" } return " <xs:restriction base=\"xs:string\">\(content) </xs:restriction>\n" } func simpleTypeForEnum(name: String, members: [String: UInt]) -> String { let content = xsMtlEnum(members) return xsSimpleType(name, content: content, mtlEnum: true) } let enumsForModelIO: [String: [String: UInt]] = [ "mdlVertexFormat": SpectraEnumDefs.mdlVertexFormat, "mdlMaterialSemantic": SpectraEnumDefs.mdlMaterialSemantic, "mdlMaterialPropertyType": SpectraEnumDefs.mdlMaterialPropertyType, "mdlMaterialTextureWrapMode": SpectraEnumDefs.mdlMaterialTextureWrapMode, "mdlMaterialTextureFilterMode": SpectraEnumDefs.mdlMaterialTextureFilterMode, "mdlMaterialMipMapFilterMode": SpectraEnumDefs.mdlMaterialMipMapFilterMode, "mdlMeshBufferType": SpectraEnumDefs.mdlMeshBufferType, "mdlGeometryType": SpectraEnumDefs.mdlGeometryType, "mdlIndexBitDepth": SpectraEnumDefs.mdlIndexBitDepth, "mdlLightType": SpectraEnumDefs.mdlLightType ] let enumsForMetal: [String: [String: UInt]] = [ "mtlVertexStepFunction": MetalEnumDefs.mtlVertexStepFunction, "mtlCompareFunction": MetalEnumDefs.mtlCompareFunction, "mtlStencilOperation": MetalEnumDefs.mtlStencilOperation, "mtlVertexFormat": MetalEnumDefs.mtlVertexFormat, "mtlBlendFactor": MetalEnumDefs.mtlBlendFactor, "mtlBlendOperation": MetalEnumDefs.mtlBlendOperation, "mtlLoadAction": MetalEnumDefs.mtlLoadAction, "mtlStoreAction": MetalEnumDefs.mtlStoreAction, "mtlMultisampleDepthResolveFilter": MetalEnumDefs.mtlMultisampleDepthResolveFilter, "mtlSamplerMinMagFilter": MetalEnumDefs.mtlSamplerMinMagFilter, "mtlSamplerMipFilter": MetalEnumDefs.mtlSamplerMipFilter, "mtlSamplerAddressMode": MetalEnumDefs.mtlSamplerAddressMode, "mtlTextureType": MetalEnumDefs.mtlTextureType, "mtlCpuCacheMode": MetalEnumDefs.mtlCpuCacheMode, "mtlStorageMode": MetalEnumDefs.mtlStorageMode, "mtlPurgeableState": MetalEnumDefs.mtlPurgeableState, "mtlPixelFormat": MetalEnumDefs.mtlPixelFormat, "mtlResourceOptions": MetalEnumDefs.mtlResourceOptions, // option set "mtlTextureUsage": MetalEnumDefs.mtlTextureUsage, // option set "mtlPrimitiveType": MetalEnumDefs.mtlPrimitiveType, "mtlIndexType": MetalEnumDefs.mtlIndexType, "mtlVisibilityResultMode": MetalEnumDefs.mtlVisibilityResultMode, "mtlCullMode": MetalEnumDefs.mtlCullMode, "mtlWinding": MetalEnumDefs.mtlWinding, "mtlDepthClipMode": MetalEnumDefs.mtlDepthClipMode, "mtlTriangleFillMode": MetalEnumDefs.mtlTriangleFillMode, "mtlDataType": MetalEnumDefs.mtlDataType, "mtlArgumentType": MetalEnumDefs.mtlArgumentType, "mtlArgumentAccess": MetalEnumDefs.mtlArgumentAccess, "mtlBlitOption": MetalEnumDefs.mtlBlitOption, // option set "mtlBufferStatus": MetalEnumDefs.mtlBufferStatus, "mtlCommandBufferError": MetalEnumDefs.mtlCommandBufferError, "mtlFeatureSet": MetalEnumDefs.mtlFeatureSet, "mtlPipelineOption": MetalEnumDefs.mtlPipelineOption, // option set "mtlFunctionType": MetalEnumDefs.mtlFunctionType, "mtlLibraryError": MetalEnumDefs.mtlLibraryError, "mtlRenderPipelineError": MetalEnumDefs.mtlRenderPipelineError, "mtlPrimitiveTopologyClass": MetalEnumDefs.mtlPrimitiveTopologyClass ] updateSpectraEnums(projectPath + "/../SpectraAssets/SpectraEnums.xsd", enums: enumsForModelIO) updateSpectraEnums(projectPath + "/../SpectraAssets/MetalEnums.xsd", enums: enumsForMetal)
mit
b217eb774eef9d2c9cdcf4d6f48eeff8
46.276786
143
0.750897
3.84811
false
false
false
false
Xiaoye220/EmptyDataSet-Swift
Example/ApplicationsViewController.swift
1
3662
// // ViewController.swift // EmptyDataSet-Swift // // Created by YZF on 27/6/17. // Copyright © 2017年 Xiaoye. All rights reserved. // import UIKit class ApplicationsViewController: UITableViewController { enum Implementation { case original case new } var applications: [Application] = [.Airbnb, .AppStore, .Camera, .Dropbox, .Facebook, .Fancy, .Foursquare, .iCloud, .Instagram, .iTunesConnect, .Kickstarter, .Path, .Pinterest, .Photos, .Podcasts, .Remote, .Safari, .Skype, .Slack, .Tumblr, .Twitter, .Videos, .Vesper, .Vine, .Whatsapp, .WWDC] var impl: Implementation! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white title = "Applications" navigationItem.backBarButtonItem = UIBarButtonItem.init(title: "", style: .plain, target: nil, action: nil) tableView.tableFooterView = UIView() navigationController?.navigationBar.titleTextAttributes = nil navigationController?.navigationBar.barTintColor = UIColor(hexColor: "f8f8f8") navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.barStyle = .default } override func viewWillAppear(_ animated: Bool) { navigationController?.navigationBar.barTintColor = UIColor(hexColor: "f8f8f8") navigationController?.navigationBar.tintColor = UIColor.black UIApplication.shared.statusBarStyle = .default } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return applications.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "cell") } let app = applications[indexPath.row] cell.textLabel?.text = app.display_name cell.detailTextLabel?.text = app.developer_name let image = UIImage.init(named: ("icon_" + app.display_name!).lowercased().replacingOccurrences(of: " ", with: "_")) cell.imageView?.image = image cell.imageView?.layer.cornerRadius = (image?.size.width)! * 0.2 cell.imageView?.layer.masksToBounds = true cell.imageView?.layer.borderColor = UIColor(white: 0, alpha: 0.2).cgColor cell.imageView?.layer.borderWidth = 0.5 cell.imageView?.layer.shouldRasterize = true cell.imageView?.layer.rasterizationScale = UIScreen.main.scale return cell! } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 70 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let app = applications[indexPath.row] var controller: UIViewController switch impl! { case .original: controller = OriginalUsageViewController(app) case .new: controller = NewUsageViewController(app) } navigationController?.pushViewController(controller, animated: true) } }
mit
8b6e03a32edd6e68810937c1a538a5dc
36.336735
124
0.6305
5.212251
false
false
false
false
shohei/firefox-ios
Client/Frontend/Browser/SwipeAnimator.swift
2
5450
/* 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 struct SwipeAnimationParameters { let totalRotationInDegrees: Double let deleteThreshold: CGFloat let totalScale: CGFloat let totalAlpha: CGFloat let minExitVelocity: CGFloat let recenterAnimationDuration: NSTimeInterval } private let DefaultParameters = SwipeAnimationParameters( totalRotationInDegrees: 10, deleteThreshold: 60, totalScale: 0.9, totalAlpha: 0, minExitVelocity: 800, recenterAnimationDuration: 0.15) protocol SwipeAnimatorDelegate: class { func swipeAnimator(animator: SwipeAnimator, viewDidExitContainerBounds: UIView) } class SwipeAnimator: NSObject { weak var delegate: SwipeAnimatorDelegate? weak var container: UIView! weak var animatingView: UIView! private var prevOffset: CGPoint! private let params: SwipeAnimationParameters var containerCenter: CGPoint { return CGPoint(x: CGRectGetWidth(container.frame) / 2, y: CGRectGetHeight(container.frame) / 2) } init(animatingView: UIView, container: UIView, params: SwipeAnimationParameters = DefaultParameters) { self.animatingView = animatingView self.container = container self.params = params super.init() let panGesture = UIPanGestureRecognizer(target: self, action: Selector("SELdidPan:")) container.addGestureRecognizer(panGesture) panGesture.delegate = self } } //MARK: Private Helpers extension SwipeAnimator { private func animateBackToCenter() { UIView.animateWithDuration(params.recenterAnimationDuration, animations: { self.animatingView.transform = CGAffineTransformIdentity self.animatingView.alpha = 1 }) } private func animateAwayWithVelocity(velocity: CGPoint, speed: CGFloat) { // Calculate the edge to calculate distance from let translation = velocity.x >= 0 ? CGRectGetWidth(container.frame) : -CGRectGetWidth(container.frame) let timeStep = NSTimeInterval(abs(translation) / speed) UIView.animateWithDuration(timeStep, animations: { self.animatingView.transform = self.transformForTranslation(translation) self.animatingView.alpha = self.alphaForDistanceFromCenter(abs(translation)) }, completion: { finished in if finished { self.animatingView.alpha = 0 self.delegate?.swipeAnimator(self, viewDidExitContainerBounds: self.animatingView) } }) } private func transformForTranslation(translation: CGFloat) -> CGAffineTransform { let halfWidth = container.frame.size.width / 2 let totalRotationInRadians = CGFloat(params.totalRotationInDegrees / 180.0 * M_PI) // Determine rotation / scaling amounts by the distance to the edge var rotation = (translation / halfWidth) * totalRotationInRadians var scale = 1 - (abs(translation) / halfWidth) * (1 - params.totalScale) let rotationTransform = CGAffineTransformMakeRotation(rotation) let scaleTransform = CGAffineTransformMakeScale(scale, scale) let translateTransform = CGAffineTransformMakeTranslation(translation, 0) return CGAffineTransformConcat(CGAffineTransformConcat(rotationTransform, scaleTransform), translateTransform) } private func alphaForDistanceFromCenter(distance: CGFloat) -> CGFloat { let halfWidth = container.frame.size.width / 2 return 1 - (distance / halfWidth) * (1 - params.totalAlpha) } } //MARK: Selectors extension SwipeAnimator { @objc func SELdidPan(recognizer: UIPanGestureRecognizer!) { let translation = recognizer.translationInView(container) switch (recognizer.state) { case .Began: prevOffset = containerCenter case .Changed: animatingView.transform = transformForTranslation(translation.x) animatingView.alpha = alphaForDistanceFromCenter(abs(translation.x)) prevOffset = CGPoint(x: translation.x, y: 0) case .Cancelled: animateBackToCenter() case .Ended: let velocity = recognizer.velocityInView(container) // Bounce back if the velocity is too low or if we have not reached the treshold yet let speed = max(abs(velocity.x), params.minExitVelocity) if (speed < params.minExitVelocity || abs(prevOffset.x) < params.deleteThreshold) { animateBackToCenter() } else { animateAwayWithVelocity(velocity, speed: speed) } default: break } } @objc func SELcloseWithoutGesture() -> Bool { animateAwayWithVelocity(CGPoint(x: -params.minExitVelocity, y: 0), speed: params.minExitVelocity) return true } } extension SwipeAnimator: UIGestureRecognizerDelegate { @objc func gestureRecognizerShouldBegin(recognizer: UIGestureRecognizer) -> Bool { let cellView = recognizer.view as UIView! let panGesture = recognizer as! UIPanGestureRecognizer let translation = panGesture.translationInView(cellView.superview!) return fabs(translation.x) > fabs(translation.y) } }
mpl-2.0
64ed9a25d54cb29ca9155667b2797df3
38.215827
118
0.689174
5.327468
false
false
false
false
SwiftAndroid/swift-jni
JNIClassManipulation.swift
1
1466
import CJNI public extension JNI { public func DefineClass(name: String, _ loader: jobject, _ buffer: UnsafePointer<jbyte>, _ bufferLength: jsize) -> jclass { let env = self._env return env.memory.memory.DefineClass(env, name, loader, buffer, bufferLength) } public func FindClass(name: String) -> jclass { let env = self._env return env.memory.memory.FindClass(env, name) } public func FromReflectedMethod(method: jobject) -> jmethodID { let env = self._env return env.memory.memory.FromReflectedMethod(env, method) } public func FromReflectedField(field: jobject) -> jfieldID { let env = self._env return env.memory.memory.FromReflectedField(env, field) } public func ToReflectedMethod(targetClass: jclass, _ methodID: jmethodID, _ isStatic: jboolean) -> jobject { let env = self._env return env.memory.memory.ToReflectedMethod(env, cls, methodID, isStatic) } public func GetSuperclass(targetClass: jclass) -> jclass { let env = self._env return env.memory.memory.GetSuperclass(env, targetClass) } public func IsAssignableFrom(classA: jclass, _ classB: jclass) -> jboolean { let env = self._env return env.memory.memory.IsAssignableFrom(env, classA, classB) } public func ToReflectedField(targetClass: jclass, _ fieldID: jfieldID, _ isStatic: jboolean) -> jobject { let env = self._env return env.memory.memory.ToReflectedField(env, cls, fieldID, isStatic) } }
apache-2.0
ae57838c74d301094941ee93fe24f1d5
33.116279
124
0.709413
3.601966
false
false
false
false
qutheory/vapor
Sources/Vapor/Multipart/MultipartPartConvertible.swift
1
2629
import struct Foundation.Data public protocol MultipartPartConvertible { var multipart: MultipartPart? { get } init?(multipart: MultipartPart) } extension MultipartPart: MultipartPartConvertible { public var multipart: MultipartPart? { return self } public init?(multipart: MultipartPart) { self = multipart } } extension String: MultipartPartConvertible { public var multipart: MultipartPart? { return MultipartPart(body: self) } public init?(multipart: MultipartPart) { self.init(decoding: multipart.body.readableBytesView, as: UTF8.self) } } extension FixedWidthInteger { public var multipart: MultipartPart? { return MultipartPart(body: self.description) } public init?(multipart: MultipartPart) { guard let string = String(multipart: multipart) else { return nil } self.init(string) } } extension Int: MultipartPartConvertible { } extension Int8: MultipartPartConvertible { } extension Int16: MultipartPartConvertible { } extension Int32: MultipartPartConvertible { } extension Int64: MultipartPartConvertible { } extension UInt: MultipartPartConvertible { } extension UInt8: MultipartPartConvertible { } extension UInt16: MultipartPartConvertible { } extension UInt32: MultipartPartConvertible { } extension UInt64: MultipartPartConvertible { } extension Float: MultipartPartConvertible { public var multipart: MultipartPart? { return MultipartPart(body: self.description) } public init?(multipart: MultipartPart) { guard let string = String(multipart: multipart) else { return nil } self.init(string) } } extension Double: MultipartPartConvertible { public var multipart: MultipartPart? { return MultipartPart(body: self.description) } public init?(multipart: MultipartPart) { guard let string = String(multipart: multipart) else { return nil } self.init(string) } } extension Bool: MultipartPartConvertible { public var multipart: MultipartPart? { return MultipartPart(body: self.description) } public init?(multipart: MultipartPart) { guard let string = String(multipart: multipart) else { return nil } self.init(string) } } extension Data: MultipartPartConvertible { public var multipart: MultipartPart? { return MultipartPart(body: self) } public init?(multipart: MultipartPart) { self.init(multipart.body.readableBytesView) } }
mit
709f8e799f25235611b102cb9e72896e
25.29
76
0.678205
4.612281
false
false
false
false
MilitiaSoftworks/MSAlertController
MSAlertController/MSAlertManager.swift
1
8878
// // MSAlertManager.swift // MSAlertController // // Created by Jacob King on 20/07/2017. // Copyright © 2017 Parkmobile Group. All rights reserved. // import Foundation // MARK: Configure UINavigationController to send a notification upon popping view controllers. private let NavigationControllerDidPopViewControllerNotification = "NavigationControllerDidPopViewControllerNotification" private let swizzling: (UINavigationController.Type) -> () = { nav in let originalSelector = #selector(nav.popViewController(animated:)) let swizzledSelector = #selector(nav.extendedPopViewController(animated:)) let originalMethod = class_getInstanceMethod(nav, originalSelector) let swizzledMethod = class_getInstanceMethod(nav, swizzledSelector) method_exchangeImplementations(originalMethod, swizzledMethod) } public extension UINavigationController { open override class func initialize() { guard self === UINavigationController.self else { return } swizzling(self) } func extendedPopViewController(animated: Bool) -> UIViewController? { let vc = self.extendedPopViewController(animated: animated) // Not infinite loop as methods have been switched. NotificationCenter.default.post(name: NSNotification.Name(NavigationControllerDidPopViewControllerNotification), object: vc) return vc } } // MARK: Helper enums. public enum MSAlertType { case information case error case notification } public enum MSAlertPriority { case normal case critical } public enum MSAlertActionType { case standard case submissive case destructive } // MARK: Alert Manager open class MSAlertManager: NSObject { open static let shared = MSAlertManager() internal var queuedAlerts = [UIViewController]() internal var alertsToQueueOnPop = [UIViewController]() internal var currentlyDisplayedAlert: UIViewController? open var queueLocked: Bool = false open var defaultShowAnimation: MSAlertControllerShowAnimation = .slideCentre open var defaultHideAnimation: MSAlertControllerHideAnimation = .slideCentre override init() { super.init() NotificationCenter.default.addObserver(self, selector: #selector(navigationControllerDidPopViewController(notification:)), name: NSNotification.Name(NavigationControllerDidPopViewControllerNotification), object: nil) } open func navigationControllerDidPopViewController(notification: Notification) { for alert in alertsToQueueOnPop { queuedAlerts.append(alert) alertWasAddedToQueue() alertsToQueueOnPop.removeObject(alert) } } fileprivate func alertWasAddedToQueue() { guard currentlyDisplayedAlert == nil else { return } // As no alert is visible, we can show one, if one is available. guard let alert = queuedAlerts.first else { return } queuedAlerts.remove(at: 0) if let alert = alert as? MSAlertController { alert.showAlert(withAnimation: self.defaultShowAnimation) currentlyDisplayedAlert = alert return } if let toast = alert as? MSToastController { toast.showToast() currentlyDisplayedAlert = alert return } } fileprivate func alertWasDismissed() { currentlyDisplayedAlert = nil // See if there is another alert to show. guard let alert = queuedAlerts.first else { return } queuedAlerts.remove(at: 0) if let alert = alert as? MSAlertController { alert.showAlert(withAnimation: self.defaultShowAnimation) currentlyDisplayedAlert = alert return } if let toast = alert as? MSToastController { toast.showToast() currentlyDisplayedAlert = alert return } } } // MARK: Alert queue helpers. extension MSAlertManager { open func queueAlert(_ alert: MSAlertController) { guard !queueLocked else { return } queuedAlerts.append(alert) alertWasAddedToQueue() } open func queueAlert(withTitle title: String, message: String, type: MSAlertType) { queueAlert(withTitle: title, message: message, dismissButtonTitle: nil, onDismiss: nil, type: type, priority: .normal) } open func queueAlert(withTitle title: String, message: String, type: MSAlertType, priority: MSAlertPriority) { queueAlert(withTitle: title, message: message, dismissButtonTitle: nil, onDismiss: nil, type: type, priority: priority) } open func queueAlert(withTitle title: String, message: String, dismissButtonTitle: String?, onDismiss:(() -> Void)?, type: MSAlertType, priority: MSAlertPriority) { guard !queueLocked else { return } switch type { case .notification: let toast = MSToastController.withText(message) toast.onDismiss = alertWasDismissed // Check if this toast message already exists in queue, as we dont want multiple for the same message if !checkForDuplicateMessage(withMessage: message) { if priority == .critical { queuedAlerts.insert(toast, at: 0) } else { queuedAlerts.append(toast) } } default: let alert = buildStandardAlert(title: title, body: message, buttonTitle: dismissButtonTitle ?? "Okay", buttonAction: onDismiss) if priority == .critical { queuedAlerts.insert(alert, at: 0) } else { queuedAlerts.append(alert) } } alertWasAddedToQueue() } open func queueAlertOnPop(_ alert: MSAlertController) { guard !queueLocked else { return } alertsToQueueOnPop.append(alert) } open func queueAlertOnPop(withTitle title: String, message: String, type: MSAlertType) { queueAlertOnPop(withTitle: title, message: message, dismissButtonTitle: nil, onDismiss: nil, type: type, priority: .normal) } open func queueAlertOnPop(withTitle title: String, message: String, type: MSAlertType, priority: MSAlertPriority) { queueAlertOnPop(withTitle: title, message: message, dismissButtonTitle: nil, onDismiss: nil, type: type, priority: priority) } open func queueAlertOnPop(withTitle title: String, message: String, dismissButtonTitle: String?, onDismiss:(() -> Void)?, type: MSAlertType, priority: MSAlertPriority) { guard !queueLocked else { return } switch type { case .notification: let toast = MSToastController.withText(message) toast.onDismiss = alertWasDismissed if priority == .critical { alertsToQueueOnPop.insert(toast, at: 0) } else { alertsToQueueOnPop.append(toast) } default: let alert = buildStandardAlert(title: title, body: message, buttonTitle: dismissButtonTitle ?? "Okay", buttonAction: onDismiss) if priority == .critical { alertsToQueueOnPop.insert(alert, at: 0) } else { alertsToQueueOnPop.append(alert) } } } internal func checkForDuplicateMessage(withMessage message: String) -> Bool { for alert in queuedAlerts { if let toast = alert as? MSToastController { return toast.text == message } } return false } internal func buildStandardAlert(title: String, body: String, buttonTitle: String, buttonAction: (() -> Void)?) -> MSAlertController { let alert = MSAlertController.empty() let titleComponent = MSAlertControllerTitleComponent.withTitleText(title) let bodyComponent = MSAlertControllerBodyComponent.withBodyText(body) let buttonComponent = MSAlertControllerButtonComponent.submissiveButtonWithText(buttonTitle) { (sender) in alert.dismissAlert(withAnimation: self.defaultHideAnimation) { self.alertWasDismissed() } buttonAction?() } titleComponent.applyConstraintMap(MSAlertControllerConstraintMap(top: 16, bottom: 8, left: 16, right: 16, height: 0)) bodyComponent.applyConstraintMap(MSAlertControllerConstraintMap(top: 8, bottom: 16, left: 16, right: 16, height: 0)) alert.components = [titleComponent, bodyComponent, buttonComponent] return alert } }
apache-2.0
5b409e813cc237c7366207675f2fd49f
34.508
224
0.644474
5.090023
false
false
false
false
SSU-CS-Department/ssumobile-ios
SSUMobile/Modules/Maps/SSUMapModule.swift
1
4071
// // SSUMapModule.swift // SSUMobile // // Created by Eric Amorde on 4/9/17. // Copyright © 2017 Sonoma State University Department of Computer Science. All rights reserved. // import Foundation class SSUMapModule: SSUCoreDataModuleBase, SSUModuleUI { @objc(sharedInstance) static let instance = SSUMapModule() // MARK: SSUModule var title: String { return NSLocalizedString("Map", comment: "The campus Map shows the location of campus buildings and provides directions") } var identifier: String { return "campusmap" } func setup() { setupCoreData(modelName: "Map", storeName: "Map") } func updateData(_ completion: (() -> Void)? = nil) { SSULogging.logDebug("Update Map") updatePoints { self.updatePerimeters { self.updateConnections { completion?() } } } } func updatePoints(completion: (() -> Void)? = nil) { let date = SSUConfiguration.instance.date(forKey:SSUMapPointsUpdatedDateKey) SSUMoonlightCommunicator.getJSONFromPath("ssumobile/map/point/", since: date) { (response, json, error) in if let error = error { SSULogging.logError("Error while attemping to update Map points: \(error)") completion?() } else if let json = json { self.buildPoints(json) { completion?() } } } } func updatePerimeters(completion: (() -> Void)? = nil) { SSUMoonlightCommunicator.getJSONFromPath("ssumobile/map/perimeter/", since: nil) { (response, json, error) in if let error = error { SSULogging.logError("Error while attemping to update Map perimeters: \(error)") completion?() } else if let json = json { self.buildPerimeters(json) { completion?() } } } } func updateConnections(completion: (() -> Void)? = nil) { SSUMoonlightCommunicator.getJSONFromPath("ssumobile/map/point_connection/", since: nil) { (response, json, error) in if let error = error { SSULogging.logError("Error while attemping to update Map connections: \(error)") completion?() } else if let json = json { self.buildConnections(json) { completion?() } } } } func buildPoints(_ json: Any, completion: (() -> Void)? = nil) { let builder = SSUPointsBuilder(context: backgroundContext) builder.build(jsonObject: json, completion: completion) } func buildPerimeters(_ json: Any, completion: (() -> Void)? = nil) { let builder = SSUBuildingPerimetersBuilder(context: backgroundContext) builder.build(jsonObject: json, completion: completion) } func buildConnections(_ json: Any, completion: (() -> Void)? = nil) { let builder = SSUConnectionsBuilder(context: backgroundContext) builder.build(jsonObject: json, completion: completion) } // MARK: Objective-C helpers @objc func buildingPerimeters(matchingPredicate predicate: NSPredicate?) -> [SSUMapBuildingPerimeter] { return SSUBuildingPerimetersBuilder.allObjects(context: context, matching: predicate) } // MARK: SSUModuleUI func imageForHomeScreen() -> UIImage? { return UIImage(named: "map_icon") } func viewForHomeScreen() -> UIView? { return nil } func initialViewController() -> UIViewController { let storyboard = UIStoryboard(name: "Map_iPhone", bundle: Bundle(for: type(of: self))) return storyboard.instantiateInitialViewController()! } func shouldNavigateToModule() -> Bool { return true } func showModuleInNavigationBar() -> Bool { return false } }
apache-2.0
7f25778c905e692ef84dcb3fb511f608
31.56
129
0.582064
4.727062
false
false
false
false
StephenVinouze/ios-charts
Charts/Classes/Renderers/ChartXAxisRendererHorizontalBarChart.swift
1
13147
// // ChartXAxisRendererHorizontalBarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif public class ChartXAxisRendererHorizontalBarChart: ChartXAxisRendererBarChart { public override init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer, chart: chart) } public override func computeAxis(xValAverageLength xValAverageLength: Double, xValues: [String?]) { guard let xAxis = xAxis else { return } xAxis.values = xValues let longest = xAxis.getLongestLabel() as NSString let labelSize = longest.sizeWithAttributes([NSFontAttributeName: xAxis.labelFont]) let labelWidth = floor(labelSize.width + xAxis.xOffset * 3.5) let labelHeight = labelSize.height let labelRotatedSize = ChartUtils.sizeOfRotatedRectangle(rectangleWidth: labelSize.width, rectangleHeight: labelHeight, degrees: xAxis.labelRotationAngle) xAxis.labelWidth = labelWidth xAxis.labelHeight = labelHeight xAxis.labelRotatedWidth = round(labelRotatedSize.width + xAxis.xOffset * 3.5) xAxis.labelRotatedHeight = round(labelRotatedSize.height) } public override func renderAxisLabels(context context: CGContext) { guard let xAxis = xAxis else { return } if !xAxis.isEnabled || !xAxis.isDrawLabelsEnabled || chart?.data === nil { return } let xoffset = xAxis.xOffset if (xAxis.labelPosition == .Top) { drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5)) } else if (xAxis.labelPosition == .TopInside) { drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, anchor: CGPoint(x: 1.0, y: 0.5)) } else if (xAxis.labelPosition == .Bottom) { drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5)) } else if (xAxis.labelPosition == .BottomInside) { drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, anchor: CGPoint(x: 0.0, y: 0.5)) } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5)) drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5)) } } /// draws the x-labels on the specified y-position public override func drawLabels(context context: CGContext, pos: CGFloat, anchor: CGPoint) { guard let xAxis = xAxis, bd = chart?.data as? BarChartData else { return } let labelFont = xAxis.labelFont let labelTextColor = xAxis.labelTextColor let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD // pre allocate to save performance (dont allocate in loop) var position = CGPoint(x: 0.0, y: 0.0) let step = bd.dataSetCount for i in self.minX.stride(to: min(self.maxX + 1, xAxis.values.count), by: xAxis.axisLabelModulus) { let label = xAxis.values[i] if (label == nil) { continue } position.x = 0.0 position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace + bd.groupSpace / 2.0 // consider groups (center label for each group) if (step > 1) { position.y += (CGFloat(step) - 1.0) / 2.0 } transformer.pointValueToPixel(&position) if (viewPortHandler.isInBoundsY(position.y)) { drawLabel(context: context, label: label!, xIndex: i, x: pos, y: position.y, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor], anchor: anchor, angleRadians: labelRotationAngleRadians) } } } public func drawLabel(context context: CGContext, label: String, xIndex: Int, x: CGFloat, y: CGFloat, attributes: [String: NSObject], anchor: CGPoint, angleRadians: CGFloat) { guard let xAxis = xAxis else { return } let formattedLabel = xAxis.valueFormatter?.stringForXValue(xIndex, original: label, viewPortHandler: viewPortHandler) ?? label ChartUtils.drawText(context: context, text: formattedLabel, point: CGPoint(x: x, y: y), attributes: attributes, anchor: anchor, angleRadians: angleRadians) } public override func renderGridLines(context context: CGContext) { guard let xAxis = xAxis, bd = chart?.data as? BarChartData else { return } if !xAxis.isEnabled || !xAxis.isDrawGridLinesEnabled { return } CGContextSaveGState(context) CGContextSetShouldAntialias(context, xAxis.gridAntialiasEnabled) CGContextSetStrokeColorWithColor(context, xAxis.gridColor.CGColor) CGContextSetLineWidth(context, xAxis.gridLineWidth) CGContextSetLineCap(context, xAxis.gridLineCap) if (xAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, xAxis.gridLineDashPhase, xAxis.gridLineDashLengths, xAxis.gridLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } var position = CGPoint(x: 0.0, y: 0.0) // take into consideration that multiple DataSets increase _deltaX let step = bd.dataSetCount for i in self.minX.stride(to: min(self.maxX + 1, xAxis.values.count), by: xAxis.axisLabelModulus) { position.x = 0.0 position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace - 0.5 transformer.pointValueToPixel(&position) if (viewPortHandler.isInBoundsY(position.y)) { _gridLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _gridLineSegmentsBuffer[0].y = position.y _gridLineSegmentsBuffer[1].x = viewPortHandler.contentRight _gridLineSegmentsBuffer[1].y = position.y CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2) } } CGContextRestoreGState(context) } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderAxisLine(context context: CGContext) { guard let xAxis = xAxis else { return } if (!xAxis.isEnabled || !xAxis.isDrawAxisLineEnabled) { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, xAxis.axisLineColor.CGColor) CGContextSetLineWidth(context, xAxis.axisLineWidth) if (xAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, xAxis.axisLineDashPhase, xAxis.axisLineDashLengths, xAxis.axisLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } if (xAxis.labelPosition == .Top || xAxis.labelPosition == .TopInside || xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } if (xAxis.labelPosition == .Bottom || xAxis.labelPosition == .BottomInside || xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } CGContextRestoreGState(context) } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderLimitLines(context context: CGContext) { guard let xAxis = xAxis else { return } var limitLines = xAxis.limitLines if (limitLines.count == 0) { return } CGContextSaveGState(context) let trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for i in 0 ..< limitLines.count { let l = limitLines[i] if !l.isEnabled { continue } position.x = 0.0 position.y = CGFloat(l.limit) position = CGPointApplyAffineTransform(position, trans) _limitLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _limitLineSegmentsBuffer[0].y = position.y _limitLineSegmentsBuffer[1].x = viewPortHandler.contentRight _limitLineSegmentsBuffer[1].y = position.y CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor) CGContextSetLineWidth(context, l.lineWidth) if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2) let label = l.label // if drawing the limit-value label is enabled if (label.characters.count > 0) { let labelLineHeight = l.valueFont.lineHeight let xOffset: CGFloat = 4.0 + l.xOffset let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset if (l.labelPosition == .RightTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y - yOffset), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .RightBottom) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y + yOffset - labelLineHeight), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .LeftTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y - yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y + yOffset - labelLineHeight), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } } } CGContextRestoreGState(context) } }
apache-2.0
d4592e34ff8ecaf2f016fed45d6b5773
37.332362
243
0.573135
5.589711
false
false
false
false
lb2281075105/LBXiongMaoTV
LBXiongMaoTV/LBXiongMaoTV/Mine(我的)/Base/LBXMBaseCell.swift
1
1981
// // LBXMBaseCell.swift // LBXiongMaoTV // // Created by 云媒 on 2017/4/14. // Copyright © 2017年 YunMei. All rights reserved. // import UIKit class LBXMBaseCell: UITableViewCell { var switchType:UISwitch = UISwitch() var labelType:UILabel = UILabel() class func baseWithCell(tableView:UITableView) -> LBXMBaseCell { var cell = tableView.dequeueReusableCell(withIdentifier: "BaseCell") as?LBXMBaseCell if cell == nil { cell = LBXMBaseCell.init(style: .default, reuseIdentifier: "BaseCell") } return cell! } var item:AnyObject?{ didSet{ if (item?.isKind(of: LBXMMineItemArrow.self))! { let itemArrow = item as?LBXMMineItemArrow imageView?.image = UIImage.init(named: itemArrow?.imageString ?? "") textLabel?.text = itemArrow?.title accessoryType = .disclosureIndicator } if (item?.isKind(of: LBXMMineItemSwitch.self))! { let itemSwitch = item as?LBXMMineItemSwitch imageView?.image = UIImage.init(named: itemSwitch?.imageString ?? "") textLabel?.text = itemSwitch?.title selectionStyle = .none accessoryView = switchType } if (item?.isKind(of: LBXMMineItemLabel.self))! { let itemLabel = item as?LBXMMineItemLabel imageView?.image = UIImage.init(named: itemLabel?.imageString ?? "") textLabel?.text = itemLabel?.title labelType.frame = CGRect.init(x: 0, y: 0, width: 100, height: 50) labelType.textAlignment = .right labelType.text = "1.86MB" accessoryView = labelType } } } }
apache-2.0
aefc13e97c8d564e0c14a0ff1d5a57cd
29.369231
92
0.52381
4.826406
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Gutenberg/Collapsable Header/Collabsable Header Filter Bar/CollapsableHeaderFilterBar.swift
2
4570
import UIKit protocol CollapsableHeaderFilterBarDelegate: AnyObject { func numberOfFilters() -> Int func filter(forIndex: Int) -> CategorySection func didSelectFilter(withIndex selectedIndex: IndexPath, withSelectedIndexes selectedIndexes: [IndexPath]) func didDeselectFilter(withIndex index: IndexPath, withSelectedIndexes selectedIndexes: [IndexPath]) } class CollapsableHeaderFilterBar: UICollectionView { weak var filterDelegate: CollapsableHeaderFilterBarDelegate? private let defaultCellHeight: CGFloat = 44 private let defaultCellWidth: CGFloat = 105 var shouldShowGhostContent: Bool = false { didSet { reloadData() } } init() { let collectionViewLayout = UICollectionViewFlowLayout() collectionViewLayout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) collectionViewLayout.minimumInteritemSpacing = 12 collectionViewLayout.minimumLineSpacing = 10 collectionViewLayout.scrollDirection = .horizontal super.init(frame: .zero, collectionViewLayout: collectionViewLayout) showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false commonInit() } required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } private func commonInit() { register(CollabsableHeaderFilterCollectionViewCell.nib, forCellWithReuseIdentifier: CollabsableHeaderFilterCollectionViewCell.cellReuseIdentifier) self.delegate = self self.dataSource = self self.backgroundColor = .clear self.isOpaque = false } private func deselectItem(_ indexPath: IndexPath) { deselectItem(at: indexPath, animated: true) collectionView(self, didDeselectItemAt: indexPath) } } extension CollapsableHeaderFilterBar: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { if collectionView.cellForItem(at: indexPath)?.isSelected ?? false { deselectItem(indexPath) return false } return true } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let indexPathsForSelectedItems = collectionView.indexPathsForSelectedItems else { return } filterDelegate?.didSelectFilter(withIndex: indexPath, withSelectedIndexes: indexPathsForSelectedItems) } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { filterDelegate?.didDeselectFilter(withIndex: indexPath, withSelectedIndexes: collectionView.indexPathsForSelectedItems ?? []) } } extension CollapsableHeaderFilterBar: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { guard !shouldShowGhostContent, let filter = filterDelegate?.filter(forIndex: indexPath.item) else { return CGSize(width: defaultCellWidth, height: defaultCellHeight) } let width = CollabsableHeaderFilterCollectionViewCell.estimatedWidth(forFilter: filter) return CGSize(width: width, height: defaultCellHeight) } } extension CollapsableHeaderFilterBar: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return shouldShowGhostContent ? 1 : (filterDelegate?.numberOfFilters() ?? 0) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cellReuseIdentifier = CollabsableHeaderFilterCollectionViewCell.cellReuseIdentifier guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath) as? CollabsableHeaderFilterCollectionViewCell else { fatalError("Expected the cell with identifier \"\(cellReuseIdentifier)\" to be a \(CollabsableHeaderFilterCollectionViewCell.self). Please make sure the collection view is registering the correct nib before loading the data") } if shouldShowGhostContent { cell.ghostAnimationWillStart() cell.startGhostAnimation(style: GhostCellStyle.muriel) } else { cell.stopGhostAnimation() cell.filter = filterDelegate?.filter(forIndex: indexPath.item) } return cell } }
gpl-2.0
5ca3084312de9fd31245edbba0b307f1
43.368932
237
0.736761
5.958279
false
false
false
false
kickstarter/ios-oss
Library/ViewModels/FindFriendsViewModel.swift
1
7805
import KsApi import Prelude import ReactiveExtensions import ReactiveSwift public protocol FindFriendsViewModelInputs { /// Call to set where Friends View Controller was loaded from func configureWith(source: FriendsSource) /// Call when press OK on Follow All Friends confirmation alert func confirmFollowAllFriends() /// Call when "Discover projects" button is tapped func discoverButtonTapped() /// Call when user updates to be Facebook Connected. func findFriendsFacebookConnectCellDidFacebookConnectUser() /// Call when the Facebook Connect section is dismissed. func findFriendsFacebookConnectCellDidDismissHeader() /// Call when an alert should be shown. func findFriendsFacebookConnectCellShowErrorAlert(_ alert: AlertError) /// Call when should display "Follow all friends?" confirmation alert func findFriendsStatsCellShowFollowAllFriendsAlert(friendCount: Int) /// Call when friend status updates from a FriendFollowCell. func updateFriend(_ updatedFriend: User) /// Call when view loads func viewDidLoad() /// Call when a new row of friends is displayed func willDisplayRow(_ row: Int, outOf totalRows: Int) } public protocol FindFriendsViewModelOutputs { /// Emits an array of friend users with the source that presented the controller. var friends: Signal<([User], FriendsSource), Never> { get } /// Emits DiscoveryParams when should go to Discovery var goToDiscovery: Signal<DiscoveryParams, Never> { get } /// Emits when error alert should show with AlertError var showErrorAlert: Signal<AlertError, Never> { get } /// Emits bool whether Facebook Connect view should show with the source that presented the controller. var showFacebookConnect: Signal<(FriendsSource, Bool), Never> { get } /// Emits friends count when should display "Follow all friends" alert. var showFollowAllFriendsAlert: Signal<Int, Never> { get } /// Emits a boolean that determines if loader is hidden. var showLoadingIndicatorView: Signal<Bool, Never> { get } /// Emits the current user and the source that presented the controller. var stats: Signal<(FriendStatsEnvelope, FriendsSource), Never> { get } } public protocol FindFriendsViewModelType { var inputs: FindFriendsViewModelInputs { get } var outputs: FindFriendsViewModelOutputs { get } } public final class FindFriendsViewModel: FindFriendsViewModelType, FindFriendsViewModelInputs, FindFriendsViewModelOutputs { public init() { let source = self.configureWithProperty.signal let followAll = self.confirmFollowAllFriendsProperty.signal .switchMap { AppEnvironment.current.apiService.followAllFriends() .on(value: { _ in AppEnvironment.current.cache[KSCache.ksr_findFriendsFollowing] = [Int: Bool]() }) .demoteErrors() } let shouldShowFacebookConnect = Signal.merge( self.viewDidLoadProperty.signal, self.userFacebookConnectedProperty.signal ) .map { _ in FindFriendsFacebookConnectCellViewModel .showFacebookConnectionSection(for: AppEnvironment.current.currentUser) } let requestFirstPageWith = Signal.merge( shouldShowFacebookConnect.filter(isFalse).ignoreValues(), followAll.ignoreValues().ksr_debounce(.seconds(2), on: AppEnvironment.current.scheduler) ) let requestNextPageWhen = self.willDisplayRowProperty.signal.skipNil() .map { row, total in row >= total - 3 && total > 1 } .skipRepeats() .filter(isTrue) .ignoreValues() let (friends, isLoading, _, _) = paginate( requestFirstPageWith: requestFirstPageWith, requestNextPageWhen: requestNextPageWhen, clearOnNewRequest: true, valuesFromEnvelope: { $0.users }, cursorFromEnvelope: { $0.urls.api.moreUsers }, requestFromParams: { AppEnvironment.current.apiService.fetchFriends() }, requestFromCursor: { $0.map { AppEnvironment.current.apiService.fetchFriends(paginationUrl: $0) } ?? .empty } ) self.friends = Signal.combineLatest( Signal.merge(friends, followAll.mapConst([])).skipRepeats(==), source ) self.goToDiscovery = self.discoverButtonTappedProperty.signal .map { DiscoveryParams.defaults |> DiscoveryParams.lens.social .~ true |> DiscoveryParams.lens.sort .~ .magic } self.showFollowAllFriendsAlert = self.showFollowAllFriendsAlertProperty.signal self.showErrorAlert = self.showFacebookConnectErrorAlertProperty.signal.skipNil() self.showFacebookConnect = shouldShowFacebookConnect.signal .map { (.findFriends, $0) } self.showLoadingIndicatorView = Signal.merge( isLoading.take(first: 1), friends.mapConst(false) ).skipRepeats() let statsEvent = shouldShowFacebookConnect .filter(isFalse) .switchMap { _ in AppEnvironment.current.apiService.fetchFriendStats() .ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler) .materialize() } let stats = Signal.combineLatest(statsEvent.values(), source) self.stats = Signal.combineLatest( shouldShowFacebookConnect, stats ).map(unpack) // unpack into 3-tuple (shouldShowFacebookConnect, friends, source) .filter { shouldShowFacebookConnect, _, _ in !shouldShowFacebookConnect }.map { _, friends, source in (friends, source) } } fileprivate let configureWithProperty = MutableProperty<FriendsSource>(FriendsSource.findFriends) public func configureWith(source: FriendsSource) { self.configureWithProperty.value = source } fileprivate let confirmFollowAllFriendsProperty = MutableProperty(()) public func confirmFollowAllFriends() { self.confirmFollowAllFriendsProperty.value = () } public func findFriendsFacebookConnectCellDidDismissHeader() {} fileprivate let userFacebookConnectedProperty = MutableProperty(()) public func findFriendsFacebookConnectCellDidFacebookConnectUser() { self.userFacebookConnectedProperty.value = () } fileprivate let showFacebookConnectErrorAlertProperty = MutableProperty<AlertError?>(nil) public func findFriendsFacebookConnectCellShowErrorAlert(_ alert: AlertError) { self.showFacebookConnectErrorAlertProperty.value = alert } fileprivate let updateFriendProperty = MutableProperty<User?>(nil) public func updateFriend(_ updatedFriend: User) { self.updateFriendProperty.value = updatedFriend } fileprivate let viewDidLoadProperty = MutableProperty(()) public func viewDidLoad() { self.viewDidLoadProperty.value = () } fileprivate let discoverButtonTappedProperty = MutableProperty(()) public func discoverButtonTapped() { self.discoverButtonTappedProperty.value = () } fileprivate let showFollowAllFriendsAlertProperty = MutableProperty<Int>(0) public func findFriendsStatsCellShowFollowAllFriendsAlert(friendCount: Int) { self.showFollowAllFriendsAlertProperty.value = friendCount } fileprivate let willDisplayRowProperty = MutableProperty<(row: Int, total: Int)?>(nil) public func willDisplayRow(_ row: Int, outOf totalRows: Int) { self.willDisplayRowProperty.value = (row, totalRows) } public let friends: Signal<([User], FriendsSource), Never> public let goToDiscovery: Signal<DiscoveryParams, Never> public let showErrorAlert: Signal<AlertError, Never> public let showFacebookConnect: Signal<(FriendsSource, Bool), Never> public let showFollowAllFriendsAlert: Signal<Int, Never> public let showLoadingIndicatorView: Signal<Bool, Never> public let stats: Signal<(FriendStatsEnvelope, FriendsSource), Never> public var inputs: FindFriendsViewModelInputs { return self } public var outputs: FindFriendsViewModelOutputs { return self } }
apache-2.0
98851466ede9918c54416990ed65fb0e
35.816038
109
0.744138
4.741798
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
Frameworks/TBAData/Sources/Event/EventRanking.swift
1
15681
import CoreData import Foundation import TBAKit extension EventRanking { public var dq: Int? { return getValue(\EventRanking.dqRaw)?.intValue } public var matchesPlayed: Int? { return getValue(\EventRanking.matchesPlayedRaw)?.intValue } public var qualAverage: Double? { return getValue(\EventRanking.qualAverageRaw)?.doubleValue } public var rank: Int { guard let rank = getValue(\EventRanking.rankRaw)?.intValue else { fatalError("Save EventRanking before accessing rank") } return rank } public var record: WLT? { return getValue(\EventRanking.recordRaw) } public var event: Event { guard let event = getValue(\EventRanking.eventRaw) else { fatalError("Save EventRanking before accessing event") } return event } public var extraStats: NSOrderedSet { guard let extraStats = getValue(\EventRanking.extraStatsRaw) else { fatalError("Save EventRanking before accessing extraStats") } return extraStats } public var extraStatsInfo: NSOrderedSet { guard let extraStatsInfo = getValue(\EventRanking.extraStatsInfoRaw) else { fatalError("Save EventRanking before accessing extraStatsInfo") } return extraStatsInfo } public var qualStatus: EventStatusQual? { return getValue(\EventRanking.qualStatusRaw) } public var sortOrders: NSOrderedSet { guard let sortOrders = getValue(\EventRanking.sortOrdersRaw) else { fatalError("Save EventRanking before accessing sortOrders") } return sortOrders } public var sortOrdersInfo: NSOrderedSet { guard let sortOrdersInfo = getValue(\EventRanking.sortOrdersInfoRaw) else { fatalError("Save EventRanking before accessing sortOrdersInfo") } return sortOrdersInfo } public var team: Team { guard let team = getValue(\EventRanking.teamRaw) else { fatalError("Save EventRanking before accessing team") } return team } public var extraStatsInfoArray: [EventRankingStatInfo] { return extraStatsInfo.array as? [EventRankingStatInfo] ?? [] } public var extraStatsArray: [EventRankingStat] { return extraStats.array as? [EventRankingStat] ?? [] } public var sortOrdersInfoArray: [EventRankingStatInfo] { return sortOrdersInfo.array as? [EventRankingStatInfo] ?? [] } public var sortOrdersArray: [EventRankingStat] { return sortOrders.array as? [EventRankingStat] ?? [] } } @objc(EventRanking) public class EventRanking: NSManagedObject { @nonobjc public class func fetchRequest() -> NSFetchRequest<EventRanking> { return NSFetchRequest<EventRanking>(entityName: EventRanking.entityName) } @NSManaged var dqRaw: NSNumber? @NSManaged var matchesPlayedRaw: NSNumber? @NSManaged var qualAverageRaw: NSNumber? @NSManaged var rankRaw: NSNumber? @NSManaged var recordRaw: WLT? @NSManaged var eventRaw: Event? @NSManaged var extraStatsRaw: NSOrderedSet? @NSManaged var extraStatsInfoRaw: NSOrderedSet? @NSManaged var qualStatusRaw: EventStatusQual? @NSManaged var sortOrdersRaw: NSOrderedSet? @NSManaged var sortOrdersInfoRaw: NSOrderedSet? @NSManaged var teamRaw: Team? } // MARK: Generated accessors for extraStatsInfoRaw extension EventRanking { @objc(insertObject:inExtraStatsInfoRawAtIndex:) @NSManaged func insertIntoExtraStatsInfoRaw(_ value: EventRankingStatInfo, at idx: Int) @objc(removeObjectFromExtraStatsInfoRawAtIndex:) @NSManaged func removeFromExtraStatsInfoRaw(at idx: Int) @objc(insertExtraStatsInfoRaw:atIndexes:) @NSManaged func insertIntoExtraStatsInfoRaw(_ values: [EventRankingStatInfo], at indexes: NSIndexSet) @objc(removeExtraStatsInfoRawAtIndexes:) @NSManaged func removeFromExtraStatsInfoRaw(at indexes: NSIndexSet) @objc(replaceObjectInExtraStatsInfoRawAtIndex:withObject:) @NSManaged func replaceExtraStatsInfoRaw(at idx: Int, with value: EventRankingStatInfo) @objc(replaceExtraStatsInfoRawAtIndexes:withExtraStatsInfoRaw:) @NSManaged func replaceExtraStatsInfoRaw(at indexes: NSIndexSet, with values: [EventRankingStatInfo]) @objc(addExtraStatsInfoRawObject:) @NSManaged func addToExtraStatsInfoRaw(_ value: EventRankingStatInfo) @objc(removeExtraStatsInfoRawObject:) @NSManaged func removeFromExtraStatsInfoRaw(_ value: EventRankingStatInfo) @objc(addExtraStatsInfoRaw:) @NSManaged func addToExtraStatsInfoRaw(_ values: NSOrderedSet) @objc(removeExtraStatsInfoRaw:) @NSManaged func removeFromExtraStatsInfoRaw(_ values: NSOrderedSet) } // MARK: Generated accessors for extraStatsRaw extension EventRanking { @objc(insertObject:inExtraStatsRawAtIndex:) @NSManaged func insertIntoExtraStatsRaw(_ value: EventRankingStat, at idx: Int) @objc(removeObjectFromExtraStatsRawAtIndex:) @NSManaged func removeFromExtraStatsRaw(at idx: Int) @objc(insertExtraStatsRaw:atIndexes:) @NSManaged func insertIntoExtraStatsRaw(_ values: [EventRankingStat], at indexes: NSIndexSet) @objc(removeExtraStatsRawAtIndexes:) @NSManaged func removeFromExtraStatsRaw(at indexes: NSIndexSet) @objc(replaceObjectInExtraStatsRawAtIndex:withObject:) @NSManaged func replaceExtraStatsRaw(at idx: Int, with value: EventRankingStat) @objc(replaceExtraStatsRawAtIndexes:withExtraStatsRaw:) @NSManaged func replaceExtraStatsRaw(at indexes: NSIndexSet, with values: [EventRankingStat]) @objc(addExtraStatsRawObject:) @NSManaged func addToExtraStatsRaw(_ value: EventRankingStat) @objc(removeExtraStatsRawObject:) @NSManaged func removeFromExtraStatsRaw(_ value: EventRankingStat) @objc(addExtraStatsRaw:) @NSManaged func addToExtraStatsRaw(_ values: NSOrderedSet) @objc(removeExtraStatsRaw:) @NSManaged func removeFromExtraStatsRaw(_ values: NSOrderedSet) } // MARK: Generated accessors for sortOrdersInfoRaw extension EventRanking { @objc(insertObject:inSortOrdersInfoRawAtIndex:) @NSManaged func insertIntoSortOrdersInfoRaw(_ value: EventRankingStatInfo, at idx: Int) @objc(removeObjectFromSortOrdersInfoRawAtIndex:) @NSManaged func removeFromSortOrdersInfoRaw(at idx: Int) @objc(insertSortOrdersInfoRaw:atIndexes:) @NSManaged func insertIntoSortOrdersInfoRaw(_ values: [EventRankingStatInfo], at indexes: NSIndexSet) @objc(removeSortOrdersInfoRawAtIndexes:) @NSManaged func removeFromSortOrdersInfoRaw(at indexes: NSIndexSet) @objc(replaceObjectInSortOrdersInfoRawAtIndex:withObject:) @NSManaged func replaceSortOrdersInfoRaw(at idx: Int, with value: EventRankingStatInfo) @objc(replaceSortOrdersInfoRawAtIndexes:withSortOrdersInfoRaw:) @NSManaged func replaceSortOrdersInfoRaw(at indexes: NSIndexSet, with values: [EventRankingStatInfo]) @objc(addSortOrdersInfoRawObject:) @NSManaged func addToSortOrdersInfoRaw(_ value: EventRankingStatInfo) @objc(removeSortOrdersInfoRawObject:) @NSManaged func removeFromSortOrdersInfoRaw(_ value: EventRankingStatInfo) @objc(addSortOrdersInfoRaw:) @NSManaged func addToSortOrdersInfoRaw(_ values: NSOrderedSet) @objc(removeSortOrdersInfoRaw:) @NSManaged func removeFromSortOrdersInfoRaw(_ values: NSOrderedSet) } // MARK: Generated accessors for sortOrdersRaw extension EventRanking { @objc(insertObject:inSortOrdersRawAtIndex:) @NSManaged func insertIntoSortOrdersRaw(_ value: EventRankingStat, at idx: Int) @objc(removeObjectFromSortOrdersRawAtIndex:) @NSManaged func removeFromSortOrdersRaw(at idx: Int) @objc(insertSortOrdersRaw:atIndexes:) @NSManaged func insertIntoSortOrdersRaw(_ values: [EventRankingStat], at indexes: NSIndexSet) @objc(removeSortOrdersRawAtIndexes:) @NSManaged func removeFromSortOrdersRaw(at indexes: NSIndexSet) @objc(replaceObjectInSortOrdersRawAtIndex:withObject:) @NSManaged func replaceSortOrdersRaw(at idx: Int, with value: EventRankingStat) @objc(replaceSortOrdersRawAtIndexes:withSortOrdersRaw:) @NSManaged func replaceSortOrdersRaw(at indexes: NSIndexSet, with values: [EventRankingStat]) @objc(addSortOrdersRawObject:) @NSManaged func addToSortOrdersRaw(_ value: EventRankingStat) @objc(removeSortOrdersRawObject:) @NSManaged func removeFromSortOrdersRaw(_ value: EventRankingStat) @objc(addSortOrdersRaw:) @NSManaged func addToSortOrdersRaw(_ values: NSOrderedSet) @objc(removeSortOrdersRaw:) @NSManaged func removeFromSortOrdersRaw(_ values: NSOrderedSet) } extension EventRanking: Managed { public static func insert(_ model: TBAEventRanking, sortOrderInfo: [TBAEventRankingSortOrder]?, extraStatsInfo: [TBAEventRankingSortOrder]?, eventKey: String, in context: NSManagedObjectContext) -> EventRanking { let predicate = NSPredicate(format: "(%K == %@ OR %K == %@) AND %K == %@", #keyPath(EventRanking.eventRaw.keyRaw), eventKey, #keyPath(EventRanking.qualStatusRaw.eventStatusRaw.eventRaw.keyRaw), eventKey, #keyPath(EventRanking.teamRaw.keyRaw), model.teamKey) return findOrCreate(in: context, matching: predicate, configure: { (ranking) in // Required: teamKey, rank ranking.teamRaw = Team.insert(model.teamKey, in: context) if let dq = model.dq { ranking.dqRaw = NSNumber(value: dq) } else { ranking.dqRaw = nil } if let matchesPlayed = model.matchesPlayed { ranking.matchesPlayedRaw = NSNumber(value: matchesPlayed) } else { ranking.matchesPlayedRaw = nil } if let qualAverage = model.qualAverage { ranking.qualAverageRaw = NSNumber(value: qualAverage) } else { ranking.qualAverageRaw = nil } ranking.rankRaw = NSNumber(value: model.rank) if let record = model.record { ranking.recordRaw = WLT(wins: record.wins, losses: record.losses, ties: record.ties) } else { ranking.recordRaw = nil } // Extra Stats exists on objects returned by /event/{event_key}/rankings // but not on models returned by /team/{team_key}/event/{event_key} `Team_Event_Status_rank` model // (This is true for any endpoint that returns a `Team_Event_Status_rank` model) ranking.updateToManyRelationship(relationship: #keyPath(EventRanking.extraStatsInfoRaw), newValues: extraStatsInfo?.map({ return EventRankingStatInfo.insert($0, in: context) })) ranking.updateToManyRelationship(relationship: #keyPath(EventRanking.extraStatsRaw), newValues: model.extraStats?.map { return EventRankingStat.insert(value: $0.doubleValue, extraStatsRanking: ranking, in: context) }) ranking.updateToManyRelationship(relationship: #keyPath(EventRanking.sortOrdersInfoRaw), newValues: sortOrderInfo?.map { return EventRankingStatInfo.insert($0, in: context) }) ranking.updateToManyRelationship(relationship: #keyPath(EventRanking.sortOrdersRaw), newValues: model.sortOrders?.map { return EventRankingStat.insert(value: $0.doubleValue, sortOrderRanking: ranking, in: context) }) }) } public override func prepareForDeletion() { super.prepareForDeletion() if let qualStatus = qualStatus { if qualStatus.eventStatus == nil { // qualStatus will become an orphan - delete managedObjectContext?.delete(qualStatus) } else { qualStatus.rankingRaw = nil } } // Loop twice - once to cleanup our relationships, once to delete. // We can't delete when we clean up our relationships, since we need to clean up // extraStatsInfoArray and sortOrdersInfoArray independently, and one EventRankingStatInfo // could be connected to both an EventRanking extraStatsInfoArray and sortOrdersInfoArray. // We need to drop relationships from both, then see if it's an orphan after. // Store all of our StatInfo objects - once we drop the relationship between // the EventRanking <-> the EventRankingStatInfo, we won't be able to check to // see if they're orphans by using the relationships on EventRanking. This allows // us to have a list of items we should check to see if they're orphaned. var stats = Set(extraStatsInfoArray) stats.formUnion(sortOrdersInfoArray) // First pass - clean up our relationships. extraStatsInfoArray.forEach({ $0.removeFromExtraStatsRankingsRaw(self) }) sortOrdersInfoArray.forEach({ $0.removeFromSortOrdersRankingsRaw(self) }) // Second pass - clean up orphaned EventRankingStatInfo objects that used to be connected to this EventRanking. stats.forEach({ guard $0.isOrphaned else { return } managedObjectContext?.delete($0) }) } } extension EventRanking { private func statString(statsInfo: [EventRankingStatInfo], stats: [EventRankingStat]) -> String? { let parts = zip(statsInfo, stats).map({ (statsTuple) -> String? in let (statInfo, stat) = statsTuple let precision = Int(statInfo.precision) let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal numberFormatter.maximumFractionDigits = precision numberFormatter.minimumFractionDigits = precision guard let valueString = numberFormatter.string(for: stat.value) else { return nil } return "\(statInfo.name): \(valueString)" }).compactMap({ $0 }) return parts.isEmpty ? nil : parts.joined(separator: ", ") } /// Description for an EventRanking's extraStats/sortOrders (ranking/tiebreaker names/values) as a comma separated string. public var rankingInfoString: String? { get { let rankingInfoStringParts = [(extraStatsInfoArray, extraStatsArray), (sortOrdersInfoArray, sortOrdersArray)].map({ (tuple) -> String? in let (statsInfo, stats) = tuple return statString(statsInfo: statsInfo, stats: stats) }).compactMap({ $0 }) return rankingInfoStringParts.isEmpty ? nil : rankingInfoStringParts.joined(separator: ", ") } } public func setEvent(event: Event) { self.eventRaw = event } } extension EventRanking { public static func eventPredicate(eventKey: String) -> NSPredicate { return NSPredicate(format: "%K == %@", #keyPath(EventRanking.eventRaw.keyRaw), eventKey) } public static func rankSortDescriptor() -> NSSortDescriptor { return NSSortDescriptor(key: #keyPath(EventRanking.rankRaw), ascending: true) } } extension EventRanking: Orphanable { public var isOrphaned: Bool { // Ranking is an orphan if it's not attached to an Event or a EventStatusQual let hasEvent = (eventRaw != nil) let hasStatus = (qualStatusRaw != nil) return !hasEvent && !hasStatus } }
mit
f367d16a4b0219ef35a6a56c366161b3
37.433824
216
0.691282
4.970206
false
false
false
false
bmichotte/HSTracker
HSTracker/HearthMirror/MirrorHelper.swift
1
4939
// // MirrorHelper.swift // HSTracker // // Created by Istvan Fehervari on 23/03/2017. // Copyright © 2017 Benjamin Michotte. All rights reserved. // import Foundation import HearthMirror import CleanroomLogger /** * MirrorHelper takes care of all Mirror-related activities */ struct MirrorHelper { /** Internal represenation of the mirror object, do not access it directly */ private static var _mirror: HearthMirror? private static let accessQueue = DispatchQueue(label: "be.michotte.hstracker.mirrorQueue") private static var mirror: HearthMirror? { if MirrorHelper._mirror == nil { if let hsApp = CoreManager.hearthstoneApp { Log.verbose?.message("Initializing HearthMirror with pid \(hsApp.processIdentifier)") MirrorHelper._mirror = MirrorHelper.initMirror(pid: hsApp.processIdentifier, blocking: false) } else { Log.error?.message("Failed to initialize HearthMirror: game is not running") } } return MirrorHelper._mirror } private static func initMirror(pid: Int32, blocking: Bool) -> HearthMirror { // get rights to attach if acquireTaskportRight() != 0 { Log.error?.message("acquireTaskportRight() failed!") } var mirror = HearthMirror(pid: pid, blocking: true) // waiting for mirror to be up and running var _waitingForMirror = true while _waitingForMirror { if let battleTag = mirror.getBattleTag() { Log.verbose?.message("Getting BattleTag from HearthMirror : \(battleTag)") _waitingForMirror = false break } else { // mirror might be partially initialized, reset Log.error?.message("Mirror is not working, trying again...") mirror = HearthMirror(pid: pid, blocking: true) Thread.sleep(forTimeInterval: 0.5) } } return mirror } /** * De-initializes the current mirror object, thus any further mirror calls will fail until the next initMirror */ static func destroy() { Log.verbose?.message("Deinitializing mirror") MirrorHelper.accessQueue.sync { MirrorHelper._mirror = nil } } // MARK: - get player decks static func getDecks() -> [MirrorDeck]? { var result: [MirrorDeck]? = nil MirrorHelper.accessQueue.sync { result = mirror?.getDecks() } return result } static func getSelectedDeck() -> Int64? { var result: Int64? = nil MirrorHelper.accessQueue.sync { result = mirror?.getSelectedDeck() as? Int64? ?? nil } return result } static func getArenaDeck() -> MirrorArenaInfo? { var result: MirrorArenaInfo? = nil MirrorHelper.accessQueue.sync { result = mirror?.getArenaDeck() } return result } static func getEditedDeck() -> MirrorDeck? { var result: MirrorDeck? = nil MirrorHelper.accessQueue.sync { result = mirror?.getEditedDeck() } return result } // MARK: - card collection static func getCardCollection() -> [MirrorCard]? { var result: [MirrorCard]? = nil MirrorHelper.accessQueue.sync { result = mirror?.getCardCollection() } return result } // MARK: - game mode static func isSpectating() -> Bool? { var result: Bool? = nil MirrorHelper.accessQueue.sync { result = mirror?.isSpectating() } return result } static func getGameType() -> Int? { var result: Int? = nil MirrorHelper.accessQueue.sync { result = mirror?.getGameType() as? Int? ?? nil } return result } static func getMatchInfo() -> MirrorMatchInfo? { var result: MirrorMatchInfo? = nil MirrorHelper.accessQueue.sync { result = mirror?.getMatchInfo() } return result } static func getFormat() -> Int? { var result: Int? = nil MirrorHelper.accessQueue.sync { result = mirror?.getFormat() as? Int? ?? nil } return result } static func getGameServerInfo() -> MirrorGameServerInfo? { var result: MirrorGameServerInfo? = nil MirrorHelper.accessQueue.sync { result = mirror?.getGameServerInfo() } return result } // MARK: - arena static func getArenaDraftChoices() -> [MirrorCard]? { var result: [MirrorCard]? = nil MirrorHelper.accessQueue.sync { result = mirror?.getArenaDraftChoices() } return result } // MARK: - brawl static func getBrawlInfo() -> MirrorBrawlInfo? { var result: MirrorBrawlInfo? = nil MirrorHelper.accessQueue.sync { result = mirror?.getBrawlInfo() } return result } }
mit
b23a6bb9bbd70243213c458822167b93
26.131868
111
0.602268
4.404996
false
false
false
false
djbe/AppwiseCore
Sources/Core/Network/Client+Error.swift
1
2983
// // Client+Error.swift // AppwiseCore // // Created by David Jennes on 24/07/2018. // import Alamofire /// Structured error information, including sub-errors if available. public struct ClientStructuredError: Decodable, LocalizedError { public let message: String // swiftlint:disable:next discouraged_optional_collection public let errors: [String: [String]]? public var errorDescription: String? { let subItems: [String] = errors? .sorted { $0.key < $1.key } .flatMap { $0.value } .map { " • \($0)" } ?? [] return ([message] + subItems).joined(separator: "\n") } } /// Potential extra errors returned by `Client.extract(from:error)` public enum ClientError: Error, LocalizedError { /// Multiple structured errors in response case errors([ClientStructuredError], underlyingError: Error) /// Message from response case message(String, underlyingError: Error) /// In case of HTTP Status 401 or 403 case unauthorized(underlyingError: Error) public var errorDescription: String? { switch self { case .errors(let errors, _): return errors .compactMap { $0.errorDescription } .joined(separator: "\n") case .message(let message, _): return message case .unauthorized: return L10n.Client.Error.unauthorized } } /// The underlying error as reported by serializers, Alamofire, ... public var underlyingError: Error { switch self { case .errors(_, let error), .message(_, let error), .unauthorized(let error): return error } } } public extension Client { /// Extract a readable error from the response in case of an error. This default implementation will: /// - Check if authorized /// - Consider the response as an array of objects, and get the first object's `message` /// - Consider the response as an object, and get the object's `message` /// - Consider the response as a string, and use that as error message /// /// - parameter response: The data response /// - parameter error: The existing error /// /// - returns: An error with the message from the response (see `ClientError`), or the existing error static func extract<T>(from response: DataResponse<T>, error: Error) -> Error { // unauthorized status code --> unauthorized if let status = response.response?.statusCode, status == 401 || status == 403 { return ClientError.unauthorized(underlyingError: error) } else if let data = response.data { // try to parse structured error or simple message if let items = try? JSONDecoder().decode([ClientStructuredError].self, from: data) { return ClientError.errors(items, underlyingError: error) } else if let item = try? JSONDecoder().decode(ClientStructuredError.self, from: data) { return ClientError.errors([item], underlyingError: error) } else if let message = String(data: data, encoding: .utf8), !message.lowercased().contains("<html"), !message.isEmpty { return ClientError.message(message, underlyingError: error) } } return error } }
mit
1e099a83bfdeae32c03232da599f6501
33.264368
102
0.706139
3.861399
false
false
false
false
keshavvishwkarma/KVConstraintKit
KVConstraintKit/KVConstraintKitOperators.swift
1
10829
// // KVConstraintKitOperators.swift // https://github.com/keshavvishwkarma/KVConstraintKit.git // // Distributed under the MIT License. // // Copyright © 2016-2017 Keshav Vishwkarma <[email protected]>. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif //********* DEFINE NEW OPERATOR *********// infix operator ~ :AdditionPrecedence infix operator <- :AdditionPrecedence infix operator +== :AdditionPrecedence infix operator +>= :AdditionPrecedence infix operator +<= :AdditionPrecedence infix operator *<= :AdditionPrecedence infix operator *== :AdditionPrecedence infix operator *>= :AdditionPrecedence infix operator |==| :AdditionPrecedence infix operator |>=| :AdditionPrecedence infix operator |<=| :AdditionPrecedence extension View : Addable, Removable, Accessable, LayoutRelationable {} // Operators Definations // MARK: Addable extension Addable where Self: View { /// To add single constraint on the receiver view @discardableResult public static func +(lhs: Self, rhs: NSLayoutConstraint) -> NSLayoutConstraint { return lhs.applyPreparedConstraintInView(constraint: rhs) } } extension View { /// To add multiple constraints on the lhs view @discardableResult public static func +(lhs: View, rhs: [NSLayoutConstraint]) -> [NSLayoutConstraint] { return rhs.map { lhs + $0 } } } // MARK: Removable extension Removable where Self: View { /// To remove single constraint from the receiver view @discardableResult public static func -(lhs: Self, rhs: NSLayoutConstraint) -> NSLayoutConstraint { lhs.removeConstraint(rhs); return rhs } /// To remove multiple constraint from the receiver view @discardableResult public static func -(lhs: Self, rhs: [NSLayoutConstraint]) -> [NSLayoutConstraint] { if rhs.isEmpty { return rhs } lhs.removeConstraints(rhs); return rhs } } // MARK: Accessable extension Accessable where Self: View { @discardableResult public static func <-(lhs: Self, rhs: LayoutAttribute) -> NSLayoutConstraint?{ return lhs.accessAppliedConstraintBy(attribute: rhs) } @discardableResult public static func <-(lhs: Self, rhs: (LayoutAttribute, LayoutRelation)) -> NSLayoutConstraint?{ return lhs.accessAppliedConstraintBy(attribute: rhs.0, relation: rhs.1) } } // MARK: LayoutRelationable extension LayoutRelationable where Self: View { /// TO ADD SINGLE RELATION CONSTRAINT //----------------------------------------- /// (containerView +<= .Top).constant = 0 @discardableResult public static func +<=(lhs: Self, rhs: LayoutAttribute) -> NSLayoutConstraint { return lhs.superview! + lhs.prepareConstraintToSuperview(attribute: rhs, attribute: rhs, relation: .lessThanOrEqual) } /// (leftContainerView +== .Top).constant = 0 @discardableResult public static func +==(lhs: Self, rhs: LayoutAttribute) -> NSLayoutConstraint { return lhs.superview! + lhs.prepareConstraintToSuperview(attribute: rhs, attribute: rhs) } /// (leftContainerView +>= .Top).constant = 0 @discardableResult public static func +>=(lhs: Self, rhs: LayoutAttribute) -> NSLayoutConstraint { return lhs.superview! + lhs.prepareConstraintToSuperview(attribute: rhs, attribute: rhs, relation: .greaterThanOrEqual) } /// TO ADD SINGLE EQUAL RELATION CONSTRAINT WITH MULTIPLEIR //------------------------------------------------------------- /// (containerView *>= (.Top, 1.5)).constant = 0 @discardableResult public static func *>=(lhs: Self, rhs: (LayoutAttribute, CGFloat)) -> NSLayoutConstraint { return lhs.superview! + lhs.prepareConstraintToSuperview(attribute: rhs.0, attribute: rhs.0, relation: .greaterThanOrEqual, multiplier: rhs.1) } /// (containerView *== (.Top, multiplier) ).constant = 0 @discardableResult public static func *==(lhs: Self, rhs: (LayoutAttribute, CGFloat)) -> NSLayoutConstraint { return lhs.superview! + lhs.prepareConstraintToSuperview(attribute: rhs.0, attribute: rhs.0, multiplier: rhs.1) } /// (containerView *<=(.Top, multiplier) ).constant = 0 @discardableResult public static func *<=(lhs: Self, rhs: (LayoutAttribute, CGFloat)) -> NSLayoutConstraint { return lhs.superview! + lhs.prepareConstraintToSuperview(attribute: rhs.0, attribute: rhs.0, relation: .lessThanOrEqual, multiplier: rhs.1) } /// TO ADD SIBLINGS RELATION CONSTRAINT //------------------------------------------------------------- @discardableResult public static func |<=|(lhs: Self, rhs: (LayoutAttribute, LayoutAttribute, View)) -> NSLayoutConstraint { return lhs.superview! + lhs.prepareConstraintFromSiblingView(attribute: rhs.0, toAttribute: rhs.1, of: rhs.2, relation:.lessThanOrEqual) } @discardableResult public static func |==|(lhs: Self, rhs: (LayoutAttribute, LayoutAttribute, View)) -> NSLayoutConstraint { return lhs.superview! + lhs.prepareConstraintFromSiblingView(attribute: rhs.0, toAttribute: rhs.1, of: rhs.2) } @discardableResult public static func |>=|(lhs: Self, rhs: (LayoutAttribute, LayoutAttribute, View)) -> NSLayoutConstraint { return lhs.superview! + lhs.prepareConstraintFromSiblingView(attribute: rhs.0, toAttribute: rhs.1, of: rhs.2, relation:.greaterThanOrEqual) } } /// MARK: - TO ADD MULTIPLE RELATIONAL CONSTRAINTS extension View { // TO ADD MULTIPLE RELATIONAL CONSTRAINTS WITH CONSTANT //-------------------------------------------------------------- // (containerView +== [.Top, Bottom, Leading, Trailing]) /// With defualt constant that is - 0 (Zero) on a specific attribute @discardableResult public static func +<=(lhs: View, rhs: [LayoutAttribute]) -> [NSLayoutConstraint] { return rhs.map { lhs +<= $0 } } @discardableResult public static func +==(lhs: View, rhs: [LayoutAttribute]) -> [NSLayoutConstraint] { return rhs.map { lhs +== $0 } } @discardableResult public static func +>=(lhs: View, rhs: [LayoutAttribute]) -> [NSLayoutConstraint] { return rhs.map { lhs +>= $0 } } // TO ADD MULTIPLE RELATION CONSTRAINT WITH MULTIPLEIR //------------------------------------------------------------- // (containerView +== [(.Height, 1.5), (.Width, 0.8)]) @discardableResult public static func *<=(lhs: View, rhs: [(LayoutAttribute, CGFloat)]) -> [NSLayoutConstraint] { return rhs.map { lhs *<= $0 } } @discardableResult public static func *==(lhs: View, rhs: [(LayoutAttribute, CGFloat)]) -> [NSLayoutConstraint] { return rhs.map { lhs *== $0 } } @discardableResult public static func *>=(lhs: View, rhs: [(LayoutAttribute, CGFloat)]) -> [NSLayoutConstraint] { return rhs.map { lhs *>= $0 } } } /// TO ADD SelfAddable CONSTRAINT //------------------------------------------------------------- extension View : SelfAddable { } @discardableResult public func +<=(lhs: View, rhs: (SelfAttribute, CGFloat)) -> NSLayoutConstraint { if rhs.0 == .aspectRatio { return lhs + View.prepareConstraint(lhs, attribute:rhs.0.attribute().0, secondView:lhs,attribute:rhs.0.attribute().1, relation:.lessThanOrEqual, constant:rhs.1) }else{ return lhs + View.prepareConstraint(lhs, attribute:rhs.0.attribute().0, attribute:rhs.0.attribute().1, relation:.lessThanOrEqual, constant:rhs.1) } } @discardableResult public func +==(lhs: View, rhs: (SelfAttribute, CGFloat)) -> NSLayoutConstraint { if rhs.0 == .aspectRatio { return lhs + View.prepareConstraint(lhs, attribute:rhs.0.attribute().0, secondView:lhs, attribute:rhs.0.attribute().1, constant:rhs.1) }else{ return lhs + View.prepareConstraint(lhs, attribute:rhs.0.attribute().0, attribute:rhs.0.attribute().1, constant:rhs.1) } } @discardableResult public func +>=(lhs: View, rhs: (SelfAttribute, CGFloat)) -> NSLayoutConstraint { if rhs.0 == .aspectRatio { return lhs + View.prepareConstraint(lhs, attribute:rhs.0.attribute().0, secondView:lhs, attribute:rhs.0.attribute().1, relation:.greaterThanOrEqual, constant:rhs.1) }else{ return lhs + View.prepareConstraint(lhs, attribute:rhs.0.attribute().0, attribute:rhs.0.attribute().1, relation:.greaterThanOrEqual, constant:rhs.1) } } // MARK: Modifiable //------------------------------------------------------------- extension View : Modifiable { } /// (containerView ~ (constraint, multiplier)) public func *(lhs: View, rhs: (NSLayoutConstraint, CGFloat)) { guard let constraint = rhs.0.modified(multiplier: rhs.1) else { return } (lhs ~ (rhs.0, constraint)) } /// (containerView ~ (constraint, multiplier)) public func ~(lhs: View, rhs: (NSLayoutConstraint, LayoutRelation)) { guard let constraint = rhs.0.modified(relation: rhs.1) else { return } (lhs ~ (rhs.0, constraint)) } /// (containerView ~ (old, new)) public func ~(lhs: View, rhs: (NSLayoutConstraint, NSLayoutConstraint)) { // Remove old one _ = rhs.0.isSelfConstraint() ? lhs - rhs.0 : lhs.superview! - rhs.0 _ = rhs.1.isSelfConstraint() ? lhs - rhs.1 : lhs.superview! - rhs.1 } /// (containerView ~ (.Top, .Equal)) public func ~(lhs: View, rhs: (LayoutAttribute, LayoutPriority)) { guard let constraint = (lhs <- rhs.0) else { return } if constraint.isSelfConstraint() { _ = lhs - constraint constraint.priority = rhs.1 _ = lhs + constraint } else { _ = lhs.superview! - constraint constraint.priority = rhs.1 _ = lhs.superview! + constraint } }
mit
81727de4965d36026198195a2d9ca8a2
42.139442
172
0.659679
4.343361
false
false
false
false
Mioke/PlanB
PlanB/PlanB/Pages/AddGroupViewController/AddGroupViewController.swift
1
4512
// // AddGroupViewController.swift // PlanB // // Created by Klein Mioke on 5/17/16. // Copyright © 2016 Klein Mioke. All rights reserved. // import UIKit class AddGroupViewController: UIViewController { var groups: [WorkGroup] = [] var selectedRow: Int? @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.tableView.rowHeight = 64 self.groups = CoreService.sharedInstance.groups self.tableView.reloadData() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func clickBack(sender: AnyObject) { if self.selectedRow == nil { // warn user return } let id = self.groups[self.selectedRow!].id CoreService.sharedInstance.selectGroupID(id) let table = WorkGroupTable() for group in groups { table.replaceRecord(group) } self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func AddGroup(sender: AnyObject) { let id = Int(NSDate().timeIntervalSince1970) let group = WorkGroup(id: id, name: "") // WorkGroupTable().replaceRecord(group) self.groups.append(group) let index = NSIndexPath(forRow: groups.count - 1, inSection: 0) self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: .Automatic) let cell = self.tableView.cellForRowAtIndexPath(index) as! GroupSelectTableViewCell cell.activeTextField() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension AddGroupViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.groups.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCellWithIdentifier(GroupSelectTableViewCell.identifier) as? GroupSelectTableViewCell else { return UITableViewCell() } cell.groupNameTF.text = self.groups[indexPath.row].name cell.groupNameTF.delegate = self cell.groupNameTF.tag = indexPath.row if self.groups[indexPath.row].id == CoreService.sharedInstance.groupID { self.selectedRow = indexPath.row tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None) } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.selectedRow = indexPath.row } } extension AddGroupViewController: UITextFieldDelegate { func textFieldDidEndEditing(textField: UITextField) { guard let newName = textField.text where newName.length > 0 else { self.groups.removeLast() self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: .Fade) return } let group = self.groups[textField.tag] group.name = newName self.groups[textField.tag] = group } // // func textFieldShouldEndEditing(textField: UITextField) -> Bool { // guard let newName = textField.text where newName.length > 0 else { // self.groups.removeLast() // self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: .Automatic) // return true // } // let group = self.groups[textField.tag] // group.name = newName // self.groups[textField.tag] = group // // return true // } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() textField.userInteractionEnabled = false return true } }
gpl-3.0
416b0c67f0ded1198d2d9f45e9e24d41
30.545455
141
0.641543
5.079955
false
false
false
false
younata/RSSClient
TethysKitSpecs/KitModuleSpec.swift
1
9273
import Quick import Nimble import Swinject import FutureHTTP import SwiftKeychainWrapper @testable import TethysKit class KitModuleSpec: QuickSpec { override func spec() { var subject: Container! = nil beforeEach { subject = Container() TethysKit.configure(container: subject) } it("binds the main operation queue to kMainQueue") { expect(subject.resolve(OperationQueue.self, name: kMainQueue)).to(beIdenticalTo(OperationQueue.main)) } it("binds a single background queue") { expect(subject.resolve(OperationQueue.self, name: kBackgroundQueue)).to(beIdenticalTo(subject.resolve(OperationQueue.self, name: kBackgroundQueue))) } describe("Services") { exists(AccountService.self, kindOf: InoreaderAccountService.self) exists(Bundle.self) exists(CredentialService.self, kindOf: KeychainCredentialService.self) exists(UserDefaults.self) exists(FileManager.self) exists(Reachable.self) exists(RealmProvider.self, kindOf: DefaultRealmProvider.self) describe("FeedService") { var credentialService: KeychainCredentialService! let keychain = KeychainWrapper.standard beforeEach { credentialService = KeychainCredentialService( keychain: keychain ) KeychainWrapper.wipeKeychain() subject.register(CredentialService.self) { _ in return credentialService } } afterEach { KeychainWrapper.wipeKeychain() } context("without a saved inoreader account") { it("is a RealmFeedService") { expect(subject.resolve(FeedService.self)).to(beAKindOf(RealmFeedService.self)) } } context("with a saved inoreader account") { beforeEach { let future = credentialService.store(credential: Credential( access: "access", expiration: Date(), refresh: "refresh", accountId: "some user id", accountType: .inoreader )) expect(future.value).toEventuallyNot(beNil(), description: "Expected future to be resolved") expect(future.value?.value).to(beVoid()) } it("is an InoreaderFeedService") { let value = subject.resolve(FeedService.self) expect(value).to(beAKindOf(InoreaderFeedService.self)) if let feedService = value as? InoreaderFeedService { expect(feedService.baseURL).to(equal(URL(string: "https://www.inoreader.com"))) } } } } exists(FeedService.self, kindOf: RealmFeedService.self) exists(FeedCoordinator.self, singleton: true) exists(LocalFeedService.self, kindOf: LocalRealmFeedService.self) exists(ArticleService.self, kindOf: RealmArticleService.self) describe("different kinds of article service") { it("local returns a realm article service") { expect(subject.resolve(ArticleService.self, name: "local")).to(beAKindOf(RealmArticleService.self)) } describe("network article services") { var credentialService: KeychainCredentialService! let keychain = KeychainWrapper.standard beforeEach { credentialService = KeychainCredentialService( keychain: keychain ) KeychainWrapper.wipeKeychain() subject.register(CredentialService.self) { _ in return credentialService } } afterEach { KeychainWrapper.wipeKeychain() } context("if the user is logged in to an inoreader account") { beforeEach { let future = credentialService.store(credential: Credential( access: "access", expiration: Date(), refresh: "refresh", accountId: "some user id", accountType: .inoreader )) expect(future.value).toEventuallyNot(beNil(), description: "Expected future to be resolved") expect(future.value?.value).to(beVoid()) } it("returns an inoreader article service") { expect(subject.resolve(ArticleService.self, name: "network")).to(beAKindOf(InoreaderArticleService.self)) } } context("if the user is not logged in to an inoreader account") { it("returns a realm article service") { expect(subject.resolve(ArticleService.self, name: "network")).to(beAKindOf(RealmArticleService.self)) } } } } exists(ArticleCoordinator.self, singleton: true) exists(HTTPClient.self, kindOf: URLSession.self, singleton: true) describe("HTTPClient with an account") { it("exists") { expect(subject.resolve(HTTPClient.self, argument: "my_account")).toNot(beNil()) } it("is a configured AuthenticatedHTTPClient") { let client = subject.resolve(HTTPClient.self, argument: "my_account") expect(client).to(beAKindOf(AuthenticatedHTTPClient.self)) guard let httpClient = client as? AuthenticatedHTTPClient else { fail("Not an AuthenticatedHTTPClient") return } expect(httpClient.client).to(beIdenticalTo(subject.resolve(HTTPClient.self))) expect(httpClient.accountId).to(equal("my_account")) expect(httpClient.refreshURL.absoluteString).to(equal("https://www.inoreader.com/oauth2/token")) expect(httpClient.clientId).to(equal(Bundle.main.infoDictionary?["InoreaderClientID"] as? String)) expect(httpClient.clientSecret).to(equal(Bundle.main.infoDictionary?["InoreaderClientSecret"] as? String)) expect(httpClient.dateOracle().timeIntervalSince(Date())).to(beCloseTo(0)) } } exists(UpdateService.self, kindOf: RealmRSSUpdateService.self) singleton(OPMLService.self) exists(BackgroundStateMonitor.self) } func exists<T>(_ type: T.Type, singleton: Bool = false, line: UInt = #line) { describe("\(type)") { it("exists") { expect(subject.resolve(type), line: line).toNot(beNil()) } } if singleton { it("is a singleton") { expect(subject.resolve(type), line: line).to(beIdenticalTo(subject.resolve(type))) } } } func singleton<T>(_ type: T.Type, line: UInt = #line) { describe("\(type)") { it("exists") { expect(subject.resolve(type), line: line).toNot(beNil()) } it("is a singleton") { expect(subject.resolve(type), line: line).to(beIdenticalTo(subject.resolve(type))) } } } func exists<T, U>(_ type: T.Type, kindOf otherType: U.Type, singleton: Bool = false, line: UInt = #line) { describe("\(type)") { it("exists") { expect(subject.resolve(type), line: line).toNot(beNil()) } it("is a \(otherType)") { expect(subject.resolve(type), line: line).to(beAKindOf(otherType)) } if singleton { it("is a singleton") { expect(subject.resolve(type), line: line).to(beIdenticalTo(subject.resolve(type))) } } } } func alwaysIs<T: Equatable>(_ type: T.Type, a obj: T, line: UInt = #line) { describe("\(type)") { it("exists") { expect(subject.resolve(type), line: line).toNot(beNil()) } it("is always \(Mirror(reflecting: obj).description)") { expect(subject.resolve(type), line: line).to(equal(obj)) } } } } }
mit
daa3bff4085aede45d00517493abeef3
39.671053
160
0.507064
5.616596
false
false
false
false
MetalheadSanya/CRUD
CRUD/Source/Error.swift
1
2088
// // NSError.swift // shiponTaxi // // Created by Alexander Zalutskiy on 25.04.16. // Copyright © 2016 Alexander Zalutskiy. All rights reserved. // import Foundation import Gloss public enum CRUDError: Error, Decodable { case incorrectURI case objectDoesNotExist case objectAlreadyExist case incorrectJsonStruct case emptyData case server(code: Int, message: String) case custom(code: Int, domain: String, message: String) public init?(json: JSON) { guard let code: Int = "code" <~~ json else { return nil } guard let message: String = "message" <~~ json else { return nil } self = .server(code: code, message: message) } init(error: NSError) { self = .custom(code: error.code, domain: error.domain, message: error.localizedDescription) } public var domain: String { switch self { case .server: return defaultConfiguration.serverDomain case let .custom(_, domain, _): return domain default: return CRUDError.appDomain } } public var code: Int { switch self { case let .server(code, _): return code case let .custom(code, _, _): return code case .incorrectJsonStruct: return 1001 case .emptyData: return 1002 case .incorrectURI: return 10000 case .objectDoesNotExist: return 10001 case .objectAlreadyExist: return 10002 } } public var message: String { switch self { case let .server(_, message): return message case let .custom(_, _, message): return message case .incorrectJsonStruct: return "Incorrect JSON structure" case .emptyData: return "Empty response body from server" case .incorrectURI: return NSLocalizedString("URI for model is incorrect", comment: "") case .objectDoesNotExist: return NSLocalizedString("Object does not exist", comment: "") case .objectAlreadyExist: return NSLocalizedString("Object already exist", comment: "") } } fileprivate static var appDomain: String { if let bundleIdentifier = Bundle.main.bundleIdentifier { return bundleIdentifier } else { return "com.alexanderZalutskiy.CRUD" } } }
bsd-3-clause
ca57e8acc834979382a593152656f81e
22.188889
93
0.701485
3.592083
false
false
false
false
superman-coder/pakr
pakr/pakr/Configuration/Constants.swift
1
1219
// // Constants.swift // pakr // // Created by Huynh Quang Thao on 4/18/16. // Copyright © 2016 Pakr. All rights reserved. // import Foundation class Constants { class Parse { static let HOST = "https://pakr-parse.herokuapp.com/parse" static let APP_ID = "1411993" static let MASTER_KEY = "1411993" static let DB_URL = "mongodb://pakr_hqthao:[email protected]:21671/pakr-database" } class Table { static let User = "User" static let Post = "Post" static let Topic = "Topic" static let Parking = "Parking" static let Comment = "Comment" static let Bookmark = "Bookmark" } class AWS { static let CognitoRegionType = AWSRegionType.USEast1 static let CognitoIdentityPoolId = "us-east-1:9d85e167-0e3e-4b68-b16b-988f763d8f98" static let DefaultServiceRegionType = AWSRegionType.APSoutheast1 static let S3BucketName = "pakr-s3" static let AWS_DOMAIN = "https://s3-ap-southeast-1.amazonaws.com/" + Constants.AWS.S3BucketName + "/" } class Color { static let PrimaryColor: UInt = 0xF44336 } static let DemoMode = true }
apache-2.0
3cee71a74b61141ea4d34dfa9bfb5dfd
28.02381
109
0.625616
3.561404
false
false
false
false
TomHarte/CLK
OSBindings/Mac/Clock SignalTests/AllSuiteATests.swift
1
877
// // Clock_SignalTests.swift // Clock SignalTests // // Created by Thomas Harte on 16/07/2015. // Copyright 2015 Thomas Harte. All rights reserved. // import XCTest class AllSuiteATests: XCTestCase { func testAllSuiteA() { if let filename = Bundle(for: type(of: self)).path(forResource: "AllSuiteA", ofType: "bin") { if let allSuiteA = try? Data(contentsOf: URL(fileURLWithPath: filename)) { let machine = CSTestMachine6502(processor: .processor6502) machine.setData(allSuiteA, atAddress: 0x4000) machine.setValue(CSTestMachine6502JamOpcode, forAddress:0x45c0); // end machine.setValue(0x4000, for: CSTestMachine6502Register.programCounter) while !machine.isJammed { machine.runForNumber(ofCycles: 1000) } XCTAssert(machine.value(forAddress: 0x0210) == 0xff, "Failed test \(machine.value(forAddress: 0x0210))") } } } }
mit
f428452049c4d988bd9be6c0289da93e
27.290323
108
0.716078
3.334601
false
true
false
false
rsmoz/swift-package-manager
Tests/PackageDescription/PackageDescriptionTests.swift
1
2178
/* This source file is part of the Swift.org open source project Copyright 2015 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import XCTestCaseProvider import PackageDescription import sys @testable import dep private func parseTOML(data: String) -> TOMLItem { do { return try TOMLItem.parse(data) } catch let err { fatalError("unexpected error while parsing: \(err)") } } class PackageTests: XCTestCase, XCTestCaseProvider { var allTests : [(String, () throws -> Void)] { return [ ("testBasics", testBasics), ("testExclude", testExclude), ("testEmptyTestDependencies", testEmptyTestDependencies), ("testTestDependencies", testTestDependencies), ("testTargetDependencyIsStringConvertible", testTargetDependencyIsStringConvertible) ] } func testBasics() { // Verify that we can round trip a basic package through TOML. let p1 = Package(name: "a", dependencies: [.Package(url: "https://example.com/example", majorVersion: 1)]) XCTAssertEqual(p1, Package.fromTOML(parseTOML(p1.toTOML()))) } func testExclude() { let exclude = ["Images", "A/B"] let p1 = Package(name: "a", exclude: exclude) let pFromTOML = Package.fromTOML(parseTOML(p1.toTOML())) XCTAssertEqual(pFromTOML.exclude, exclude) } func testEmptyTestDependencies() { let p = Package(testDependencies: []) XCTAssertEqual(p.testDependencies, []) } func testTestDependencies() { let dependencies = [Package.Dependency.Package(url: "../TestingLib", majorVersion: 1)] let p = Package(testDependencies: dependencies) let pFromTOML = Package.fromTOML(parseTOML(p.toTOML())) XCTAssertEqual(pFromTOML.testDependencies, dependencies) } func testTargetDependencyIsStringConvertible() { XCTAssertEqual(Target.Dependency.Target(name: "foo"), "foo") } }
apache-2.0
2e2c166e01adb8b75a23bb3147143673
32.507692
114
0.674013
4.604651
false
true
false
false
tad-iizuka/swift-sdk
Source/PersonalityInsightsV2/Models/TraitTreeNode.swift
3
3688
/** * Copyright IBM Corporation 2016 * * 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 /** Detailed results for a specific characteristic of the input text. */ public struct TraitTreeNode: JSONDecodable { /// The globally unique id of the characteristic. public let id: String /// The user-displayable name of the characteristic. public let name: String /// The category of the characteristic: personality, /// needs, values, or behavior (for temporal data). public let category: String? /// For personality, needs, and values characteristics, the normalized /// percentile score for the characteristic, from 0-1. For example, if /// the percentage for Openness is 0.25, the author scored in the 25th /// percentile; the author is more open than 24% of the population and /// less open than 74% of the population. For temporal behavior /// characteristics, the percentage of timestamped data that occurred /// during that day or hour. public let percentage: Double? /// Indicates the sampling error of the percentage based on the number /// of words in the input, from 0-1. The number defines a 95% confidence /// interval around the percentage. For example, if the sampling error /// is 4% and the percentage is 61%, it is 95% likely that the actual /// percentage value is between 57% and 65% if more words are given. public let samplingError: Double? /// For personality, needs, and values characteristics, the raw score /// for the characteristic. A positive or negative score indicates /// more or less of the characteristic; zero indicates neutrality /// or no evidence for a score. The raw score is computed based on /// the input and the service model; it is not normalized or compared /// with a sample population. The raw score enables comparison of the /// results against a different sampling population and with a custom /// normalization approach. public let rawScore: Double? /// Indicates the sampling error of the raw score based on the number /// of words in the input; the practical range is 0-1. The number /// defines a 95% confidence interval around the raw score. For /// example, if the raw sampling error is 5% and the raw score is /// 65%, it is 95% likely that the actual raw score is between /// 60% and 70% if more words are given. public let rawSamplingError: Double? /// Recursive array of characteristics inferred from the input text. public let children: [TraitTreeNode]? /// Used internally to initialize a `TraitTreeNode` model from JSON. public init(json: JSON) throws { id = try json.getString(at: "id") name = try json.getString(at: "name") category = try? json.getString(at: "category") percentage = try? json.getDouble(at: "percentage") samplingError = try? json.getDouble(at: "sampling_error") rawScore = try? json.getDouble(at: "raw_score") rawSamplingError = try? json.getDouble(at: "raw_sampling_error") children = try? json.decodedArray(at: "children") } }
apache-2.0
f76034cf451cd5335eadd2b0ed9ee0e4
44.530864
76
0.70282
4.503053
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/PersistableRecordTests.swift
1
93239
import XCTest import GRDB private struct PersistableRecordPerson : PersistableRecord { var name: String? var age: Int? static let databaseTableName = "persons" func encode(to container: inout PersistenceContainer) { container["name"] = name container["age"] = age } } private class PersistableRecordPersonClass : PersistableRecord { var id: Int64? var name: String? var age: Int? init(id: Int64?, name: String?, age: Int?) { self.id = id self.name = name self.age = age } static let databaseTableName = "persons" func encode(to container: inout PersistenceContainer) { // mangle case container["ID"] = id container["naME"] = name container["Age"] = age } func didInsert(_ inserted: InsertionSuccess) { id = inserted.rowID } } private struct PersistableRecordCountry : PersistableRecord { var isoCode: String var name: String static let databaseTableName = "countries" func encode(to container: inout PersistenceContainer) { container["isoCode"] = isoCode container["name"] = name } } private class Callbacks { var willInsertCount = 0 var aroundInsertEnterCount = 0 var aroundInsertExitCount = 0 var didInsertCount = 0 var willUpdateCount = 0 var aroundUpdateEnterCount = 0 var aroundUpdateExitCount = 0 var didUpdateCount = 0 var willSaveCount = 0 var aroundSaveEnterCount = 0 var aroundSaveExitCount = 0 var didSaveCount = 0 var willDeleteCount = 0 var aroundDeleteEnterCount = 0 var aroundDeleteExitCount = 0 var didDeleteCount = 0 } private struct PersistableRecordCustomizedCountry : PersistableRecord { var isoCode: String var name: String let callbacks = Callbacks() static let databaseTableName = "countries" func encode(to container: inout PersistenceContainer) { container["isoCode"] = isoCode container["name"] = name } func willInsert(_ db: Database) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.willInsertCount += 1 } func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.aroundInsertEnterCount += 1 _ = try insert() callbacks.aroundInsertExitCount += 1 } func didInsert(_ inserted: InsertionSuccess) { callbacks.didInsertCount += 1 } func willUpdate(_ db: Database, columns: Set<String>) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.willUpdateCount += 1 } func aroundUpdate(_ db: Database, columns: Set<String>, update: () throws -> PersistenceSuccess) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.aroundUpdateEnterCount += 1 _ = try update() callbacks.aroundUpdateExitCount += 1 } func didUpdate(_ updated: PersistenceSuccess) { callbacks.didUpdateCount += 1 } func willSave(_ db: Database) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.willSaveCount += 1 } func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.aroundSaveEnterCount += 1 _ = try save() callbacks.aroundSaveExitCount += 1 } func didSave(_ saved: PersistenceSuccess) { callbacks.didSaveCount += 1 } func willDelete(_ db: Database) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.willDeleteCount += 1 } func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.aroundDeleteEnterCount += 1 _ = try delete() callbacks.aroundDeleteExitCount += 1 } func didDelete(deleted: Bool) { callbacks.didDeleteCount += 1 } } private struct Citizenship : PersistableRecord { let personID: Int64 let countryIsoCode: String static let databaseTableName = "citizenships" func encode(to container: inout PersistenceContainer) { container["countryIsoCode"] = countryIsoCode container["personID"] = personID } } private struct PartialPlayer: Codable, PersistableRecord, FetchableRecord { static let databaseTableName = "player" let callbacks = Callbacks() var id: Int64? var name: String enum CodingKeys: String, CodingKey { case id, name } func willInsert(_ db: Database) throws { callbacks.willInsertCount += 1 } func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { callbacks.aroundInsertEnterCount += 1 _ = try insert() callbacks.aroundInsertExitCount += 1 } func didInsert(_ inserted: InsertionSuccess) { callbacks.didInsertCount += 1 } func willUpdate(_ db: Database, columns: Set<String>) throws { callbacks.willUpdateCount += 1 } func aroundUpdate(_ db: Database, columns: Set<String>, update: () throws -> PersistenceSuccess) throws { callbacks.aroundUpdateEnterCount += 1 _ = try update() callbacks.aroundUpdateExitCount += 1 } func didUpdate(_ updated: PersistenceSuccess) { callbacks.didUpdateCount += 1 } func willSave(_ db: Database) throws { callbacks.willSaveCount += 1 } func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { callbacks.aroundSaveEnterCount += 1 _ = try save() callbacks.aroundSaveExitCount += 1 } func didSave(_ saved: PersistenceSuccess) { callbacks.didSaveCount += 1 } func willDelete(_ db: Database) throws { callbacks.willDeleteCount += 1 } func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { callbacks.aroundDeleteEnterCount += 1 _ = try delete() callbacks.aroundDeleteExitCount += 1 } func didDelete(deleted: Bool) { callbacks.didDeleteCount += 1 } } private struct FullPlayer: Codable, PersistableRecord, FetchableRecord { static let databaseTableName = "player" var id: Int64? var name: String var score: Int enum CodingKeys: String, CodingKey { case id, name, score } let callbacks = Callbacks() func willInsert(_ db: Database) throws { callbacks.willInsertCount += 1 } func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { callbacks.aroundInsertEnterCount += 1 _ = try insert() callbacks.aroundInsertExitCount += 1 } func didInsert(_ inserted: InsertionSuccess) { callbacks.didInsertCount += 1 } func willUpdate(_ db: Database, columns: Set<String>) throws { callbacks.willUpdateCount += 1 } func aroundUpdate(_ db: Database, columns: Set<String>, update: () throws -> PersistenceSuccess) throws { callbacks.aroundUpdateEnterCount += 1 _ = try update() callbacks.aroundUpdateExitCount += 1 } func didUpdate(_ updated: PersistenceSuccess) { callbacks.didUpdateCount += 1 } func willSave(_ db: Database) throws { callbacks.willSaveCount += 1 } func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { callbacks.aroundSaveEnterCount += 1 _ = try save() callbacks.aroundSaveExitCount += 1 } func didSave(_ saved: PersistenceSuccess) { callbacks.didSaveCount += 1 } func willDelete(_ db: Database) throws { callbacks.willDeleteCount += 1 } func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { callbacks.aroundDeleteEnterCount += 1 _ = try delete() callbacks.aroundDeleteExitCount += 1 } func didDelete(deleted: Bool) { callbacks.didDeleteCount += 1 } } class PersistableRecordTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("setUp") { db in try db.execute(sql: """ CREATE TABLE persons ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INT NOT NULL); CREATE TABLE countries ( isoCode TEXT NOT NULL PRIMARY KEY, name TEXT NOT NULL); CREATE TABLE citizenships ( countryIsoCode TEXT NOT NULL REFERENCES countries(isoCode), personID INTEGER NOT NULL REFERENCES persons(id)); CREATE TABLE player( id INTEGER PRIMARY KEY, name NOT NULL UNIQUE, -- UNIQUE for upsert tests score INTEGER NOT NULL DEFAULT 1000); """) } try migrator.migrate(dbWriter) } // MARK: - PersistableRecordPerson func testInsertPersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let person = PersistableRecordPerson(name: "Arthur", age: 42) try person.insert(db) let rows = try Row.fetchAll(db, sql: "SELECT * FROM persons") XCTAssertEqual(rows.count, 1) XCTAssertEqual(rows[0]["name"] as String, "Arthur") } } func testSavePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let person = PersistableRecordPerson(name: "Arthur", age: 42) try person.save(db) let rows = try Row.fetchAll(db, sql: "SELECT * FROM persons") XCTAssertEqual(rows.count, 1) XCTAssertEqual(rows[0]["name"] as String, "Arthur") } } // MARK: - PersistableRecordPersonClass func testInsertPersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let person = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person.insert(db) let rows = try Row.fetchAll(db, sql: "SELECT * FROM persons") XCTAssertEqual(rows.count, 1) XCTAssertEqual(rows[0]["id"] as Int64, person.id!) XCTAssertEqual(rows[0]["name"] as String, "Arthur") } } func testUpdatePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let person1 = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person1.insert(db) let person2 = PersistableRecordPersonClass(id: nil, name: "Barbara", age: 39) try person2.insert(db) person1.name = "Craig" try person1.update(db) XCTAssertTrue([ "UPDATE \"persons\" SET \"age\"=42, \"name\"='Craig' WHERE \"id\"=1", "UPDATE \"persons\" SET \"name\"='Craig', \"age\"=42 WHERE \"id\"=1" ].contains(self.lastSQLQuery)) let rows = try Row.fetchAll(db, sql: "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["id"] as Int64, person1.id!) XCTAssertEqual(rows[0]["name"] as String, "Craig") XCTAssertEqual(rows[1]["id"] as Int64, person2.id!) XCTAssertEqual(rows[1]["name"] as String, "Barbara") } } func testPartialUpdatePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let person1 = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 24) try person1.insert(db) let person2 = PersistableRecordPersonClass(id: nil, name: "Barbara", age: 36) try person2.insert(db) do { person1.name = "Craig" try person1.update(db, columns: [String]()) XCTAssertEqual(self.lastSQLQuery, "UPDATE \"persons\" SET \"id\"=1 WHERE \"id\"=1") let rows = try Row.fetchAll(db, sql: "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["id"] as Int64, person1.id!) XCTAssertEqual(rows[0]["name"] as String, "Arthur") XCTAssertEqual(rows[0]["age"] as Int, 24) XCTAssertEqual(rows[1]["id"] as Int64, person2.id!) XCTAssertEqual(rows[1]["name"] as String, "Barbara") XCTAssertEqual(rows[1]["age"] as Int, 36) } do { person1.name = "Craig" person1.age = 25 try person1.update(db, columns: [Column("name")]) XCTAssertEqual(self.lastSQLQuery, "UPDATE \"persons\" SET \"name\"='Craig' WHERE \"id\"=1") let rows = try Row.fetchAll(db, sql: "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["id"] as Int64, person1.id!) XCTAssertEqual(rows[0]["name"] as String, "Craig") XCTAssertEqual(rows[0]["age"] as Int, 24) XCTAssertEqual(rows[1]["id"] as Int64, person2.id!) XCTAssertEqual(rows[1]["name"] as String, "Barbara") XCTAssertEqual(rows[1]["age"] as Int, 36) } do { person1.name = "David" try person1.update(db, columns: ["AgE"]) // case insensitivity XCTAssertEqual(self.lastSQLQuery, "UPDATE \"persons\" SET \"age\"=25 WHERE \"id\"=1") let rows = try Row.fetchAll(db, sql: "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["id"] as Int64, person1.id!) XCTAssertEqual(rows[0]["name"] as String, "Craig") XCTAssertEqual(rows[0]["age"] as Int, 25) XCTAssertEqual(rows[1]["id"] as Int64, person2.id!) XCTAssertEqual(rows[1]["name"] as String, "Barbara") XCTAssertEqual(rows[1]["age"] as Int, 36) } } } func testSavePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let person1 = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person1.save(db) var rows = try Row.fetchAll(db, sql: "SELECT * FROM persons") XCTAssertEqual(rows.count, 1) XCTAssertEqual(rows[0]["id"] as Int64, person1.id!) XCTAssertEqual(rows[0]["name"] as String, "Arthur") let person2 = PersistableRecordPersonClass(id: nil, name: "Barbara", age: 39) try person2.save(db) person1.name = "Craig" try person1.save(db) rows = try Row.fetchAll(db, sql: "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["id"] as Int64, person1.id!) XCTAssertEqual(rows[0]["name"] as String, "Craig") XCTAssertEqual(rows[1]["id"] as Int64, person2.id!) XCTAssertEqual(rows[1]["name"] as String, "Barbara") try person1.delete(db) try person1.save(db) rows = try Row.fetchAll(db, sql: "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["id"] as Int64, person1.id!) XCTAssertEqual(rows[0]["name"] as String, "Craig") XCTAssertEqual(rows[1]["id"] as Int64, person2.id!) XCTAssertEqual(rows[1]["name"] as String, "Barbara") } } func testDeletePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let person1 = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person1.insert(db) let person2 = PersistableRecordPersonClass(id: nil, name: "Barbara", age: 39) try person2.insert(db) var deleted = try person1.delete(db) XCTAssertTrue(deleted) deleted = try person1.delete(db) XCTAssertFalse(deleted) let rows = try Row.fetchAll(db, sql: "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 1) XCTAssertEqual(rows[0]["id"] as Int64, person2.id!) XCTAssertEqual(rows[0]["name"] as String, "Barbara") } } func testExistsPersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let person = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person.insert(db) XCTAssertTrue(try person.exists(db)) try person.delete(db) XCTAssertFalse(try person.exists(db)) } } // MARK: - PersistableRecordCountry func testInsertPersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let country = PersistableRecordCountry(isoCode: "FR", name: "France") try country.insert(db) let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries") XCTAssertEqual(rows.count, 1) XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France") } } func testUpdatePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var country1 = PersistableRecordCountry(isoCode: "FR", name: "France") try country1.insert(db) let country2 = PersistableRecordCountry(isoCode: "US", name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" try country1.update(db) XCTAssertEqual(self.lastSQLQuery, "UPDATE \"countries\" SET \"name\"='France Métropolitaine' WHERE \"isoCode\"='FR'") let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France Métropolitaine") XCTAssertEqual(rows[1]["isoCode"] as String, "US") XCTAssertEqual(rows[1]["name"] as String, "United States") } } func testPartialUpdatePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var country1 = PersistableRecordCountry(isoCode: "FR", name: "France") try country1.insert(db) let country2 = PersistableRecordCountry(isoCode: "US", name: "United States") try country2.insert(db) do { country1.name = "France Métropolitaine" try country1.update(db, columns: [String]()) XCTAssertEqual(self.lastSQLQuery, "UPDATE \"countries\" SET \"isoCode\"='FR' WHERE \"isoCode\"='FR'") let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France") XCTAssertEqual(rows[1]["isoCode"] as String, "US") XCTAssertEqual(rows[1]["name"] as String, "United States") } do { country1.name = "France Métropolitaine" try country1.update(db, columns: [Column("name")]) XCTAssertEqual(self.lastSQLQuery, "UPDATE \"countries\" SET \"name\"='France Métropolitaine' WHERE \"isoCode\"='FR'") let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France Métropolitaine") XCTAssertEqual(rows[1]["isoCode"] as String, "US") XCTAssertEqual(rows[1]["name"] as String, "United States") } } } func testSavePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var country1 = PersistableRecordCountry(isoCode: "FR", name: "France") try country1.save(db) var rows = try Row.fetchAll(db, sql: "SELECT * FROM countries") XCTAssertEqual(rows.count, 1) XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France") let country2 = PersistableRecordCountry(isoCode: "US", name: "United States") try country2.save(db) country1.name = "France Métropolitaine" try country1.save(db) rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France Métropolitaine") XCTAssertEqual(rows[1]["isoCode"] as String, "US") XCTAssertEqual(rows[1]["name"] as String, "United States") try country1.delete(db) try country1.save(db) rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France Métropolitaine") XCTAssertEqual(rows[1]["isoCode"] as String, "US") XCTAssertEqual(rows[1]["name"] as String, "United States") } } func testDeletePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let country1 = PersistableRecordCountry(isoCode: "FR", name: "France") try country1.insert(db) let country2 = PersistableRecordCountry(isoCode: "US", name: "United States") try country2.insert(db) var deleted = try country1.delete(db) XCTAssertTrue(deleted) deleted = try country1.delete(db) XCTAssertFalse(deleted) let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 1) XCTAssertEqual(rows[0]["isoCode"] as String, "US") XCTAssertEqual(rows[0]["name"] as String, "United States") } } func testExistsPersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let country = PersistableRecordCountry(isoCode: "FR", name: "France") try country.insert(db) XCTAssertTrue(try country.exists(db)) try country.delete(db) XCTAssertFalse(try country.exists(db)) } } // MARK: - PersistableRecordCustomizedCountry func testInsertPersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let country = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France") try country.insert(db) XCTAssertEqual(country.callbacks.willInsertCount, 1) XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(country.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(country.callbacks.didInsertCount, 1) XCTAssertEqual(country.callbacks.willUpdateCount, 0) XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 0) XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) XCTAssertEqual(country.callbacks.didUpdateCount, 0) XCTAssertEqual(country.callbacks.willSaveCount, 1) XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(country.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(country.callbacks.didSaveCount, 1) XCTAssertEqual(country.callbacks.willDeleteCount, 0) XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(country.callbacks.didDeleteCount, 0) let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries") XCTAssertEqual(rows.count, 1) XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France") } } func testUpdatePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var country1 = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France") try country1.insert(db) let country2 = PersistableRecordCustomizedCountry( isoCode: "US", name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" try country1.update(db) XCTAssertEqual(self.lastSQLQuery, "UPDATE \"countries\" SET \"name\"='France Métropolitaine' WHERE \"isoCode\"='FR'") XCTAssertEqual(country1.callbacks.willInsertCount, 1) XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(country1.callbacks.didInsertCount, 1) XCTAssertEqual(country1.callbacks.willUpdateCount, 1) XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 1) XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) XCTAssertEqual(country1.callbacks.didUpdateCount, 1) XCTAssertEqual(country1.callbacks.willSaveCount, 2) XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 2) XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 2) XCTAssertEqual(country1.callbacks.didSaveCount, 2) XCTAssertEqual(country1.callbacks.willDeleteCount, 0) XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(country1.callbacks.didDeleteCount, 0) let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France Métropolitaine") XCTAssertEqual(rows[1]["isoCode"] as String, "US") XCTAssertEqual(rows[1]["name"] as String, "United States") } } func testPersistenceErrorPersistableRecordCustomizedCountry() throws { let country = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France") let dbQueue = try makeDatabaseQueue() do { try dbQueue.inDatabase { db in try country.update(db) } XCTFail("Expected PersistenceError") } catch PersistenceError.recordNotFound(databaseTableName: "countries", key: ["isoCode": "FR".databaseValue]) { } XCTAssertEqual(country.callbacks.willInsertCount, 0) XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 0) XCTAssertEqual(country.callbacks.aroundInsertExitCount, 0) XCTAssertEqual(country.callbacks.didInsertCount, 0) XCTAssertEqual(country.callbacks.willUpdateCount, 1) XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 1) XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) // last update has failed XCTAssertEqual(country.callbacks.didUpdateCount, 0) // last update has failed XCTAssertEqual(country.callbacks.willSaveCount, 1) XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(country.callbacks.aroundSaveExitCount, 0) // last update has failed XCTAssertEqual(country.callbacks.didSaveCount, 0) // last update has failed XCTAssertEqual(country.callbacks.willDeleteCount, 0) XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(country.callbacks.didDeleteCount, 0) } func testPartialUpdatePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var country1 = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France") try country1.insert(db) let country2 = PersistableRecordCustomizedCountry( isoCode: "US", name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" try country1.update(db, columns: ["name"]) XCTAssertEqual(self.lastSQLQuery, "UPDATE \"countries\" SET \"name\"='France Métropolitaine' WHERE \"isoCode\"='FR'") XCTAssertEqual(country1.callbacks.willInsertCount, 1) XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(country1.callbacks.didInsertCount, 1) XCTAssertEqual(country1.callbacks.willUpdateCount, 1) XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 1) XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) XCTAssertEqual(country1.callbacks.didUpdateCount, 1) XCTAssertEqual(country1.callbacks.willSaveCount, 2) XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 2) XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 2) XCTAssertEqual(country1.callbacks.didSaveCount, 2) XCTAssertEqual(country1.callbacks.willDeleteCount, 0) XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(country1.callbacks.didDeleteCount, 0) let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France Métropolitaine") XCTAssertEqual(rows[1]["isoCode"] as String, "US") XCTAssertEqual(rows[1]["name"] as String, "United States") } } func testSavePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var country1 = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France") try country1.save(db) XCTAssertEqual(country1.callbacks.willInsertCount, 1) XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(country1.callbacks.didInsertCount, 1) XCTAssertEqual(country1.callbacks.willUpdateCount, 1) XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 1) XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 0) // last update has failed XCTAssertEqual(country1.callbacks.didUpdateCount, 0) // last update has failed XCTAssertEqual(country1.callbacks.willSaveCount, 1) XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(country1.callbacks.didSaveCount, 1) XCTAssertEqual(country1.callbacks.willDeleteCount, 0) XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(country1.callbacks.didDeleteCount, 0) var rows = try Row.fetchAll(db, sql: "SELECT * FROM countries") XCTAssertEqual(rows.count, 1) XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France") let country2 = PersistableRecordCustomizedCountry( isoCode: "US", name: "United States") try country2.save(db) country1.name = "France Métropolitaine" try country1.save(db) XCTAssertEqual(country1.callbacks.willInsertCount, 1) XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(country1.callbacks.didInsertCount, 1) XCTAssertEqual(country1.callbacks.willUpdateCount, 2) XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 2) XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) XCTAssertEqual(country1.callbacks.didUpdateCount, 1) XCTAssertEqual(country1.callbacks.willSaveCount, 2) XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 2) XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 2) XCTAssertEqual(country1.callbacks.didSaveCount, 2) XCTAssertEqual(country1.callbacks.willDeleteCount, 0) XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(country1.callbacks.didDeleteCount, 0) rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France Métropolitaine") XCTAssertEqual(rows[1]["isoCode"] as String, "US") XCTAssertEqual(rows[1]["name"] as String, "United States") _ = try country1.delete(db) try country1.save(db) XCTAssertEqual(country1.callbacks.willInsertCount, 2) XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 2) XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 2) XCTAssertEqual(country1.callbacks.didInsertCount, 2) XCTAssertEqual(country1.callbacks.willUpdateCount, 3) XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 3) XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) // last update has failed XCTAssertEqual(country1.callbacks.didUpdateCount, 1) // last update has failed XCTAssertEqual(country1.callbacks.willSaveCount, 3) XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 3) XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 3) XCTAssertEqual(country1.callbacks.didSaveCount, 3) XCTAssertEqual(country1.callbacks.willDeleteCount, 1) XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 1) XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 1) XCTAssertEqual(country1.callbacks.didDeleteCount, 1) rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France Métropolitaine") XCTAssertEqual(rows[1]["isoCode"] as String, "US") XCTAssertEqual(rows[1]["name"] as String, "United States") } } func testDeletePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let country1 = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France") try country1.insert(db) let country2 = PersistableRecordCustomizedCountry( isoCode: "US", name: "United States") try country2.insert(db) var deleted = try country1.delete(db) XCTAssertTrue(deleted) deleted = try country1.delete(db) XCTAssertFalse(deleted) XCTAssertEqual(country1.callbacks.willInsertCount, 1) XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(country1.callbacks.didInsertCount, 1) XCTAssertEqual(country1.callbacks.willUpdateCount, 0) XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 0) XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 0) XCTAssertEqual(country1.callbacks.didUpdateCount, 0) XCTAssertEqual(country1.callbacks.willSaveCount, 1) XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(country1.callbacks.didSaveCount, 1) XCTAssertEqual(country1.callbacks.willDeleteCount, 2) XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 2) XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 2) XCTAssertEqual(country1.callbacks.didDeleteCount, 2) let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 1) XCTAssertEqual(rows[0]["isoCode"] as String, "US") XCTAssertEqual(rows[0]["name"] as String, "United States") } } func testExistsPersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let country = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France") try country.insert(db) XCTAssertTrue(try country.exists(db)) XCTAssertEqual(country.callbacks.willInsertCount, 1) XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(country.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(country.callbacks.didInsertCount, 1) XCTAssertEqual(country.callbacks.willUpdateCount, 0) XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 0) XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) XCTAssertEqual(country.callbacks.didUpdateCount, 0) XCTAssertEqual(country.callbacks.willSaveCount, 1) XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(country.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(country.callbacks.didSaveCount, 1) XCTAssertEqual(country.callbacks.willDeleteCount, 0) XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(country.callbacks.didDeleteCount, 0) _ = try country.delete(db) XCTAssertFalse(try country.exists(db)) XCTAssertEqual(country.callbacks.willInsertCount, 1) XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(country.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(country.callbacks.didInsertCount, 1) XCTAssertEqual(country.callbacks.willUpdateCount, 0) XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 0) XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) XCTAssertEqual(country.callbacks.didUpdateCount, 0) XCTAssertEqual(country.callbacks.willSaveCount, 1) XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(country.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(country.callbacks.didSaveCount, 1) XCTAssertEqual(country.callbacks.willDeleteCount, 1) XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 1) XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 1) XCTAssertEqual(country.callbacks.didDeleteCount, 1) } } // MARK: - Errors func testInsertErrorDoesNotPreventSubsequentInserts() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let person = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 12) try person.insert(db) try PersistableRecordCountry(isoCode: "FR", name: "France").insert(db) do { try Citizenship(personID: person.id!, countryIsoCode: "US").insert(db) } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) } try Citizenship(personID: person.id!, countryIsoCode: "FR").insert(db) } } } // MARK: - Custom nested Codable types - nested saved as JSON extension PersistableRecordTests { func testOptionalNestedStruct() throws { struct NestedStruct : Codable { let firstName: String? let lastName: String? } struct StructWithNestedType : PersistableRecord, Codable { static let databaseTableName = "t1" let nested: NestedStruct? } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("nested", .text) } let nested = NestedStruct(firstName: "Bob", lastName: "Dylan") let value = StructWithNestedType(nested: nested) try value.insert(db) let dbValue = try DatabaseValue.fetchOne(db, sql: "SELECT nested FROM t1")! // Encodable has a default implementation which encodes a model to JSON as String. // We expect here JSON in the form of a String XCTAssert(dbValue.storage.value is String) let string = dbValue.storage.value as! String if let data = string.data(using: .utf8) { do { let decoded = try JSONDecoder().decode(NestedStruct.self, from: data) XCTAssertEqual(nested.firstName, decoded.firstName) XCTAssertEqual(nested.lastName, decoded.lastName) } catch { XCTFail(error.localizedDescription) } } else { XCTFail("Failed to convert " + string) } } } func testOptionalNestedStructNil() throws { struct NestedStruct : Encodable { let firstName: String? let lastName: String? } struct StructWithNestedType : PersistableRecord, Encodable { static let databaseTableName = "t1" let nested: NestedStruct? } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("nested", .text) } let value = StructWithNestedType(nested: nil) try value.insert(db) let dbValue = try DatabaseValue.fetchOne(db, sql: "SELECT nested FROM t1")! // We expect here nil XCTAssertNil(dbValue.storage.value) } } func testOptionalNestedArrayStruct() throws { struct NestedStruct : Codable { let firstName: String? let lastName: String? } struct StructWithNestedType : PersistableRecord, Codable { static let databaseTableName = "t1" let nested: [NestedStruct]? } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("nested", .text) } let nested = NestedStruct(firstName: "Bob", lastName: "Dylan") let value = StructWithNestedType(nested: [nested, nested]) try value.insert(db) let dbValue = try DatabaseValue.fetchOne(db, sql: "SELECT nested FROM t1")! // Encodable has a default implementation which encodes a model to JSON as String. // We expect here JSON in the form of a String XCTAssert(dbValue.storage.value is String) let string = dbValue.storage.value as! String if let data = string.data(using: .utf8) { do { let decoded = try JSONDecoder().decode([NestedStruct].self, from: data) XCTAssertEqual(decoded.count, 2) XCTAssertEqual(nested.firstName, decoded.first!.firstName) XCTAssertEqual(nested.lastName, decoded.first!.lastName) XCTAssertEqual(nested.firstName, decoded.last!.firstName) XCTAssertEqual(nested.lastName, decoded.last!.lastName) } catch { XCTFail(error.localizedDescription) } } else { XCTFail("Failed to convert " + string) } } } func testOptionalNestedArrayStructNil() throws { struct NestedStruct : Encodable { let firstName: String? let lastName: String? } struct StructWithNestedType : PersistableRecord, Encodable { static let databaseTableName = "t1" let nested: [NestedStruct]? } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("nested", .text) } let value = StructWithNestedType(nested: nil) try value.insert(db) let dbValue = try DatabaseValue.fetchOne(db, sql: "SELECT nested FROM t1")! // We expect here nil XCTAssertNil(dbValue.storage.value) } } func testNonOptionalNestedStruct() throws { struct NestedStruct : Codable { let firstName: String let lastName: String } struct StructWithNestedType : PersistableRecord, Codable { static let databaseTableName = "t1" let nested: NestedStruct } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("nested", .text) } let nested = NestedStruct(firstName: "Bob", lastName: "Dylan") let value = StructWithNestedType(nested: nested) try value.insert(db) let dbValue = try DatabaseValue.fetchOne(db, sql: "SELECT nested FROM t1")! // Encodable has a default implementation which encodes a model to JSON as String. // We expect here JSON in the form of a String XCTAssert(dbValue.storage.value is String) let string = dbValue.storage.value as! String if let data = string.data(using: .utf8) { do { let decoded = try JSONDecoder().decode(NestedStruct.self, from: data) XCTAssertEqual(nested.firstName, decoded.firstName) XCTAssertEqual(nested.lastName, decoded.lastName) } catch { XCTFail(error.localizedDescription) } } else { XCTFail("Failed to convert " + string) } } } func testNonOptionalNestedArrayStruct() throws { struct NestedStruct : Codable { let firstName: String let lastName: String } struct StructWithNestedType : PersistableRecord, Codable { static let databaseTableName = "t1" let nested: [NestedStruct] } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("nested", .text) } let nested = NestedStruct(firstName: "Bob", lastName: "Dylan") let value = StructWithNestedType(nested: [nested]) try value.insert(db) let dbValue = try DatabaseValue.fetchOne(db, sql: "SELECT nested FROM t1")! // Encodable has a default implementation which encodes a model to JSON as String. // We expect here JSON in the form of a String XCTAssert(dbValue.storage.value is String) let string = dbValue.storage.value as! String if let data = string.data(using: .utf8) { do { let decoded = try JSONDecoder().decode([NestedStruct].self, from: data) XCTAssertEqual(nested.firstName, decoded.first!.firstName) XCTAssertEqual(nested.lastName, decoded.first!.lastName) } catch { XCTFail(error.localizedDescription) } } else { XCTFail("Failed to convert " + string) } } } func testStringStoredInArray() throws { struct TestStruct : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" let numbers: [String] } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("numbers", .text) } let model = TestStruct(numbers: ["test1", "test2", "test3"]) try model.insert(db) // Encodable has a default implementation which encodes a model to JSON as String. // We expect here JSON in the form of a String guard let fetchModel = try TestStruct.fetchOne(db) else { XCTFail("Could not find record in db") return } XCTAssertEqual(model.numbers, fetchModel.numbers) } } func testOptionalStringStoredInArray() throws { struct TestStruct : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" let numbers: [String]? } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("numbers", .text) } let model = TestStruct(numbers: ["test1", "test2", "test3"]) try model.insert(db) // Encodable has a default implementation which encodes a model to JSON as String. // We expect here JSON in the form of a String guard let fetchModel = try TestStruct.fetchOne(db) else { XCTFail("Could not find record in db") return } XCTAssertEqual(model.numbers, fetchModel.numbers) } } } // MARK: - Insert and Fetch extension PersistableRecordTests { func test_insertAndFetch_as() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard sqlite3_libversion_number() >= 3035000 else { throw XCTSkip("RETURNING clause is not available") } #else guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { throw XCTSkip("RETURNING clause is not available") } #endif let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { sqlQueries.removeAll() let partialPlayer = PartialPlayer(name: "Arthur") let fullPlayer = try XCTUnwrap(partialPlayer.insertAndFetch(db, as: FullPlayer.self)) XCTAssert(sqlQueries.contains(""" INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING * """), sqlQueries.joined(separator: "\n")) XCTAssertEqual(fullPlayer.id, 1) XCTAssertEqual(fullPlayer.name, "Arthur") XCTAssertEqual(fullPlayer.score, 1000) XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) } } } func test_insertAndFetch_selection_fetch() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard sqlite3_libversion_number() >= 3035000 else { throw XCTSkip("RETURNING clause is not available") } #else guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { throw XCTSkip("RETURNING clause is not available") } #endif let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { sqlQueries.removeAll() let partialPlayer = PartialPlayer(name: "Arthur") let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { (statement: Statement) in try Int.fetchOne(statement)! } XCTAssert(sqlQueries.contains(""" INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "score" """), sqlQueries.joined(separator: "\n")) XCTAssertEqual(score, 1000) XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) } } } } // MARK: - Save and Fetch extension PersistableRecordTests { func test_saveAndFetch_as() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard sqlite3_libversion_number() >= 3035000 else { throw XCTSkip("RETURNING clause is not available") } #else guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { throw XCTSkip("RETURNING clause is not available") } #endif let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { sqlQueries.removeAll() let partialPlayer = PartialPlayer(name: "Arthur") let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") }) XCTAssert(sqlQueries.contains(""" INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING * """), sqlQueries.joined(separator: "\n")) XCTAssertEqual(fullPlayer.id, 1) XCTAssertEqual(fullPlayer.name, "Arthur") XCTAssertEqual(fullPlayer.score, 1000) XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) } do { let partialPlayer = PartialPlayer(id: 1, name: "Arthur") try partialPlayer.delete(db) sqlQueries.removeAll() let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) XCTAssert(sqlQueries.contains(""" UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING * """), sqlQueries.joined(separator: "\n")) XCTAssert(sqlQueries.contains(""" INSERT INTO "player" ("id", "name") VALUES (1,'Arthur') RETURNING * """), sqlQueries.joined(separator: "\n")) XCTAssertEqual(fullPlayer.id, 1) XCTAssertEqual(fullPlayer.name, "Arthur") XCTAssertEqual(fullPlayer.score, 1000) XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 1) } do { sqlQueries.removeAll() let partialPlayer = PartialPlayer(id: 1, name: "Arthur") let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") }) XCTAssert(sqlQueries.contains(""" UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING * """), sqlQueries.joined(separator: "\n")) XCTAssertEqual(fullPlayer.id, 1) XCTAssertEqual(fullPlayer.name, "Arthur") XCTAssertEqual(fullPlayer.score, 1000) XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 0) XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 1) XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) } } } func test_saveAndFetch_selection_fetch() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard sqlite3_libversion_number() >= 3035000 else { throw XCTSkip("RETURNING clause is not available") } #else guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { throw XCTSkip("RETURNING clause is not available") } #endif let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { sqlQueries.removeAll() let partialPlayer = PartialPlayer(name: "Arthur") let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in try Int.fetchOne(statement) } XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") }) XCTAssert(sqlQueries.contains(""" INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "score" """), sqlQueries.joined(separator: "\n")) XCTAssertEqual(score, 1000) XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) } do { let partialPlayer = PartialPlayer(id: 1, name: "Arthur") try partialPlayer.delete(db) sqlQueries.removeAll() let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in try Int.fetchOne(statement) } XCTAssert(sqlQueries.contains(""" UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING "score" """), sqlQueries.joined(separator: "\n")) XCTAssert(sqlQueries.contains(""" INSERT INTO "player" ("id", "name") VALUES (1,'Arthur') RETURNING "score" """), sqlQueries.joined(separator: "\n")) XCTAssertEqual(score, 1000) XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 1) } do { sqlQueries.removeAll() let partialPlayer = PartialPlayer(id: 1, name: "Arthur") let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in try Int.fetchOne(statement) } XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") }) XCTAssert(sqlQueries.contains(""" UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING "score" """), sqlQueries.joined(separator: "\n")) XCTAssertEqual(score, 1000) XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 0) XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 1) XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) } } } } // MARK: - Upsert extension PersistableRecordTests { func test_upsert() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard sqlite3_libversion_number() >= 3035000 else { throw XCTSkip("UPSERT is not available") } #else guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { throw XCTSkip("UPSERT is not available") } #endif try makeDatabaseQueue().write { db in do { let player = FullPlayer(name: "Arthur", score: 1000) try player.upsert(db) // Test SQL XCTAssertEqual(lastSQLQuery, """ INSERT INTO "player" ("id", "name", "score") \ VALUES (NULL,'Arthur',1000) \ ON CONFLICT DO UPDATE SET "name" = "excluded"."name", "score" = "excluded"."score" \ RETURNING "rowid" """) // Test database state let rows = try Row.fetchAll(db, FullPlayer.orderByPrimaryKey()) XCTAssertEqual(rows, [ ["id": 1, "name": "Arthur", "score":1000], ]) // Test callbacks XCTAssertEqual(player.callbacks.willInsertCount, 1) XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(player.callbacks.didInsertCount, 1) XCTAssertEqual(player.callbacks.willUpdateCount, 0) XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 0) XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 0) XCTAssertEqual(player.callbacks.didUpdateCount, 0) XCTAssertEqual(player.callbacks.willSaveCount, 1) XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(player.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(player.callbacks.didSaveCount, 1) XCTAssertEqual(player.callbacks.willDeleteCount, 0) XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(player.callbacks.didDeleteCount, 0) } // Test conflict on name do { // Set the last inserted row id to some arbitrary value _ = try FullPlayer(id: 42, name: "Barbara", score: 0).inserted(db) XCTAssertNotEqual(db.lastInsertedRowID, 1) let player = FullPlayer(name: "Arthur", score: 100) try player.upsert(db) // Test database state let rows = try Row.fetchAll(db, FullPlayer.orderByPrimaryKey()) XCTAssertEqual(rows, [ ["id": 1, "name": "Arthur", "score":100], ["id": 42, "name": "Barbara", "score":0], ]) } // Test conflict on id do { let player = FullPlayer(id: 1, name: "Craig", score: 500) try player.upsert(db) // Test database state let rows = try Row.fetchAll(db, FullPlayer.orderByPrimaryKey()) XCTAssertEqual(rows, [ ["id": 1, "name": "Craig", "score":500], ["id": 42, "name": "Barbara", "score":0], ]) } // Test conflict on both id and name (same row) do { let player = FullPlayer(id: 1, name: "Craig", score: 200) try player.upsert(db) // Test database state let rows = try Row.fetchAll(db, FullPlayer.orderByPrimaryKey()) XCTAssertEqual(rows, [ ["id": 1, "name": "Craig", "score":200], ["id": 42, "name": "Barbara", "score":0], ]) } // Test conflict on both id and name (different rows) do { let player = FullPlayer(id: 1, name: "Barbara", score: 300) do { try player.upsert(db) XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.message, "UNIQUE constraint failed: player.name") XCTAssertEqual(error.sql!, """ INSERT INTO "player" ("id", "name", "score") \ VALUES (?,?,?) \ ON CONFLICT DO UPDATE SET "name" = "excluded"."name", "score" = "excluded"."score" \ RETURNING "rowid" """) } // Test callbacks XCTAssertEqual(player.callbacks.willInsertCount, 1) XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(player.callbacks.aroundInsertExitCount, 0) XCTAssertEqual(player.callbacks.didInsertCount, 0) XCTAssertEqual(player.callbacks.willUpdateCount, 0) XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 0) XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 0) XCTAssertEqual(player.callbacks.didUpdateCount, 0) XCTAssertEqual(player.callbacks.willSaveCount, 1) XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(player.callbacks.aroundSaveExitCount, 0) XCTAssertEqual(player.callbacks.didSaveCount, 0) XCTAssertEqual(player.callbacks.willDeleteCount, 0) XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(player.callbacks.didDeleteCount, 0) } } } func test_upsertAndFetch_do_update_set_where() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard sqlite3_libversion_number() >= 3035000 else { throw XCTSkip("UPSERT is not available") } #else guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { throw XCTSkip("UPSERT is not available") } #endif try makeDatabaseQueue().write { db in // Test exemples of https://www.sqlite.org/lang_UPSERT.html do { try db.execute(sql: """ CREATE TABLE vocabulary( word TEXT PRIMARY KEY, kind TEXT, isTainted BOOLEAN DEFAULT 0, count INT DEFAULT 1); INSERT INTO vocabulary(word, isTainted) VALUES('jovial', 1); """) struct Vocabulary: Decodable, PersistableRecord, FetchableRecord { var word: String var kind: String var isTainted: Bool var count: Int? func encode(to container: inout PersistenceContainer) { // Don't encode count container["word"] = word container["kind"] = kind container["isTainted"] = isTainted } } // One column with specific assignment (count) // One column with no assignment (isTainted) // One column with default overwrite assignment (kind) do { let vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false) let upserted = try vocabulary.upsertAndFetch( db, onConflict: ["word"], doUpdate: { _ in [Column("count") += 1, // increment count Column("isTainted").noOverwrite] // don't overwrite isTainted }) // Test SQL XCTAssertEqual(lastSQLQuery, """ INSERT INTO "vocabulary" ("word", "kind", "isTainted") \ VALUES ('jovial','adjective',0) \ ON CONFLICT("word") \ DO UPDATE SET "count" = "count" + 1, "kind" = "excluded"."kind" \ RETURNING *, "rowid" """) // Test database state let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary") XCTAssertEqual(rows, [ ["word": "jovial", "kind": "adjective", "isTainted": 1, "count": 2], ]) // Test upserted record XCTAssertEqual(upserted.word, "jovial") XCTAssertEqual(upserted.kind, "adjective") XCTAssertEqual(upserted.isTainted, true) // Not overwritten XCTAssertEqual(upserted.count, 2) // incremented } // All columns with no assignment: make sure we return something do { let vocabulary = Vocabulary(word: "jovial", kind: "ignored", isTainted: false) let upserted = try vocabulary.upsertAndFetch( db, onConflict: ["word"], doUpdate: { _ in [Column("count").noOverwrite, Column("isTainted").noOverwrite, Column("kind").noOverwrite] }) // Test SQL (the DO UPDATE clause is not empty, so that the // RETURNING clause could return something). XCTAssertEqual(lastSQLQuery, """ INSERT INTO "vocabulary" ("word", "kind", "isTainted") \ VALUES ('jovial','ignored',0) \ ON CONFLICT("word") \ DO UPDATE SET "word" = "word" \ RETURNING *, "rowid" """) // Test database state let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary") XCTAssertEqual(rows, [ ["word": "jovial", "kind": "adjective", "isTainted": 1, "count": 2], ]) // Test upserted record XCTAssertEqual(upserted.word, "jovial") XCTAssertEqual(upserted.kind, "adjective") XCTAssertEqual(upserted.isTainted, true) XCTAssertEqual(upserted.count, 2) } } do { try db.execute(sql: """ CREATE TABLE phonebook(name TEXT PRIMARY KEY, phonenumber TEXT); INSERT INTO phonebook(name,phonenumber) VALUES('Alice','ignored'); """) struct Phonebook: Codable, PersistableRecord, FetchableRecord { var name: String var phonenumber: String } let phonebook = Phonebook(name: "Alice", phonenumber: "704-555-1212") let upserted = try phonebook.upsertAndFetch( db, onConflict: ["name"], doUpdate: { excluded in [Column("phonenumber").set(to: excluded["phonenumber"])] }) // Test SQL XCTAssertEqual(lastSQLQuery, """ INSERT INTO "phonebook" ("name", "phonenumber") \ VALUES ('Alice','704-555-1212') \ ON CONFLICT("name") DO UPDATE SET "phonenumber" = "excluded"."phonenumber" \ RETURNING *, "rowid" """) // Test database state let rows = try Row.fetchAll(db, sql: "SELECT * FROM phonebook") XCTAssertEqual(rows, [ ["name": "Alice", "phonenumber": "704-555-1212"], ]) // Test upserted record XCTAssertEqual(upserted.name, "Alice") XCTAssertEqual(upserted.phonenumber, "704-555-1212") } } } func test_upsertAndFetch() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard sqlite3_libversion_number() >= 3035000 else { throw XCTSkip("UPSERT is not available") } #else guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { throw XCTSkip("UPSERT is not available") } #endif let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { sqlQueries.removeAll() let player = FullPlayer(id: 1, name: "Arthur", score: 1000) let upsertedPlayer = try player.upsertAndFetch(db) XCTAssert(sqlQueries.contains(""" INSERT INTO "player" ("id", "name", "score") \ VALUES (1,'Arthur',1000) \ ON CONFLICT DO UPDATE SET "name" = "excluded"."name", "score" = "excluded"."score" \ RETURNING *, "rowid" """), sqlQueries.joined(separator: "\n")) // Test database state let rows = try Row.fetchAll(db, FullPlayer.orderByPrimaryKey()) XCTAssertEqual(rows, [ ["id": 1, "name": "Arthur", "score":1000], ]) XCTAssertEqual(player.id, 1) XCTAssertEqual(upsertedPlayer.id, 1) XCTAssertEqual(upsertedPlayer.name, "Arthur") XCTAssertEqual(upsertedPlayer.score, 1000) XCTAssertEqual(player.callbacks.willInsertCount, 1) XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(player.callbacks.didInsertCount, 1) XCTAssertEqual(player.callbacks.willUpdateCount, 0) XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 0) XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 0) XCTAssertEqual(player.callbacks.didUpdateCount, 0) XCTAssertEqual(player.callbacks.willSaveCount, 1) XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(player.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(player.callbacks.didSaveCount, 1) XCTAssertEqual(player.callbacks.willDeleteCount, 0) XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(player.callbacks.didDeleteCount, 0) } do { sqlQueries.removeAll() let player = FullPlayer(id: 1, name: "Barbara", score: 100) let upsertedPlayer = try player.upsertAndFetch(db) XCTAssert(sqlQueries.contains(""" INSERT INTO "player" ("id", "name", "score") \ VALUES (1,'Barbara',100) \ ON CONFLICT DO UPDATE SET "name" = "excluded"."name", "score" = "excluded"."score" \ RETURNING *, "rowid" """), sqlQueries.joined(separator: "\n")) // Test database state let rows = try Row.fetchAll(db, FullPlayer.orderByPrimaryKey()) XCTAssertEqual(rows, [ ["id": 1, "name": "Barbara", "score":100], ]) XCTAssertEqual(player.id, 1) XCTAssertEqual(upsertedPlayer.id, 1) XCTAssertEqual(upsertedPlayer.name, "Barbara") XCTAssertEqual(upsertedPlayer.score, 100) XCTAssertEqual(player.callbacks.willInsertCount, 1) XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(player.callbacks.didInsertCount, 1) XCTAssertEqual(player.callbacks.willUpdateCount, 0) XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 0) XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 0) XCTAssertEqual(player.callbacks.didUpdateCount, 0) XCTAssertEqual(player.callbacks.willSaveCount, 1) XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(player.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(player.callbacks.didSaveCount, 1) XCTAssertEqual(player.callbacks.willDeleteCount, 0) XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(player.callbacks.didDeleteCount, 0) } } } func test_upsertAndFetch_as() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard sqlite3_libversion_number() >= 3035000 else { throw XCTSkip("UPSERT is not available") } #else guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { throw XCTSkip("UPSERT is not available") } #endif let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { sqlQueries.removeAll() let partialPlayer = PartialPlayer(name: "Arthur") let fullPlayer = try partialPlayer.upsertAndFetch(db, as: FullPlayer.self) XCTAssert(sqlQueries.contains(""" INSERT INTO "player" ("id", "name") \ VALUES (NULL,'Arthur') \ ON CONFLICT DO UPDATE SET "name" = "excluded"."name" \ RETURNING *, "rowid" """), sqlQueries.joined(separator: "\n")) XCTAssertEqual(fullPlayer.id, 1) XCTAssertEqual(fullPlayer.name, "Arthur") XCTAssertEqual(fullPlayer.score, 1000) XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) } } } }
mit
c47a9681bfa529211b76b61f2a21a3b0
43.03401
133
0.575252
5.07099
false
false
false
false
tad-iizuka/swift-sdk
Source/NaturalLanguageClassifierV1/Models/ClassifierDetails.swift
3
2432
/** * Copyright IBM Corporation 2016 * * 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 /** A classifer supported by the Natural Language Classifier service. */ public struct ClassifierDetails: JSONDecodable { /// A unique identifier for this classifier. public let classifierId: String /// The user-supplied name of the classifier. public let name: String? /// The language used for the classifier. public let language: String /// The date and time (UTC) that the classifier was created. public let created: String /// A link to the classifer. public let url: String /// The classifier's status. public let status: ClassifierStatus /// A human-readable descriptiono of the classifier's status. public let statusDescription: String /// Used internally to initialize a `ClassifierDetails` model from JSON. public init(json: JSON) throws { classifierId = try json.getString(at: "classifier_id") name = try? json.getString(at: "name") language = try json.getString(at: "language") created = try json.getString(at: "created") url = try json.getString(at: "url") statusDescription = try json.getString(at: "status_description") guard let classifierStatus = ClassifierStatus(rawValue: try json.getString(at: "status")) else { throw JSON.Error.valueNotConvertible(value: json, to: ClassifierStatus.self) } status = classifierStatus } } /** The status of a classifier. */ public enum ClassifierStatus: String { /// Available case available = "Available" /// Failed case failed = "Failed" /// NonExistent case nonExistent = "Non Existent" /// Training case training = "Training" /// Unavailable case unavailable = "Unavailable" }
apache-2.0
cd0185d2d0cabb262968f5e7cf569de0
30.584416
104
0.671875
4.562852
false
false
false
false
ixx1232/CoreDataStudt
CoreDataStudy/CoreDataStudy/AppDelegate.swift
1
6100
// // AppDelegate.swift // CoreDataStudy // // Created by apple on 15/12/31. // Copyright © 2015年 www.ixx.com. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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 "com.ixx.CoreDataStudy" 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("CoreDataStudy", 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
9fea968c992e7248b08cc42f5cedbaf6
53.927928
291
0.719698
5.87946
false
false
false
false
swiftix/swift
test/SILGen/objc_extensions.swift
1
10492
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs/ -I %S/Inputs -enable-source-import %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import objc_extensions_helper class Sub : Base {} extension Sub { override var prop: String! { didSet { // Ignore it. } // Make sure that we are generating the @objc thunk and are calling the actual method. // // CHECK-LABEL: sil hidden [thunk] @_T015objc_extensions3SubC4propSQySSGvgTo : $@convention(objc_method) (Sub) -> @autoreleased Optional<NSString> { // CHECK: bb0([[SELF:%.*]] : $Sub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[GETTER_FUNC:%.*]] = function_ref @_T015objc_extensions3SubC4propSQySSGvg : $@convention(method) (@guaranteed Sub) -> @owned Optional<String> // CHECK: apply [[GETTER_FUNC]]([[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: } // end sil function '_T015objc_extensions3SubC4propSQySSGvgTo' // Then check the body of the getter calls the super_method. // CHECK-LABEL: sil hidden @_T015objc_extensions3SubC4propSQySSGvg : $@convention(method) (@guaranteed Sub) -> @owned Optional<String> { // CHECK: bb0([[SELF:%.*]] : $Sub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[SELF_COPY_CAST:%.*]] = upcast [[SELF_COPY]] : $Sub to $Base // CHECK: [[BORROWED_SELF_COPY_CAST:%.*]] = begin_borrow [[SELF_COPY_CAST]] // CHECK: [[CAST_BACK:%.*]] = unchecked_ref_cast [[BORROWED_SELF_COPY_CAST]] : $Base to $Sub // CHECK: [[SUPER_METHOD:%.*]] = objc_super_method [[CAST_BACK]] : $Sub, #Base.prop!getter.1.foreign // CHECK: end_borrow [[BORROWED_SELF_COPY_CAST]] // CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[SELF_COPY_CAST]]) // CHECK: bb3( // CHECK: destroy_value [[SELF_COPY_CAST]] // CHECK: } // end sil function '_T015objc_extensions3SubC4propSQySSGvg' // Then check the setter @objc thunk. // // CHECK-LABEL: sil hidden [thunk] @_T015objc_extensions3SubC4propSQySSGvsTo : $@convention(objc_method) (Optional<NSString>, Sub) -> () { // CHECK: bb0([[NEW_VALUE:%.*]] : $Optional<NSString>, [[SELF:%.*]] : $Sub): // CHECK: [[NEW_VALUE_COPY:%.*]] = copy_value [[NEW_VALUE]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Sub // CHECK: switch_enum [[NEW_VALUE_COPY]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SUCC_BB:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL_BB:bb[0-9]+]] // CHECK: [[SUCC_BB]]([[STR:%.*]] : $NSString): // CHECK: [[FAIL_BB]]: // CHECK: bb3([[BRIDGED_NEW_VALUE:%.*]] : $Optional<String>): // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NORMAL_FUNC:%.*]] = function_ref @_T015objc_extensions3SubC4propSQySSGvs : $@convention(method) (@owned Optional<String>, @guaranteed Sub) -> () // CHECK: apply [[NORMAL_FUNC]]([[BRIDGED_NEW_VALUE]], [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: } // end sil function '_T015objc_extensions3SubC4propSQySSGvsTo' // Then check the body of the actually setter value and make sure that we // call the didSet function. // CHECK-LABEL: sil hidden @_T015objc_extensions3SubC4propSQySSGvs : $@convention(method) (@owned Optional<String>, @guaranteed Sub) -> () { // First we get the old value. // CHECK: bb0([[NEW_VALUE:%.*]] : $Optional<String>, [[SELF:%.*]] : $Sub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_SELF_COPY:%.*]] = upcast [[SELF_COPY]] : $Sub to $Base // CHECK: [[BORROWED_UPCAST_SELF_COPY:%.*]] = begin_borrow [[UPCAST_SELF_COPY]] // CHECK: [[CAST_BACK:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_SELF_COPY]] : $Base to $Sub // CHECK: [[GET_SUPER_METHOD:%.*]] = objc_super_method [[CAST_BACK]] : $Sub, #Base.prop!getter.1.foreign : (Base) -> () -> String!, $@convention(objc_method) (Base) -> @autoreleased Optional<NSString> // CHECK: end_borrow [[BORROWED_UPCAST_SELF_COPY]] from [[UPCAST_SELF_COPY]] // CHECK: [[OLD_NSSTRING:%.*]] = apply [[GET_SUPER_METHOD]]([[UPCAST_SELF_COPY]]) // CHECK: bb3([[OLD_NSSTRING_BRIDGED:%.*]] : $Optional<String>): // This next line is completely not needed. But we are emitting it now. // CHECK: destroy_value [[UPCAST_SELF_COPY]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_SELF_COPY:%.*]] = upcast [[SELF_COPY]] : $Sub to $Base // CHECK: [[BORROWED_UPCAST_SELF:%.*]] = begin_borrow [[UPCAST_SELF_COPY]] : $Base // CHECK: [[SUPERREF_DOWNCAST:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_SELF]] : $Base to $Sub // CHECK: [[SET_SUPER_METHOD:%.*]] = objc_super_method [[SUPERREF_DOWNCAST]] : $Sub, #Base.prop!setter.1.foreign : (Base) -> (String!) -> (), $@convention(objc_method) (Optional<NSString>, Base) -> () // CHECK: end_borrow [[BORROWED_UPCAST_SELF]] // CHECK: [[BORROWED_NEW_VALUE:%.*]] = begin_borrow [[NEW_VALUE]] // CHECK: [[NEW_VALUE_COPY:%.*]] = copy_value [[BORROWED_NEW_VALUE]] // CHECK: switch_enum [[NEW_VALUE_COPY]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: bb4([[OLD_STRING:%.*]] : $String): // CHECK: bb6([[BRIDGED_NEW_STRING:%.*]] : $Optional<NSString>): // CHECK: end_borrow [[BORROWED_NEW_VALUE]] // CHECK: apply [[SET_SUPER_METHOD]]([[BRIDGED_NEW_STRING]], [[UPCAST_SELF_COPY]]) // CHECK: destroy_value [[BRIDGED_NEW_STRING]] // CHECK: destroy_value [[UPCAST_SELF_COPY]] // CHECK: [[DIDSET_NOTIFIER:%.*]] = function_ref @_T015objc_extensions3SubC4propSQySSGvW : $@convention(method) (@owned Optional<String>, @guaranteed Sub) -> () // CHECK: [[BORROWED_OLD_NSSTRING_BRIDGED:%.*]] = begin_borrow [[OLD_NSSTRING_BRIDGED]] // CHECK: [[COPIED_OLD_NSSTRING_BRIDGED:%.*]] = copy_value [[BORROWED_OLD_NSSTRING_BRIDGED]] // CHECK: end_borrow [[BORROWED_OLD_NSSTRING_BRIDGED]] from [[OLD_NSSTRING_BRIDGED]] // This is an identity cast that should be eliminated by SILGen peepholes. // CHECK: apply [[DIDSET_NOTIFIER]]([[COPIED_OLD_NSSTRING_BRIDGED]], [[SELF]]) // CHECK: destroy_value [[OLD_NSSTRING_BRIDGED]] // CHECK: destroy_value [[NEW_VALUE]] // CHECK: } // end sil function '_T015objc_extensions3SubC4propSQySSGvs' } func foo() { } override func objCBaseMethod() {} } // CHECK-LABEL: sil hidden @_T015objc_extensions20testOverridePropertyyAA3SubCF func testOverrideProperty(_ obj: Sub) { // CHECK: bb0([[ARG:%.*]] : $Sub): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: = objc_method [[BORROWED_ARG]] : $Sub, #Sub.prop!setter.1.foreign : (Sub) -> (String!) -> () obj.prop = "abc" } // CHECK: } // end sil function '_T015objc_extensions20testOverridePropertyyAA3SubCF' testOverrideProperty(Sub()) // CHECK-LABEL: sil shared [thunk] @_T015objc_extensions3SubC3fooyyFTc // CHECK: function_ref @_T015objc_extensions3SubC3fooyyFTD // CHECK: } // end sil function '_T015objc_extensions3SubC3fooyyFTc' // CHECK: sil shared [transparent] [serializable] [thunk] @_T015objc_extensions3SubC3fooyyFTD // CHECK: bb0([[SELF:%.*]] : $Sub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: objc_method [[SELF_COPY]] : $Sub, #Sub.foo!1.foreign // CHECK: } // end sil function '_T015objc_extensions3SubC3fooyyFTD' func testCurry(_ x: Sub) { _ = x.foo } extension Sub { var otherProp: String { get { return "hello" } set { } } } class SubSub : Sub { // CHECK-LABEL: sil hidden @_T015objc_extensions03SubC0C14objCBaseMethodyyF // CHECK: bb0([[SELF:%.*]] : $SubSub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_SELF_COPY:%.*]] = upcast [[SELF_COPY]] : $SubSub to $Sub // CHECK: [[BORROWED_UPCAST_SELF_COPY:%.*]] = begin_borrow [[UPCAST_SELF_COPY]] // CHECK: [[DOWNCAST:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_SELF_COPY]] : $Sub to $SubSub // CHECK: objc_super_method [[DOWNCAST]] : $SubSub, #Sub.objCBaseMethod!1.foreign : (Sub) -> () -> (), $@convention(objc_method) (Sub) -> () // CHECK: end_borrow [[BORROWED_UPCAST_SELF_COPY]] from [[UPCAST_SELF_COPY]] // CHECK: } // end sil function '_T015objc_extensions03SubC0C14objCBaseMethodyyF' override func objCBaseMethod() { super.objCBaseMethod() } } extension SubSub { // CHECK-LABEL: sil hidden @_T015objc_extensions03SubC0C9otherPropSSvs // CHECK: bb0([[NEW_VALUE:%.*]] : $String, [[SELF:%.*]] : $SubSub): // CHECK: [[SELF_COPY_1:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_SELF_COPY_1:%.*]] = upcast [[SELF_COPY_1]] : $SubSub to $Sub // CHECK: [[BORROWED_UPCAST_SELF_COPY_1:%.*]] = begin_borrow [[UPCAST_SELF_COPY_1]] // CHECK: [[DOWNCAST_BORROWED_UPCAST_SELF_COPY_1:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_SELF_COPY_1]] : $Sub to $SubSub // CHECK: = objc_super_method [[DOWNCAST_BORROWED_UPCAST_SELF_COPY_1]] : $SubSub, #Sub.otherProp!getter.1.foreign // CHECK: end_borrow [[BORROWED_UPCAST_SELF_COPY_1]] from [[UPCAST_SELF_COPY_1]] // CHECK: [[SELF_COPY_2:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_SELF_COPY_2:%.*]] = upcast [[SELF_COPY_2]] : $SubSub to $Sub // CHECK: [[BORROWED_UPCAST_SELF_COPY_2:%.*]] = begin_borrow [[UPCAST_SELF_COPY_2]] // CHECK: [[DOWNCAST_BORROWED_UPCAST_SELF_COPY_2:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_SELF_COPY_2]] : $Sub to $SubSub // CHECK: = objc_super_method [[DOWNCAST_BORROWED_UPCAST_SELF_COPY_2]] : $SubSub, #Sub.otherProp!setter.1.foreign // CHECK: end_borrow [[BORROWED_UPCAST_SELF_COPY_2]] from [[UPCAST_SELF_COPY_2]] // CHECK: } // end sil function '_T015objc_extensions03SubC0C9otherPropSSvs' override var otherProp: String { didSet { // Ignore it. } } } // SR-1025 extension Base { fileprivate static var x = 1 } // CHECK-LABEL: sil hidden @_T015objc_extensions19testStaticVarAccessyyF func testStaticVarAccess() { // CHECK: [[F:%.*]] = function_ref @_T0So4BaseC15objc_extensionsE1x33_1F05E59585E0BB585FCA206FBFF1A92DLLSivau // CHECK: [[PTR:%.*]] = apply [[F]]() // CHECK: [[ADDR:%.*]] = pointer_to_address [[PTR]] _ = Base.x }
apache-2.0
0d332d8f2d96ed812f09f15286d05d5b
54.513228
206
0.62276
3.348867
false
false
false
false
roambotics/swift
test/SILGen/back_deploy_attribute_throwing_func.swift
2
3441
// RUN: %target-swift-emit-sil -parse-as-library -module-name back_deploy %s -target %target-cpu-apple-macosx10.50 -verify // RUN: %target-swift-emit-silgen -parse-as-library -module-name back_deploy %s | %FileCheck %s // RUN: %target-swift-emit-silgen -parse-as-library -module-name back_deploy %s -target %target-cpu-apple-macosx10.50 | %FileCheck %s // RUN: %target-swift-emit-silgen -parse-as-library -module-name back_deploy %s -target %target-cpu-apple-macosx10.60 | %FileCheck %s // REQUIRES: OS=macosx // -- Fallback definition of throwingFunc() // CHECK-LABEL: sil non_abi [serialized] [ossa] @$s11back_deploy12throwingFuncyyKFTwB : $@convention(thin) () -> @error any Error // CHECK: bb0: // CHECK: [[RESULT:%.*]] = tuple () // CHECK: return [[RESULT]] : $() // -- Back deployment thunk for throwingFunc() // CHECK-LABEL: sil non_abi [serialized] [thunk] [ossa] @$s11back_deploy12throwingFuncyyKFTwb : $@convention(thin) () -> @error any Error // CHECK: bb0: // CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10 // CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52 // CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0 // CHECK: [[OSVFN:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 // CHECK: [[AVAIL:%.*]] = apply [[OSVFN]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 // CHECK: cond_br [[AVAIL]], [[AVAIL_BB:bb[0-9]+]], [[UNAVAIL_BB:bb[0-9]+]] // // CHECK: [[UNAVAIL_BB]]: // CHECK: [[FALLBACKFN:%.*]] = function_ref @$s11back_deploy12throwingFuncyyKFTwB : $@convention(thin) () -> @error any Error // CHECK: try_apply [[FALLBACKFN]]() : $@convention(thin) () -> @error any Error, normal [[UNAVAIL_NORMAL_BB:bb[0-9]+]], error [[UNAVAIL_ERROR_BB:bb[0-9]+]] // // CHECK: [[UNAVAIL_ERROR_BB]]([[ARG:%.*]] : @owned $any Error): // CHECK: br [[RETHROW_BB:bb[0-9]+]]([[ARG]] : $any Error) // // CHECK: [[UNAVAIL_NORMAL_BB]]([[ARG:%.*]] : $()): // CHECK: br [[RETURN_BB:bb[0-9]+]] // // CHECK: [[AVAIL_BB]]: // CHECK: [[ORIGFN:%.*]] = function_ref @$s11back_deploy12throwingFuncyyKF : $@convention(thin) () -> @error any Error // CHECK: try_apply [[ORIGFN]]() : $@convention(thin) () -> @error any Error, normal [[AVAIL_NORMAL_BB:bb[0-9]+]], error [[AVAIL_ERROR_BB:bb[0-9]+]] // // CHECK: [[AVAIL_ERROR_BB]]([[ARG:%.*]] : @owned $any Error): // CHECK: br [[RETHROW_BB]]([[ARG]] : $any Error) // // CHECK: [[AVAIL_NORMAL_BB]]([[ARG:%.*]] : $()): // CHECK: br [[RETURN_BB]] // // CHECK: [[RETURN_BB]] // CHECK: [[RESULT:%.*]] = tuple () // CHECK: return [[RESULT]] : $() // // CHECK: [[RETHROW_BB]]([[RETHROW_BB_ARG:%.*]] : @owned $any Error) // CHECK: throw [[RETHROW_BB_ARG]] : $any Error // -- Original definition of throwingFunc() // CHECK-LABEL: sil [available 10.52] [ossa] @$s11back_deploy12throwingFuncyyKF : $@convention(thin) () -> @error any Error @available(macOS 10.51, *) @_backDeploy(before: macOS 10.52) public func throwingFunc() throws {} // CHECK-LABEL: sil hidden [available 10.51] [ossa] @$s11back_deploy6calleryyKF : $@convention(thin) () -> @error any Error @available(macOS 10.51, *) func caller() throws { // -- Verify the thunk is called // CHECK: {{%.*}} = function_ref @$s11back_deploy12throwingFuncyyKFTwb : $@convention(thin) () -> @error any Error try throwingFunc() }
apache-2.0
8b15802ed162e11c4a6b16008216f35d
53.619048
167
0.630921
3.131028
false
false
false
false
sschiau/swift
test/Frontend/skip-non-inlinable-function-bodies.swift
2
8580
// RUN: %empty-directory(%t) // 1. Make sure you can't -emit-ir or -c when you're skipping non-inlinable function bodies // RUN: not %target-swift-frontend -emit-ir %s -experimental-skip-non-inlinable-function-bodies %s 2>&1 | %FileCheck %s --check-prefix ERROR // RUN: not %target-swift-frontend -c %s -experimental-skip-non-inlinable-function-bodies %s 2>&1 | %FileCheck %s --check-prefix ERROR // ERROR: -experimental-skip-non-inlinable-function-bodies does not support emitting IR // 2. Emit the SIL for a module and check it against the expected strings in function bodies. // If we're doing the right skipping, then the strings that are CHECK-NOT'd won't have been typechecked or SILGen'd. // RUN: %target-swift-frontend -emit-sil -O -experimental-skip-non-inlinable-function-bodies %s 2>&1 | %FileCheck %s --check-prefixes CHECK,CHECK-SIL-ONLY // 3. Emit the module interface while skipping non-inlinable function bodies. Check it against the same set of strings. // RUN: %target-swift-frontend -typecheck %s -enable-library-evolution -emit-module-interface-path %t/Module.skipping.swiftinterface -experimental-skip-non-inlinable-function-bodies // RUN: %FileCheck %s --check-prefixes CHECK,CHECK-INTERFACE-ONLY < %t/Module.skipping.swiftinterface // 4. Emit the module interface normally. Also check it against the same set of strings. // RUN: %target-swift-frontend -typecheck %s -enable-library-evolution -emit-module-interface-path %t/Module.swiftinterface // RUN: %FileCheck %s --check-prefixes CHECK,CHECK-INTERFACE-ONLY < %t/Module.swiftinterface // 5. The module interfaces should be exactly the same. // RUN: diff -u %t/Module.skipping.swiftinterface %t/Module.swiftinterface @usableFromInline @inline(never) func _blackHole(_ s: String) {} public struct Struct { @inlinable public func inlinableFunc() { _blackHole("@inlinable method body") // CHECK: @inlinable method body } @inline(__always) public func inlineAlwaysFunc() { _blackHole("@inline(__always) method body") // CHECK-NOT: @inline(__always) method body } @_transparent public func transparentFunc() { _blackHole("@_transparent method body") // CHECK: @_transparent method body } func internalFunc() { _blackHole("internal method body") // CHECK-NOT: internal method body } public func publicFunc() { _blackHole("public method body") // CHECK-NOT: public method body } private func privateFunc() { _blackHole("private method body") // CHECK-NOT: private method body } @inlinable public init() { _blackHole("@inlinable init body") // CHECK: @inlinable init body } @inline(__always) public init(a: Int) { _blackHole("@inline(__always) init body") // CHECK-NOT: @inline(__always) init body } @_transparent public init(b: Int) { _blackHole("@_transparent init body") // CHECK: @_transparent init body } init(c: Int) { _blackHole("internal init body") // CHECK-NOT: internal init body } public init(d: Int) { _blackHole("public init body") // CHECK-NOT: public init body } private init(e: Int) { _blackHole("private init body") // CHECK-NOT: private init body } @inlinable public subscript() -> Int { _blackHole("@inlinable subscript getter") // CHECK: @inlinable subscript getter return 0 } @inline(__always) public subscript(a: Int, b: Int) -> Int { _blackHole("@inline(__always) subscript getter") // CHECK-NOT: @inline(__always) subscript getter return 0 } public subscript(a: Int, b: Int, c: Int) -> Int { @_transparent get { _blackHole("@_transparent subscript getter") // CHECK: @_transparent subscript getter return 0 } } subscript(a: Int, b: Int, c: Int, d: Int) -> Int { _blackHole("internal subscript getter") // CHECK-NOT: internal subscript getter return 0 } public subscript(a: Int, b: Int, c: Int, d: Int, e: Int) -> Int { _blackHole("public subscript getter") // CHECK-NOT: public subscript getter return 0 } private subscript(e: Int) -> Int { _blackHole("private subscript getter") // CHECK-NOT: private subscript getter return 0 } @inlinable public var inlinableVar: Int { _blackHole("@inlinable getter body") // CHECK: @inlinable getter body return 0 } @inline(__always) public var inlineAlwaysVar: Int { _blackHole("@inline(__always) getter body") // CHECK-NOT: @inline(__always) getter body return 0 } @_transparent public var transparentVar: Int { _blackHole("@_transparent getter body") // CHECK: @_transparent getter body return 0 } public var publicVar: Int { _blackHole("public getter body") // CHECK-NOT: public getter body return 0 } public var inlinableSetter: Int { get { 0 } @inlinable set { _blackHole("@inlinable setter body") // CHECK: @inlinable setter body } } public var inlineAlwaysSetter: Int { get { 0 } @inline(__always) set { _blackHole("@inline(__always) setter body") // CHECK-NOT: @inline(__always) setter body } } public var regularSetter: Int { get { 0 } set { _blackHole("@inline(__always) setter body") // CHECK-NOT: regular setter body } } } @_fixed_layout public class InlinableDesubscript { @inlinable deinit { _blackHole("@inlinable deinit body") // CHECK: @inlinable deinit body } } @_fixed_layout public class InlineAlwaysDeinit { @inline(__always) deinit { _blackHole("@inline(__always) deinit body") // CHECK-NOT: @inline(__always) deinit body } } public class NormalDeinit { deinit { _blackHole("regular deinit body") // CHECK-NOT: regular deinit body } } @inlinable public func inlinableFunc() { _blackHole("@inlinable func body") // CHECK: @inlinable func body } @inline(__always) public func inlineAlwaysFunc() { _blackHole("@inline(__always) func body") // CHECK-NOT: @inline(__always) func body } @_transparent public func transparentFunc() { _blackHole("@_transparent func body") // CHECK: @_transparent func body } func internalFunc() { _blackHole("internal func body") // CHECK-NOT: internal func body } public func publicFunc() { _blackHole("public func body") // CHECK-NOT: public func body } private func privateFunc() { _blackHole("private func body") // CHECK-NOT: private func body } @inlinable public func inlinableLocalTypeFunc() { typealias InlinableLocalType = Int _blackHole("@inlinable func body with local type") // CHECK: @inlinable func body with local type func takesInlinableLocalType(_ x: InlinableLocalType) { _blackHole("nested func body inside @inlinable func body taking local type") // CHECK: nested func body inside @inlinable func body taking local type } takesInlinableLocalType(0) } @inline(__always) public func inlineAlwaysLocalTypeFunc() { typealias InlineAlwaysLocalType = Int _blackHole("@inline(__always) func body with local type") // CHECK-NOT: @inline(__always) func body with local type func takesInlineAlwaysLocalType(_ x: InlineAlwaysLocalType) { _blackHole("nested func body inside @inline(__always) func body taking local type") // CHECK-NOT: nested func body inside @inline(__always) func body taking local type } takesInlineAlwaysLocalType(0) } @_transparent public func _transparentLocalTypeFunc() { typealias TransparentLocalType = Int _blackHole("@_transparent func body with local type") // CHECK: @_transparent func body with local type func takesTransparentLocalType(_ x: TransparentLocalType) { _blackHole("nested func body inside @_transparent func body taking local type") // CHECK: nested func body inside @_transparent func body taking local type } takesTransparentLocalType(0) } public func publicLocalTypeFunc() { typealias LocalType = Int _blackHole("public func body with local type") // CHECK-NOT: public func body with local type func takesLocalType(_ x: LocalType) { _blackHole("nested func body inside public func body taking local type") // CHECK-NOT: nested func body inside public func body taking local type } takesLocalType(0) } @inlinable public func inlinableNestedLocalTypeFunc() { func nestedFunc() { _blackHole("nested func body inside @inlinable func body") // CHECK: nested func body inside @inlinable func body typealias InlinableNestedLocalType = Int func takesLocalType(_ x: InlinableNestedLocalType) { _blackHole("nested func body inside @inlinable func body taking local type") // CHECK: nested func body inside @inlinable func body taking local type } takesLocalType(0) } nestedFunc() }
apache-2.0
94c5f4205fe8e2caeb32740f5bbcfb4d
33.596774
181
0.700816
4.003733
false
false
false
false
jpipard/DKImagePickerController
DKImageManager/Data/DKGroupDataManager.swift
2
5579
// // DKGroupDataManager.swift // DKImagePickerControllerDemo // // Created by ZhangAo on 15/12/16. // Copyright © 2015年 ZhangAo. All rights reserved. // import Photos @objc protocol DKGroupDataManagerObserver { optional func groupDidUpdate(groupId: String) optional func groupDidRemove(groupId: String) optional func group(groupId: String, didRemoveAssets assets: [DKAsset]) optional func group(groupId: String, didInsertAssets assets: [DKAsset]) } public class DKGroupDataManager: DKBaseManager, PHPhotoLibraryChangeObserver { private var groups: [String : DKAssetGroup]? public var groupIds: [String]? public var assetGroupTypes: [PHAssetCollectionSubtype]? public var assetFetchOptions: PHFetchOptions? public var showsEmptyAlbums: Bool = true deinit { PHPhotoLibrary.sharedPhotoLibrary().unregisterChangeObserver(self) } public func invalidate() { self.groupIds?.removeAll() self.groupIds = nil self.groups?.removeAll() self.groups = nil PHPhotoLibrary.sharedPhotoLibrary().unregisterChangeObserver(self) } public func fetchGroups(completeBlock: (groups: [String]?, error: NSError?) -> Void) { if let assetGroupTypes = self.assetGroupTypes { if self.groups != nil { completeBlock(groups: self.groupIds, error: nil) return } var groups: [String : DKAssetGroup] = [:] var groupIds: [String] = [] for (_, groupType) in assetGroupTypes.enumerate() { let fetchResult = PHAssetCollection.fetchAssetCollectionsWithType(self.collectionTypeForSubtype(groupType), subtype: groupType, options: nil) fetchResult.enumerateObjectsUsingBlock { object, index, stop in if let collection = object as? PHAssetCollection { let assetGroup = DKAssetGroup() assetGroup.groupId = collection.localIdentifier self.updateGroup(assetGroup, collection: collection) if self.showsEmptyAlbums || assetGroup.totalCount > 0 { groups[assetGroup.groupId] = assetGroup groupIds.append(assetGroup.groupId) } } } } self.groups = groups self.groupIds = groupIds PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self) completeBlock(groups: groupIds, error: nil) } } public func fetchGroupWithGroupId(groupId: String) -> DKAssetGroup { return self.groups![groupId]! } public func fetchGroupThumbnailForGroup(groupId: String, size: CGSize, options: PHImageRequestOptions, completeBlock: (image: UIImage?, info: [NSObject : AnyObject]?) -> Void) { let group = self.fetchGroupWithGroupId(groupId) if group.fetchResult.count == 0 { completeBlock(image: nil, info: nil) return } let latestAsset = DKAsset(originalAsset:group.fetchResult.firstObject as! PHAsset) latestAsset.fetchImageWithSize(size, options: options, completeBlock: completeBlock) } public func fetchAssetWithGroup(group: DKAssetGroup, index: Int) -> DKAsset { let asset = DKAsset(originalAsset:group.fetchResult[index] as! PHAsset) return asset } // MARK: - Private methods private func collectionTypeForSubtype(subtype: PHAssetCollectionSubtype) -> PHAssetCollectionType { return subtype.rawValue < PHAssetCollectionSubtype.SmartAlbumGeneric.rawValue ? .Album : .SmartAlbum } private func updateGroup(group: DKAssetGroup, collection: PHAssetCollection) { group.groupName = collection.localizedTitle self.updateGroup(group, fetchResult: PHAsset.fetchAssetsInAssetCollection(collection, options: self.assetFetchOptions)) group.originalCollection = collection } private func updateGroup(group: DKAssetGroup, fetchResult: PHFetchResult) { group.fetchResult = fetchResult group.totalCount = group.fetchResult.count } // MARK: - PHPhotoLibraryChangeObserver methods public func photoLibraryDidChange(changeInstance: PHChange) { for group in self.groups!.values { if let changeDetails = changeInstance.changeDetailsForObject(group.originalCollection) { if changeDetails.objectWasDeleted { self.groups![group.groupId] = nil self.notifyObserversWithSelector(#selector(DKGroupDataManagerObserver.groupDidRemove(_:)), object: group.groupId) continue } if let objectAfterChanges = changeDetails.objectAfterChanges as? PHAssetCollection { self.updateGroup(self.groups![group.groupId]!, collection: objectAfterChanges) self.notifyObserversWithSelector(#selector(DKGroupDataManagerObserver.groupDidUpdate(_:)), object: group.groupId) } } if let changeDetails = changeInstance.changeDetailsForFetchResult(group.fetchResult) { if let removedIndexes = changeDetails.removedIndexes { var removedAssets = [DKAsset]() removedIndexes.enumerateIndexesUsingBlock({ index, stop in removedAssets.append(self.fetchAssetWithGroup(group, index: index)) }) self.notifyObserversWithSelector(#selector(DKGroupDataManagerObserver.group(_:didRemoveAssets:)), object: group.groupId, objectTwo: removedAssets) } self.updateGroup(group, fetchResult: changeDetails.fetchResultAfterChanges) if changeDetails.insertedObjects.count > 0 { var insertedAssets = [DKAsset]() for insertedAsset in changeDetails.insertedObjects { insertedAssets.append(DKAsset(originalAsset: insertedAsset as! PHAsset)) } self.notifyObserversWithSelector(#selector(DKGroupDataManagerObserver.group(_:didInsertAssets:)), object: group.groupId, objectTwo: insertedAssets) } } } } }
mit
5ddad668abf84e1101ff38b3d3e3828c
35.927152
178
0.735294
4.373333
false
false
false
false
ken0nek/swift
validation-test/Reflection/reflect_NSString.swift
1
1884
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_NSString // RUN: %target-run %target-swift-reflection-test %t/reflect_NSString 2>&1 | FileCheck %s --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop import SwiftReflectionTest import Foundation class TestClass { var t: NSString init(t: NSString) { self.t = t } } var obj = TestClass(t: "Hello, NSString!") reflect(object: obj) // CHECK-64: Reflecting an object. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_NSString.TestClass) // CHECK-64: Type info: // CHECK-64: (class_instance size=24 alignment=16 stride=32 num_extra_inhabitants=0 // CHECK-64: (field name=t offset=16 // CHECK-64: (reference kind=strong refcounting=unknown))) // CHECK-32: Reflecting an object. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_NSString.TestClass) // CHECK-32: Type info: // CHECK-32: (class_instance size=16 alignment=16 stride=16 num_extra_inhabitants=0 // CHECK-32: (field name=t offset=12 // CHECK-32: (reference kind=strong refcounting=unknown))) reflect(any: obj) // CHECK-64: Reflecting an existential. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_NSString.TestClass) // CHECK-64: Type info: // CHECK-64: (reference kind=strong refcounting=native) // CHECK-32: Reflecting an existential. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_NSString.TestClass) // CHECK-32: Type info: // CHECK-32: (reference kind=strong refcounting=native) doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
apache-2.0
5e3c4127d2fa47eab9471f83ddc44b9b
29.387097
126
0.697452
3.19322
false
true
false
false
apple/swift-driver
Tests/SwiftDriverTests/DependencyGraphSerializationTests.swift
1
12243
//===----------- DependencyGraphSerializationTests.swift ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import XCTest @_spi(Testing) import SwiftDriver import TSCBasic class DependencyGraphSerializationTests: XCTestCase, ModuleDependencyGraphMocker { static let maxIndex = 12 static let mockGraphCreator = MockModuleDependencyGraphCreator(maxIndex: maxIndex) /// Unit test of the `ModuleDependencyGraph` serialization /// /// Ensure that a round-trip fails when the minor version number changes func testSerializedVersionChangeDetection() throws { let mockPath = VirtualPath.absolute(AbsolutePath("/module-dependency-graph")) let fs = InMemoryFileSystem() let graph = Self.mockGraphCreator.mockUpAGraph() let currentVersion = ModuleDependencyGraph.serializedGraphVersion let alteredVersion = currentVersion.withAlteredMinor try graph.blockingConcurrentAccessOrMutation { try graph.write( to: mockPath, on: fs, compilerVersion: "Swift 99", mockSerializedGraphVersion: alteredVersion) } do { let outputFileMap = OutputFileMap.mock(maxIndex: Self.maxIndex) let info = IncrementalCompilationState.IncrementalDependencyAndInputSetup.mock(outputFileMap: outputFileMap, fileSystem: fs) try info.blockingConcurrentAccessOrMutation { _ = try ModuleDependencyGraph.read(from: mockPath, info: info) XCTFail("Should have thrown an exception") } } catch let ModuleDependencyGraph.ReadError.mismatchedSerializedGraphVersion(expected, read) { XCTAssertEqual(expected, currentVersion) XCTAssertEqual(read, alteredVersion) } catch { XCTFail("Threw an unexpected exception: \(error.localizedDescription)") } } func roundTrip(_ originalGraph: ModuleDependencyGraph) throws { let mockPath = VirtualPath.absolute(AbsolutePath("/module-dependency-graph")) let fs = InMemoryFileSystem() try originalGraph.blockingConcurrentMutation { try originalGraph.write(to: mockPath, on: fs, compilerVersion: "Swift 99") } let outputFileMap = OutputFileMap.mock(maxIndex: Self.maxIndex) let info = IncrementalCompilationState.IncrementalDependencyAndInputSetup.mock(outputFileMap: outputFileMap, fileSystem: fs) let deserializedGraph = try info.blockingConcurrentAccessOrMutation { try ModuleDependencyGraph.read(from: mockPath, info: info)! } let descsToCompare = [originalGraph, deserializedGraph].map { graph -> (nodes: Set<String>, uses: [String: Set<String>], feds: Set<String>) in var nodes = Set<String>() graph.nodeFinder.forEachNode { nodes.insert($0.description(in: graph)) } let uses: [String: Set<String>] = graph.nodeFinder.usesByDef.reduce(into: Dictionary()) { usesByDef, keyAndNodes in usesByDef[keyAndNodes.0.description(in: graph)] = keyAndNodes.1.reduce(into: Set()) { $0.insert($1.description(in: graph))} } let feds: Set<String> = graph.fingerprintedExternalDependencies.reduce(into: Set()) { $0.insert($1.description(in: graph)) } return (nodes, uses, feds) } XCTAssertEqual(descsToCompare[0].nodes, descsToCompare[1].nodes, "Round trip node difference!") XCTAssertEqual(descsToCompare[0].uses, descsToCompare[1].uses, "Round trip def-uses difference!") XCTAssertEqual(descsToCompare[0].feds, descsToCompare[1].feds, "Round trip fingerprinted external dependency difference!") } func testRoundTripFixtures() throws { struct GraphFixture { var commands: [LoadCommand] enum LoadCommand { case load(index: Int, nodes: [MockDependencyKind: [String]], fingerprint: String? = nil) case reload(index: Int, nodes: [MockDependencyKind: [String]], fingerprint: String? = nil) } } let fixtures: [GraphFixture] = [ GraphFixture(commands: []), GraphFixture(commands: [ .load(index: 0, nodes: [.topLevel: ["a->", "b->"]]), .load(index: 1, nodes: [.nominal: ["c->", "d->"]]), .load(index: 2, nodes: [.topLevel: ["e", "f"]]), .load(index: 3, nodes: [.nominal: ["g", "h"]]), .load(index: 4, nodes: [.dynamicLookup: ["i", "j"]]), .load(index: 5, nodes: [.dynamicLookup: ["k->", "l->"]]), .load(index: 6, nodes: [.member: ["m,mm", "n,nn"]]), .load(index: 7, nodes: [.member: ["o,oo->", "p,pp->"]]), .load(index: 8, nodes: [.externalDepend: ["/foo->", "/bar->"]]), .load(index: 9, nodes: [ .nominal: ["a", "b", "c->", "d->"], .topLevel: ["b", "c", "d->", "a->"] ]) ]), GraphFixture(commands: [ .load(index: 0, nodes: [.topLevel: ["a0", "a->"]]), .load(index: 1, nodes: [.topLevel: ["b0", "b->"]]), .load(index: 2, nodes: [.topLevel: ["c0", "c->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["a", "a->"]]), .load(index: 1, nodes: [.topLevel: ["a", "b->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["a->", "b"]]), .load(index: 1, nodes: [.topLevel: ["b->", "a"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.member: ["a,aa"]]), .load(index: 1, nodes: [.member: ["a,bb->"]]), .load(index: 2, nodes: [.potentialMember: ["a"]]), .load(index: 3, nodes: [.member: ["b,aa->"]]), .load(index: 4, nodes: [.member: ["b,bb->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.topLevel: ["a", "b", "c"]]), .load(index: 1, nodes: [.topLevel: ["x->", "b->", "z->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.topLevel: ["a->", "b->", "c->"]]), .load(index: 1, nodes: [.topLevel: ["x", "b", "z"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["a", "b", "c"]]), .load(index: 1, nodes: [.nominal: ["x->", "b->", "z->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["a"], .topLevel: ["a"]]), .load(index: 1, nodes: [.nominal: ["a->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["a"], .topLevel: ["a"]]), .load(index: 1, nodes: [.nominal: ["a->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["a"]]), .load(index: 1, nodes: [.nominal: ["a->"], .topLevel: ["a->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["a"], .topLevel: ["a"]]), .load(index: 1, nodes: [.nominal: ["a->"], .topLevel: ["a->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.dynamicLookup: ["a", "b", "c"]]), .load(index: 1, nodes: [.dynamicLookup: ["x->", "b->", "z->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.member: ["a,aa", "b,bb", "c,cc"]]), .load(index: 1, nodes: [.member: ["x,xx->", "b,bb->", "z,zz->"]]) ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["a", "b", "c"]]), .load(index: 1, nodes: [.nominal: ["x->", "b->", "z->"]]), .load(index: 2, nodes: [.nominal: ["q->", "b->", "s->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["a", "b", "c"]]), .load(index: 1, nodes: [.nominal: ["x->", "b->", "z->"]]), .load(index: 2, nodes: [.nominal: ["q->", "r->", "c->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["a", "b", "c"]]), .load(index: 1, nodes: [.nominal: ["x->", "b->", "z"]]), .load(index: 2, nodes: [.nominal: ["z->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["a", "b", "c"]]), .load(index: 1, nodes: [.nominal: ["x->", "b->", "#z"]]), .load(index: 2, nodes: [.nominal: ["#z->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.topLevel: ["a", "b", "c"]]), .load(index: 1, nodes: [.topLevel: ["x->", "#b->"], .nominal: ["z"]]), .load(index: 2, nodes: [.nominal: ["z->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.topLevel: ["a", "b"]]), .load(index: 1, nodes: [.topLevel: ["a->", "z"]]), .load(index: 2, nodes: [.topLevel: ["z->"]]), .load(index: 10, nodes: [.topLevel: ["y", "z", "q->"]]), .load(index: 11, nodes: [.topLevel: ["y->"]]), .load(index: 12, nodes: [.topLevel: ["q->", "q"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["a"]]), .load(index: 1, nodes: [.nominal: ["a->"]]), .load(index: 2, nodes: [.nominal: ["b->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["a"]]), .load(index: 1, nodes: [.nominal: ["a->"]]), .load(index: 2, nodes: [.nominal: ["b->"]]), .reload(index: 0, nodes: [.nominal: ["a", "b"]]) ]), GraphFixture(commands: [ .reload(index: 1, nodes: [.nominal: ["b", "a->"]]) ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["A1@1", "A2@2", "A1->"]]), .load(index: 1, nodes: [.nominal: ["B1", "A1->"]]), .load(index: 2, nodes: [.nominal: ["C1", "A2->"]]), .load(index: 3, nodes: [.nominal: ["D1"]]), .reload(index: 0, nodes: [.nominal: ["A1", "A2"]], fingerprint: "changed") ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["A"]]), .load(index: 1, nodes: [.nominal: ["B", "C", "A->"]]), .load(index: 2, nodes: [.nominal: ["B->"]]), .load(index: 3, nodes: [.nominal: ["C->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["A"]]), .load(index: 1, nodes: [.nominal: ["B", "C", "A->B"]]), .load(index: 2, nodes: [.nominal: ["B->"]]), .load(index: 3, nodes: [.nominal: ["C->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["A1@1", "A2@2"]]), .load(index: 1, nodes: [.nominal: ["B1", "C1", "A1->"]]), .load(index: 2, nodes: [.nominal: ["B1->"]]), .load(index: 3, nodes: [.nominal: ["C1->"]]), .load(index: 4, nodes: [.nominal: ["B2", "C2", "A2->"]]), .load(index: 5, nodes: [.nominal: ["B2->"]]), .load(index: 6, nodes: [.nominal: ["C2->"]]), ]), GraphFixture(commands: [ .load(index: 0, nodes: [.nominal: ["A1@1", "A2@2"]]), .load(index: 1, nodes: [.nominal: ["B1", "C1", "A1->B1"]]), .load(index: 2, nodes: [.nominal: ["B1->"]]), .load(index: 3, nodes: [.nominal: ["C1->"]]), .load(index: 4, nodes: [.nominal: ["B2", "C2", "A2->B2"]]), .load(index: 5, nodes: [.nominal: ["B2->"]]), .load(index: 6, nodes: [.nominal: ["C2->"]]), .reload(index: 0, nodes: [.nominal: ["A1@11", "A2@2"]]) ]), GraphFixture(commands: [ .load(index: 0, nodes: [.externalDepend: ["/foo->", "/bar->"]], fingerprint: "ABCDEFG"), .reload(index: 0, nodes: [.externalDepend: ["/foo->", "/bar->"]], fingerprint: "HIJKLMNOP"), ]), ] for fixture in fixtures { let graph = Self.mockGraphCreator.mockUpAGraph() for loadCommand in fixture.commands { switch loadCommand { case .load(index: let index, nodes: let nodes, fingerprint: let fingerprint): graph.simulateLoad(index, nodes, fingerprint) case .reload(index: let index, nodes: let nodes, fingerprint: let fingerprint): _ = graph.simulateReload(index, nodes, fingerprint) } } try roundTrip(graph) } } }
apache-2.0
0115edec0ba5609abe89f205efdd6163
43.198556
130
0.538348
3.440978
false
false
false
false
Lweek/Formulary
Exemplary/ViewController.swift
1
2610
// // ViewController.swift // Exemplary // // Created by Fabian Canas on 1/16/15. // Copyright (c) 2015 Fabian Canas. All rights reserved. // import UIKit import Formulary class ViewController: FormViewController { override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = editButtonItem() let decimalFormatter = NSNumberFormatter() decimalFormatter.maximumFractionDigits = 5 let integerFormatter = NSNumberFormatter() self.form = Form(sections: [ FormSection(rows: [ TextEntryFormRow(name:"Name", tag: "name", validation: RequiredString("Name")), TextEntryFormRow(name: "Email", tag: "email", textType: TextEntryType.Email), TextEntryFormRow(name:"Age", tag: "age", textType: TextEntryType.Number, validation: MinimumNumber("Age", 13), formatter: integerFormatter)], name:"Profile"), FormSection(rows: [ TextEntryFormRow(name:"Favorite Number", tag: "favoriteNumber", value: nil, textType: .Decimal, validation: MinimumNumber("Your favorite number", 47) && MaximumNumber("Your favorite number", 47), formatter: decimalFormatter), FormRow(name:"Do you like goats?", tag: "likesGoats", type: .Switch, value: false), TextEntryFormRow(name:"Other Thoughts?", tag: "thoughts", textType: .Plain),], name:"Preferences", footerName: "Fin"), OptionSection(rowValues:["Ice Cream", "Pizza", "Beer"], name: "Food", value: ["Pizza", "Ice Cream"]), FormSection(rows: [ FormRow(name:"Show Values", tag: "show", type: .Button, value: nil, action: { _ in let data = NSJSONSerialization.dataWithJSONObject(values(self.form), options: nil, error: nil)! let s = NSString(data: data, encoding: NSUTF8StringEncoding) let alert = UIAlertController(title: "Form Values", message: s as? String, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) }) ]) ]) setEditing(true, animated: false) } override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) editingEnabled = editing } }
mit
f6a73de955e727afe776a8d7946d89ca
44.789474
241
0.603831
4.80663
false
false
false
false
pdcgomes/RendezVous
Vendor/docopt/Docopt.swift
1
12115
// // Docopt.swift // Docopt // // Created by Pavel S. Mazurin on 2/28/15. // Copyright (c) 2015 kovpas. All rights reserved. // import Foundation import Darwin public class Docopt { private(set) public var result: [String: AnyObject]! private let doc: String private let version: String? private let help: Bool private let optionsFirst: Bool private let arguments: [String] public static func parse(doc: String, argv: [String], help: Bool = false, version: String? = nil, optionsFirst: Bool = false) -> [String: AnyObject] { return Docopt(doc, argv: argv, help: help, version: version, optionsFirst: optionsFirst).result } internal init(_ doc: String, argv: [String]? = nil, help: Bool = false, version: String? = nil, optionsFirst: Bool = false) { self.doc = doc self.version = version self.help = help self.optionsFirst = optionsFirst var args: [String] if argv == nil { if Process.argc > 1 { args = Process.arguments args.removeAtIndex(0) // arguments[0] is always the program_name } else { args = [String]() } } else { args = argv! } arguments = args.filter { $0 != "" } result = parse(optionsFirst) } private func parse(optionsFirst: Bool) -> [String: AnyObject] { let usageSections = Docopt.parseSection("usage:", source: doc) if usageSections.count == 0 { DocoptLanguageError("\"usage:\" (case-insensitive) not found.").raise() } else if usageSections.count > 1 { DocoptLanguageError("More than one \"usage:\" (case-insensitive).").raise() } DocoptExit.usage = usageSections[0] var options = Docopt.parseDefaults(doc) let pattern = Docopt.parsePattern(Docopt.formalUsage(DocoptExit.usage), options: &options) let argv = Docopt.parseArgv(Tokens(arguments), options: &options, optionsFirst: optionsFirst) let patternOptions = Set(pattern.flat(Option)) for optionsShortcut in pattern.flat(OptionsShortcut) { let docOptions = Set(Docopt.parseDefaults(doc)) optionsShortcut.children = Array(docOptions.subtract(patternOptions)) } Docopt.extras(help, version: version, options: argv, doc: doc) let (matched, left, collected) = pattern.fix().match(argv) var result = [String: AnyObject]() if matched && left.isEmpty { let collectedLeafs = collected as! [LeafPattern] let flatPattern = pattern.flat().filter { pattern in (collectedLeafs.filter {$0.name == pattern.name}).isEmpty } + collectedLeafs for leafChild: LeafPattern in flatPattern { result[leafChild.name!] = leafChild.value ?? NSNull() } return result } DocoptExit().raise() return result } static private func extras(help: Bool, version: String?, options: [LeafPattern], doc: String) { let helpOption = options.filter { $0.name == "--help" || $0.name == "-h" } if help && !(helpOption.isEmpty) { print(doc.strip()) exit(0) } let versionOption = options.filter { $0.name == "--version" } if version != nil && !(versionOption.isEmpty) { print(version!.strip()) exit(0) } } static internal func parseSection(name: String, source: String) -> [String] { return source.findAll("^([^\n]*\(name)[^\n]*\n?(?:[ \t].*?(?:\n|$))*)", flags: [.CaseInsensitive, .AnchorsMatchLines] ) } static internal func parseDefaults(doc: String) -> [Option] { var defaults = [Option]() let optionsSection = parseSection("options:", source: doc) for s in optionsSection { // FIXME corner case "bla: options: --foo" let (_, _, s) = s.partition(":") // get rid of "options:" var splitgen = ("\n" + s).split("\n[ \t]*(-\\S+?)").generate() var split = [String]() while let s1 = splitgen.next(), let s2 = splitgen.next() { split.append(s1 + s2) } defaults += split.filter({$0.hasPrefix("-")}).map { Option.parse($0) } } return defaults } static internal func parseLong(tokens: Tokens, inout options: [Option]) -> [Option] { let (long, eq, val) = tokens.move()!.partition("=") assert(long.hasPrefix("--")) var value: String? = eq != "" || val != "" ? val : nil var similar = options.filter {$0.long == long} if tokens.error is DocoptExit && similar.isEmpty { // if no exact match similar = options.filter {$0.long?.hasPrefix(long) ?? false} } var o: Option if similar.count > 1 { let allSimilar = " ".join(similar.map {$0.long ?? ""}) tokens.error.raise("\(long) is not a unique prefix: \(allSimilar)") return [] } else if similar.count < 1 { let argCount: UInt = (eq == "=") ? 1 : 0 o = Option(nil, long: long, argCount: argCount) options.append(o) if tokens.error is DocoptExit { o = Option(nil, long: long, argCount: argCount, value: argCount > 0 ? value : true) } } else { o = Option(similar[0]) if o.argCount == 0 { if value != nil { tokens.error.raise("\(o.long) requires argument") } } else { if value == nil { if let current = tokens.current() where current != "--" { value = tokens.move() } else { tokens.error.raise("\(o.long) requires argument") } } } if tokens.error is DocoptExit { o.value = value ?? true } } return [o] } static internal func parseShorts(tokens: Tokens, inout options: [Option]) -> [Option] { let token = tokens.move()! assert(token.hasPrefix("-") && !token.hasPrefix("--")) var left = token.stringByReplacingOccurrencesOfString("-", withString: "") var parsed = [Option]() while left != "" { let short = "-" + left[0..<1] let similar = options.filter {$0.short == short} var o: Option left = left[1..<left.characters.count] if similar.count > 1 { tokens.error.raise("\(short) is specified ambiguously \(similar.count) times") return [] } else if similar.count < 1 { o = Option(short) options.append(o) if tokens.error is DocoptExit { o = Option(short, value: true) } } else { var value: String? = nil o = Option(similar[0]) if o.argCount != 0 { if let current = tokens.current() where current != "--" && left == "" { value = tokens.move() } else if left == "" { tokens.error.raise("\(short) requires argument") } else { value = left } left = "" } if tokens.error is DocoptExit { o.value = value ?? true } } parsed.append(o) } return parsed } static internal func parseAtom(tokens: Tokens, inout options: [Option]) -> [Pattern] { let token = tokens.current()! if ["(", "["].contains(token) { tokens.move() let u = parseExpr(tokens, options: &options) let (matching, result) = (token == "(") ? (")", [Required(u)]) : ("]", [Optional(u)]) if tokens.move() != matching { tokens.error.raise("unmatched '\(token)'") } return result } if token == "options" { tokens.move() return [OptionsShortcut()] } if token.hasPrefix("--") && token != "--" { return parseLong(tokens, options: &options) } if token.hasPrefix("-") && !["--", "-"].contains(token) { return parseShorts(tokens, options: &options) } if (token.hasPrefix("<") && token.hasSuffix(">")) || token.isupper() { return [Argument(tokens.move()!)] } return [Command(tokens.move()!)] } static internal func parseSeq(tokens: Tokens, inout options: [Option]) -> [Pattern] { var result = [Pattern]() while let current = tokens.current() where !["]", ")", "|"].contains(current) { var atom = parseAtom(tokens, options: &options) if tokens.current() == "..." { atom = [OneOrMore(atom)] tokens.move() } result += atom } return result } static internal func parseExpr(tokens: Tokens, inout options: [Option]) -> [Pattern] { var seq = parseSeq(tokens, options: &options) if tokens.current() != "|" { return seq } var result = seq.count > 1 ? [Required(seq)] : seq while tokens.current() == "|" { tokens.move() seq = parseSeq(tokens, options: &options) result += seq.count > 1 ? [Required(seq)] : seq } return result.count > 1 ? [Either(result)] : result } /** * Parse command-line argument vector. * * If options_first: * argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ; * else: * argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ; */ static internal func parseArgv(tokens: Tokens, inout options: [Option], optionsFirst: Bool = false) -> [LeafPattern] { var parsed = [LeafPattern]() while let current = tokens.current() { if tokens.current() == "--" { while let token = tokens.move() { parsed.append(Argument(nil, value: token)) } return parsed } else if current.hasPrefix("--") { for arg in parseLong(tokens, options: &options) { parsed.append(arg) } } else if current.hasPrefix("-") && current != "-" { for arg in parseShorts(tokens, options: &options) { parsed.append(arg) } } else if optionsFirst { while let token = tokens.move() { parsed.append(Argument(nil, value: token)) } return parsed } else { parsed.append(Command(nil, value: tokens.move())) } } return parsed } static internal func parsePattern(source: String, inout options: [Option]) -> Pattern { let tokens: Tokens = Tokens.fromPattern(source) let result: [Pattern] = parseExpr(tokens, options: &options) if tokens.current() != nil { tokens.error.raise("unexpected ending: \(tokens)") } return Required(result) } static internal func formalUsage(section: String) -> String { let (_, _, s) = section.partition(":") // drop "usage:" let pu: [String] = s.split() return "( " + " ".join(pu[1..<pu.count].map { $0 == pu[0] ? ") | (" : $0 }) + " )" } }
mit
ece277c9b82566af76ee0b6c297a2aa1
35.935976
154
0.492282
4.517151
false
false
false
false
twobitlabs/TBLCategories
Swift Extensions/UIImage+TBL.swift
1
1698
import UIKit extension UIImage { func imageWithColor(_ color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) let context = UIGraphicsGetCurrentContext()! context.translateBy(x: 0, y: self.size.height) context.scaleBy(x: 1.0, y: -1.0); context.setBlendMode(.normal) let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) as CGRect context.clip(to: rect, mask: self.cgImage!) color.setFill() context.fill(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage UIGraphicsEndImageContext() return newImage } class func imageWithText(_ text: String, textAttributes: [NSAttributedString.Key: Any]) -> UIImage { let size = text.size(withAttributes: textAttributes) UIGraphicsBeginImageContext(size) text.draw(in: CGRect(origin: CGPoint.zero, size: size), withAttributes: textAttributes) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } class func imageWithText(_ text: String, font: UIFont, color: UIColor? = UIColor.darkText) -> UIImage { var attributes = [NSAttributedString.Key: Any]() attributes[NSAttributedString.Key.font] = font attributes[NSAttributedString.Key.foregroundColor] = color return imageWithText(text, textAttributes: attributes) } class func imageWithText(_ text: String, fontSize: CGFloat, color: UIColor? = nil) -> UIImage { return imageWithText(text, font: UIFont.systemFont(ofSize: fontSize), color: color) } }
mit
efd818d20b3bc0f4d61aa32aca6fb409
36.733333
107
0.679623
4.810198
false
false
false
false
MakeSchool/TripPlanner
TripPlanner/Model/GooglePlaces/LocationSearchResult.swift
1
1555
// // LocationSearchResult.swift // TripPlanner // // Created by Benjamin Encz on 7/24/15. // Copyright © 2015 Make School. All rights reserved. // import Foundation import CoreLocation struct Place { let description: String let id: String let matchedSubstrings: [SubstringMatch] let placeId: String let reference: String let terms: [Term] let types: [String] // TODO: consider renaming 'Place.description' to make this type CustomStringConvertible var placeDescription: String { get { return terms.map{$0.value}.joinWithSeparator(", ") } } } struct PlaceWithLocation { let locationSearchEntry: Place let location: CLLocationCoordinate2D } struct Predictions { let predictions: [Place] } struct Term { let offset: Int let value: String } struct SubstringMatch { let length: Int let offset: Int } // MARK: Equatable implementations extension Place: Equatable {} func ==(lhs: Place, rhs: Place) -> Bool { return lhs.description == rhs.description && lhs.id == rhs.id && lhs.matchedSubstrings == rhs.matchedSubstrings && lhs.placeId == rhs.placeId && lhs.reference == rhs.reference && lhs.terms == rhs.terms && lhs.types == rhs.types } extension SubstringMatch: Equatable {} func ==(lhs: SubstringMatch, rhs: SubstringMatch) -> Bool { return lhs.length == rhs.length && lhs.offset == rhs.offset } extension Term: Equatable {} func ==(lhs: Term, rhs: Term) -> Bool { return lhs.offset == rhs.offset && lhs.value == rhs.value }
mit
88531d19ea4274a8f0f8d56de2fdfdd1
19.181818
90
0.673102
3.846535
false
false
false
false
rvanmelle/QuickSettings
SettingsExample/QuickSettings/QSModel.swift
1
12507
// // Model.swift // SettingsExample // // Created by Reid van Melle on 2016-10-30. // Copyright © 2016 Reid van Melle. All rights reserved. // import Foundation /** To create a list of option items, create something that conforms to the SettingsOptions protocol. This includes a list of the string options to be displayed to the user and a defaultValue if nothing has been selected. */ public protocol QSSettingsOptions { var options: [String] { get } var defaultValue: String { get } func description(for: String) -> String? } public protocol QSDescriptionEnum: Hashable { var description: String? { get } } /** This is a quick wrapper for an enum : String which makes it conform to SettingsOptions. This allows a string enumeration to be easily used to display a set of options to the user. */ public class QSEnumSettingsOptions<T> : QSSettingsOptions where T: RawRepresentable, T: QSDescriptionEnum, T.RawValue == String { public typealias Option = T private let defaultVal: T public init(defaultValue: T) { self.defaultVal = defaultValue } public var defaultValue: String { return defaultVal.rawValue } public var options: [String] { return Array(iterateEnum(T.self)).map { $0.rawValue } } public func description(for val: String) -> String? { return T(rawValue: val)?.description } } private func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> { var i = 0 return AnyIterator { let next = withUnsafePointer(to: &i) { $0.withMemoryRebound(to: T.self, capacity: 1) { $0.pointee } } if next.hashValue != i { return nil } i += 1 return next } } // http://nshipster.com/swift-documentation/ // http://useyourloaf.com/blog/swift-documentation-quick-guide/ public protocol QSSettable { /** Resets/overwrite all of the settings with default values. - parameter dataSource: the conforming datastore to be initialized - Warning: DESTRUCTIVE OPERATION -- this will overwrite existing data with defaults */ func reset(_ dataSource: QSSettingsDataSource) /** Initializes the dataStore to fill in any missing values with defaults. - parameter dataSource: the conforming datastore to be initialized - important: THIS WILL NOT OVERWRITE EXISTING VALUES */ func initialize(_ dataSource: QSSettingsDataSource) func setting(for key: String) -> QSSettable? var uniqueId: String? { get } } public struct QSInfo: QSSettable { let label: String let text: String /** Handy function to create an Info setting - parameter label: the info title to display to the user - parameter text: the text info to display to the user - returns: a Setting of type QSInfo */ public init(label: String, text: String) { self.label = label self.text = text } public func reset(_ dataSource: QSSettingsDataSource) {} public func initialize(_ dataSource: QSSettingsDataSource) {} public func setting(for key: String) -> QSSettable? { return nil } public var uniqueId: String? { return nil } } public struct QSToggle: QSSettable { let label: String let key: String let defaultValue: Bool /** Create a Toggle setting - parameter label: the string to display to the user - parameter id: the key used to store/retrieve from the datastore - parameter defaultValue: value to be used if none has been set - returns: a Setting of type Setting.Toggle */ public init(label: String, key: String, defaultValue: Bool) { self.label = label self.key = key self.defaultValue = defaultValue } internal func value(from dataSource: QSSettingsDataSource) -> Bool { return dataSource.hasValue(forKey: key) ? dataSource.value(forKey: key, type: Bool.self)! : defaultValue //dataSource.bool(forKey: key) : defaultValue } public func reset(_ dataSource: QSSettingsDataSource) {} public func initialize(_ dataSource: QSSettingsDataSource) {} public func setting(for settingKey: String) -> QSSettable? { return key == settingKey ? self : nil } public var uniqueId: String? { return key } } public enum QSTextSettingType { case text case name case url case int case phone case password case email case decimal var autocorrection: UITextAutocorrectionType { switch self { case .text: return .yes case .decimal, .email, .int, .name, .password, .phone, .url: return .no } } var autocapitalization: UITextAutocapitalizationType { switch self { case .text, .decimal, .email, .int, .password, .phone, .url: return .none case .name: return .words } } var keyboard: UIKeyboardType { switch self { case .text: return .default case .decimal: return .decimalPad case .email: return .emailAddress case .int: return .numberPad case .name: return .namePhonePad case .password: return .default case .phone: return .phonePad case .url: return .URL } } var secure: Bool { switch self { case .password: return true case .text, .decimal, .email, .int, .name, .phone, .url: return false } } } public struct QSText: QSSettable { let label: String let key: String let defaultValue: String? let type: QSTextSettingType let placeholder: String? /** Handy function to create a Text setting - parameter label: the string to display to the user - parameter id: the key used to store/retrieve from the datastore - parameter defaultValue: value to be used if none has been set - returns: a Setting of type QSText */ public init(label: String, key: String, defaultValue: String? = nil, placeholder: String? = nil, type: QSTextSettingType = .text) { self.label = label self.key = key self.defaultValue = defaultValue self.type = type self.placeholder = placeholder } internal func value(from dataSource: QSSettingsDataSource) -> String? { guard type != .password else { return nil } return dataSource.hasValue(forKey: key) ? dataSource.value(forKey: key, type: String.self)! : defaultValue //dataSource.string(forKey: key) : defaultValue } public func reset(_ dataSource: QSSettingsDataSource) { guard type != .password else { return } dataSource.set(defaultValue, forKey: key) } public func initialize(_ dataSource: QSSettingsDataSource) { if !dataSource.hasValue(forKey: key) { reset(dataSource) } } public func setting(for settingKey: String) -> QSSettable? { return key == settingKey ? self : nil } public var uniqueId: String? { return key } } public struct QSSlider: QSSettable { let label: String let key: String let min: Float let max: Float let defaultValue: Float /** Handy function to create a Slider setting - parameter label: the string to display to the user - parameter id: the key used to store/retrieve from the datastore - parameter min: minimum value for the slider - parameter max: maximum value for the slider - parameter defaultValue: value to be used if none has been set - returns: a Setting of type QSSlider */ public init(label: String, key: String, min: Float, max: Float, defaultValue: Float) { self.label = label self.key = key self.min = min self.max = max self.defaultValue = defaultValue } public func reset(_ dataSource: QSSettingsDataSource) { dataSource.set(defaultValue, forKey: key) } public func initialize(_ dataSource: QSSettingsDataSource) { if !dataSource.hasValue(forKey: key) { reset(dataSource) } } public func setting(for settingKey: String) -> QSSettable? { return key == settingKey ? self : nil } public var uniqueId: String? { return key } } public struct QSGroup: QSSettable { let title: String? let children: [QSSettable] let footer: String? /** Create a Group setting - parameter title: the title of the group to be displayed to the user - parameter children: the list of Setting objects to be display in the group - parameter footer: a description string displayed underneath the group - returns: a Setting of type QSGroup */ public init(title: String?, children: [QSSettable], footer: String? = nil) { self.title = title self.children = children self.footer = footer } public init(title: String?, footer: String?, childrenCallback: (() -> [QSSettable])) { self.title = title self.footer = footer self.children = childrenCallback() } public func reset(_ dataSource: QSSettingsDataSource) { for c in children { c.reset(dataSource) } } public func initialize(_ dataSource: QSSettingsDataSource) { for c in children { c.initialize(dataSource) } } public func setting(for key: String) -> QSSettable? { for c in children { if let _ = c.setting(for:key) { return c } } return nil } public var uniqueId: String? { return nil } } public struct QSAction: QSSettable { public enum ActionType { case normal, `default`, destructive } let title: String let actionCallback: () -> Void let actionType: ActionType public init(title: String, actionType: ActionType = .normal, actionCallback: @escaping () -> Void) { self.title = title self.actionCallback = actionCallback self.actionType = actionType } public func reset(_ dataSource: QSSettingsDataSource) {} public func initialize(_ dataSource: QSSettingsDataSource) {} public func setting(for key: String) -> QSSettable? { return nil } public var uniqueId: String? { return nil } } public struct QSSelect: QSSettable { let label: String let key: String let options: QSSettingsOptions /** Create a Select setting - parameter label: the string to display to the user - parameter id: the key used to store/retrieve from the datastore - parameter options: an object conforming to SettingsOptions - returns: a Setting of type QSSelect */ public init(label: String, key: String, options: QSSettingsOptions) { self.label = label self.key = key self.options = options } internal func value(from dataSource: QSSettingsDataSource) -> String? { if dataSource.hasValue(forKey: key) { let proposedValue = dataSource.value(forKey: key, type: String.self)! if options.options.contains(proposedValue) { return proposedValue } else { return options.defaultValue } } else { return options.defaultValue } } public func reset(_ dataSource: QSSettingsDataSource) { dataSource.set(options.defaultValue, forKey: key) } public func initialize(_ dataSource: QSSettingsDataSource) { if !dataSource.hasValue(forKey: key) { reset(dataSource) } } public func setting(for settingKey: String) -> QSSettable? { return key == settingKey ? self : nil } public var uniqueId: String? { return key } } public protocol QSSettingsDataSource: class { func hasValue(forKey: String) -> Bool func set(_ value: Any?, forKey defaultName: String) func value<T>(forKey key: String, type: T.Type) -> T? } /** Make user defaults conform to the SettingsDataSource protocol */ extension UserDefaults : QSSettingsDataSource { public func value<T>(forKey key: String, type: T.Type) -> T? { switch type { case is String.Type: return string(forKey: key) as? T case is Int.Type: return integer(forKey: key) as? T case is Float.Type: return float(forKey: key) as? T case is Bool.Type: return bool(forKey: key) as? T default: fatalError() } } public func hasValue(forKey key: String) -> Bool { if let _ = value(forKey: key) { return true } else { return false } } }
mit
0574c6d671c26ac347b17671c91259a1
30.501259
135
0.64489
4.41596
false
false
false
false
zenangst/Tailor
Sources/Shared/Extensions/Array+Tailor.swift
1
1878
public extension Array { /** - Parameter name: String - Returns: A mappable object array, otherwise it returns empty array */ func objects<T: Mappable>(_ name: String? = nil) -> [T] { var objects = [T]() if let name = name { for dictionary in self { guard let dictionary = dictionary as? [String : Any], let value = dictionary[name] as? [String : Any] else { continue } objects.append(T(value)) } } else { for dictionary in self { guard let dictionary = dictionary as? [String : Any] else { continue } objects.append(T(dictionary)) } } return objects } /** - Parameter name: String - Returns: A mappable object array, otherwise it returns nil */ func objects<T: SafeMappable>(_ name: String? = nil) throws -> [T] { var objects = [T]() if let name = name { for dictionary in self { guard let dictionary = dictionary as? [String : Any], let value = dictionary[name] as? [String : Any] else { continue } objects.append(try T(value)) } } else { for dictionary in self { guard let dictionary = dictionary as? [String : Any] else { continue } objects.append(try T(dictionary)) } } return objects } /** - Parameter name: The index - Returns: A child dictionary at that index, otherwise it returns nil */ func dictionary(_ index: Int) -> [String : Any]? { guard index < self.count, let value = self[index] as? [String : Any] else { return nil } return value } /** - Parameter name: The index - Returns: A child array at that index, otherwise it returns nil */ func array(_ index: Int) -> [[String : Any]]? { guard index < self.count, let value = self[index] as? [[String : Any]] else { return nil } return value } }
mit
509941278f09490d086ff6ddeb4d14da
25.828571
78
0.588392
4.064935
false
false
false
false
CatchChat/Yep
Yep/ViewControllers/Conversation/ConversationViewController+TextIndicator.swift
1
1570
// // ConversationViewController+TextIndicator.swift // Yep // // Created by NIX on 16/4/14. // Copyright © 2016年 Catch Inc. All rights reserved. // import UIKit import RealmSwift import YepKit import YepNetworking extension ConversationViewController { func promptSendMessageFailed(reason reason: Reason, errorMessage: String?, reserveErrorMessage: String) { if case .NoSuccessStatusCode(_, let errorCode) = reason where errorCode == ErrorCode.BlockedByRecipient { indicateBlockedByRecipient() } else { let message = errorMessage ?? reserveErrorMessage YepAlert.alertSorry(message: message, inViewController: self) } } private func indicateBlockedByRecipient() { SafeDispatch.async { [weak self] in if let conversation = self?.conversation { self?.indicateBlockedByRecipientInConversation(conversation) } } } private func indicateBlockedByRecipientInConversation(conversation: Conversation) { guard let realm = conversation.realm else { return } let message = Message() let messageID = "BlockedByRecipient." + NSUUID().UUIDString message.messageID = messageID message.blockedByRecipient = true message.conversation = conversation let _ = try? realm.write { realm.add(message) } updateConversationCollectionViewWithMessageIDs([messageID], messageAge: .New, scrollToBottom: true, success: { _ in }) } }
mit
7a5af7de3fbcf4a998c5e7e13d7a1f6c
29.134615
123
0.660498
5.104235
false
false
false
false
daggmano/photo-management-studio
src/Client/OSX/PMS-2/Photo Management Studio/Photo Management Studio/TitleCellView.swift
1
1450
// // TitleCell.swift // Photo Management Studio // // Created by Darren Oster on 23/03/2016. // Copyright © 2016 Criterion Software. All rights reserved. // import Cocoa class TitleCellView: NSTableCellView { @IBOutlet weak var outlineView: NSOutlineView! @IBOutlet weak var titleButton: NSButton! @IBOutlet weak var addButton: NSButton! var representedItem: LibraryItem? override func viewWillDraw() { self.titleButton.title = (representedItem?.text)!.uppercaseString addButton.hidden = !representedItem!.titleHasAdd() } @IBAction func onShowHide(sender: AnyObject?) { if let button = sender as? NSButton { if let item = getItemForRepresentedObject(representedItem!) { if (button.state == 1) { outlineView.expandItem(item, expandChildren: true) } else { outlineView.collapseItem(item, collapseChildren: true) } } } } private func getItemForRepresentedObject(object: LibraryItem) -> AnyObject? { let c = outlineView.numberOfRows for i in 0 ..< c { if let o = outlineView.itemAtRow(i)?.representedObject as? LibraryItem { if (o == object) { return outlineView.itemAtRow(i) } } } return nil } }
mit
0c489f61ec420309abfcc233a46a1813
27.411765
84
0.574879
5.03125
false
false
false
false
nastia05/TTU-iOS-Developing-Course
Lecture 11/TTUNotes/TTUNotes/ModelController.swift
1
1323
// // ModelController.swift // TTUNotes // // Created by Anastasiia Soboleva on 08.03.17. // Copyright © 2017 Anastasiia Soboleva. All rights reserved. // import Foundation import CoreData private var isLoaded = false private let container = NSPersistentContainer(name: "Model") //This is a good async way to initialise a Core Data stack and load a persistence store extension NSPersistentContainer { static func notesContainer(errorHandler eh: @escaping (Error) -> Void, complationHanlder ch: @escaping (NSPersistentContainer) -> Void) { assert(Thread.isMainThread) guard !isLoaded else { return ch(container) } let group = DispatchGroup() container.persistentStoreDescriptions.forEach { $0.shouldAddStoreAsynchronously = true group.enter() } container.loadPersistentStores(completionHandler: { (description, error) in if let err = error { return eh(err) } group.leave() }) group.notify(queue: .main) { container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyStoreTrump isLoaded = true ch(container) } } }
mit
793fd919d47a00847b213956b471bec5
25.44
141
0.600605
5.007576
false
false
false
false
intelygenz/Kommander-iOS
Source/Dispatcher.swift
2
4870
// // Dispatcher.swift // Kommander // // Created by Alejandro Ruperez Hernando on 26/1/17. // Copyright © 2017 Intelygenz. All rights reserved. // import Foundation /// Dispatcher open class Dispatcher { /// Dispatcher operation queue final var operationQueue = OperationQueue() /// Dispatcher dispatch queue final var dispatchQueue = DispatchQueue(label: UUID().uuidString) /// Main queue dispatcher public static var main: Dispatcher { return MainDispatcher() } /// Current queue dispatcher public static var current: Dispatcher { return CurrentDispatcher() } /// Dispatcher with default quality of service public static var `default`: Dispatcher { return Dispatcher() } /// Dispatcher with user interactive quality of service public static var userInteractive: Dispatcher { return Dispatcher(qos: .userInteractive) } /// Dispatcher with user initiated quality of service public static var userInitiated: Dispatcher { return Dispatcher(qos: .userInitiated) } /// Dispatcher with utility quality of service public static var utility: Dispatcher { return Dispatcher(qos: .utility) } /// Dispatcher with background quality of service public static var background: Dispatcher { return Dispatcher(qos: .background) } /// Dispatcher instance with custom OperationQueue public init(name: String = UUID().uuidString, qos: QualityOfService = .default, maxConcurrentOperations: Int = OperationQueue.defaultMaxConcurrentOperationCount) { operationQueue.name = name operationQueue.qualityOfService = qos operationQueue.maxConcurrentOperationCount = maxConcurrentOperations dispatchQueue = DispatchQueue(label: name, qos: dispatchQoS(qos), attributes: .concurrent, autoreleaseFrequency: .inherit, target: operationQueue.underlyingQueue) } /// Execute Operation instance in OperationQueue open func execute(_ operation: Operation) { operationQueue.addOperation(operation) } /// Execute [Operation] instance collection in OperationQueue open func execute(_ operations: [Operation], waitUntilFinished: Bool = false) { operationQueue.addOperations(operations, waitUntilFinished: waitUntilFinished) } /// Execute closure in OperationQueue @discardableResult open func execute(_ closure: @escaping () -> Void) -> Operation { let operation = BlockOperation(block: closure) execute(operation) return operation } /// Execute [closure] collection in OperationQueue concurrently or sequentially @discardableResult open func execute(_ closures: [() -> Void], concurrent: Bool = true, waitUntilFinished: Bool = false) -> [Operation] { var lastOperation: Operation? let operations = closures.map { closure -> Operation in let operation = BlockOperation(block: closure) if let lastOperation = lastOperation, !concurrent { operation.addDependency(lastOperation) } lastOperation = operation return operation } execute(operations, waitUntilFinished: waitUntilFinished) return operations } /// Execute closure in DispatchQueue after delay open func execute(after delay: DispatchTimeInterval, closure: @escaping () -> Void) { guard delay != .never else { return } dispatchQueue.asyncAfter(deadline: .now() + delay, execute: closure) } /// Execute DispatchWorkItem instance in DispatchQueue after delay open func execute(after delay: DispatchTimeInterval, work: DispatchWorkItem) { guard delay != .never else { work.cancel() return } dispatchQueue.asyncAfter(deadline: .now() + delay, execute: work) } /// Execute DispatchWorkItem instance in DispatchQueue open func execute(_ work: DispatchWorkItem) { dispatchQueue.async(execute: work) } } public extension Array where Element: Operation { /// Execute [Operation] instance collection in OperationQueue public func execute(in operationQueue: OperationQueue, waitUntilFinished: Bool = false) { operationQueue.addOperations(self, waitUntilFinished: waitUntilFinished) } /// Execute [Operation] instance collection in Dispatcher public func execute(in dispatcher: Dispatcher, waitUntilFinished: Bool = false) { dispatcher.execute(self, waitUntilFinished: waitUntilFinished) } } private extension Dispatcher { final func dispatchQoS(_ qos: QualityOfService) -> DispatchQoS { switch qos { case .userInteractive: return .userInteractive case .userInitiated: return .userInitiated case .utility: return .utility case .background: return .background default: return .default } } }
mit
749206959c72414e2605b6e513247017
38.266129
170
0.697885
5.526674
false
false
false
false
drunknbass/Emby.ApiClient.Swift
Emby.ApiClient/model/connect/PinExchangeResult.swift
1
957
// // PinExchangeResult.swift // Emby.ApiClient // // Created by Vedran Ozir on 08/10/15. // Copyright © 2015 Vedran Ozir. All rights reserved. // import Foundation //package mediabrowser.model.connect; public class PinExchangeResult: GenericResult { public required init(jSON: JSON_Object) { super.init(jSON: jSON) if let Id = jSON["Id"] as? String { self.UserId = Id } if let AccessToken = jSON["AccessToken"] as? String { self.AccessToken = AccessToken } } private var UserId: String? public final func getUserId() -> String? { return UserId; } public final func setUserId(value: String) { UserId = value; } private var AccessToken: String? public final func getAccessToken() -> String? { return AccessToken; } public final func setAccessToken(value: String) { AccessToken = value; } }
mit
c193f65b2f36ad4bf5a02deb64ec6de3
21.255814
61
0.608787
4.174672
false
false
false
false
IFTTT/RazzleDazzle
Source/ScaleAnimation.swift
1
1100
// // ScaleAnimation.swift // RazzleDazzle // // Created by Laura Skelton on 6/13/15. // Copyright (c) 2015 IFTTT. All rights reserved. // import UIKit /** Animates the scale of the `transform` of a `UIView`. */ public class ScaleAnimation : Animation<CGFloat>, Animatable { private let view : UIView public init(view: UIView) { self.view = view } public func animate(_ time: CGFloat) { if !hasKeyframes() {return} let scale = self[time] let scaleTransform = CGAffineTransform(scaleX: scale, y: scale) view.scaleTransform = scaleTransform var newTransform = scaleTransform if let rotationTransform = view.rotationTransform { newTransform = newTransform.concatenating(rotationTransform) } if let translationTransform = view.translationTransform { newTransform = newTransform.concatenating(translationTransform) } view.transform = newTransform } public override func validateValue(_ value: CGFloat) -> Bool { return (value >= 0) } }
mit
e15f523fe6aebee8a101b3d5976c7247
27.205128
75
0.646364
4.545455
false
false
false
false
danielsaidi/KeyboardKit
Sources/KeyboardKit/UIKit/Views/UIKeyboardButtonCollectionView.swift
1
1982
// // UIKeyboardButtonCollectionView.swift // KeyboardKit // // Created by Daniel Saidi on 2019-05-02. // Copyright © 2021 Daniel Saidi. All rights reserved. // import UIKit /** This collection view displays a single cell for each action. You can customize it and its appearance in any way you want, e.g. by setting a custom flow layout. This view can be created with a set of actions and a button creator, which creates a button for each action and adds it to the dequeued cell. This view simplifies setting up a collection-based keyboard, but does so at a performance cost. It's way less performant than `KeyboardCollectionView` since it recreates the button views each time a cell is reused. */ open class UIKeyboardButtonCollectionView: UIKeyboardCollectionView { // MARK: - Initialization public init(actions: [KeyboardAction], buttonCreator: @escaping KeyboardButtonCreator) { self.buttonCreator = buttonCreator super.init(actions: actions) } public required init?(coder aDecoder: NSCoder) { self.buttonCreator = { _ in fatalError() } super.init(coder: aDecoder) } // MARK: - Types public typealias KeyboardButtonCreator = (KeyboardAction) -> (UIView) // MARK: - Properties private let buttonCreator: KeyboardButtonCreator // MARK: - UICollectionViewDataSource open func action(at indexPath: IndexPath) -> KeyboardAction { return actions[indexPath.item] } open override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = super.collectionView(collectionView, cellForItemAt: indexPath) cell.subviews.forEach { $0.removeFromSuperview() } let action = self.action(at: indexPath) let button = buttonCreator(action) cell.addSubview(button, fill: true) return cell } }
mit
aee28fe27585fb3cef845515f041934d
29.476923
135
0.69258
4.855392
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/General/Categories/UIApplication+HiPDA.swift
1
908
// // UIApplication+HiPDA.swift // HiPDA // // Created by leizh007 on 2017/6/3. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation extension UIApplication { class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { if let presented = controller?.presentedViewController { return topViewController(controller: presented) } if let navigationController = controller as? UINavigationController { return topViewController(controller: navigationController.visibleViewController) } if let tabController = controller as? UITabBarController { if let selected = tabController.selectedViewController { return topViewController(controller: selected) } } return controller } }
mit
7ed3df15537c1b950ad984bf9eb29c58
31.321429
139
0.680663
5.801282
false
false
false
false
Foild/StatefulViewController
Example/PlaceholderViews/ErrorView.swift
1
1677
// // ErrorView.swift // Example // // Created by Alexander Schuch on 29/08/14. // Copyright (c) 2014 Alexander Schuch. All rights reserved. // import UIKit class ErrorView: BasicPlaceholderView { let textLabel = UILabel() let detailTextLabel = UILabel() let tapGestureRecognizer = UITapGestureRecognizer() override func setupView() { super.setupView() backgroundColor = UIColor.whiteColor() self.addGestureRecognizer(tapGestureRecognizer) textLabel.text = "Something went wrong." textLabel.translatesAutoresizingMaskIntoConstraints = false centerView.addSubview(textLabel) detailTextLabel.text = "Tap to reload" let fontDescriptor = UIFontDescriptor.preferredFontDescriptorWithTextStyle(UIFontTextStyleFootnote) detailTextLabel.font = UIFont(descriptor: fontDescriptor, size: 0) detailTextLabel.textAlignment = .Center detailTextLabel.textColor = UIColor.grayColor() detailTextLabel.translatesAutoresizingMaskIntoConstraints = false centerView.addSubview(detailTextLabel) let views = ["label": textLabel, "detailLabel": detailTextLabel] let hConstraints = NSLayoutConstraint.constraintsWithVisualFormat("|-[label]-|", options: .AlignAllCenterY, metrics: nil, views: views) let hConstraintsDetail = NSLayoutConstraint.constraintsWithVisualFormat("|-[detailLabel]-|", options: .AlignAllCenterY, metrics: nil, views: views) let vConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label]-[detailLabel]-|", options: .AlignAllCenterX, metrics: nil, views: views) centerView.addConstraints(hConstraints) centerView.addConstraints(hConstraintsDetail) centerView.addConstraints(vConstraints) } }
mit
731d50c01f52affed0b41080799f7beb
35.456522
153
0.782349
4.991071
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/maximum-product-of-word-lengths.swift
2
1910
/** * https://leetcode.com/problems/maximum-product-of-word-lengths/ * * */ // Date: Thu May 27 08:38:11 PDT 2021 class Solution { func maxProduct(_ words: [String]) -> Int { var map: [String : Set<Character>] = [:] for word in words { var set: Set<Character> = [] for c in word { set.insert(c) } map[word] = set } var result = 0 for index1 in stride(from: 1, to: words.count, by: 1) { let set1 = map[words[index1], default: []] for index2 in stride(from: 0, to: index1, by: 1) { let set2 = map[words[index2], default: []] if set1.isDisjoint(with: set2) { result = max(result, words[index1].count * words[index2].count) } } } return result } }/** * https://leetcode.com/problems/maximum-product-of-word-lengths/ * * */ // Date: Thu May 27 08:49:32 PDT 2021 class Solution { func maxProduct(_ words: [String]) -> Int { var map: [Set<Character> : String] = [:] for word in words { var set: Set<Character> = [] for c in word { set.insert(c) } if let w = map[set] { map[set] = w.count > word.count ? w : word } else { map[set] = word } } var result = 0 let keys = Array(map.keys) for index1 in stride(from: 1, to: keys.count, by: 1) { let set1 = keys[index1] for index2 in stride(from: 0, to: index1, by: 1) { let set2 = keys[index2] if set1.isDisjoint(with: set2) { result = max(result, map[set1, default: ""].count * map[set2, default: ""].count) } } } return result } }
mit
e1abc31fdbbe2be1dea0c05a6727537f
29.822581
101
0.464921
3.708738
false
false
false
false
kello711/HackingWithSwift
project23/Project23/GameScene.swift
1
2910
// // GameScene.swift // Project23 // // Created by Hudzilla on 16/09/2015. // Copyright (c) 2015 Paul Hudson. All rights reserved. // import GameplayKit import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { var starfield: SKEmitterNode! var player: SKSpriteNode! var possibleEnemies = ["ball", "hammer", "tv"] var gameTimer: NSTimer! var gameOver = false var scoreLabel: SKLabelNode! var score: Int = 0 { didSet { scoreLabel.text = "Score: \(score)" } } override func didMoveToView(view: SKView) { backgroundColor = UIColor.blackColor() starfield = SKEmitterNode(fileNamed: "Starfield")! starfield.position = CGPoint(x: 1024, y: 384) starfield.advanceSimulationTime(10) addChild(starfield) starfield.zPosition = -1 player = SKSpriteNode(imageNamed: "player") player.position = CGPoint(x: 100, y: 384) player.physicsBody = SKPhysicsBody(texture: player.texture!, size: player.size) player.physicsBody!.contactTestBitMask = 1 addChild(player) scoreLabel = SKLabelNode(fontNamed: "Chalkduster") scoreLabel.position = CGPoint(x: 16, y: 16) scoreLabel.horizontalAlignmentMode = .Left addChild(scoreLabel) score = 0 physicsWorld.gravity = CGVector(dx: 0, dy: 0) physicsWorld.contactDelegate = self gameTimer = NSTimer.scheduledTimerWithTimeInterval(0.35, target: self, selector: #selector(createEnemy), userInfo: nil, repeats: true) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { } override func update(currentTime: CFTimeInterval) { for node in children { if node.position.x < -300 { node.removeFromParent() } } if !gameOver { score += 1 } } func createEnemy() { possibleEnemies = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(possibleEnemies) as! [String] let randomDistribution = GKRandomDistribution(lowestValue: 50, highestValue: 736) let sprite = SKSpriteNode(imageNamed: possibleEnemies[0]) sprite.position = CGPoint(x: 1200, y: randomDistribution.nextInt()) addChild(sprite) sprite.physicsBody = SKPhysicsBody(texture: sprite.texture!, size: sprite.size) sprite.physicsBody?.categoryBitMask = 1 sprite.physicsBody?.velocity = CGVector(dx: -500, dy: 0) sprite.physicsBody?.angularVelocity = 5 sprite.physicsBody?.linearDamping = 0 sprite.physicsBody?.angularDamping = 0 } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { guard let touch = touches.first else { return } var location = touch.locationInNode(self) if location.y < 100 { location.y = 100 } else if location.y > 668 { location.y = 668 } player.position = location } func didBeginContact(contact: SKPhysicsContact) { let explosion = SKEmitterNode(fileNamed: "explosion")! explosion.position = player.position addChild(explosion) player.removeFromParent() gameOver = true } }
unlicense
e3d41b98445bbd410cd25662924af760
25.454545
136
0.725773
3.803922
false
false
false
false
zisko/swift
stdlib/public/core/IntegerParsing.swift
1
7216
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @inline(__always) internal func _asciiDigit<CodeUnit : UnsignedInteger, Result : BinaryInteger>( codeUnit u_: CodeUnit, radix: Result ) -> Result? { let digit = _ascii16("0")..._ascii16("9") let lower = _ascii16("a")..._ascii16("z") let upper = _ascii16("A")..._ascii16("Z") let u = UInt16(truncatingIfNeeded: u_) let d: UInt16 if _fastPath(digit ~= u) { d = u &- digit.lowerBound } else if _fastPath(upper ~= u) { d = u &- upper.lowerBound &+ 10 } else if _fastPath(lower ~= u) { d = u &- lower.lowerBound &+ 10 } else { return nil } guard _fastPath(d < radix) else { return nil } return Result(truncatingIfNeeded: d) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @inline(__always) internal func _parseUnsignedASCII< Rest : IteratorProtocol, Result: FixedWidthInteger >( first: Rest.Element, rest: inout Rest, radix: Result, positive: Bool ) -> Result? where Rest.Element : UnsignedInteger { let r0 = _asciiDigit(codeUnit: first, radix: radix) guard _fastPath(r0 != nil), var result = r0 else { return nil } if !positive { let (result0, overflow0) = (0 as Result).subtractingReportingOverflow(result) guard _fastPath(!overflow0) else { return nil } result = result0 } while let u = rest.next() { let d0 = _asciiDigit(codeUnit: u, radix: radix) guard _fastPath(d0 != nil), let d = d0 else { return nil } let (result1, overflow1) = result.multipliedReportingOverflow(by: radix) let (result2, overflow2) = positive ? result1.addingReportingOverflow(d) : result1.subtractingReportingOverflow(d) guard _fastPath(!overflow1 && !overflow2) else { return nil } result = result2 } return result } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @inline(__always) internal func _parseASCII< CodeUnits : IteratorProtocol, Result: FixedWidthInteger >( codeUnits: inout CodeUnits, radix: Result ) -> Result? where CodeUnits.Element : UnsignedInteger { let c0_ = codeUnits.next() guard _fastPath(c0_ != nil), let c0 = c0_ else { return nil } if _fastPath(c0 != _ascii16("+") && c0 != _ascii16("-")) { return _parseUnsignedASCII( first: c0, rest: &codeUnits, radix: radix, positive: true) } let c1_ = codeUnits.next() guard _fastPath(c1_ != nil), let c1 = c1_ else { return nil } if _fastPath(c0 == _ascii16("-")) { return _parseUnsignedASCII( first: c1, rest: &codeUnits, radix: radix, positive: false) } else { return _parseUnsignedASCII( first: c1, rest: &codeUnits, radix: radix, positive: true) } } extension FixedWidthInteger { // _parseASCII function thunk that prevents inlining used as an implementation // detail for FixedWidthInteger.init(_: radix:) on the slow path to save code // size. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @_semantics("optimize.sil.specialize.generic.partial.never") @inline(never) internal static func _parseASCIISlowPath< CodeUnits : IteratorProtocol, Result: FixedWidthInteger >( codeUnits: inout CodeUnits, radix: Result ) -> Result? where CodeUnits.Element : UnsignedInteger { return _parseASCII(codeUnits: &codeUnits, radix: radix) } /// Creates a new integer value from the given string and radix. /// /// The string passed as `text` may begin with a plus or minus sign character /// (`+` or `-`), followed by one or more numeric digits (`0-9`) or letters /// (`a-z` or `A-Z`). Parsing of the string is case insensitive. /// /// let x = Int("123") /// // x == 123 /// /// let y = Int("-123", radix: 8) /// // y == -83 /// let y = Int("+123", radix: 8) /// // y == +83 /// /// let z = Int("07b", radix: 16) /// // z == 123 /// /// If `text` is in an invalid format or contains characters that are out of /// bounds for the given `radix`, or if the value it denotes in the given /// `radix` is not representable, the result is `nil`. For example, the /// following conversions result in `nil`: /// /// Int(" 100") // Includes whitespace /// Int("21-50") // Invalid format /// Int("ff6600") // Characters out of bounds /// Int("zzzzzzzzzzzzz", radix: 36) // Out of range /// /// - Parameters: /// - text: The ASCII representation of a number in the radix passed as /// `radix`. /// - radix: The radix, or base, to use for converting `text` to an integer /// value. `radix` must be in the range `2...36`. The default is 10. @_inlineable // FIXME(sil-serialize-all) @_semantics("optimize.sil.specialize.generic.partial.never") public init?<S : StringProtocol>(_ text: S, radix: Int = 10) { _precondition(2...36 ~= radix, "Radix not in range 2...36") let r = Self(radix) let range = text._encodedOffsetRange let guts = text._wholeString._guts defer { _fixLifetime(guts) } let result: Self? if _slowPath(guts._isOpaque) { var i = guts._asOpaque()[range].makeIterator() result = Self._parseASCIISlowPath(codeUnits: &i, radix: r) } else if guts.isASCII { var i = guts._unmanagedASCIIView[range].makeIterator() result = _parseASCII(codeUnits: &i, radix: r) } else { var i = guts._unmanagedUTF16View[range].makeIterator() result = Self._parseASCIISlowPath(codeUnits: &i, radix: r) } guard _fastPath(result != nil) else { return nil } self = result._unsafelyUnwrappedUnchecked } /// Creates a new integer value from the given string. /// /// The string passed as `description` may begin with a plus or minus sign /// character (`+` or `-`), followed by one or more numeric digits (`0-9`). /// /// let x = Int("123") /// // x == 123 /// /// If `description` is in an invalid format, or if the value it denotes in /// base 10 is not representable, the result is `nil`. For example, the /// following conversions result in `nil`: /// /// Int(" 100") // Includes whitespace /// Int("21-50") // Invalid format /// Int("ff6600") // Characters out of bounds /// Int("10000000000000000000000000") // Out of range /// /// - Parameter description: The ASCII representation of a number. @_inlineable // FIXME(sil-serialize-all) @_semantics("optimize.sil.specialize.generic.partial.never") @inline(__always) public init?(_ description: String) { self.init(description, radix: 10) } }
apache-2.0
13d364bf30bf1a465c2759139b4741c5
37.382979
80
0.619595
3.842386
false
false
false
false
honghaoz/UW-Quest-iOS
UW Quest/Helper/Constant.swift
1
1400
// // Constants.swift // UW Quest // // Created by Honghao Zhang on 2014-09-15. // Copyright (c) 2014 Honghao. All rights reserved. // import Foundation // Colors let UQMainColor = UIColor(red:0/255.0, green:90/255.0, blue:127/255.0, alpha:255/255.0) let UQBackgroundColor = UQLightWhiteGrayColor let UQTextFieldFontColor = UQFontGrayColor let UQLabelFontColor = UQFontGrayColor let UQCellBackgroundColor = UIColor(white: 0.89, alpha: 0.3) let UQBlueColor: UIColor = UIColor(red: 0.22, green: 0.48, blue: 0.69, alpha: 1) let UQLightBlueColor: UIColor = UIColor(red: 0, green: 0.6, blue: 0.97, alpha: 1) let UQDarkBlueColor: UIColor = UIColor(red: 0.04, green: 0.11, blue: 0.24, alpha: 1) let UQGreenColor: UIColor = UIColor(red: 0, green: 0.78, blue: 0.45, alpha: 1) let UQBlackStoneColor: UIColor = UIColor(red: 0.22, green: 0.25, blue: 0.29, alpha: 1) let UQLightGrayColor: UIColor = UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1) let UQFontGrayColor: UIColor = UIColor(white: 0.3, alpha: 0.9) let UQLightWhiteGrayColor: UIColor = UIColor(white: 0.95, alpha: 1) let kBorderColor: UIColor = UQLightGrayColor let kBorderCornerRadius: CGFloat = 5.0 let kBorderWidth: CGFloat = 1.0 // URLs let watiamURLString = "https://watiam.uwaterloo.ca/idm/user/login.jsp" let honghaozURLString = "http://honghaoz.com" let honghaoLinkedInURLString = "http://ca.linkedin.com/in/honghaozhang"
apache-2.0
feddf7f6353632499a3ac85827fcf99c
33.170732
87
0.728571
2.811245
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/RealmSwift/RealmSwift/ObjectSchema.swift
40
2662
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm /** This class represents Realm model object schemas. When using Realm, `ObjectSchema` instances allow performing migrations and introspecting the database's schema. Object schemas map to tables in the core database. */ public struct ObjectSchema: CustomStringConvertible { // MARK: Properties internal let rlmObjectSchema: RLMObjectSchema /** An array of `Property` instances representing the managed properties of a class described by the schema. - see: `Property` */ public var properties: [Property] { return rlmObjectSchema.properties.map { Property($0) } } /// The name of the class the schema describes. public var className: String { return rlmObjectSchema.className } /// The property which serves as the primary key for the class the schema describes, if any. public var primaryKeyProperty: Property? { if let rlmProperty = rlmObjectSchema.primaryKeyProperty { return Property(rlmProperty) } return nil } /// A human-readable description of the properties contained in the object schema. public var description: String { return rlmObjectSchema.description } // MARK: Initializers internal init(_ rlmObjectSchema: RLMObjectSchema) { self.rlmObjectSchema = rlmObjectSchema } // MARK: Property Retrieval /// Returns the property with the given name, if it exists. public subscript(propertyName: String) -> Property? { if let rlmProperty = rlmObjectSchema[propertyName] { return Property(rlmProperty) } return nil } } // MARK: Equatable extension ObjectSchema: Equatable { /// Returns whether the two object schemas are equal. public static func == (lhs: ObjectSchema, rhs: ObjectSchema) -> Bool { return lhs.rlmObjectSchema.isEqual(to: rhs.rlmObjectSchema) } }
mit
8a8b056dc8e667b93f6f8c739fed66e4
31.463415
112
0.665665
5.229862
false
false
false
false
OscarSwanros/swift
test/SILGen/protocol_class_refinement.swift
3
4943
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s protocol UID { func uid() -> Int var clsid: Int { get set } var iid: Int { get } } extension UID { var nextCLSID: Int { get { return clsid + 1 } set { clsid = newValue - 1 } } } protocol ObjectUID : class, UID {} extension ObjectUID { var secondNextCLSID: Int { get { return clsid + 2 } set { } } } class Base {} // CHECK-LABEL: sil hidden @_T025protocol_class_refinement12getObjectUID{{[_0-9a-zA-Z]*}}F func getObjectUID<T: ObjectUID>(x: T) -> (Int, Int, Int, Int) { var x = x // CHECK: [[XBOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ObjectUID> { var τ_0_0 } <T> // CHECK: [[PB:%.*]] = project_box [[XBOX]] // CHECK: [[SET_CLSID:%.*]] = witness_method $T, #UID.clsid!setter.1 // -- call x.uid() // CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1 // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X:%.*]] = load [copy] [[READ]] // CHECK: [[X_TMP:%.*]] = alloc_stack // CHECK: store [[X]] to [init] [[X_TMP]] // CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]]) // CHECK: [[X2:%.*]] = load [take] [[X_TMP]] // CHECK: destroy_value [[X2]] // -- call set x.clsid // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T // CHECK: apply [[SET_CLSID]]<T>([[UID]], [[WRITE]]) x.clsid = x.uid() // CHECK: [[SET_NEXTCLSID:%.*]] = function_ref @_T025protocol_class_refinement3UIDPAAE9nextCLSIDSivs // -- call x.uid() // CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1 // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X:%.*]] = load [copy] [[READ]] // CHECK: [[X_TMP:%.*]] = alloc_stack // CHECK: store [[X]] to [init] [[X_TMP]] // CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]]) // CHECK: [[X2:%.*]] = load [take] [[X_TMP]] // CHECK: destroy_value [[X2]] // -- call nextCLSID from protocol ext // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T // CHECK: apply [[SET_NEXTCLSID]]<T>([[UID]], [[WRITE]]) x.nextCLSID = x.uid() // -- call x.uid() // CHECK: [[READ1:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X1:%.*]] = load [copy] [[READ1]] // CHECK: [[SET_SECONDNEXT:%.*]] = function_ref @_T025protocol_class_refinement9ObjectUIDPAAE15secondNextCLSIDSivs // CHECK: [[BORROWED_X1:%.*]] = begin_borrow [[X1]] // CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1 // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X:%.*]] = load [copy] [[READ]] // CHECK: [[X_TMP:%.*]] = alloc_stack // CHECK: store [[X]] to [init] [[X_TMP]] // CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]]) // CHECK: [[X2:%.*]] = load [take] [[X_TMP]] // CHECK: destroy_value [[X2]] // -- call secondNextCLSID from class-constrained protocol ext // CHECK: apply [[SET_SECONDNEXT]]<T>([[UID]], [[BORROWED_X1]]) // CHECK: end_borrow [[BORROWED_X1]] from [[X1]] // CHECK: destroy_value [[X1]] x.secondNextCLSID = x.uid() return (x.iid, x.clsid, x.nextCLSID, x.secondNextCLSID) // CHECK: return } // CHECK-LABEL: sil hidden @_T025protocol_class_refinement16getBaseObjectUID{{[_0-9a-zA-Z]*}}F func getBaseObjectUID<T: UID where T: Base>(x: T) -> (Int, Int, Int) { var x = x // CHECK: [[XBOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : Base, τ_0_0 : UID> { var τ_0_0 } <T> // CHECK: [[PB:%.*]] = project_box [[XBOX]] // CHECK: [[SET_CLSID:%.*]] = witness_method $T, #UID.clsid!setter.1 // -- call x.uid() // CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1 // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X:%.*]] = load [copy] [[READ]] // CHECK: [[X_TMP:%.*]] = alloc_stack // CHECK: store [[X]] to [init] [[X_TMP]] // CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]]) // CHECK: [[X2:%.*]] = load [take] [[X_TMP]] // CHECK: destroy_value [[X2]] // -- call set x.clsid // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T // CHECK: apply [[SET_CLSID]]<T>([[UID]], [[WRITE]]) x.clsid = x.uid() // CHECK: [[SET_NEXTCLSID:%.*]] = function_ref @_T025protocol_class_refinement3UIDPAAE9nextCLSIDSivs // -- call x.uid() // CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1 // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X:%.*]] = load [copy] [[READ]] // CHECK: [[X_TMP:%.*]] = alloc_stack // CHECK: store [[X]] to [init] [[X_TMP]] // CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]]) // CHECK: [[X2:%.*]] = load [take] [[X_TMP]] // CHECK: destroy_value [[X2]] // -- call nextCLSID from protocol ext // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T // CHECK: apply [[SET_NEXTCLSID]]<T>([[UID]], [[WRITE]]) x.nextCLSID = x.uid() return (x.iid, x.clsid, x.nextCLSID) // CHECK: return }
apache-2.0
5fc4659df523419f76d0ed31c281e27a
38.806452
116
0.536264
2.908662
false
false
false
false
hooman/swift
test/Distributed/actor_protocols.swift
1
2661
// RUN: %target-typecheck-verify-swift -enable-experimental-distributed -disable-availability-checking // REQUIRES: concurrency // REQUIRES: distributed import _Distributed // ==== ----------------------------------------------------------------------- @available(SwiftStdlib 5.5, *) actor A: Actor {} // ok @available(SwiftStdlib 5.5, *) class C: Actor, UnsafeSendable { // expected-error@-1{{non-actor type 'C' cannot conform to the 'Actor' protocol}} {{1-6=actor}} // expected-warning@-2{{'UnsafeSendable' is deprecated: Use @unchecked Sendable instead}} nonisolated var unownedExecutor: UnownedSerialExecutor { fatalError() } } @available(SwiftStdlib 5.5, *) struct S: Actor { // expected-error@-1{{non-class type 'S' cannot conform to class protocol 'Actor'}} nonisolated var unownedExecutor: UnownedSerialExecutor { fatalError() } } @available(SwiftStdlib 5.5, *) struct E: Actor { // expected-error@-1{{non-class type 'E' cannot conform to class protocol 'Actor'}} nonisolated var unownedExecutor: UnownedSerialExecutor { fatalError() } } // ==== ----------------------------------------------------------------------- @available(SwiftStdlib 5.5, *) distributed actor DA: DistributedActor {} // ok @available(SwiftStdlib 5.5, *) actor A2: DistributedActor { // expected-error@-1{{non-distributed actor type 'A2' cannot conform to the 'DistributedActor' protocol}} {{1-1=distributed }} nonisolated var id: AnyActorIdentity { fatalError() } nonisolated var actorTransport: ActorTransport { fatalError() } init(transport: ActorTransport) { fatalError() } static func resolve(_ identity: AnyActorIdentity, using transport: ActorTransport) throws -> Self { fatalError() } } @available(SwiftStdlib 5.5, *) class C2: DistributedActor { // expected-error@-1{{non-actor type 'C2' cannot conform to the 'Actor' protocol}} // expected-error@-2{{non-final class 'C2' cannot conform to `Sendable`; use `@unchecked Sendable`}} nonisolated var id: AnyActorIdentity { fatalError() } nonisolated var actorTransport: ActorTransport { fatalError() } required init(transport: ActorTransport) { fatalError() } static func resolve(_ identity: AnyActorIdentity, using transport: ActorTransport) throws -> Self { fatalError() } } @available(SwiftStdlib 5.5, *) struct S2: DistributedActor { // expected-error@-1{{non-class type 'S2' cannot conform to class protocol 'DistributedActor'}} // expected-error@-2{{non-class type 'S2' cannot conform to class protocol 'AnyActor'}} // expected-error@-3{{type 'S2' does not conform to protocol 'Identifiable'}} }
apache-2.0
daee0f4e4b651206771fdf2ea0b27335
29.94186
128
0.670049
4.217116
false
false
false
false
dvxiaofan/Pro-Swift-Learning
Part-02/09-ArrayAdding.playground/Contents.swift
1
449
//: Playground - noun: a place where people can play import UIKit struct Dog { var name: String var age: Int } let popy = Dog(name: "popy", age: 2) let rus = Dog(name: "rus", age: 4) let rover = Dog(name: "rover", age: 3) var dogs = [popy, rus, rover] let lastDog = Dog(name: "hheh", age: 7) dogs += [lastDog] let lastDog2 = Dog(name: "kkkkkk", age: 8) dogs += [lastDog2] //print(dogs) if let dog = dogs.popLast() { print(dog) }
mit
2bd3684b1d5a11dac8abf642b5523e95
16.307692
52
0.616927
2.536723
false
false
false
false
narner/AudioKit
AudioKit/Common/Nodes/Analysis/Frequency Tracker/AKFrequencyTracker.swift
1
2146
// // AKFrequencyTracker.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// This is based on an algorithm originally created by Miller Puckette. /// open class AKFrequencyTracker: AKNode, AKToggleable, AKComponent, AKInput { public typealias AKAudioUnitType = AKFrequencyTrackerAudioUnit /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(effect: "ptrk") // MARK: - Properties fileprivate var internalAU: AKAudioUnitType? /// Tells whether the node is processing (ie. started, playing, or active) @objc open dynamic var isStarted: Bool { return internalAU?.isPlaying() ?? false } /// Detected Amplitude (Use AKAmplitude tracker if you don't need frequency) @objc open dynamic var amplitude: Double { return Double(internalAU?.amplitude ?? 0) / Double(AKSettings.numberOfChannels) } /// Detected frequency @objc open dynamic var frequency: Double { return Double(internalAU?.frequency ?? 0) * Double(AKSettings.numberOfChannels) } // MARK: - Initialization /// Initialize this Pitch-tracker node /// /// - parameter input: Input node to process /// - parameter hopSize: Hop size. /// - parameter peakCount: Number of peaks. /// @objc public init( _ input: AKNode? = nil, hopSize: Double = 512, peakCount: Double = 20) { _Self.register() super.init() AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in self?.avAudioNode = avAudioUnit self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType input?.connect(to: self!) } } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing @objc open func start() { internalAU?.start() } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { internalAU?.stop() } }
mit
dc54e507d3e489d96bc90f57531e548c
29.211268
95
0.655478
4.703947
false
false
false
false
joao-parana/udemy-swift-course
Programacao-sem-Complicacao/PsC/lib/json.swift
2
11665
// // json.swift // json // // Created by Dan Kogai on 7/15/14. // Copyright (c) 2014 Dan Kogai. All rights reserved. // import Foundation /// init public class JSON { private let _value:AnyObject /// pass the object that was returned from /// NSJSONSerialization public init(_ obj:AnyObject) { self._value = obj } /// pass the JSON object for another instance public init(_ json:JSON){ self._value = json._value } } /// class properties extension JSON { public typealias NSNull = Foundation.NSNull public typealias NSError = Foundation.NSError public class var null:NSNull { return NSNull() } /// constructs JSON object from string public convenience init(string:String) { var err:NSError? let enc:NSStringEncoding = NSUTF8StringEncoding var obj:AnyObject? = NSJSONSerialization.JSONObjectWithData( string.dataUsingEncoding(enc)!, options:nil, error:&err ) self.init(err != nil ? err! : obj!) } /// parses string to the JSON object /// same as JSON(string:String) public class func parse(string:String)->JSON { return JSON(string:string) } /// constructs JSON object from the content of NSURL public convenience init(nsurl:NSURL) { var enc:NSStringEncoding = NSUTF8StringEncoding var err:NSError? let str:String? = NSString( contentsOfURL:nsurl, usedEncoding:&enc, error:&err ) if err != nil { self.init(err!) } else { self.init(string:str!) } } /// fetch the JSON string from NSURL and parse it /// same as JSON(nsurl:NSURL) public class func fromNSURL(nsurl:NSURL) -> JSON { return JSON(nsurl:nsurl) } /// constructs JSON object from the content of URL public convenience init(url:String) { if let nsurl = NSURL(string:url) as NSURL? { self.init(nsurl:nsurl) } else { self.init(NSError( domain:"JSONErrorDomain", code:400, userInfo:[NSLocalizedDescriptionKey: "malformed URL"] ) ) } } /// fetch the JSON string from URL in the string public class func fromURL(url:String) -> JSON { return JSON(url:url) } /// does what JSON.stringify in ES5 does. /// when the 2nd argument is set to true it pretty prints public class func stringify(obj:AnyObject, pretty:Bool=false) -> String! { if !NSJSONSerialization.isValidJSONObject(obj) { JSON(NSError( domain:"JSONErrorDomain", code:422, userInfo:[NSLocalizedDescriptionKey: "not an JSON object"] )) return nil } return JSON(obj).toString(pretty:pretty) } } /// instance properties extension JSON { /// access the element like array public subscript(idx:Int) -> JSON { switch _value { case let err as NSError: return self case let ary as NSArray: if 0 <= idx && idx < ary.count { return JSON(ary[idx]) } return JSON(NSError( domain:"JSONErrorDomain", code:404, userInfo:[ NSLocalizedDescriptionKey: "[\(idx)] is out of range" ])) default: return JSON(NSError( domain:"JSONErrorDomain", code:500, userInfo:[ NSLocalizedDescriptionKey: "not an array" ])) } } /// access the element like dictionary public subscript(key:String)->JSON { switch _value { case let err as NSError: return self case let dic as NSDictionary: if let val:AnyObject = dic[key] { return JSON(val) } return JSON(NSError( domain:"JSONErrorDomain", code:404, userInfo:[ NSLocalizedDescriptionKey: "[\"\(key)\"] not found" ])) default: return JSON(NSError( domain:"JSONErrorDomain", code:500, userInfo:[ NSLocalizedDescriptionKey: "not an object" ])) } } /// access json data object public var data:AnyObject? { return self.isError ? nil : self._value } /// Gives the type name as string. /// e.g. if it returns "Double" /// .asDouble returns Double public var type:String { switch _value { case is NSError: return "NSError" case is NSNull: return "NSNull" case let o as NSNumber: switch String.fromCString(o.objCType)! { case "c", "C": return "Bool" case "q", "l", "i", "s": return "Int" case "Q", "L", "I", "S": return "UInt" default: return "Double" } case is NSString: return "String" case is NSArray: return "Array" case is NSDictionary: return "Dictionary" default: return "NSError" } } /// check if self is NSError public var isError: Bool { return _value is NSError } /// check if self is NSNull public var isNull: Bool { return _value is NSNull } /// check if self is Bool public var isBool: Bool { return type == "Bool" } /// check if self is Int public var isInt: Bool { return type == "Int" } /// check if self is UInt public var isUInt: Bool { return type == "UInt" } /// check if self is Double public var isDouble: Bool { return type == "Double" } /// check if self is any type of number public var isNumber: Bool { if let o = _value as? NSNumber { let t = String.fromCString(o.objCType)! return t != "c" && t != "C" } return false } /// check if self is String public var isString: Bool { return _value is NSString } /// check if self is Array public var isArray: Bool { return _value is NSArray } /// check if self is Dictionary public var isDictionary: Bool { return _value is NSDictionary } /// check if self is a valid leaf node. public var isLeaf: Bool { return !(isArray || isDictionary || isError) } /// gives NSError if it holds the error. nil otherwise public var asError:NSError? { return _value as? NSError } /// gives NSNull if self holds it. nil otherwise public var asNull:NSNull? { return _value is NSNull ? JSON.null : nil } /// gives Bool if self holds it. nil otherwise public var asBool:Bool? { switch _value { case let o as NSNumber: switch String.fromCString(o.objCType)! { case "c", "C": return Bool(o.boolValue) default: return nil } default: return nil } } /// gives Int if self holds it. nil otherwise public var asInt:Int? { switch _value { case let o as NSNumber: switch String.fromCString(o.objCType)! { case "c", "C": return nil default: return Int(o.longLongValue) } default: return nil } } /// gives Double if self holds it. nil otherwise public var asDouble:Double? { switch _value { case let o as NSNumber: switch String.fromCString(o.objCType)! { case "c", "C": return nil default: return Double(o.doubleValue) } default: return nil } } // an alias to asDouble public var asNumber:Double? { return asDouble } /// gives String if self holds it. nil otherwise public var asString:String? { switch _value { case let o as NSString: return o as String default: return nil } } /// if self holds NSArray, gives a [JSON] /// with elements therein. nil otherwise public var asArray:[JSON]? { switch _value { case let o as NSArray: var result = [JSON]() for v:AnyObject in o { result.append(JSON(v)) } return result default: return nil } } /// if self holds NSDictionary, gives a [String:JSON] /// with elements therein. nil otherwise public var asDictionary:[String:JSON]? { switch _value { case let o as NSDictionary: var result = [String:JSON]() for (k:AnyObject, v:AnyObject) in o { result[k as String] = JSON(v) } return result default: return nil } } /// Yields date from string public var asDate:NSDate? { if let dateString = _value as? NSString { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ" return dateFormatter.dateFromString(dateString) } return nil } /// gives the number of elements if an array or a dictionary. /// you can use this to check if you can iterate. public var length:Int { switch _value { case let o as NSArray: return o.count case let o as NSDictionary: return o.count default: return 0 } } } extension JSON : SequenceType { public func generate()->GeneratorOf<(AnyObject,JSON)> { switch _value { case let o as NSArray: var i = -1 return GeneratorOf<(AnyObject, JSON)> { if ++i == o.count { return nil } return (i, JSON(o[i])) } case let o as NSDictionary: var ks = o.allKeys.reverse() return GeneratorOf<(AnyObject, JSON)> { if ks.isEmpty { return nil } let k = ks.removeLast() as String return (k, JSON(o.valueForKey(k)!)) } default: return GeneratorOf<(AnyObject, JSON)>{ nil } } } public func mutableCopyOfTheObject() -> AnyObject { return _value.mutableCopy() } } extension JSON : Printable { /// stringifies self. /// if pretty:true it pretty prints public func toString(pretty:Bool=false)->String { switch _value { case is NSError: return "\(_value)" case is NSNull: return "null" case let o as NSNumber: switch String.fromCString(o.objCType)! { case "c", "C": return o.boolValue.description case "q", "l", "i", "s": return o.longLongValue.description case "Q", "L", "I", "S": return o.unsignedLongLongValue.description default: switch o.doubleValue { case 0.0/0.0: return "0.0/0.0" // NaN case -1.0/0.0: return "-1.0/0.0" // -infinity case +1.0/0.0: return "+1.0/0.0" // infinity default: return o.doubleValue.description } } case let o as NSString: return o.debugDescription default: let opts = pretty ? NSJSONWritingOptions.PrettyPrinted : nil if let data = NSJSONSerialization.dataWithJSONObject( _value, options:opts, error:nil ) as NSData? { if let nsstring = NSString( data:data, encoding:NSUTF8StringEncoding ) as NSString? { return nsstring } } return "YOU ARE NOT SUPPOSED TO SEE THIS!" } } public var description:String { return toString() } }
mit
660287a822fe9ebbae022692ef449d25
32.713873
78
0.55045
4.533618
false
false
false
false
argon/mas
MasKitTests/Errors/MASErrorTestCase.swift
1
3606
// // MASErrorTestCase.swift // mas-tests // // Created by Ben Chatelain on 2/11/18. // Copyright © 2018 Andrew Naylor. All rights reserved. // @testable import MasKit import Foundation import XCTest class MASErrorTestCase: XCTestCase { private let errorDomain = "MAS" var error: MASError! var nserror: NSError! /// Convenience property for setting the value which will be use for the localized description /// value of the next NSError created. Only used when the NSError does not have a user info /// entry for localized description. var localizedDescription: String { get { return "dummy value" } set { NSError.setUserInfoValueProvider(forDomain: errorDomain) { (_: Error, _: String) -> Any? in newValue } } } override func setUp() { super.setUp() nserror = NSError(domain: errorDomain, code: 999) localizedDescription = "foo" } override func tearDown() { nserror = nil error = nil super.tearDown() } func testNotSignedIn() { error = .notSignedIn XCTAssertEqual(error.description, "Not signed in") } func testSignInFailed() { error = .signInFailed(error: nil) XCTAssertEqual(error.description, "Sign in failed") } func testSignInFailedError() { error = .signInFailed(error: nserror) XCTAssertEqual(error.description, "Sign in failed: foo") } func testAlreadySignedIn() { error = .alreadySignedIn XCTAssertEqual(error.description, "Already signed in") } func testPurchaseFailed() { error = .purchaseFailed(error: nil) XCTAssertEqual(error.description, "Download request failed") } func testPurchaseFailedError() { error = .purchaseFailed(error: nserror) XCTAssertEqual(error.description, "Download request failed: foo") } func testDownloadFailed() { error = .downloadFailed(error: nil) XCTAssertEqual(error.description, "Download failed") } func testDownloadFailedError() { error = .downloadFailed(error: nserror) XCTAssertEqual(error.description, "Download failed: foo") } func testNoDownloads() { error = .noDownloads XCTAssertEqual(error.description, "No downloads began") } func testCancelled() { error = .cancelled XCTAssertEqual(error.description, "Download cancelled") } func testSearchFailed() { error = .searchFailed XCTAssertEqual(error.description, "Search failed") } func testNoSearchResultsFound() { error = .noSearchResultsFound XCTAssertEqual(error.description, "No results found") } func testNoVendorWebsite() { error = .noVendorWebsite XCTAssertEqual(error.description, "App does not have a vendor website") } func testNotInstalled() { error = .notInstalled XCTAssertEqual(error.description, "Not installed") } func testUninstallFailed() { error = .uninstallFailed XCTAssertEqual(error.description, "Uninstall failed") } func testUrlEncoding() { error = .urlEncoding XCTAssertEqual(error.description, "Unable to encode service URL") } func testNoData() { error = .noData XCTAssertEqual(error.description, "Service did not return data") } func testJsonParsing() { error = .jsonParsing(error: nil) XCTAssertEqual(error.description, "Unable to parse response JSON") } }
mit
dbfbd92dd9b9b6d8905dfea4fa59810d
26.519084
103
0.638835
4.749671
false
true
false
false
frootloops/swift
test/IRGen/closure.swift
1
3237
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 // -- partial_apply context metadata // CHECK: [[METADATA:@.*]] = private constant %swift.full_boxmetadata { void (%swift.refcounted*)* @objectdestroy, i8** null, %swift.type { i64 64 }, i32 16, i8* bitcast ({ i32, i32, i32, i32 }* @"\01l__swift3_reflection_descriptor" to i8*) } func a(i i: Int) -> (Int) -> Int { return { x in i } } // -- Closure entry point // CHECK: define internal swiftcc i64 @_T07closure1aS2icSi1i_tFS2icfU_(i64, i64) protocol Ordinable { func ord() -> Int } func b<T : Ordinable>(seq seq: T) -> (Int) -> Int { return { i in i + seq.ord() } } // -- partial_apply stub // CHECK: define internal swiftcc i64 @_T07closure1aS2icSi1i_tFS2icfU_TA(i64, %swift.refcounted* swiftself) // CHECK: } // -- Closure entry point // CHECK: define internal swiftcc i64 @_T07closure1bS2icx3seq_tAA9OrdinableRzlFS2icfU_(i64, %swift.refcounted*, %swift.type* %T, i8** %T.Ordinable) {{.*}} { // -- partial_apply stub // CHECK: define internal swiftcc i64 @_T07closure1bS2icx3seq_tAA9OrdinableRzlFS2icfU_TA(i64, %swift.refcounted* swiftself) {{.*}} { // CHECK: entry: // CHECK: [[CONTEXT:%.*]] = bitcast %swift.refcounted* %1 to <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* // CHECK: [[BINDINGSADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 1 // CHECK: [[TYPEADDR:%.*]] = bitcast [16 x i8]* [[BINDINGSADDR]] // CHECK: [[TYPE:%.*]] = load %swift.type*, %swift.type** [[TYPEADDR]], align 8 // CHECK: [[WITNESSADDR_0:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[TYPEADDR]], i32 1 // CHECK: [[WITNESSADDR:%.*]] = bitcast %swift.type** [[WITNESSADDR_0]] // CHECK: [[WITNESS:%.*]] = load i8**, i8*** [[WITNESSADDR]], align 8 // CHECK: [[BOXADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 2 // CHECK: [[BOX:%.*]] = load %swift.refcounted*, %swift.refcounted** [[BOXADDR]], align 8 // CHECK: [[RES:%.*]] = tail call swiftcc i64 @_T07closure1bS2icx3seq_tAA9OrdinableRzlFS2icfU_(i64 %0, %swift.refcounted* [[BOX]], %swift.type* [[TYPE]], i8** [[WITNESS]]) // CHECK: ret i64 [[RES]] // CHECK: } // -- <rdar://problem/14443343> Boxing of tuples with generic elements // CHECK: define hidden swiftcc { i8*, %swift.refcounted* } @_T07closure14captures_tuplex_q_tycx_q_t1x_tr0_lF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U) func captures_tuple<T, U>(x x: (T, U)) -> () -> (T, U) { // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_getTupleTypeMetadata2(%swift.type* %T, %swift.type* %U, i8* null, i8** null) // CHECK-NOT: @swift_getTupleTypeMetadata2 // CHECK: [[BOX:%.*]] = call swiftcc { %swift.refcounted*, %swift.opaque* } @swift_allocBox(%swift.type* [[METADATA]]) // CHECK: [[ADDR:%.*]] = extractvalue { %swift.refcounted*, %swift.opaque* } [[BOX]], 1 // CHECK: bitcast %swift.opaque* [[ADDR]] to <{}>* return {x} }
apache-2.0
f5f2933a25c162ba7f13490b15ca905b
56.803571
242
0.640717
3.121504
false
false
false
false
dfsilva/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Auth/AAAuthViewController.swift
1
3735
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation open class AAAuthViewController: AAViewController { open let nextBarButton = UIButton() fileprivate var keyboardHeight: CGFloat = 0 override open func viewDidLoad() { super.viewDidLoad() nextBarButton.setTitle(AALocalized("NavigationNext"), for: UIControlState()) nextBarButton.setTitleColor(UIColor.white, for: UIControlState()) nextBarButton.setBackgroundImage(Imaging.roundedImage(ActorSDK.sharedActor().style.nextBarColor, radius: 4), for: UIControlState()) nextBarButton.setBackgroundImage(Imaging.roundedImage(ActorSDK.sharedActor().style.nextBarColor.alpha(0.7), radius: 4), for: .highlighted) nextBarButton.addTarget(self, action: #selector(AAAuthViewController.nextDidTap), for: .touchUpInside) view.addSubview(nextBarButton) } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() layoutNextBar() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Forcing initial layout before keyboard show to avoid weird animations layoutNextBar() NotificationCenter.default.addObserver(self, selector: #selector(AAAuthViewController.keyboardWillAppearInt(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(AAAuthViewController.keyboardWillDisappearInt(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } fileprivate func layoutNextBar() { nextBarButton.frame = CGRect(x: view.width - 95, y: view.height - 44 - keyboardHeight + 6, width: 85, height: 32) } func keyboardWillAppearInt(_ notification: Notification) { let dict = (notification as NSNotification).userInfo! let rect = (dict[UIKeyboardFrameBeginUserInfoKey]! as AnyObject).cgRectValue let orientation = UIApplication.shared.statusBarOrientation let frameInWindow = self.view.superview!.convert(view.bounds, to: nil) let windowBounds = view.window!.bounds let keyboardTop: CGFloat = windowBounds.size.height - rect!.height let heightCoveredByKeyboard: CGFloat if AADevice.isiPad { if orientation == .landscapeLeft || orientation == .landscapeRight { heightCoveredByKeyboard = frameInWindow.maxY - keyboardTop - 52 /*???*/ } else if orientation == .portrait || orientation == .portraitUpsideDown { heightCoveredByKeyboard = frameInWindow.maxY - keyboardTop } else { heightCoveredByKeyboard = 0 } } else { heightCoveredByKeyboard = (rect?.height)! } keyboardHeight = max(0, heightCoveredByKeyboard) layoutNextBar() keyboardWillAppear(keyboardHeight) } func keyboardWillDisappearInt(_ notification: Notification) { keyboardHeight = 0 layoutNextBar() keyboardWillDisappear() } open func keyboardWillAppear(_ height: CGFloat) { } open func keyboardWillDisappear() { } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) keyboardHeight = 0 layoutNextBar() } /// Call this method when authentication successful open func onAuthenticated() { ActorSDK.sharedActor().didLoggedIn() } open func nextDidTap() { } }
agpl-3.0
dac14d3b815fccbda9bef1562f654651
35.980198
183
0.660241
5.817757
false
false
false
false
chris-wood/reveiller
reveiller/Pods/SwiftCharts/SwiftCharts/AxisValues/ChartAxisValueDate.swift
10
1205
// // ChartAxisValueDate.swift // swift_charts // // Created by ischuetz on 01/03/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public class ChartAxisValueDate: ChartAxisValue { private let formatter: NSDateFormatter private let labelSettings: ChartLabelSettings public var date: NSDate { return ChartAxisValueDate.dateFromScalar(self.scalar) } public init(date: NSDate, formatter: NSDateFormatter, labelSettings: ChartLabelSettings = ChartLabelSettings()) { self.formatter = formatter self.labelSettings = labelSettings super.init(scalar: ChartAxisValueDate.scalarFromDate(date)) } override public var labels: [ChartAxisLabel] { let axisLabel = ChartAxisLabel(text: self.formatter.stringFromDate(self.date), settings: self.labelSettings) axisLabel.hidden = self.hidden return [axisLabel] } public class func dateFromScalar(scalar: Double) -> NSDate { return NSDate(timeIntervalSince1970: NSTimeInterval(scalar)) } public class func scalarFromDate(date: NSDate) -> Double { return Double(date.timeIntervalSince1970) } }
mit
67b03144616758874d43a5a6886fa075
29.125
117
0.698755
4.958848
false
false
false
false
weareyipyip/SwiftStylable
Sources/SwiftStylable/Classes/Style/StylableComponents/STTableViewCell.swift
1
5865
// // STTableViewCell.swift // SwiftStylable // // Created by Marcel Bloemendaal on 10/08/16. // Copyright © 2016 YipYip. All rights reserved. // import UIKit @IBDesignable open class STTableViewCell : UITableViewCell, Stylable, BackgroundAndBorderStylable { private var _stComponentHelper: STComponentHelper! private var _selected = false private var _highlighted = false private var _normalBackgroundColor:UIColor? private var _borderColor:UIColor? private var _highlightedBackgroundColor:UIColor? private var _highlightedBorderColor:UIColor? private var _selectedBackgroundColor:UIColor? private var _selectedBorderColor:UIColor? // ----------------------------------------------------------------------------------------------------------------------- // // MARK: - Initializers & deinit // // ----------------------------------------------------------------------------------------------------------------------- required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setUpSTComponentHelper() } // ----------------------------------------------------------------------------------------------------------------------- // // MARK: - Computed properties // // ----------------------------------------------------------------------------------------------------------------------- @IBInspectable open var styleName:String? { set { self._stComponentHelper.styleName = newValue } get { return self._stComponentHelper.styleName } } @IBInspectable open var substyleName:String? { set { self._stComponentHelper.substyleName = newValue } get { return self._stComponentHelper.substyleName } } var normalBackgroundColor: UIColor? { get { return self._normalBackgroundColor } set { self._normalBackgroundColor = newValue } } var highlightedBackgroundColor: UIColor? { get { return self._highlightedBackgroundColor } set { self._highlightedBackgroundColor = newValue } } var selectedBackgroundColor: UIColor? { get { return self._selectedBackgroundColor } set { self._selectedBackgroundColor = newValue } } var borderColor: UIColor? { get { var color:UIColor? if let cgColor = self.layer.borderColor { color = UIColor(cgColor: cgColor) } return color } set { self.layer.borderColor = newValue?.cgColor } } var highlightedBorderColor: UIColor? { get { return self._highlightedBorderColor } set { self._highlightedBorderColor = newValue } } var selectedBorderColor: UIColor? { get { return self._selectedBorderColor } set { self._selectedBorderColor = newValue } } // ----------------------------------------------------------------------------------------------------------------------- // // MARK: - Public methods // // ----------------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------- // -- TableViewCell overrides // ----------------------------------------------------------- override open func setSelected(_ selected: Bool, animated: Bool) { self._selected = selected if self.styleName != nil { self.updateColors() } else { super.setSelected(selected, animated: animated) } } override open func setHighlighted(_ highlighted: Bool, animated: Bool) { self._highlighted = highlighted if self.styleName != nil { self.updateColors() } else { super.setHighlighted(highlighted, animated: animated) } } // ----------------------------------------------------------- // -- Stylable implementation // ----------------------------------------------------------- open func applyStyle(_ style:Style) { self._stComponentHelper.applyStyle(style) self.updateColors() } // ----------------------------------------------------------------------------------------------------------------------- // // MARK: - Private methods // // ----------------------------------------------------------------------------------------------------------------------- private func setUpSTComponentHelper() { self._stComponentHelper = STComponentHelper(stylable: self, stylePropertySets: [ BackgroundAndBorderStyler(self, canBeHighlighted: true, canBeSelected: true) ]) } private func updateColors() { if self._highlighted { self.backgroundColor = self._highlightedBackgroundColor ?? self._normalBackgroundColor self.layer.borderColor = (self._highlightedBorderColor?.cgColor ?? self._borderColor?.cgColor) ?? UIColor.clear.cgColor } else if self._selected { self.backgroundColor = self._selectedBackgroundColor ?? self._normalBackgroundColor self.layer.borderColor = (self._selectedBorderColor?.cgColor ?? self._borderColor?.cgColor) ?? UIColor.clear.cgColor } else { self.backgroundColor = self._normalBackgroundColor self.layer.borderColor = (self._borderColor ?? UIColor.clear).cgColor } } }
mit
6fa3f7713fd72060cd03f18e9d124959
31.043716
131
0.458049
6.625989
false
false
false
false
Adlai-Holler/Bond
Bond/iOS/Bond+UITableView.swift
2
12310
// // Bond+UITableView.swift // Bond // // 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. // import UIKit extension NSIndexSet { convenience init(array: [Int]) { let set = NSMutableIndexSet() for index in array { set.addIndex(index) } self.init(indexSet: set) } } @objc class TableViewDynamicArrayDataSource: NSObject, UITableViewDataSource { weak var dynamic: DynamicArray<DynamicArray<UITableViewCell>>? @objc weak var nextDataSource: UITableViewDataSource? init(dynamic: DynamicArray<DynamicArray<UITableViewCell>>) { self.dynamic = dynamic super.init() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.dynamic?.count ?? 0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dynamic?[section].count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return self.dynamic?[indexPath.section][indexPath.item] ?? UITableViewCell() } // Forwards func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let ds = self.nextDataSource { return ds.tableView?(tableView, titleForHeaderInSection: section) } else { return nil } } func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { if let ds = self.nextDataSource { return ds.tableView?(tableView, titleForFooterInSection: section) } else { return nil } } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { if let ds = self.nextDataSource { return ds.tableView?(tableView, canEditRowAtIndexPath: indexPath) ?? false } else { return false } } func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { if let ds = self.nextDataSource { return ds.tableView?(tableView, canMoveRowAtIndexPath: indexPath) ?? false } else { return false } } func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! { if let ds = self.nextDataSource { return ds.sectionIndexTitlesForTableView?(tableView) ?? [] } else { return [] } } func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { if let ds = self.nextDataSource { return ds.tableView?(tableView, sectionForSectionIndexTitle: title, atIndex: index) ?? index } else { return index } } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if let ds = self.nextDataSource { ds.tableView?(tableView, commitEditingStyle: editingStyle, forRowAtIndexPath: indexPath) } } func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { if let ds = self.nextDataSource { ds.tableView?(tableView, moveRowAtIndexPath: sourceIndexPath, toIndexPath: destinationIndexPath) } } } private class UITableViewDataSourceSectionBond<T>: ArrayBond<UITableViewCell> { weak var tableView: UITableView? var shouldReloadRows: ((UITableView, [NSIndexPath]) -> [NSIndexPath])? var section: Int init(tableView: UITableView?, section: Int, disableAnimation: Bool = false, shouldReloadRows: ((UITableView, [NSIndexPath]) -> [NSIndexPath])?) { self.tableView = tableView self.section = section self.shouldReloadRows = shouldReloadRows super.init() self.didInsertListener = { [unowned self] a, i in if let tableView: UITableView = self.tableView { perform(animated: !disableAnimation) { tableView.beginUpdates() tableView.insertRowsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) }, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() } } } self.didRemoveListener = { [unowned self] a, i in if let tableView = self.tableView { perform(animated: !disableAnimation) { tableView.beginUpdates() tableView.deleteRowsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) }, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() } } } self.didUpdateListener = { [unowned self] a, i in if let tableView = self.tableView { perform(animated: !disableAnimation) { var indexPaths = i.map { NSIndexPath(forItem: $0, inSection: self.section)! } if let shouldReloadRows = self.shouldReloadRows { indexPaths = shouldReloadRows(tableView, indexPaths) } if !indexPaths.isEmpty { tableView.beginUpdates() tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() } } } } self.didResetListener = { [weak self] array in if let tableView = self?.tableView { tableView.reloadData() } } } deinit { self.unbindAll() } } public class UITableViewDataSourceBond<T>: ArrayBond<DynamicArray<UITableViewCell>> { weak var tableView: UITableView? private var dataSource: TableViewDynamicArrayDataSource? private var sectionBonds: [UITableViewDataSourceSectionBond<Void>] = [] public let disableAnimation: Bool /** return only the rows that should be reloaded in the table view. Defaults to reloading all rows */ public var shouldReloadRows: ((UITableView, [NSIndexPath]) -> [NSIndexPath])? { didSet { for section in sectionBonds { section.shouldReloadRows = shouldReloadRows } } } public weak var nextDataSource: UITableViewDataSource? { didSet(newValue) { dataSource?.nextDataSource = newValue } } public init(tableView: UITableView, disableAnimation: Bool = false, shouldReloadRows: ((UITableView, [NSIndexPath]) -> [NSIndexPath])? = nil) { self.disableAnimation = disableAnimation self.tableView = tableView self.shouldReloadRows = shouldReloadRows super.init() self.didInsertListener = { [weak self] array, i in if let s = self { if let tableView: UITableView = self?.tableView { perform(animated: !disableAnimation) { tableView.beginUpdates() tableView.insertSections(NSIndexSet(array: i), withRowAnimation: UITableViewRowAnimation.Automatic) for section in sorted(i, <) { let sectionBond = UITableViewDataSourceSectionBond<Void>(tableView: tableView, section: section, disableAnimation: disableAnimation, shouldReloadRows: self?.shouldReloadRows) let sectionDynamic = array[section] sectionDynamic.bindTo(sectionBond) s.sectionBonds.insert(sectionBond, atIndex: section) for var idx = section + 1; idx < s.sectionBonds.count; idx++ { s.sectionBonds[idx].section += 1 } } tableView.endUpdates() } } } } self.didRemoveListener = { [weak self] array, i in if let s = self { if let tableView = s.tableView { perform(animated: !disableAnimation) { tableView.beginUpdates() tableView.deleteSections(NSIndexSet(array: i), withRowAnimation: UITableViewRowAnimation.Automatic) for section in sorted(i, >) { s.sectionBonds[section].unbindAll() s.sectionBonds.removeAtIndex(section) for var idx = section; idx < s.sectionBonds.count; idx++ { s.sectionBonds[idx].section -= 1 } } tableView.endUpdates() } } } } self.didUpdateListener = { [weak self] array, i in if let s = self { if let tableView = s.tableView { perform(animated: !disableAnimation) { tableView.beginUpdates() tableView.reloadSections(NSIndexSet(array: i), withRowAnimation: UITableViewRowAnimation.Automatic) for section in i { let sectionBond = UITableViewDataSourceSectionBond<Void>(tableView: tableView, section: section, disableAnimation: disableAnimation, shouldReloadRows: self?.shouldReloadRows) let sectionDynamic = array[section] sectionDynamic.bindTo(sectionBond) self?.sectionBonds[section].unbindAll() self?.sectionBonds[section] = sectionBond } tableView.endUpdates() } } } } self.didResetListener = { [weak self] array in if let tableView = self?.tableView { tableView.reloadData() } } } public func bind(dynamic: DynamicArray<UITableViewCell>) { bind(DynamicArray([dynamic])) } public override func bind(dynamic: Dynamic<Array<DynamicArray<UITableViewCell>>>, fire: Bool, strongly: Bool) { super.bind(dynamic, fire: false, strongly: strongly) if let dynamic = dynamic as? DynamicArray<DynamicArray<UITableViewCell>> { for section in 0..<dynamic.count { let sectionBond = UITableViewDataSourceSectionBond<Void>(tableView: self.tableView, section: section, disableAnimation: disableAnimation, shouldReloadRows: shouldReloadRows) let sectionDynamic = dynamic[section] sectionDynamic.bindTo(sectionBond) sectionBonds.append(sectionBond) } dataSource = TableViewDynamicArrayDataSource(dynamic: dynamic) dataSource?.nextDataSource = self.nextDataSource tableView?.dataSource = dataSource tableView?.reloadData() } } deinit { self.unbindAll() tableView?.dataSource = nil self.dataSource = nil } } private var bondDynamicHandleUITableView: UInt8 = 0 extension UITableView /*: Bondable */ { public var designatedBond: UITableViewDataSourceBond<UITableViewCell> { if let d: AnyObject = objc_getAssociatedObject(self, &bondDynamicHandleUITableView) { return (d as? UITableViewDataSourceBond<UITableViewCell>)! } else { let bond = UITableViewDataSourceBond<UITableViewCell>(tableView: self, disableAnimation: false) objc_setAssociatedObject(self, &bondDynamicHandleUITableView, bond, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) return bond } } } private func perform(#animated: Bool, block: () -> Void) { if !animated { UIView.performWithoutAnimation(block) } else { block() } } public func ->> <T>(left: DynamicArray<UITableViewCell>, right: UITableViewDataSourceBond<T>) { right.bind(left) } public func ->> (left: DynamicArray<UITableViewCell>, right: UITableView) { left ->> right.designatedBond } public func ->> (left: DynamicArray<DynamicArray<UITableViewCell>>, right: UITableView) { left ->> right.designatedBond }
mit
0d8486dc8126420c15f77f47653893c8
34.475504
188
0.674005
4.884921
false
false
false
false
Echx/GridOptic
GridOptic/GridOptic/GridOptic/OpticRepresentation/GOOpticRep.swift
1
4544
// // GOOpticRep.swift // GridOptic // // Created by Jiang Sheng on 1/4/15. // Copyright (c) 2015 Echx. All rights reserved. // import UIKit class GOOpticRep: NSObject, NSCoding { var id: String var center: GOCoordinate var edges = [GOSegment]() var type = DeviceType.Mirror var direction: CGVector = OpticRepDefaults.defaultDirection var refractionIndex : CGFloat = GOConstant.vacuumRefractionIndex var bezierPath: UIBezierPath { // the bezier path representation of the optic instrument for drawing get { var path = UIBezierPath() for edge in self.edges { path.appendPath(edge.bezierPath) } return path } } var numOfEdges : Int { get { return edges.count } } var vertices: [CGPoint] { get { fatalError("The computational variable vertices must be overriden by subclasses") } } init(id: String, center: GOCoordinate) { self.id = id self.center = center super.init() } init(refractionIndex: CGFloat, id: String, center: GOCoordinate) { self.id = id self.refractionIndex = refractionIndex self.center = center super.init() self.updateEdgesParent() } required convenience init(coder aDecoder: NSCoder) { let id = aDecoder.decodeObjectForKey(GOCodingKey.optic_id) as String let edges = aDecoder.decodeObjectForKey(GOCodingKey.optic_edges) as [GOSegment] let typeRaw = aDecoder.decodeObjectForKey(GOCodingKey.optic_type) as Int let type = DeviceType(rawValue: typeRaw) let center = aDecoder.decodeObjectForKey(GOCodingKey.optic_center) as GOCoordinate let refIndex = aDecoder.decodeObjectForKey(GOCodingKey.optic_refractionIndex) as CGFloat self.init(refractionIndex: refIndex, id: id, center: center) self.type = type! self.edges = edges } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(id, forKey: GOCodingKey.optic_id) aCoder.encodeObject(edges, forKey: GOCodingKey.optic_edges) aCoder.encodeObject(type.rawValue, forKey: GOCodingKey.optic_type) aCoder.encodeObject(center, forKey: GOCodingKey.optic_center) aCoder.encodeObject(refractionIndex, forKey: GOCodingKey.optic_refractionIndex) } func refresh() { let direction = self.direction self.direction = OpticRepDefaults.defaultDirection self.setUpEdges() self.setDirection(direction) self.updateEdgesParent() self.updateEdgesType() } func containsPoint(point: CGPoint) -> Bool { // check whether the point is contained with in the optic representation var framePath = UIBezierPath() let vertices = self.vertices framePath.moveToPoint(vertices[0]) for var i = 1; i < vertices.count; i++ { var vertex = vertices[i] framePath.addLineToPoint(vertex) } framePath.closePath() return framePath.containsPoint(point) } func setUpEdges() { fatalError("setUpEdges must be overridden by child classes") } func setDirection(direction: CGVector) { fatalError("setDirection must be overridden by child classes") } func setCenter(center: GOCoordinate) { self.center = center self.refresh() } func setDeviceType(type: DeviceType) { self.type = type self.updateEdgesType() } func updateEdgesParent() { for edge in self.edges { edge.parent = self.id } } func updateEdgesType() { // udpate the type of edge according to the property of the device for edge in self.edges { switch self.type { case DeviceType.Mirror: edge.willReflect = true edge.willRefract = false case DeviceType.Lens: edge.willReflect = false edge.willRefract = true case DeviceType.Wall: edge.willReflect = false edge.willRefract = false case DeviceType.Emitter: edge.willReflect = false edge.willRefract = false default: fatalError("Device Type Not Defined") } } } }
mit
3854fb531ed4933121cadf495a31d407
29.496644
96
0.599912
4.636735
false
false
false
false
gradyzhuo/Acclaim
Sources/Procedure/SimpleStep.swift
1
6627
// // Step.swift // Procedure // // Created by Grady Zhuo on 22/11/2016. // Copyright © 2016 Grady Zhuo. All rights reserved. // import Foundation public typealias OutputIntents = Intents open class SimpleStep : Step, Propagatable, Flowable, CustomStringConvertible, Identitiable { public var previous: Step? public typealias IntentType = SimpleIntent public var identifier: String{ return queue.label } public lazy var name: String = self.identifier public internal(set) var tasks: [Task] = [] public var next: Step?{ didSet{ let current = self next.map{ nextStep in var nextStep = nextStep nextStep.previous = current } } } internal let autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency internal let attributes: DispatchQueue.Attributes internal let qos: DispatchQoS public var queue: DispatchQueue internal var flowHandler:(OutputIntents)->FlowControl = { _ in return .next } public convenience init(direction: Task.PropagationDirection = .forward, do action: @escaping Task.Action){ let newTask = Task(propagationDirection: direction, do: action) self.init(task: newTask) } internal init(tasks:[Task], attributes: DispatchQueue.Attributes = .concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency = .inherit, qos: DispatchQoS = .default, other: SimpleStep? = nil){ self.autoreleaseFrequency = autoreleaseFrequency self.attributes = attributes self.qos = qos self.queue = DispatchQueue(label: Utils.Generator.identifier(), qos: qos, attributes: attributes, autoreleaseFrequency: autoreleaseFrequency, target: other?.queue) self.invoke(tasks: tasks) } public convenience init(task: Task) { self.init(tasks: [task]) } public required convenience init(tasks: [Task] = []) { self.init(tasks: tasks, attributes: .concurrent, autoreleaseFrequency: .inherit, qos: .userInteractive, other: nil) } public func invoke(tasks: [Task]) { for task in tasks { invoke(task: task) } } public func setControl(_ flowControl: @escaping (OutputIntents)->FlowControl){ flowHandler = flowControl } public func run(with inputs: Intent...){ self.run(with: Intents(array: inputs)) } public func run(with inputs: Intents = []){ self.run(with: inputs, direction: .forward) } public func run(with inputs: Intents, direction: Task.PropagationDirection){ let workItem = self._run(with: inputs, direction: direction) self.queue.sync(execute: workItem) } public func cancel(){ for act in tasks { act.cancel() } } internal func _run(with inputs: Intents, direction: Task.PropagationDirection)->DispatchWorkItem{ let queue = self.queue let didFinish = self.actionsDidFinish let group = DispatchGroup() let workItem = DispatchWorkItem{ var outputs: Intents = [] self.tasks.filter{ $0.propagationDirection == direction }.forEach{ task in group.enter() task.run(with: inputs, inQueue: queue){ action, intents in outputs.add(intents: intents) group.leave() } } group.notify(queue: self.queue){ print("here notify") didFinish(inputs, outputs) } } return workItem } internal func actionsDidFinish(original inputs: Intents, outputs: Intents){ let outputs = inputs + outputs let control = flowHandler(outputs) switch control { case .repeat: run(with: outputs) case .cancel: print("cancelled") case .finish: print("finished") case .nextWith(let filter): goNext(with: filter(outputs)) case .previousWith(let filter): goBack(with: filter(outputs)) case .jumpTo(let other, let filter): jump(to: other, with: filter(outputs)) } } public func goNext(with intents: Intents){ if let next = next as? Propagatable { next.run(with: intents, direction: .forward) }else{ next?.run(with: intents) } } public func goBack(with intents: Intents){ if let previous = previous as? Propagatable { previous.run(with: intents, direction: .backward) }else{ previous?.run(with: intents) } } public func jump(to step: Step, with intents: Intents){ if let step = step as? Propagatable { step.run(with: intents, direction: .forward) }else{ step.run(with: intents) } } public var description: String{ let actionDescriptions = tasks.reduce("") { (result, action) -> String in return result.count == 0 ? "<\(action)>" : "\(result)\n<\(action)>" } return "\(type(of: self))(\(identifier)): [\(actionDescriptions)]" } deinit { print("deinit Step : \(identifier)") } } extension SimpleStep : Hashable { public func hash(into hasher: inout Hasher) { identifier.hash(into: &hasher) } } public func ==<T:Hashable>(lhs: T, rhs: T)->Bool{ return lhs.hashValue == rhs.hashValue } extension SimpleStep : Copyable{ public func copy(with zone: NSZone? = nil) -> Any { let tasksCopy = self.tasks.map{ $0.copy } let aCopy = SimpleStep(tasks: tasksCopy, attributes: attributes, autoreleaseFrequency: autoreleaseFrequency, qos: qos) aCopy.flowHandler = flowHandler return aCopy } } extension SimpleStep { public func invoke(task: Task){ tasks.append(task) } public func invoke(direction: Task.PropagationDirection = .forward, do action: @escaping Task.Action)->Task{ let newTask = Task(propagationDirection: direction, do: action) self.invoke(task: newTask) return newTask } public func remove(tasks: [Task]){ for task in tasks { self.remove(task: task) } } public func remove(task: Task){ tasks = tasks.filter { return $0 != task } } }
mit
dfefc087ba2489242a1bce1bc9b79dff
28.448889
208
0.587232
4.699291
false
false
false
false
kstaring/swift
stdlib/public/SDK/CryptoTokenKit/TKSmartCard.swift
4
1780
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import CryptoTokenKit import Foundation @available(OSX 10.10, *) extension TKSmartCard { public func send(ins: UInt8, p1: UInt8, p2: UInt8, data: Data? = nil, le: Int? = nil, reply: @escaping (Data?, UInt16, Error?) -> Void) { self.__sendIns(ins, p1: p1, p2: p2, data: data, le: le.map { NSNumber(value: $0) }, reply: reply) } @available(OSX 10.12, *) public func send(ins: UInt8, p1: UInt8, p2: UInt8, data: Data? = nil, le: Int? = nil) throws -> (sw: UInt16, response: Data) { var sw: UInt16 = 0 let response = try self.__sendIns(ins, p1: p1, p2: p2, data: data, le: le.map { NSNumber(value: $0) }, sw: &sw) return (sw: sw, response: response) } @available(OSX 10.12, *) public func withSession<T>(_ body: @escaping () throws -> T) throws -> T { var result: T? try self.__inSession(executeBlock: { (errorPointer: NSErrorPointer) -> Bool in do { result = try body() return true } catch let error as NSError { errorPointer?.pointee = error return false } }) // it is safe to force unwrap the result here, as the self.__inSession // function rethrows the errors which happened inside the block return result! } }
apache-2.0
b19c913e6eeb73067ded84b5143b7500
31.962963
80
0.577528
3.747368
false
false
false
false
gnachman/iTerm2
sources/ModalPasswordAlert.swift
2
2984
// // ModalPasswordAlert.swift // iTerm2SharedARC // // Created by George Nachman on 3/19/22. // import AppKit class ModalPasswordAlert { private let prompt: String var username: String? init(_ prompt: String) { self.prompt = prompt } func run(window: NSWindow?) -> String? { let alert = NSAlert() alert.messageText = prompt alert.addButton(withTitle: "OK") alert.addButton(withTitle: "Cancel") let newPassword = NSSecureTextField(frame: NSRect(x: 0, y: 0, width: 200, height: 22)) newPassword.isEditable = true newPassword.isSelectable = true newPassword.placeholderString = "Password" let wrapper = NSStackView() wrapper.orientation = .vertical wrapper.distribution = .fillEqually wrapper.alignment = .leading wrapper.spacing = 5 wrapper.translatesAutoresizingMaskIntoConstraints = false wrapper.addConstraint(NSLayoutConstraint(item: wrapper, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 200)) let usernameField: NSTextField? if let username = username { let field = NSTextField(frame: newPassword.frame) usernameField = field field.isEditable = true field.isSelectable = true field.stringValue = username field.placeholderString = "User name" wrapper.addArrangedSubview(field) field.nextKeyView = newPassword newPassword.nextKeyView = field } else { usernameField = nil } wrapper.addArrangedSubview(newPassword) alert.accessoryView = wrapper let timer = Timer(timeInterval: 0, repeats: false) { [weak self] _ in guard let self = self else { return } alert.layout() if let username = self.username, !username.isEmpty { newPassword.window?.makeFirstResponder(newPassword) } else if let usernameField = usernameField { usernameField.window?.makeFirstResponder(usernameField) } } RunLoop.main.add(timer, forMode: .common) let result = { () -> NSApplication.ModalResponse in if let window = window, window.isVisible { return alert.runSheetModal(for: window) } else { return alert.runModal() } }() if result == .alertFirstButtonReturn { username = usernameField?.stringValue return newPassword.stringValue } return nil } }
gpl-2.0
e7d187188cd91be8962d68524c877d4a
32.909091
94
0.54189
5.727447
false
false
false
false
Johennes/firefox-ios
Storage/SQL/BrowserTable.swift
1
40247
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger let BookmarksFolderTitleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.") let BookmarksFolderTitleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.") let BookmarksFolderTitleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.") let BookmarksFolderTitleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.") let _TableBookmarks = "bookmarks" // Removed in v12. Kept for migration. let TableBookmarksMirror = "bookmarksMirror" // Added in v9. let TableBookmarksMirrorStructure = "bookmarksMirrorStructure" // Added in v10. let TableBookmarksBuffer = "bookmarksBuffer" // Added in v12. bookmarksMirror is renamed to bookmarksBuffer. let TableBookmarksBufferStructure = "bookmarksBufferStructure" // Added in v12. let TableBookmarksLocal = "bookmarksLocal" // Added in v12. Supersedes 'bookmarks'. let TableBookmarksLocalStructure = "bookmarksLocalStructure" // Added in v12. let TableFavicons = "favicons" let TableHistory = "history" let TableCachedTopSites = "cached_top_sites" let TableDomains = "domains" let TableVisits = "visits" let TableFaviconSites = "favicon_sites" let TableQueuedTabs = "queue" let TableActivityStreamBlocklist = "activity_stream_blocklist" let TablePageMetadata = "page_metadata" let ViewBookmarksBufferOnMirror = "view_bookmarksBuffer_on_mirror" let ViewBookmarksBufferStructureOnMirror = "view_bookmarksBufferStructure_on_mirror" let ViewBookmarksLocalOnMirror = "view_bookmarksLocal_on_mirror" let ViewBookmarksLocalStructureOnMirror = "view_bookmarksLocalStructure_on_mirror" let ViewAllBookmarks = "view_all_bookmarks" let ViewAwesomebarBookmarks = "view_awesomebar_bookmarks" let ViewAwesomebarBookmarksWithIcons = "view_awesomebar_bookmarks_with_favicons" let ViewHistoryVisits = "view_history_visits" let ViewWidestFaviconsForSites = "view_favicons_widest" let ViewHistoryIDsWithWidestFavicons = "view_history_id_favicon" let ViewIconForURL = "view_icon_for_url" let IndexHistoryShouldUpload = "idx_history_should_upload" let IndexVisitsSiteIDDate = "idx_visits_siteID_date" // Removed in v6. let IndexVisitsSiteIDIsLocalDate = "idx_visits_siteID_is_local_date" // Added in v6. let IndexBookmarksMirrorStructureParentIdx = "idx_bookmarksMirrorStructure_parent_idx" // Added in v10. let IndexBookmarksLocalStructureParentIdx = "idx_bookmarksLocalStructure_parent_idx" // Added in v12. let IndexBookmarksBufferStructureParentIdx = "idx_bookmarksBufferStructure_parent_idx" // Added in v12. let IndexBookmarksMirrorStructureChild = "idx_bookmarksMirrorStructure_child" // Added in v14. let IndexPageMetadataCacheKey = "idx_page_metadata_cache_key_uniqueindex" // Added in v19 private let AllTables: [String] = [ TableDomains, TableFavicons, TableFaviconSites, TableHistory, TableVisits, TableCachedTopSites, TableBookmarksBuffer, TableBookmarksBufferStructure, TableBookmarksLocal, TableBookmarksLocalStructure, TableBookmarksMirror, TableBookmarksMirrorStructure, TableQueuedTabs, TableActivityStreamBlocklist, TablePageMetadata, ] private let AllViews: [String] = [ ViewHistoryIDsWithWidestFavicons, ViewWidestFaviconsForSites, ViewIconForURL, ViewBookmarksBufferOnMirror, ViewBookmarksBufferStructureOnMirror, ViewBookmarksLocalOnMirror, ViewBookmarksLocalStructureOnMirror, ViewAllBookmarks, ViewAwesomebarBookmarks, ViewAwesomebarBookmarksWithIcons, ViewHistoryVisits ] private let AllIndices: [String] = [ IndexHistoryShouldUpload, IndexVisitsSiteIDIsLocalDate, IndexBookmarksBufferStructureParentIdx, IndexBookmarksLocalStructureParentIdx, IndexBookmarksMirrorStructureParentIdx, IndexBookmarksMirrorStructureChild, IndexPageMetadataCacheKey ] private let AllTablesIndicesAndViews: [String] = AllViews + AllIndices + AllTables private let log = Logger.syncLogger /** * The monolithic class that manages the inter-related history etc. tables. * We rely on SQLiteHistory having initialized the favicon table first. */ public class BrowserTable: Table { static let DefaultVersion = 19 // Bug 1303734. // TableInfo fields. var name: String { return "BROWSER" } var version: Int { return BrowserTable.DefaultVersion } let sqliteVersion: Int32 let supportsPartialIndices: Bool public init() { let v = sqlite3_libversion_number() self.sqliteVersion = v self.supportsPartialIndices = v >= 3008000 // 3.8.0. let ver = String.fromCString(sqlite3_libversion())! log.info("SQLite version: \(ver) (\(v)).") } func run(db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool { let err = db.executeChange(sql, withArgs: args) if err != nil { log.error("Error running SQL in BrowserTable. \(err?.localizedDescription)") log.error("SQL was \(sql)") } return err == nil } // TODO: transaction. func run(db: SQLiteDBConnection, queries: [(String, Args?)]) -> Bool { for (sql, args) in queries { if !run(db, sql: sql, args: args) { return false } } return true } func run(db: SQLiteDBConnection, queries: [String]) -> Bool { for sql in queries { if !run(db, sql: sql) { return false } } return true } func runValidQueries(db: SQLiteDBConnection, queries: [(String?, Args?)]) -> Bool { for (sql, args) in queries { if let sql = sql { if !run(db, sql: sql, args: args) { return false } } } return true } func runValidQueries(db: SQLiteDBConnection, queries: [String?]) -> Bool { return self.run(db, queries: optFilter(queries)) } func prepopulateRootFolders(db: SQLiteDBConnection) -> Bool { let type = BookmarkNodeType.Folder.rawValue let now = NSDate.nowNumber() let status = SyncStatus.New.rawValue let localArgs: Args = [ BookmarkRoots.RootID, BookmarkRoots.RootGUID, type, BookmarkRoots.RootGUID, status, now, BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, BookmarkRoots.RootGUID, status, now, BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, BookmarkRoots.RootGUID, status, now, BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, BookmarkRoots.RootGUID, status, now, BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, BookmarkRoots.RootGUID, status, now, ] // Compute these args using the sequence in RootChildren, rather than hard-coding. var idx = 0 var structureArgs = Args() structureArgs.reserveCapacity(BookmarkRoots.RootChildren.count * 3) BookmarkRoots.RootChildren.forEach { guid in structureArgs.append(BookmarkRoots.RootGUID) structureArgs.append(guid) structureArgs.append(idx) idx += 1 } // Note that we specify an empty title and parentName for these records. We should // never need a parentName -- we don't use content-based reconciling or // reparent these -- and we'll use the current locale's string, retrieved // via titleForSpecialGUID, if necessary. let local = "INSERT INTO \(TableBookmarksLocal) " + "(id, guid, type, parentid, title, parentName, sync_status, local_modified) VALUES " + Array(count: BookmarkRoots.RootChildren.count + 1, repeatedValue: "(?, ?, ?, ?, '', '', ?, ?)").joinWithSeparator(", ") let structure = "INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) VALUES " + Array(count: BookmarkRoots.RootChildren.count, repeatedValue: "(?, ?, ?)").joinWithSeparator(", ") return self.run(db, queries: [(local, localArgs), (structure, structureArgs)]) } let topSitesTableCreate = "CREATE TABLE IF NOT EXISTS \(TableCachedTopSites) (" + "historyID INTEGER, " + "url TEXT NOT NULL, " + "title TEXT NOT NULL, " + "guid TEXT NOT NULL UNIQUE, " + "domain_id INTEGER, " + "domain TEXT NO NULL, " + "localVisitDate REAL, " + "remoteVisitDate REAL, " + "localVisitCount INTEGER, " + "remoteVisitCount INTEGER, " + "iconID INTEGER, " + "iconURL TEXT, " + "iconDate REAL, " + "iconType INTEGER, " + "iconWidth INTEGER, " + "frecencies REAL" + ")" let domainsTableCreate = "CREATE TABLE IF NOT EXISTS \(TableDomains) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "domain TEXT NOT NULL UNIQUE, " + "showOnTopSites TINYINT NOT NULL DEFAULT 1" + ")" let queueTableCreate = "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" + "url TEXT NOT NULL UNIQUE, " + "title TEXT" + ") " let activityStreamBlocklistCreate = "CREATE TABLE IF NOT EXISTS \(TableActivityStreamBlocklist) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "url TEXT NOT NULL UNIQUE, " + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP " + ") " let pageMetadataCreate = "CREATE TABLE IF NOT EXISTS \(TablePageMetadata) (" + "id INTEGER PRIMARY KEY, " + "cache_key LONGVARCHAR UNIQUE, " + "site_url TEXT, " + "media_url LONGVARCHAR, " + "title TEXT, " + "type VARCHAR(32), " + "description TEXT, " + "provider_name TEXT, " + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, " + "expired_at LONG" + ") " let indexPageMetadataCreate = "CREATE UNIQUE INDEX IF NOT EXISTS \(IndexPageMetadataCacheKey) ON page_metadata (cache_key)" let iconColumns = ", faviconID INTEGER REFERENCES \(TableFavicons)(id) ON DELETE SET NULL" let mirrorColumns = ", is_overridden TINYINT NOT NULL DEFAULT 0" let serverColumns = ", server_modified INTEGER NOT NULL" + // Milliseconds. ", hasDupe TINYINT NOT NULL DEFAULT 0" // Boolean, 0 (false) if deleted. let localColumns = ", local_modified INTEGER" + // Can be null. Client clock. In extremis only. ", sync_status TINYINT NOT NULL" // SyncStatus enum. Set when changed or created. func getBookmarksTableCreationStringForTable(table: String, withAdditionalColumns: String="") -> String { // The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry. // For now we have the simplest possible schema: everything in one. let sql = "CREATE TABLE IF NOT EXISTS \(table) " + // Shared fields. "( id INTEGER PRIMARY KEY AUTOINCREMENT" + ", guid TEXT NOT NULL UNIQUE" + ", type TINYINT NOT NULL" + // Type enum. // Record/envelope metadata that'll allow us to do merges. ", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean ", parentid TEXT" + // GUID ", parentName TEXT" + // Type-specific fields. These should be NOT NULL in many cases, but we're going // for a sparse schema, so this'll do for now. Enforce these in the application code. ", feedUri TEXT, siteUri TEXT" + // LIVEMARKS ", pos INT" + // SEPARATORS ", title TEXT, description TEXT" + // FOLDERS, BOOKMARKS, QUERIES ", bmkUri TEXT, tags TEXT, keyword TEXT" + // BOOKMARKS, QUERIES ", folderName TEXT, queryId TEXT" + // QUERIES withAdditionalColumns + ", CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1)" + ", CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1)" + ")" return sql } /** * We need to explicitly store what's provided by the server, because we can't rely on * referenced child nodes to exist yet! */ func getBookmarksStructureTableCreationStringForTable(table: String, referencingMirror mirror: String) -> String { let sql = "CREATE TABLE IF NOT EXISTS \(table) " + "( parent TEXT NOT NULL REFERENCES \(mirror)(guid) ON DELETE CASCADE" + ", child TEXT NOT NULL" + // Should be the GUID of a child. ", idx INTEGER NOT NULL" + // Should advance from 0. ")" return sql } private let bufferBookmarksView = "CREATE VIEW \(ViewBookmarksBufferOnMirror) AS " + "SELECT" + " -1 AS id" + ", mirror.guid AS guid" + ", mirror.type AS type" + ", mirror.is_deleted AS is_deleted" + ", mirror.parentid AS parentid" + ", mirror.parentName AS parentName" + ", mirror.feedUri AS feedUri" + ", mirror.siteUri AS siteUri" + ", mirror.pos AS pos" + ", mirror.title AS title" + ", mirror.description AS description" + ", mirror.bmkUri AS bmkUri" + ", mirror.folderName AS folderName" + ", null AS faviconID" + ", 0 AS is_overridden" + // LEFT EXCLUDING JOIN to get mirror records that aren't in the buffer. // We don't have an is_overridden flag to help us here. " FROM \(TableBookmarksMirror) mirror LEFT JOIN" + " \(TableBookmarksBuffer) buffer ON mirror.guid = buffer.guid" + " WHERE buffer.guid IS NULL" + " UNION ALL " + "SELECT" + " -1 AS id" + ", guid" + ", type" + ", is_deleted" + ", parentid" + ", parentName" + ", feedUri" + ", siteUri" + ", pos" + ", title" + ", description" + ", bmkUri" + ", folderName" + ", null AS faviconID" + ", 1 AS is_overridden" + " FROM \(TableBookmarksBuffer) WHERE is_deleted IS 0" // TODO: phrase this without the subselect… private let bufferBookmarksStructureView = // We don't need to exclude deleted parents, because we drop those from the structure // table when we see them. "CREATE VIEW \(ViewBookmarksBufferStructureOnMirror) AS " + "SELECT parent, child, idx, 1 AS is_overridden FROM \(TableBookmarksBufferStructure) " + "UNION ALL " + // Exclude anything from the mirror that's present in the buffer -- dynamic is_overridden. "SELECT parent, child, idx, 0 AS is_overridden FROM \(TableBookmarksMirrorStructure) " + "LEFT JOIN \(TableBookmarksBuffer) ON parent = guid WHERE guid IS NULL" private let localBookmarksView = "CREATE VIEW \(ViewBookmarksLocalOnMirror) AS " + "SELECT -1 AS id, guid, type, is_deleted, parentid, parentName, feedUri," + " siteUri, pos, title, description, bmkUri, folderName, faviconID, NULL AS local_modified, server_modified, 0 AS is_overridden " + "FROM \(TableBookmarksMirror) WHERE is_overridden IS NOT 1 " + "UNION ALL " + "SELECT -1 AS id, guid, type, is_deleted, parentid, parentName, feedUri, siteUri, pos, title, description, bmkUri, folderName, faviconID," + " local_modified, NULL AS server_modified, 1 AS is_overridden " + "FROM \(TableBookmarksLocal) WHERE is_deleted IS NOT 1" // TODO: phrase this without the subselect… private let localBookmarksStructureView = "CREATE VIEW \(ViewBookmarksLocalStructureOnMirror) AS " + "SELECT parent, child, idx, 1 AS is_overridden FROM \(TableBookmarksLocalStructure) " + "WHERE " + "((SELECT is_deleted FROM \(TableBookmarksLocal) WHERE guid = parent) IS NOT 1) " + "UNION ALL " + "SELECT parent, child, idx, 0 AS is_overridden FROM \(TableBookmarksMirrorStructure) " + "WHERE " + "((SELECT is_overridden FROM \(TableBookmarksMirror) WHERE guid = parent) IS NOT 1) " // This view exists only to allow for text searching of URLs and titles in the awesomebar. // As such, we cheat a little: we include buffer, non-overridden mirror, and local. // Usually this will be indistinguishable from a more sophisticated approach, and it's way // easier. private let allBookmarksView = "CREATE VIEW \(ViewAllBookmarks) AS " + "SELECT guid, bmkUri AS url, title, description, faviconID FROM " + "\(TableBookmarksMirror) WHERE " + "type = \(BookmarkNodeType.Bookmark.rawValue) AND is_overridden IS 0 AND is_deleted IS 0 " + "UNION ALL " + "SELECT guid, bmkUri AS url, title, description, faviconID FROM " + "\(TableBookmarksLocal) WHERE " + "type = \(BookmarkNodeType.Bookmark.rawValue) AND is_deleted IS 0 " + "UNION ALL " + "SELECT guid, bmkUri AS url, title, description, -1 AS faviconID FROM " + "\(TableBookmarksBuffer) WHERE " + "type = \(BookmarkNodeType.Bookmark.rawValue) AND is_deleted IS 0" // This smushes together remote and local visits. So it goes. private let historyVisitsView = "CREATE VIEW \(ViewHistoryVisits) AS " + "SELECT h.url AS url, MAX(v.date) AS visitDate FROM " + "\(TableHistory) h JOIN \(TableVisits) v ON v.siteID = h.id " + "GROUP BY h.id" // Join all bookmarks against history to find the most recent visit. // visits. private let awesomebarBookmarksView = "CREATE VIEW \(ViewAwesomebarBookmarks) AS " + "SELECT b.guid AS guid, b.url AS url, b.title AS title, " + "b.description AS description, b.faviconID AS faviconID, " + "h.visitDate AS visitDate " + "FROM \(ViewAllBookmarks) b " + "LEFT JOIN " + "\(ViewHistoryVisits) h ON b.url = h.url" private let awesomebarBookmarksWithIconsView = "CREATE VIEW \(ViewAwesomebarBookmarksWithIcons) AS " + "SELECT b.guid AS guid, b.url AS url, b.title AS title, " + "b.description AS description, b.visitDate AS visitDate, " + "f.id AS iconID, f.url AS iconURL, f.date AS iconDate, " + "f.type AS iconType, f.width AS iconWidth " + "FROM \(ViewAwesomebarBookmarks) b " + "LEFT JOIN " + "\(TableFavicons) f ON f.id = b.faviconID" func create(db: SQLiteDBConnection) -> Bool { let favicons = "CREATE TABLE IF NOT EXISTS \(TableFavicons) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "url TEXT NOT NULL UNIQUE, " + "width INTEGER, " + "height INTEGER, " + "type INTEGER NOT NULL, " + "date REAL NOT NULL" + ") " let history = "CREATE TABLE IF NOT EXISTS \(TableHistory) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's. "url TEXT UNIQUE, " + // May only be null for deleted records. "title TEXT NOT NULL, " + "server_modified INTEGER, " + // Can be null. Integer milliseconds. "local_modified INTEGER, " + // Can be null. Client clock. In extremis only. "is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted. "should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added. "domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " + "CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" + ")" // Right now we don't need to track per-visit deletions: Sync can't // represent them! See Bug 1157553 Comment 6. // We flip the should_upload flag on the history item when we add a visit. // If we ever want to support logic like not bothering to sync if we added // and then rapidly removed a visit, then we need an 'is_new' flag on each visit. let visits = "CREATE TABLE IF NOT EXISTS \(TableVisits) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " + "date REAL NOT NULL, " + // Microseconds since epoch. "type INTEGER NOT NULL, " + "is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. "UNIQUE (siteID, date, type) " + ") " let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " + "ON \(TableVisits) (siteID, is_local, date)" let faviconSites = "CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " + "faviconID INTEGER NOT NULL REFERENCES \(TableFavicons)(id) ON DELETE CASCADE, " + "UNIQUE (siteID, faviconID) " + ") " let widestFavicons = "CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " + "SELECT " + "\(TableFaviconSites).siteID AS siteID, " + "\(TableFavicons).id AS iconID, " + "\(TableFavicons).url AS iconURL, " + "\(TableFavicons).date AS iconDate, " + "\(TableFavicons).type AS iconType, " + "MAX(\(TableFavicons).width) AS iconWidth " + "FROM \(TableFaviconSites), \(TableFavicons) WHERE " + "\(TableFaviconSites).faviconID = \(TableFavicons).id " + "GROUP BY siteID " let historyIDsWithIcon = "CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " + "SELECT \(TableHistory).id AS id, " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM \(TableHistory) " + "LEFT OUTER JOIN " + "\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID " let iconForURL = "CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " + "SELECT history.url AS url, icons.iconID AS iconID FROM " + "\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " + "\(TableHistory).id = icons.siteID " // Locally we track faviconID. // Local changes end up in the mirror, so we track it there too. // The buffer and the mirror additionally track some server metadata. let bookmarksLocal = getBookmarksTableCreationStringForTable(TableBookmarksLocal, withAdditionalColumns: self.localColumns + self.iconColumns) let bookmarksLocalStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksLocalStructure, referencingMirror: TableBookmarksLocal) let bookmarksBuffer = getBookmarksTableCreationStringForTable(TableBookmarksBuffer, withAdditionalColumns: self.serverColumns) let bookmarksBufferStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksBufferStructure, referencingMirror: TableBookmarksBuffer) let bookmarksMirror = getBookmarksTableCreationStringForTable(TableBookmarksMirror, withAdditionalColumns: self.serverColumns + self.mirrorColumns + self.iconColumns) let bookmarksMirrorStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksMirrorStructure, referencingMirror: TableBookmarksMirror) let indexLocalStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksLocalStructureParentIdx) " + "ON \(TableBookmarksLocalStructure) (parent, idx)" let indexBufferStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksBufferStructureParentIdx) " + "ON \(TableBookmarksBufferStructure) (parent, idx)" let indexMirrorStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " + "ON \(TableBookmarksMirrorStructure) (parent, idx)" let indexMirrorStructureChild = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureChild) " + "ON \(TableBookmarksMirrorStructure) (child)" let queries: [String] = [ self.domainsTableCreate, history, favicons, visits, bookmarksBuffer, bookmarksBufferStructure, bookmarksLocal, bookmarksLocalStructure, bookmarksMirror, bookmarksMirrorStructure, indexBufferStructureParentIdx, indexLocalStructureParentIdx, indexMirrorStructureParentIdx, indexMirrorStructureChild, faviconSites, indexShouldUpload, indexSiteIDDate, widestFavicons, historyIDsWithIcon, iconForURL, pageMetadataCreate, indexPageMetadataCreate, self.queueTableCreate, self.topSitesTableCreate, self.localBookmarksView, self.localBookmarksStructureView, self.bufferBookmarksView, self.bufferBookmarksStructureView, allBookmarksView, historyVisitsView, awesomebarBookmarksView, awesomebarBookmarksWithIconsView, activityStreamBlocklistCreate ] assert(queries.count == AllTablesIndicesAndViews.count, "Did you forget to add your table, index, or view to the list?") log.debug("Creating \(queries.count) tables, views, and indices.") return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } func updateTable(db: SQLiteDBConnection, from: Int) -> Bool { let to = BrowserTable.DefaultVersion if from == to { log.debug("Skipping update from \(from) to \(to).") return true } if from == 0 { // This is likely an upgrade from before Bug 1160399. log.debug("Updating browser tables from zero. Assuming drop and recreate.") return drop(db) && create(db) } if from > to { // This is likely an upgrade from before Bug 1160399. log.debug("Downgrading browser tables. Assuming drop and recreate.") return drop(db) && create(db) } log.debug("Updating browser tables from \(from) to \(to).") if from < 4 && to >= 4 { return drop(db) && create(db) } if from < 5 && to >= 5 { if !self.run(db, sql: self.queueTableCreate) { return false } } if from < 6 && to >= 6 { if !self.run(db, queries: [ "DROP INDEX IF EXISTS \(IndexVisitsSiteIDDate)", "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) ON \(TableVisits) (siteID, is_local, date)", self.domainsTableCreate, "ALTER TABLE \(TableHistory) ADD COLUMN domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE", ]) { return false } let urls = db.executeQuery("SELECT DISTINCT url FROM \(TableHistory) WHERE url IS NOT NULL", factory: { $0["url"] as! String }) if !fillDomainNamesFromCursor(urls, db: db) { return false } } if from < 8 && to == 8 { // Nothing to do: we're just shifting the favicon table to be owned by this class. return true } if from < 9 && to >= 9 { if !self.run(db, sql: getBookmarksTableCreationStringForTable(TableBookmarksMirror)) { return false } } if from < 10 && to >= 10 { if !self.run(db, sql: getBookmarksStructureTableCreationStringForTable(TableBookmarksMirrorStructure, referencingMirror: TableBookmarksMirror)) { return false } let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " + "ON \(TableBookmarksMirrorStructure) (parent, idx)" if !self.run(db, sql: indexStructureParentIdx) { return false } } if from < 11 && to >= 11 { if !self.run(db, sql: self.topSitesTableCreate) { return false } } if from < 12 && to >= 12 { let bookmarksLocal = getBookmarksTableCreationStringForTable(TableBookmarksLocal, withAdditionalColumns: self.localColumns + self.iconColumns) let bookmarksLocalStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksLocalStructure, referencingMirror: TableBookmarksLocal) let bookmarksMirror = getBookmarksTableCreationStringForTable(TableBookmarksMirror, withAdditionalColumns: self.serverColumns + self.mirrorColumns + self.iconColumns) let bookmarksMirrorStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksMirrorStructure, referencingMirror: TableBookmarksMirror) let indexLocalStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksLocalStructureParentIdx) " + "ON \(TableBookmarksLocalStructure) (parent, idx)" let indexBufferStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksBufferStructureParentIdx) " + "ON \(TableBookmarksBufferStructure) (parent, idx)" let indexMirrorStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " + "ON \(TableBookmarksMirrorStructure) (parent, idx)" let prep = [ // Drop indices. "DROP INDEX IF EXISTS idx_bookmarksMirrorStructure_parent_idx", // Rename the old mirror tables to buffer. // The v11 one is the same shape as the current buffer table. "ALTER TABLE \(TableBookmarksMirror) RENAME TO \(TableBookmarksBuffer)", "ALTER TABLE \(TableBookmarksMirrorStructure) RENAME TO \(TableBookmarksBufferStructure)", // Create the new mirror and local tables. bookmarksLocal, bookmarksMirror, bookmarksLocalStructure, bookmarksMirrorStructure, ] // Only migrate bookmarks. The only folders are our roots, and we'll create those later. // There should be nothing else in the table, and no structure. // Our old bookmarks table didn't have creation date, so we use the current timestamp. let modified = NSDate.now() let status = SyncStatus.New.rawValue // We don't specify a title, expecting it to be generated on the fly, because we're smarter than Android. // We also don't migrate the 'id' column; we'll generate new ones that won't conflict with our roots. let migrateArgs: Args = [BookmarkRoots.MobileFolderGUID] let migrateLocal = "INSERT INTO \(TableBookmarksLocal) " + "(guid, type, bmkUri, title, faviconID, local_modified, sync_status, parentid, parentName) " + "SELECT guid, type, url AS bmkUri, title, faviconID, " + "\(modified) AS local_modified, \(status) AS sync_status, ?, '' " + "FROM \(_TableBookmarks) WHERE type IS \(BookmarkNodeType.Bookmark.rawValue)" // Create structure for our migrated bookmarks. // In order to get contiguous positions (idx), we first insert everything we just migrated under // Mobile Bookmarks into a temporary table, then use rowid as our idx. let temporaryTable = "CREATE TEMPORARY TABLE children AS " + "SELECT guid FROM \(_TableBookmarks) WHERE " + "type IS \(BookmarkNodeType.Bookmark.rawValue) ORDER BY id ASC" let createStructure = "INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) " + "SELECT ? AS parent, guid AS child, (rowid - 1) AS idx FROM children" let migrate: [(String, Args?)] = [ (migrateLocal, migrateArgs), (temporaryTable, nil), (createStructure, migrateArgs), // Drop the temporary table. ("DROP TABLE children", nil), // Drop the old bookmarks table. ("DROP TABLE \(_TableBookmarks)", nil), // Create indices for each structure table. (indexBufferStructureParentIdx, nil), (indexLocalStructureParentIdx, nil), (indexMirrorStructureParentIdx, nil) ] if !self.run(db, queries: prep) || !self.prepopulateRootFolders(db) || !self.run(db, queries: migrate) { return false } // TODO: trigger a sync? } // Add views for the overlays. if from < 14 && to >= 14 { let indexMirrorStructureChild = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureChild) " + "ON \(TableBookmarksMirrorStructure) (child)" if !self.run(db, queries: [ self.bufferBookmarksView, self.bufferBookmarksStructureView, self.localBookmarksView, self.localBookmarksStructureView, indexMirrorStructureChild]) { return false } } if from == 14 && to >= 15 { // We screwed up some of the views. Recreate them. if !self.run(db, queries: [ "DROP VIEW IF EXISTS \(ViewBookmarksBufferStructureOnMirror)", "DROP VIEW IF EXISTS \(ViewBookmarksLocalStructureOnMirror)", "DROP VIEW IF EXISTS \(ViewBookmarksBufferOnMirror)", "DROP VIEW IF EXISTS \(ViewBookmarksLocalOnMirror)", self.bufferBookmarksView, self.bufferBookmarksStructureView, self.localBookmarksView, self.localBookmarksStructureView]) { return false } } if from < 16 && to >= 16 { if !self.run(db, queries: [ allBookmarksView, historyVisitsView, awesomebarBookmarksView, awesomebarBookmarksWithIconsView]) { return false } } if from < 17 && to >= 17 { if !self.run(db, queries: [ // Adds the local_modified, server_modified times to the local bookmarks view "DROP VIEW IF EXISTS \(ViewBookmarksLocalOnMirror)", self.localBookmarksView]) { return false } } if from < 18 && to >= 18 { if !self.run(db, queries: [ // Adds the Activity Stream blocklist table activityStreamBlocklistCreate]) { return false } } if from < 19 && to >= 19 { if !self.run(db, queries: [ // Adds tables/indicies for metadata content pageMetadataCreate, indexPageMetadataCreate]) { return false } } return true } private func fillDomainNamesFromCursor(cursor: Cursor<String>, db: SQLiteDBConnection) -> Bool { if cursor.count == 0 { return true } // URL -> hostname, flattened to make args. var pairs = Args() pairs.reserveCapacity(cursor.count * 2) for url in cursor { if let url = url, host = url.asURL?.normalizedHost() { pairs.append(url) pairs.append(host) } } cursor.close() let tmpTable = "tmp_hostnames" let table = "CREATE TEMP TABLE \(tmpTable) (url TEXT NOT NULL UNIQUE, domain TEXT NOT NULL, domain_id INT)" if !self.run(db, sql: table, args: nil) { log.error("Can't create temporary table. Unable to migrate domain names. Top Sites is likely to be broken.") return false } // Now insert these into the temporary table. Chunk by an even number, for obvious reasons. let chunks = chunk(pairs, by: BrowserDB.MaxVariableNumber - (BrowserDB.MaxVariableNumber % 2)) for chunk in chunks { let ins = "INSERT INTO \(tmpTable) (url, domain) VALUES " + Array<String>(count: chunk.count / 2, repeatedValue: "(?, ?)").joinWithSeparator(", ") if !self.run(db, sql: ins, args: Array(chunk)) { log.error("Couldn't insert domains into temporary table. Aborting migration.") return false } } // Now make those into domains. let domains = "INSERT OR IGNORE INTO \(TableDomains) (domain) SELECT DISTINCT domain FROM \(tmpTable)" // … and fill that temporary column. let domainIDs = "UPDATE \(tmpTable) SET domain_id = (SELECT id FROM \(TableDomains) WHERE \(TableDomains).domain = \(tmpTable).domain)" // Update the history table from the temporary table. let updateHistory = "UPDATE \(TableHistory) SET domain_id = (SELECT domain_id FROM \(tmpTable) WHERE \(tmpTable).url = \(TableHistory).url)" // Clean up. let dropTemp = "DROP TABLE \(tmpTable)" // Now run these. if !self.run(db, queries: [domains, domainIDs, updateHistory, dropTemp]) { log.error("Unable to migrate domains.") return false } return true } /** * The Table mechanism expects to be able to check if a 'table' exists. In our (ab)use * of Table, that means making sure that any of our tables and views exist. * We do that by fetching all tables from sqlite_master with matching names, and verifying * that we get back more than one. * Note that we don't check for views -- trust to luck. */ func exists(db: SQLiteDBConnection) -> Bool { return db.tablesExist(AllTables) } func drop(db: SQLiteDBConnection) -> Bool { log.debug("Dropping all browser tables.") let additional = [ "DROP TABLE IF EXISTS faviconSites" // We renamed it to match naming convention. ] let views = AllViews.map { "DROP VIEW IF EXISTS \($0)" } let indices = AllIndices.map { "DROP INDEX IF EXISTS \($0)" } let tables = AllTables.map { "DROP TABLE IF EXISTS \($0)" } let queries = Array([views, indices, tables, additional].flatten()) return self.run(db, queries: queries) } }
mpl-2.0
31a051565279e4e867b34502bf8f683d
43.123904
238
0.622649
4.802602
false
false
false
false
seongkyu-sim/BaseVCKit
BaseVCKit/Classes/extensions/UILabelExtensions.swift
1
4316
// // UILabelExtensions.swift // BaseVCKit // // Created by frank on 2015. 11. 10.. // Copyright © 2016년 colavo. All rights reserved. // import UIKit public extension UILabel { static func configureLabel(color:UIColor, size:CGFloat, weight: UIFont.Weight = UIFont.Weight.regular) -> UILabel { let label = UILabel() label.textAlignment = NSTextAlignment.left label.font = UIFont.systemFont(ofSize: size, weight: weight) label.textColor = color label.numberOfLines = 0 return label } // MARK: - Attributed func setAttributedText(fullText: String, highlightText: String, highlightColor: UIColor? = nil, highlightFontWeight: UIFont.Weight? = nil) { let range = (fullText as NSString).range(of: highlightText) let attributedString = NSMutableAttributedString(string:fullText) if let highlightColor = highlightColor { // height color attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: highlightColor , range: range) } // set bold var originFontSize = CGFloat(15) if let originFont = self.font { originFontSize = originFont.pointSize } var font = UIFont.systemFont(ofSize: originFontSize, weight: UIFont.Weight.medium) if let highlightFontWeight = highlightFontWeight { font = UIFont.systemFont(ofSize: originFontSize, weight: highlightFontWeight) } attributedString.addAttribute(NSAttributedString.Key.font, value: font , range: range) self.attributedText = attributedString } // MARK: - Strikethrough line func renderStrikethrough(text:String?, color:UIColor = UIColor.black) { guard let text = text else { return } let attributedText = NSMutableAttributedString(string: text , attributes: [NSAttributedString.Key.strikethroughStyle: NSUnderlineStyle.single.rawValue, NSAttributedString.Key.strikethroughColor: color]) attributedText.addAttribute(NSAttributedString.Key.baselineOffset, value: 0, range: NSMakeRange(0, attributedText.length)) self.attributedText = attributedText } // MARK: - Ellipse Indecator func startEllipseAnimate(withText txt: String = "") { defaultTxt = txt stopEllipseAnimate() ellipseTimer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { timer in self.ellipseUpdate(loading: true) } } func stopEllipseAnimate() { if let aTimer = ellipseTimer { aTimer.invalidate() ellipseTimer = nil } ellipseUpdate(loading: false) } private struct AssociatedKeys { static var ellipseTimerKey = "ellipseTimer" static var defaultTxtKey = "defaultTxtKey" } private var ellipseTimer: Timer? { get { return objc_getAssociatedObject(self, &AssociatedKeys.ellipseTimerKey) as? Timer } set { willChangeValue(forKey: "ellipseTimer") objc_setAssociatedObject(self, &AssociatedKeys.ellipseTimerKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN) didChangeValue(forKey: "ellipseTimer") } } private var defaultTxt: String? { get { return objc_getAssociatedObject(self, &AssociatedKeys.defaultTxtKey) as? String } set { if let newValue = newValue { willChangeValue(forKey: "defaultTxt") objc_setAssociatedObject(self, &AssociatedKeys.defaultTxtKey, newValue as NSString?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) didChangeValue(forKey: "defaultTxt") } } } private func ellipseUpdate(loading: Bool) { guard let defaultTxt = defaultTxt else { return } guard loading else { self.text = defaultTxt return } if self.text == defaultTxt { self.text = defaultTxt + "." }else if self.text == defaultTxt + "." { self.text = defaultTxt + ".." }else if self.text == defaultTxt + ".." { self.text = defaultTxt + "..." }else { self.text = defaultTxt } } }
mit
0ff6309896e900f156f6d00f7f9d84d5
32.695313
210
0.634593
4.929143
false
false
false
false
huangboju/Moots
UICollectionViewLayout/uicollectionview-layouts-kit-master/vertical-snap-flow/Core/Controller/VerticalSnapCollectionViewController.swift
1
3291
// // VerticalSnapCollectionViewController.swift // vertical-snap-flow-layout // // Created by Astemir Eleev on 21/05/2018. // Copyright © 2018 Astemir Eleev. All rights reserved. // import UIKit //public extension UICollectionView { // // /// Registers custom UICollectionViewCell for a UICollectionView instance. UICollectionViewCell needs to be located in current Bundle // /// // /// Usage example: // /// let collectionView = UICollectionView() // /// collectionView.register(cellNamed: UICollectionViewCell.self, reuseableIdentifier: "item-cell") // /// // /// - Parameters: // /// - name: is a name of a UICollectionView that is going to be registered (hint: use UICollectionView.self as a parameter in order to avoid any misspellings) // /// - id: is a reusable identifier for a UICollectionView cell // public func register(cellNamed name: UICollectionViewCell.Type, reusableId id: String) { // let nibName = String(describing: name) // let bundle = Bundle(identifier: nibName) // let cellNib = UINib(nibName: nibName, bundle: bundle) // self.register(cellNib, forCellWithReuseIdentifier: id) // } //} class VerticalSnapCollectionViewController: UICollectionViewController { // MARK: - Properties private var adapter = VerticalSnapCollectionAdapter() fileprivate var data: [Comics]? // MARK: - Outlets @IBOutlet weak var snapFlowCollectionLayout: VerticalSnapCollectionFlowLayout! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false self.collectionView?.register(cell: VerticalSnapCollectionViewCell.self, reusableId: VerticalSnapCollectionViewCell.reusableId) // Do any additional setup after loading the view. data = ComicsManager.covers() collectionView?.backgroundColor = .clear collectionView?.contentInset = UIEdgeInsets.init(top: 24, left: 16, bottom: 24, right: 16) } // MARK: UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items return data?.count ?? 0 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // Configure the cell guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: VerticalSnapCollectionViewCell.reusableId, for: indexPath) as? VerticalSnapCollectionViewCell else { fatalError(#function + " could not dequeue VerticalSnapCollectionViewCell using the reusable identifier: \(VerticalSnapCollectionViewCell.reusableId)") } // Configure the cell guard let comics = data?[indexPath.item] else { fatalError(#function + " could not fetch comics from data source using the index path item: \(indexPath.item)") } adapter.configure(cell: cell, forDisplaying: comics) return cell } }
mit
82fcc037b26d5d1aa67c1ca361558172
37.705882
181
0.690578
5.15674
false
false
false
false
huangboju/Moots
算法学习/数据结构/DataStructures/DataStructures/Classes/BitSet.swift
1
319
public struct BitSet { private (set) public var size: Int private let N = 64 public typealias Word = UInt64 fileprivate(set) public var words: [Word] public init(size: Int) { precondition(size > 0) self.size = size let n = (size + (N - 1)) / N words = [Word](repeating: 0, count: n) } }
mit
cb34d8efb1bbf44294cb269acbb62d7d
20.266667
43
0.61442
3.357895
false
false
false
false
PandaraWen/DJIDemoKit
DJIDemoKit/DDKStartViewController.swift
1
13901
// // ViewController.swift // DJIDemoKitDemo // // Created by Pandara on 2017/8/31. // Copyright © 2017年 Pandara. All rights reserved. // import UIKit import DJISDK public protocol DDKStartViewControllerDelegate: NSObjectProtocol { func startViewControllerDidClickGoButton(_ viewCon: DDKStartViewController) } public class DDKStartViewController: UIViewController { fileprivate var goButton: UIButton! fileprivate var tableview: UITableView! public weak var delegate: DDKStartViewControllerDelegate? fileprivate var infoTitles = ["Model", "Activation state", "Binding state"] fileprivate var settingTitles = ["📟 Use Remote log", "⛓ Enable bridge", "🎚 Log enable"] public override func viewDidLoad() { super.viewDidLoad() self.title = "Start up" self.view.backgroundColor = UIColor.white self.setupGoButton() self.setupTableview() self.refreshComponents() DJISDKManager.appActivationManager().delegate = self DJISDKManager.registerApp(with: self) } } // MARK: UI fileprivate extension DDKStartViewController { func setupGoButton() { self.goButton = { let button = UIButton() button.setBackgroundImage(UIImage.image(of: UIColor.ddkVIBlue, with: CGSize(width: 1, height: 1)), for: .normal) button.addTarget(self, action: #selector(onGoButtonClicked(_:)), for: .touchUpInside) button.setTitleColor(UIColor.white, for: .normal) button.setTitle("Go", for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 15) self.view.addSubview(button) button.snp.makeConstraints({ (make) in make.left.bottom.right.equalTo(self.view) make.height.equalTo(45) }) return button }() } func setupTableview() { self.tableview = { let tableview = UITableView() tableview.delegate = self tableview.dataSource = self tableview.backgroundColor = UIColor.clear if #available(iOS 11.0, *) { tableview.contentInsetAdjustmentBehavior = .never } tableview.delaysContentTouches = false tableview.register(DDKTableSectionHeader.self, forHeaderFooterViewReuseIdentifier: "DDKTableSectionHeader") tableview.tableFooterView = UITableView() self.view.addSubview(tableview) tableview.snp.makeConstraints({ (make) in make.left.right.equalTo(self.view) make.top.equalTo(self.view).offset(20) make.bottom.equalTo(self.goButton.snp.top) }) return tableview }() } } // MARK: Private methods fileprivate extension DDKStartViewController { func string(from activationState: DJIAppActivationState) -> String { var activationStateString = "" switch activationState { case .activated: activationStateString = "Activated" case .loginRequired: activationStateString = "LoginRequired" case .notSupported: activationStateString = "NotSupported" case .unknown: activationStateString = "Unknown" } return activationStateString } func string(from bindingState: DJIAppActivationAircraftBindingState) -> String { var bindingStateString = "" switch bindingState { case .bound: bindingStateString = "Bound" case .initial: bindingStateString = "Initial" case .notRequired: bindingStateString = "NotRequired" case .notSupported: bindingStateString = "NotSupported" case .unbound: bindingStateString = "Unbound" case .unboundButCannotSync: bindingStateString = "UnboundButCannotSync" case .unknown: bindingStateString = "Unknown" } return bindingStateString } func refreshComponents() { self.tableview.reloadData() self.goButton.isEnabled = (DJISDKManager.appActivationManager().appActivationState == .activated && DJISDKManager.appActivationManager().aircraftBindingState == .bound) } func setInfoCellDetail(_ infoCell: UITableViewCell, at row: Int) { switch row { case 0: // Model name infoCell.detailTextLabel?.text = DDKComponentHelper.fetchProduct()?.model ?? "Not connected" case 1: // Activation state infoCell.detailTextLabel?.text = self.string(from: DJISDKManager.appActivationManager().appActivationState) case 2: // Binding state infoCell.detailTextLabel?.text = self.string(from: DJISDKManager.appActivationManager().aircraftBindingState) default: break } infoCell.textLabel?.text = self.infoTitles[row] } func setSettingCellDetail(_ settingCell: UITableViewCell, at row: Int) { switch row { case 0: // Remote log settingCell.detailTextLabel?.text = DDKConfig.default.enableRemoteLog ? "✅" : "No" case 1: // Bridger settingCell.detailTextLabel?.text = DDKConfig.default.enableBridger ? "✅" : "No" case 2: // Log enable settingCell.detailTextLabel?.text = DDKLogger.shareLogger.enable ? "✅" : "No" default: break } settingCell.textLabel?.text = self.settingTitles[row] } } // MARK: Actions fileprivate extension DDKStartViewController { @objc func onGoButtonClicked(_ sender: Any) { self.delegate?.startViewControllerDidClickGoButton(self) } } // MARK: Settings fileprivate extension DDKStartViewController { func enableRemoteLog() { let alert = UIAlertController(title: "Use remote log", message: "Input remote log server's ip and port", preferredStyle: .alert) alert.addTextField(configurationHandler: { (textfield) in textfield.placeholder = "192.168.x.x" if let remoteLogIP = UserDefaults.standard.object(forKey: kUDRemoteLogIP) as? String { textfield.text = remoteLogIP } }) alert.addTextField(configurationHandler: { (textfield) in textfield.placeholder = "4567" if let remoteLogPort = UserDefaults.standard.object(forKey: kUDRemoteLogPort) as? String { textfield.text = remoteLogPort } }) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in guard let ip = alert.textFields![0].text, let port = alert.textFields![1].text else { return } UserDefaults.standard.set(ip, forKey: kUDRemoteLogIP) UserDefaults.standard.set(port, forKey: kUDRemoteLogPort) DDKConfig.default.enableRemoteLog(ip: ip, port: port) ddkLogOK("Remote log set up") self.tableview.reloadData() })) self.present(alert, animated: true, completion: nil) } func enableBridger() { let alert = UIAlertController(title: "Use remote log", message: "Input remote log server's ip and port", preferredStyle: .alert) alert.addTextField(configurationHandler: { (textfield) in textfield.placeholder = "192.168.x.x" if let remoteLogIP = UserDefaults.standard.object(forKey: kUDBridgerIP) as? String { textfield.text = remoteLogIP } }) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in guard let ip = alert.textFields![0].text else { return } UserDefaults.standard.set(ip, forKey: kUDBridgerIP) DJISDKManager.stopConnectionToProduct() DDKConfig.default.enableBridger(ip: ip) self.tableview.reloadData() if DDKComponentHelper.fetchProduct() == nil { DJISDKManager.enableBridgeMode(withBridgeAppIP: DDKConfig.default.bridgerIP) } })) self.present(alert, animated: true, completion: nil) } } extension DDKStartViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard indexPath.section == 1 else { return } switch indexPath.row { case 0: // Remote log self.enableRemoteLog() case 1: // Enable bridge self.enableBridger() case 2: // Log enable DDKLogger.shareLogger.enable = !DDKLogger.shareLogger.enable self.tableview.reloadData() default: break } } } extension DDKStartViewController: UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { return 2 } public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30 } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "DDKTableSectionHeader") as! DDKTableSectionHeader switch section { case 0: header.titleLabel.text = "Infomations" case 1: header.titleLabel.text = "Settings" default: break } return header } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return self.infoTitles.count case 1: return self.settingTitles.count default: return 0 } } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 45 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: var infoCell: UITableViewCell if let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell") { infoCell = cell } else { infoCell = UITableViewCell(style: .value1, reuseIdentifier: "InfoCell") infoCell.textLabel?.font = UIFont.boldSystemFont(ofSize: 13) infoCell.detailTextLabel?.font = UIFont.systemFont(ofSize: 14) } self.setInfoCellDetail(infoCell, at: indexPath.row) return infoCell case 1: var settingCell: UITableViewCell if let cell = tableView.dequeueReusableCell(withIdentifier: "SettingCell") { settingCell = cell } else { settingCell = UITableViewCell(style: .value1, reuseIdentifier: "SettingCell") settingCell.textLabel?.font = UIFont.boldSystemFont(ofSize: 13) settingCell.detailTextLabel?.font = UIFont.systemFont(ofSize: 14) settingCell.accessoryType = .disclosureIndicator } self.setSettingCellDetail(settingCell, at: indexPath.row) return settingCell default: return UITableViewCell() } } } extension DDKStartViewController: DJISDKManagerDelegate { public func appRegisteredWithError(_ error: Error?) { if let error = error { ddkLogError("\(error.localizedDescription)") } else { ddkLogOK("Register app success") if DDKConfig.default.enableBridger && DDKComponentHelper.fetchProduct() == nil { DJISDKManager.enableBridgeMode(withBridgeAppIP: DDKConfig.default.bridgerIP) } else { DJISDKManager.startConnectionToProduct() } } } public func productConnected(_ product: DJIBaseProduct?) { ddkLogInfo("Product connected: \(product?.model ?? "")") } public func productDisconnected() { ddkLogInfo("Product disconnected") } public func componentConnected(withKey key: String?, andIndex index: Int) { ddkLogInfo("Component connected: \(key ?? ""), \(index)") } public func componentDisconnected(withKey key: String?, andIndex index: Int) { ddkLogInfo("Component disconnected: \(key ?? ""), \(index)") } } extension DDKStartViewController: DJIAppActivationManagerDelegate { public func manager(_ manager: DJIAppActivationManager!, didUpdate appActivationState: DJIAppActivationState) { self.refreshComponents() if appActivationState == .loginRequired { DJISDKManager.userAccountManager().logIntoDJIUserAccount(withAuthorizationRequired: false, withCompletion: { (state, error) in if let error = error { DDKHelper.showAlert(title: "Error", message: error.localizedDescription, at: self) } }) } ddkLogInfo("App activation state: \(appActivationState.rawValue)") } public func manager(_ manager: DJIAppActivationManager!, didUpdate aircraftBindingState: DJIAppActivationAircraftBindingState) { self.refreshComponents() ddkLogInfo("Aircraft binding state: \(aircraftBindingState.rawValue)") } }
mit
33610a9d2a0967ff7deac36e095ea101
36.423181
176
0.618482
4.916431
false
false
false
false
dpricha89/DrApp
Source/TableCells/MapCell.swift
1
2153
// // MapCell.swift // Venga // // Created by David Richards on 7/22/17. // Copyright © 2017 David Richards. All rights reserved. // import UIKit import MapKit import SnapKit open class MapCell: UITableViewCell, MKMapViewDelegate { let map = MKMapView() public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // Setup the delegate self.map.delegate = self // Make the select color none self.selectionStyle = .none self.backgroundColor = .clear // size the map to the same size as the cell self.contentView.addSubview(self.map) self.map.snp.makeConstraints { (make) -> Void in make.edges.equalTo(self.contentView) } } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func addAnnotation(lat: Float, lng: Float) { let annotation = MKPointAnnotation() annotation.coordinate.latitude = CLLocationDegrees(lat) annotation.coordinate.longitude = CLLocationDegrees(lng) self.map.addAnnotation(annotation) self.map.showAnnotations(self.map.annotations, animated: true) } open func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if !(annotation is MKPointAnnotation) { return nil } var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "demo") if annotationView == nil { annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "demo") annotationView!.canShowCallout = true } else { annotationView!.annotation = annotation } // Add custom annotation if let annotationView = annotationView { //annotationView.image = UIImage.fontAwesomeIcon(name: .mapMarker, textColor: FlatMint(), size: CGSize(width: 50, height: 50)) } return annotationView } }
apache-2.0
6b0cd0a44368a8f997c44f0208a4425c
31.119403
138
0.637082
5.111639
false
false
false
false
xdliu002/TongjiAppleClubDeviceManagement
TAC-DM/HistoryViewController.swift
1
7720
// // HistoryViewController.swift // TAC-DM // // Created by Harold Liu on 8/21/15. // Copyright (c) 2015 TAC. All rights reserved. // import UIKit class HistoryViewController: UITableViewController,UIAlertViewDelegate, DMDelegate{ // MARK:-TODO: change the test data to real // 建议将每条记录写成一个struct, 里面有它的属性 var dmModel: DatabaseModel! var borrowRecords:[HistoryRecord] = [] // MARK:- Custom Nav @IBAction func back() { SVProgressHUD.dismiss() (tabBarController as! TabBarController).sidebar.showInViewController(self, animated: true) } @IBOutlet weak var navView: UIView! // MARK:- Configure UI override func viewDidLoad() { super.viewDidLoad() dmModel = DatabaseModel.getInstance() dmModel.delegate = self self.refreshControl = UIRefreshControl() self.refreshControl!.addTarget(self, action: Selector("refresh"), forControlEvents: .ValueChanged) } func refresh() { SVProgressHUD.show() updateUI() print("data is refresh") tableView.reloadData() refreshControl?.endRefreshing() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) configureUI() self.navView.backgroundColor = UIColor.clearColor() self.navigationController?.navigationBarHidden = true updateUI() SVProgressHUD.show() } //更新历史列表 func updateUI() { borrowRecords = [] dmModel.getRecordList() } func configureUI () { self.tableView.backgroundView = UIImageView(image: UIImage(named: "history background")) self.navigationController?.navigationBar.barTintColor = UIColor(patternImage:UIImage(named: "history background")!) self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor() , NSFontAttributeName :UIFont(name: "Hiragino Kaku Gothic ProN", size: 30)!] } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("HistoryCell") as! HistoryTableViewCell if 0 == indexPath.row%2 { cell.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.6) cell.nameLabel?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.0) cell.typeLabel?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.0) cell.timeLabel?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.0) if !borrowRecords.isEmpty { cell.nameLabel?.text = borrowRecords[indexPath.row/2].borrowerName cell.typeLabel?.text = borrowRecords[indexPath.row/2].borrowItemName cell.timeLabel?.text = borrowRecords[indexPath.row/2].borrowTime if borrowRecords[indexPath.row/2].returnTime != "0" { cell.statusImg.image = UIImage(named: "checked icon") cell.status = true } else { cell.statusImg.image = UIImage(named: "unchecked icon") cell.status = false } } } else { cell.backgroundColor = UIColor.clearColor() cell.nameLabel?.text = "" cell.typeLabel?.text = "" cell.timeLabel?.text = "" cell.statusImg?.image = nil } return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if 0 == indexPath.row%2 { return 75 } else { return 5 } } //TODO:- ADD DATA *2 ATTENTION override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return borrowRecords.count * 2 } @IBAction func backAction(sender: AnyObject) { // self.navigationController?.navigationBarHidden = true SVProgressHUD.dismiss() (tabBarController as! TabBarController).sidebar.showInViewController(self, animated: true) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) as! HistoryTableViewCell if cell.status == false { let alert = UIAlertController(title: "确认归还?", message: "姓名:\(cell.nameLabel.text!) \n 电话号码: \(borrowRecords[indexPath.row/2].borrowerPhone) \n 设备: \(cell.typeLabel.text!) \n ", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction) in cell.statusImg.image = UIImage(named: "checked icon") cell.status = true self.dealWithAction(self.borrowRecords[indexPath.row/2].historyId)})) alert.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } tableView.deselectRowAtIndexPath(indexPath, animated: true) } // MARK:-TODO: update the status of database func dealWithAction(recordId:String) { dmModel.returnItem(recordId) } func getRequiredInfo(Info: String) { switch Info { case "1": print("归还物品成功") SVProgressHUD.showSuccessWithStatus("Your borrowed thing has been return") case "0": print("归还物品失败") SVProgressHUD.showErrorWithStatus("Sorry,there are some troubles,please contact with TAC member") default: let borrowHistoryList = Info.componentsSeparatedByString("|") let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy/MM/dd" for record in borrowHistoryList { print("RECORD:\(record)") //判断历史是否为空 if "" == record { //历史数据为空 break } else { let oneRecord = record.componentsSeparatedByString(",") let oneHistoryRecord = HistoryRecord(historyId: oneRecord[0], borrowerName: oneRecord[1], borrowerPhone: oneRecord[2], borrowItemId: oneRecord[3], borrowItemName: oneRecord[4], borrowItemInfo: oneRecord[5], borrowTime: getReallytime(oneRecord[6], dateFormatter: dateFormatter), returnTime: oneRecord[7], borrowNumber: oneRecord[8]) borrowRecords.append(oneHistoryRecord) } } self.tableView.reloadData() SVProgressHUD.dismiss() } } //时间戳转换 func getReallytime(timeStringFrom1970Millisecond:String, dateFormatter:NSDateFormatter) -> String { let timeNSString:NSString = (timeStringFrom1970Millisecond as NSString).substringToIndex(10) let date = NSDate(timeIntervalSince1970: timeNSString.doubleValue) return dateFormatter.stringFromDate(date) } }
mit
7e156cf4f176d481a0d4be199b605a55
36.681592
142
0.604436
5.216253
false
false
false
false
xuephil/Perfect
PerfectLib/NetNamedPipe.swift
2
12995
// // NetNamedPipe.swift // PerfectLib // // Created by Kyle Jessup on 7/5/15. // Copyright (C) 2015 PerfectlySoft, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version, as supplemented by the // Perfect Additional Terms. // // 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 Affero General Public License, as supplemented by the // Perfect Additional Terms, for more details. // // You should have received a copy of the GNU Affero General Public License // and the Perfect Additional Terms that immediately follow the terms and // conditions of the GNU Affero General Public License along with this // program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>. // #if os(Linux) import SwiftGlibc let AF_UNIX: Int32 = 1 let SOL_SOCKET: Int32 = 1 let SCM_RIGHTS: Int32 = 0x01 #else import Darwin #endif /// This sub-class of NetTCP handles networking over an AF_UNIX named pipe connection. public class NetNamedPipe : NetTCP { /// Initialize the object using an existing file descriptor. public convenience init(fd: Int32) { self.init() self.fd.fd = fd self.fd.family = AF_UNIX self.fd.switchToNBIO() } /// Override socket initialization to handle the UNIX socket type. public override func initSocket() { #if os(Linux) fd.fd = socket(AF_UNIX, Int32(SOCK_STREAM.rawValue), 0) #else fd.fd = socket(AF_UNIX, SOCK_STREAM, 0) #endif fd.family = AF_UNIX fd.switchToNBIO() } public override func sockName() -> (String, UInt16) { var addr = UnsafeMutablePointer<sockaddr_un>.alloc(1) let len = UnsafeMutablePointer<socklen_t>.alloc(1) defer { addr.dealloc(1) len.dealloc(1) } len.memory = socklen_t(sizeof(sockaddr_in)) getsockname(fd.fd, UnsafeMutablePointer<sockaddr>(addr), len) var nameBuf = [CChar]() let mirror = Mirror(reflecting: addr.memory.sun_path) let childGen = mirror.children.generate() for _ in 0..<1024 { let (_, elem) = childGen.next()! if (elem as! Int8) == 0 { break } nameBuf.append(elem as! Int8) } nameBuf.append(0) let s = String.fromCString(nameBuf) ?? "" let p = UInt16(0) return (s, p) } public override func peerName() -> (String, UInt16) { var addr = UnsafeMutablePointer<sockaddr_un>.alloc(1) let len = UnsafeMutablePointer<socklen_t>.alloc(1) defer { addr.dealloc(1) len.dealloc(1) } len.memory = socklen_t(sizeof(sockaddr_in)) getpeername(fd.fd, UnsafeMutablePointer<sockaddr>(addr), len) var nameBuf = [CChar]() let mirror = Mirror(reflecting: addr.memory.sun_path) let childGen = mirror.children.generate() for _ in 0..<1024 { let (_, elem) = childGen.next()! if (elem as! Int8) == 0 { break } nameBuf.append(elem as! Int8) } nameBuf.append(0) let s = String.fromCString(nameBuf) ?? "" let p = UInt16(0) return (s, p) } /// Bind the socket to the address path /// - parameter address: The path on the file system at which to create and bind the socket /// - throws: `PerfectError.NetworkError` public func bind(address: String) throws { initSocket() let utf8 = address.utf8 #if os(Linux) // BSDs have a size identifier in front, Linux does not let addrLen = sizeof(sockaddr_un) #else let addrLen = sizeof(UInt8) + sizeof(sa_family_t) + utf8.count + 1 #endif let addrPtr = UnsafeMutablePointer<UInt8>.alloc(addrLen) defer { addrPtr.destroy() } var memLoc = 0 #if os(Linux) // BSDs use one byte for sa_family_t, Linux uses two let afUnixShort = UInt16(AF_UNIX) addrPtr[memLoc] = UInt8(afUnixShort & 0xFF) memLoc += 1 addrPtr[memLoc] = UInt8((afUnixShort >> 8) & 0xFF) memLoc += 1 #else addrPtr[memLoc] = UInt8(addrLen) memLoc += 1 addrPtr[memLoc] = UInt8(AF_UNIX) memLoc += 1 #endif for char in utf8 { addrPtr[memLoc] = char memLoc += 1 } addrPtr[memLoc] = 0 #if os(Linux) let bRes = SwiftGlibc.bind(fd.fd, UnsafePointer<sockaddr>(addrPtr), socklen_t(addrLen)) #else let bRes = Darwin.bind(fd.fd, UnsafePointer<sockaddr>(addrPtr), socklen_t(addrLen)) #endif if bRes == -1 { throw PerfectError.NetworkError(errno, String.fromCString(strerror(errno))!) } } /// Connect to the indicated server socket /// - parameter address: The server socket file. /// - parameter timeoutSeconds: The number of seconds to wait for the connection to complete. A timeout of negative one indicates that there is no timeout. /// - parameter callBack: The closure which will be called when the connection completes. If the connection completes successfully then the current NetNamedPipe instance will be passed to the callback, otherwise, a nil object will be passed. /// - returns: `PerfectError.NetworkError` public func connect(address: String, timeoutSeconds: Double, callBack: (NetNamedPipe?) -> ()) throws { initSocket() let utf8 = address.utf8 let addrLen = sizeof(UInt8) + sizeof(sa_family_t) + utf8.count + 1 let addrPtr = UnsafeMutablePointer<UInt8>.alloc(addrLen) defer { addrPtr.destroy() } var memLoc = 0 addrPtr[memLoc] = UInt8(addrLen) memLoc += 1 addrPtr[memLoc] = UInt8(AF_UNIX) memLoc += 1 for char in utf8 { addrPtr[memLoc] = char memLoc += 1 } addrPtr[memLoc] = 0 #if os(Linux) let cRes = SwiftGlibc.connect(fd.fd, UnsafePointer<sockaddr>(addrPtr), socklen_t(addrLen)) #else let cRes = Darwin.connect(fd.fd, UnsafePointer<sockaddr>(addrPtr), socklen_t(addrLen)) #endif if cRes != -1 { callBack(self) } else { guard errno == EINPROGRESS else { try ThrowNetworkError() } let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: fd.fd, what: EV_WRITE, userData: nil) { (fd:Int32, w:Int16, ud:AnyObject?) -> () in if (Int32(w) & EV_TIMEOUT) != 0 { callBack(nil) } else { callBack(self) } } event.add(timeoutSeconds) } } /// Send the existing opened file descriptor over the connection to the recipient /// - parameter fd: The file descriptor to send /// - parameter callBack: The callback to call when the send completes. The parameter passed will be `true` if the send completed without error. /// - throws: `PerfectError.NetworkError` public func sendFd(fd: Int32, callBack: (Bool) -> ()) throws { let length = sizeof(cmsghdr) + sizeof(Int32) #if os(Linux) let msghdr = UnsafeMutablePointer<SwiftGlibc.msghdr>.alloc(1) #else let msghdr = UnsafeMutablePointer<Darwin.msghdr>.alloc(1) #endif let nothingPtr = UnsafeMutablePointer<iovec>.alloc(1) let nothing = UnsafeMutablePointer<CChar>.alloc(1) let buffer = UnsafeMutablePointer<CChar>.alloc(length) defer { msghdr.destroy() msghdr.dealloc(1) buffer.destroy() buffer.dealloc(length) nothingPtr.destroy() nothingPtr.dealloc(1) nothing.destroy() nothing.dealloc(1) } let cmsg = UnsafeMutablePointer<cmsghdr>(buffer) #if os(Linux) cmsg.memory.cmsg_len = Int(socklen_t(length)) #else cmsg.memory.cmsg_len = socklen_t(length) #endif cmsg.memory.cmsg_level = SOL_SOCKET cmsg.memory.cmsg_type = SCM_RIGHTS let asInts = UnsafeMutablePointer<Int32>(cmsg.advancedBy(1)) asInts.memory = fd nothing.memory = 33 nothingPtr.memory.iov_base = UnsafeMutablePointer<Void>(nothing) nothingPtr.memory.iov_len = 1 msghdr.memory.msg_name = UnsafeMutablePointer<Void>(()) msghdr.memory.msg_namelen = 0 msghdr.memory.msg_flags = 0 msghdr.memory.msg_iov = nothingPtr msghdr.memory.msg_iovlen = 1 msghdr.memory.msg_control = UnsafeMutablePointer<Void>(buffer) #if os(Linux) msghdr.memory.msg_controllen = Int(socklen_t(length)) #else msghdr.memory.msg_controllen = socklen_t(length) #endif let res = sendmsg(Int32(self.fd.fd), msghdr, 0) if res > 0 { callBack(true) } else if res == -1 && errno == EAGAIN { let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: self.fd.fd, what: EV_WRITE, userData: nil) { [weak self] (fd:Int32, w:Int16, ud:AnyObject?) -> () in if (Int32(w) & EV_TIMEOUT) != 0 { callBack(false) } else { do { try self?.sendFd(fd, callBack: callBack) } catch { callBack(false) } } } event.add() } else { try ThrowNetworkError() } } /// Receive an existing opened file descriptor from the sender /// - parameter callBack: The callback to call when the receive completes. The parameter passed will be the received file descriptor or invalidSocket. /// - throws: `PerfectError.NetworkError` public func receiveFd(callBack: (Int32) -> ()) throws { let length = sizeof(cmsghdr) + sizeof(Int32) var msghdrr = msghdr() let nothingPtr = UnsafeMutablePointer<iovec>.alloc(1) let nothing = UnsafeMutablePointer<CChar>.alloc(1) let buffer = UnsafeMutablePointer<CChar>.alloc(length) defer { buffer.destroy() buffer.dealloc(length) nothingPtr.destroy() nothingPtr.dealloc(1) nothing.destroy() nothing.dealloc(1) } nothing.memory = 33 nothingPtr.memory.iov_base = UnsafeMutablePointer<Void>(nothing) nothingPtr.memory.iov_len = 1 msghdrr.msg_iov = UnsafeMutablePointer<iovec>(nothingPtr) msghdrr.msg_iovlen = 1 msghdrr.msg_control = UnsafeMutablePointer<Void>(buffer) #if os(Linux) msghdrr.msg_controllen = Int(socklen_t(length)) #else msghdrr.msg_controllen = socklen_t(length) #endif let cmsg = UnsafeMutablePointer<cmsghdr>(buffer) #if os(Linux) cmsg.memory.cmsg_len = Int(socklen_t(length)) #else cmsg.memory.cmsg_len = socklen_t(length) #endif cmsg.memory.cmsg_level = SOL_SOCKET cmsg.memory.cmsg_type = SCM_RIGHTS let asInts = UnsafeMutablePointer<Int32>(cmsg.advancedBy(1)) asInts.memory = -1 let res = recvmsg(Int32(self.fd.fd), &msghdrr, 0) if res > 0 { let receivedInt = asInts.memory callBack(receivedInt) } else if res == -1 && errno == EAGAIN { let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: self.fd.fd, what: EV_READ, userData: nil) { [weak self] (fd:Int32, w:Int16, ud:AnyObject?) -> () in if (Int32(w) & EV_TIMEOUT) != 0 { callBack(invalidSocket) } else { do { try self?.receiveFd(callBack) } catch { callBack(invalidSocket) } } } event.add() } else { try ThrowNetworkError() } } /// Send the existing & opened `File`'s descriptor over the connection to the recipient /// - parameter file: The `File` whose descriptor to send /// - parameter callBack: The callback to call when the send completes. The parameter passed will be `true` if the send completed without error. /// - throws: `PerfectError.NetworkError` public func sendFile(file: File, callBack: (Bool) -> ()) throws { try self.sendFd(Int32(file.fd), callBack: callBack) } /// Send the existing & opened `NetTCP`'s descriptor over the connection to the recipient /// - parameter file: The `NetTCP` whose descriptor to send /// - parameter callBack: The callback to call when the send completes. The parameter passed will be `true` if the send completed without error. /// - throws: `PerfectError.NetworkError` public func sendFile(file: NetTCP, callBack: (Bool) -> ()) throws { try self.sendFd(file.fd.fd, callBack: callBack) } /// Receive an existing opened `File` descriptor from the sender /// - parameter callBack: The callback to call when the receive completes. The parameter passed will be the received `File` object or nil. /// - throws: `PerfectError.NetworkError` public func receiveFile(callBack: (File?) -> ()) throws { try self.receiveFd { (fd: Int32) -> () in if fd == invalidSocket { callBack(nil) } else { callBack(File(fd: fd, path: "")) } } } /// Receive an existing opened `NetTCP` descriptor from the sender /// - parameter callBack: The callback to call when the receive completes. The parameter passed will be the received `NetTCP` object or nil. /// - throws: `PerfectError.NetworkError` public func receiveNetTCP(callBack: (NetTCP?) -> ()) throws { try self.receiveFd { (fd: Int32) -> () in if fd == invalidSocket { callBack(nil) } else { callBack(NetTCP(fd: fd)) } } } /// Receive an existing opened `NetNamedPipe` descriptor from the sender /// - parameter callBack: The callback to call when the receive completes. The parameter passed will be the received `NetNamedPipe` object or nil. /// - throws: `PerfectError.NetworkError` public func receiveNetNamedPipe(callBack: (NetNamedPipe?) -> ()) throws { try self.receiveFd { (fd: Int32) -> () in if fd == invalidSocket { callBack(nil) } else { callBack(NetNamedPipe(fd: fd)) } } } override func makeFromFd(fd: Int32) -> NetTCP { return NetNamedPipe(fd: fd) } }
agpl-3.0
7d88e7f1a5d47987af512963d8e3e0c0
29.576471
242
0.689419
3.187393
false
false
false
false
marcelobns/Photobooth
PhotoboothiOS/AppDelegate.swift
1
3373
// // Copyright (C) 2015 Twitter, Inc. and other contributors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import Accounts import Fabric import TwitterKit import Crashlytics @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { assert(NSBundle.mainBundle().objectForInfoDictionaryKey("Fabric") != nil, "Welcome to Photobooth. Please remember to onboard using the Fabric Mac app. Check the instructions in the README file.") Fabric.with([Twitter(), Crashlytics()]).debug = true if Twitter.sharedInstance().session() == nil { let storyboard = UIStoryboard(name: "Main", bundle: nil) let authViewController: AnyObject! = storyboard.instantiateViewControllerWithIdentifier("AuthViewController") self.window?.rootViewController = authViewController as? UIViewController } // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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:. } }
mit
9f9e1368f1d5374ab180f30dbfce8f11
48.602941
285
0.732879
5.511438
false
false
false
false
NobodyNada/chatbot
Sources/Frontend/Filters/FilterMisleadingLinks.swift
3
2616
// // FilterMisleadingLinks.swift // FireAlarm // // Created by Ashish Ahuja on 23/04/17. // // import Foundation import SwiftChatSE import SwiftStack import Dispatch import FireAlarmCore class FilterMisleadingLinks: Filter { init() {} func check(post: Post, site: String) -> FilterResult? { do { let regex = try NSRegularExpression(pattern: "<a href=\"([^\"]*)\" rel=\"nofollow(?: noreferrer)?\">\\s*([^<\\s]*)(?=\\s*</a>)", options: [] ) guard let body = post.body else { print("No body for \(post.id.map { String($0) } ?? "<no ID>")!") return nil } #if os(Linux) let nsString = body._bridgeToObjectiveC() #else let nsString = body as NSString #endif for match in regex.matches(in: body, options: [], range: NSMakeRange(0, nsString.length)) { let linkString = nsString.substring(with: match.range(at: 1)) let textString = nsString.substring(with: match.range(at: 2)) guard let link = URL(string: linkString), let text = URL(string: textString), let linkHost = link.host?.lowercased(), let textHost = text.host?.lowercased() else { continue } if (!textHost.isEmpty && textHost != linkHost && !linkHost.contains("rads.stackoverflow.com") && "www." + textHost != linkHost && "www." + linkHost != textHost && linkHost.contains(".") && textHost.contains(".") && !linkHost.trimmingCharacters(in: .whitespaces).contains(" ") && !textHost.trimmingCharacters(in: .whitespaces).contains(" ") && !linkHost.contains("//http") && !textHost.contains("//http")) { return FilterResult( type: .customFilter(filter: self), header: "Misleading link", details: "Link appears to go to `\(textHost)` but actually goes to `\(linkHost)`" ) } } return nil } catch { handleError(error, "while checking for misleading links") return nil } } func save() throws { } }
mit
934ddaf6b551aec98e55f0f6258a2be1
31.7
111
0.460245
4.862454
false
false
false
false
yichizhang/StringScore_Swift
Source/StringScore.swift
1
4259
// // Based on string_score 0.1.21 by Joshaven Potter. // https://github.com/joshaven/string_score/ // // Copyright (c) 2016-present YICHI ZHANG // https://github.com/yichizhang // [email protected] // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // import Foundation private extension String { func charAt(_ i: Int) -> Character { let index = self.index(self.startIndex, offsetBy: i) return self[index] } func charStrAt(_ i: Int) -> String { return String(charAt(i)) } } public extension String { func score(word: String, fuzziness: Double? = nil) -> Double { // If the string is equal to the word, perfect match. if self == word { return 1 } //if it's not a perfect match and is empty return 0 if word.isEmpty || self.isEmpty { return 0 } var runningScore = 0.0 var charScore = 0.0 var finalScore = 0.0 let string = self let lString = string.lowercased() let strLength = lString.count let lWord = word.lowercased() let wordLength = word.count var idxOf: String.Index! var startAt = lString.startIndex var fuzzies = 1.0 var fuzzyFactor = 0.0 var fuzzinessIsNil = true // Cache fuzzyFactor for speed increase if let fuzziness = fuzziness { fuzzyFactor = 1 - fuzziness fuzzinessIsNil = false } for i in 0 ..< wordLength { // Find next first case-insensitive match of word's i-th character. // The search in "string" begins at "startAt". if let range = lString.range( of: lWord.charStrAt(i), options: [.caseInsensitive, .diacriticInsensitive], range: startAt..<lString.endIndex, locale: nil ) { // start index of word's i-th character in string. idxOf = range.lowerBound if startAt == idxOf { // Consecutive letter & start-of-string Bonus charScore = 0.7 } else { charScore = 0.1 // Acronym Bonus // Weighing Logic: Typing the first character of an acronym is as if you // preceded it with two perfect character matches. if lString[lString.index(before: idxOf)] == " " { charScore += 0.8 } } } else { // Character not found. if fuzzinessIsNil { // Fuzziness is nil. Return 0. return 0 } else { fuzzies += fuzzyFactor continue } } // Same case bonus. if (lString[idxOf] == word[word.index(word.startIndex, offsetBy: i)]) { charScore += 0.1 } // Update scores and startAt position for next round of indexOf runningScore += charScore startAt = lString.index(after: idxOf) } // Reduce penalty for longer strings. finalScore = 0.5 * (runningScore / Double(strLength) + runningScore / Double(wordLength)) / fuzzies if (finalScore < 0.85) && (lWord.charStrAt(0).compare(lString.charStrAt(0), options: .diacriticInsensitive) == .orderedSame) { finalScore += 0.15 } return finalScore } }
mit
67276404daf8c2f9d82f1d368d148b02
29.640288
106
0.623855
4.126938
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/Utility/InteractiveNotificationsManager.swift
1
26249
import Foundation import CocoaLumberjack import UserNotifications import WordPressFlux // MARK: - InteractiveNotificationsManager /// In this class, we'll encapsulate all of the code related to UNNotificationCategory and /// UNNotificationAction instantiation, along with the required handlers. /// final class InteractiveNotificationsManager: NSObject { /// Returns the shared InteractiveNotificationsManager instance. /// @objc static let shared = InteractiveNotificationsManager() /// The analytics event tracker. /// private let eventTracker = NotificationEventTracker() /// Returns the Core Data main context. /// @objc var context: NSManagedObjectContext { return ContextManager.sharedInstance().mainContext } /// Returns a CommentService instance. /// @objc var commentService: CommentService { return CommentService(managedObjectContext: context) } /// Returns a NotificationSyncMediator instance. /// var notificationSyncMediator: NotificationSyncMediator? { return NotificationSyncMediator() } /// Registers the device for User Notifications. /// /// This method should be called once during the app initialization process. /// @objc func registerForUserNotifications() { let notificationCenter = UNUserNotificationCenter.current() notificationCenter.delegate = self notificationCenter.setNotificationCategories(supportedNotificationCategories()) } /// Requests authorization to interact with the user when notifications arrive. /// /// The first time this method is called it will ask the user for permission to show notifications. /// Because of this, this should be called only when we know we will need to show notifications (for instance, after login). /// @objc func requestAuthorization(completion: @escaping (_ allowed: Bool) -> Void) { defer { WPAnalytics.track(.pushNotificationOSAlertShown) } let options: UNAuthorizationOptions = [.badge, .sound, .alert, .providesAppNotificationSettings] let notificationCenter = UNUserNotificationCenter.current() notificationCenter.requestAuthorization(options: options) { (allowed, _) in DispatchQueue.main.async { if allowed { WPAnalytics.track(.pushNotificationOSAlertAllowed) } else { WPAnalytics.track(.pushNotificationOSAlertDenied) } } completion(allowed) } } /// Handle an action taken from a remote notification /// /// - Parameters: /// - identifier: The identifier of the action /// - userInfo: The notification's Payload /// /// - Returns: True on success /// @objc @discardableResult func handleAction(with identifier: String, category: String, threadId: String?, userInfo: NSDictionary, responseText: String?) -> Bool { if let noteCategory = NoteCategoryDefinition(rawValue: category), noteCategory.isLocalNotification { return handleLocalNotificationAction(with: identifier, category: category, threadId: threadId, userInfo: userInfo, responseText: responseText) } if NoteActionDefinition.approveLogin == NoteActionDefinition(rawValue: identifier) { return approveAuthChallenge(userInfo) } guard AccountHelper.isDotcomAvailable(), let noteID = userInfo.object(forKey: "note_id") as? NSNumber, let siteID = userInfo.object(forKey: "blog_id") as? NSNumber, let commentID = userInfo.object(forKey: "comment_id") as? NSNumber else { return false } if identifier == UNNotificationDefaultActionIdentifier { showDetailsWithNoteID(noteID) return true } guard let action = NoteActionDefinition(rawValue: identifier) else { return false } var legacyAnalyticsEvent: WPAnalyticsStat? = nil switch action { case .commentApprove: legacyAnalyticsEvent = .notificationsCommentApproved approveCommentWithCommentID(commentID, noteID: noteID, siteID: siteID) case .commentLike: legacyAnalyticsEvent = .notificationsCommentLiked likeCommentWithCommentID(commentID, noteID: noteID, siteID: siteID) case .commentReply: if let responseText = responseText { legacyAnalyticsEvent = .notificationsCommentRepliedTo replyToCommentWithCommentID(commentID, noteID: noteID, siteID: siteID, content: responseText) } else { DDLogError("Tried to reply to a comment notification with no text") } default: break } if let actionEvent = legacyAnalyticsEvent { let modernEventProperties: [String: Any] = [ WPAppAnalyticsKeyQuickAction: action.quickActionName, WPAppAnalyticsKeyBlogID: siteID, WPAppAnalyticsKeyCommentID: commentID ] WPAppAnalytics.track(.pushNotificationQuickActionCompleted, withProperties: modernEventProperties) let legacyEventProperties = [ WPAppAnalyticsKeyLegacyQuickAction: true ] WPAppAnalytics.track(actionEvent, withProperties: legacyEventProperties) } return true } func handleLocalNotificationAction(with identifier: String, category: String, threadId: String?, userInfo: NSDictionary, responseText: String?) -> Bool { if let noteCategory = NoteCategoryDefinition(rawValue: category) { switch noteCategory { case .mediaUploadSuccess, .mediaUploadFailure: if identifier == UNNotificationDefaultActionIdentifier { MediaNoticeNavigationCoordinator.navigateToMediaLibrary(with: userInfo) return true } if let action = NoteActionDefinition(rawValue: identifier) { switch action { case .mediaWritePost: MediaNoticeNavigationCoordinator.presentEditor(with: userInfo) case .mediaRetry: MediaNoticeNavigationCoordinator.retryMediaUploads(with: userInfo) default: break } } case .postUploadSuccess, .postUploadFailure: if identifier == UNNotificationDefaultActionIdentifier { ShareNoticeNavigationCoordinator.navigateToPostList(with: userInfo) return true } if let action = NoteActionDefinition(rawValue: identifier) { switch action { case .postRetry: PostNoticeNavigationCoordinator.retryPostUpload(with: userInfo) case .postView: PostNoticeNavigationCoordinator.presentPostEpilogue(with: userInfo) default: break } } case .shareUploadSuccess: if identifier == UNNotificationDefaultActionIdentifier { ShareNoticeNavigationCoordinator.navigateToPostList(with: userInfo) return true } if let action = NoteActionDefinition(rawValue: identifier) { switch action { case .shareEditPost: ShareNoticeNavigationCoordinator.presentEditor(with: userInfo) default: break } } case .shareUploadFailure: if identifier == UNNotificationDefaultActionIdentifier { ShareNoticeNavigationCoordinator.navigateToBlogDetails(with: userInfo) return true } case .bloggingReminderWeekly: // This event should actually be tracked for all notification types, but in order to implement // the tracking this correctly we'll have to review the other notification_type values to match Android. // https://github.com/wordpress-mobile/WordPress-Android/blob/e3b65c4b1adc0fbc102e640750990d7655d89185/WordPress/src/main/java/org/wordpress/android/push/NotificationType.kt // // Since this task is non-trivial and beyond the scope of my current work, I'll only track this // specific notification type for now in a way that matches Android, but using a mechanism that // is extensible to track other notification types in the future. eventTracker.notificationTapped(type: .bloggingReminders) if identifier == UNNotificationDefaultActionIdentifier { let targetBlog: Blog? = blog(from: threadId) WPTabBarController.sharedInstance()?.mySitesCoordinator.showCreateSheet(for: targetBlog) } case .weeklyRoundup: let targetBlog = blog(from: userInfo) let siteId = targetBlog?.dotComID?.intValue eventTracker.notificationTapped(type: .weeklyRoundup, siteId: siteId) if identifier == UNNotificationDefaultActionIdentifier { guard let targetBlog = targetBlog else { DDLogError("Could not obtain the blog from the Weekly Notification thread ID.") break } let targetDate = date(from: userInfo) WPTabBarController.sharedInstance()?.mySitesCoordinator.showStats( for: targetBlog, timePeriod: .weeks, date: targetDate) } default: break } } return true } } // MARK: - Notifications: Retrieving Stored Data extension InteractiveNotificationsManager { static let blogIDKey = "blogID" static let dateKey = "date" private func blog(from userInfo: NSDictionary) -> Blog? { if let blogID = userInfo[Self.blogIDKey] as? Int { return try? Blog.lookup(withID: blogID, in: ContextManager.shared.mainContext) } return nil } private func blog(from threadId: String?) -> Blog? { if let threadId = threadId, let blogId = Int(threadId) { return try? Blog.lookup(withID: blogId, in: ContextManager.shared.mainContext) } return nil } /// Retrieves a date from the userInfo dictionary using a generic "date" key. This was made generic on purpose. /// private func date(from userInfo: NSDictionary) -> Date? { userInfo[Self.dateKey] as? Date } } // MARK: - Private Helpers // private extension InteractiveNotificationsManager { /// Likes a comment and marks the associated notification as read /// /// - Parameters: /// - commentID: The comment identifier /// - siteID: The site identifier /// func likeCommentWithCommentID(_ commentID: NSNumber, noteID: NSNumber, siteID: NSNumber) { commentService.likeComment(withID: commentID, siteID: siteID, success: { self.notificationSyncMediator?.markAsReadAndSync(noteID.stringValue) DDLogInfo("Liked comment from push notification") }, failure: { error in DDLogInfo("Couldn't like comment from push notification") }) } /// Approves a comment and marks the associated notification as read /// /// - Parameters: /// - commentID: The comment identifier /// - siteID: The site identifier /// func approveCommentWithCommentID(_ commentID: NSNumber, noteID: NSNumber, siteID: NSNumber) { commentService.approveComment(withID: commentID, siteID: siteID, success: { self.notificationSyncMediator?.markAsReadAndSync(noteID.stringValue) DDLogInfo("Successfully moderated comment from push notification") }, failure: { error in DDLogInfo("Couldn't moderate comment from push notification") }) } /// Opens the details for a given notificationId /// /// - Parameter noteID: The Notification's Identifier /// func showDetailsWithNoteID(_ noteId: NSNumber) { WPTabBarController.sharedInstance().showNotificationsTabForNote(withID: noteId.stringValue) } /// Replies to a comment and marks the associated notification as read /// /// - Parameters: /// - commentID: The comment identifier /// - siteID: The site identifier /// - content: The text for the comment reply /// func replyToCommentWithCommentID(_ commentID: NSNumber, noteID: NSNumber, siteID: NSNumber, content: String) { commentService.replyToComment(withID: commentID, siteID: siteID, content: content, success: { self.notificationSyncMediator?.markAsReadAndSync(noteID.stringValue) DDLogInfo("Successfully replied comment from push notification") }, failure: { error in DDLogInfo("Couldn't reply to comment from push notification") }) } /// Returns a collection of *UNNotificationCategory* instances, for each one of the /// supported NoteCategoryDefinition enum case's. /// /// - Returns: A set of *UNNotificationCategory* instances. /// func supportedNotificationCategories() -> Set<UNNotificationCategory> { let categories: [UNNotificationCategory] = NoteCategoryDefinition.allDefinitions.map({ $0.notificationCategory() }) return Set(categories) } /// Handles approving an 2fa authentication challenge. /// /// - Parameter userInfo: The notification's Payload /// - Returns: True if successfule. Otherwise false. /// func approveAuthChallenge(_ userInfo: NSDictionary) -> Bool { return PushNotificationsManager.shared.handleAuthenticationApprovedAction(userInfo) } } // MARK: - Nested Types // extension InteractiveNotificationsManager { /// Describes information about Custom Actions that WPiOS can perform, as a response to /// a Push Notification event. /// enum NoteCategoryDefinition: String { case commentApprove = "approve-comment" case commentLike = "like-comment" case commentReply = "replyto-comment" case commentReplyWithLike = "replyto-like-comment" case mediaUploadSuccess = "media-upload-success" case mediaUploadFailure = "media-upload-failure" case postUploadSuccess = "post-upload-success" case postUploadFailure = "post-upload-failure" case shareUploadSuccess = "share-upload-success" case shareUploadFailure = "share-upload-failure" case login = "push_auth" case bloggingReminderWeekly = "blogging-reminder-weekly" case weeklyRoundup = "weekly-roundup" var actions: [NoteActionDefinition] { switch self { case .commentApprove: return [.commentApprove] case .commentLike: return [.commentLike] case .commentReply: return [.commentReply] case .commentReplyWithLike: return [.commentReply, .commentLike] case .mediaUploadSuccess: return [.mediaWritePost] case .mediaUploadFailure: return [.mediaRetry] case .postUploadSuccess: return [.postView] case .postUploadFailure: return [.postRetry] case .shareUploadSuccess: return [.shareEditPost] case .shareUploadFailure: return [] case .login: return [.approveLogin, .denyLogin] case .bloggingReminderWeekly: return [] case .weeklyRoundup: return [] } } var identifier: String { return rawValue } var isLocalNotification: Bool { return NoteCategoryDefinition.localDefinitions.contains(self) } func notificationCategory() -> UNNotificationCategory { return UNNotificationCategory( identifier: identifier, actions: actions.map({ $0.notificationAction() }), intentIdentifiers: [], options: []) } static var allDefinitions = [commentApprove, commentLike, commentReply, commentReplyWithLike, mediaUploadSuccess, mediaUploadFailure, postUploadSuccess, postUploadFailure, shareUploadSuccess, shareUploadFailure, login, bloggingReminderWeekly] static var localDefinitions = [mediaUploadSuccess, mediaUploadFailure, postUploadSuccess, postUploadFailure, shareUploadSuccess, shareUploadFailure, bloggingReminderWeekly, weeklyRoundup] } /// Describes the custom actions that WPiOS can perform in response to a Push notification. /// enum NoteActionDefinition: String { case commentApprove = "COMMENT_MODERATE_APPROVE" case commentLike = "COMMENT_LIKE" case commentReply = "COMMENT_REPLY" case mediaWritePost = "MEDIA_WRITE_POST" case mediaRetry = "MEDIA_RETRY" case postRetry = "POST_RETRY" case postView = "POST_VIEW" case shareEditPost = "SHARE_EDIT_POST" case approveLogin = "APPROVE_LOGIN_ATTEMPT" case denyLogin = "DENY_LOGIN_ATTEMPT" var description: String { switch self { case .commentApprove: return NSLocalizedString("Approve", comment: "Approve comment (verb)") case .commentLike: return NSLocalizedString("Like", comment: "Like (verb)") case .commentReply: return NSLocalizedString("Reply", comment: "Reply to a comment (verb)") case .mediaWritePost: return NSLocalizedString("Write Post", comment: "Opens the editor to write a new post.") case .mediaRetry: return NSLocalizedString("Retry", comment: "Opens the media library .") case .postRetry: return NSLocalizedString("Retry", comment: "Retries the upload of a user's post.") case .postView: return NSLocalizedString("View", comment: "Opens the post epilogue screen to allow sharing / viewing of a post.") case .shareEditPost: return NSLocalizedString("Edit Post", comment: "Opens the editor to edit an existing post.") case .approveLogin: return NSLocalizedString("Approve", comment: "Verb. Approves a 2fa authentication challenge, and logs in a user.") case .denyLogin: return NSLocalizedString("Deny", comment: "Verb. Denies a 2fa authentication challenge.") } } var destructive: Bool { return false } var identifier: String { return rawValue } var requiresAuthentication: Bool { return false } var requiresForeground: Bool { switch self { case .mediaWritePost, .mediaRetry, .postView, .shareEditPost: return true default: return false } } var notificationActionOptions: UNNotificationActionOptions { var options = UNNotificationActionOptions() if requiresAuthentication { options.insert(.authenticationRequired) } if destructive { options.insert(.destructive) } if requiresForeground { options.insert(.foreground) } return options } func notificationAction() -> UNNotificationAction { switch self { case .commentReply: return UNTextInputNotificationAction(identifier: identifier, title: description, options: notificationActionOptions, textInputButtonTitle: NSLocalizedString("Reply", comment: "Verb. Button title. Reply to a comment."), textInputPlaceholder: NSLocalizedString("Write a reply…", comment: "Placeholder text for inline compose view")) default: return UNNotificationAction(identifier: identifier, title: description, options: notificationActionOptions) } } /// Quick action analytics support. Returns either a quick action name (if defined) or an empty string. /// NB: This maintains parity with Android. /// var quickActionName: String { switch self { case .commentApprove: return "approve" case .commentLike: return "like" case .commentReply: return "reply-to" default: return "" } } static var allDefinitions = [commentApprove, commentLike, commentReply, mediaWritePost, mediaRetry, postRetry, postView, shareEditPost, approveLogin, denyLogin] } } // MARK: - UNUserNotificationCenterDelegate Conformance // extension InteractiveNotificationsManager: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Swift.Void) { let userInfo = notification.request.content.userInfo as NSDictionary // If the app is open, and a Zendesk view is being shown, Zendesk will display an alert allowing the user to view the updated ticket. handleZendeskNotification(userInfo: userInfo) // Otherwise see if it's an auth notification if PushNotificationsManager.shared.handleAuthenticationNotification(userInfo, userInteraction: true, completionHandler: nil) { return } // If it's a blogging reminder notification, display it in-app if notification.request.content.categoryIdentifier == NoteCategoryDefinition.bloggingReminderWeekly.rawValue || notification.request.content.categoryIdentifier == NoteCategoryDefinition.weeklyRoundup.rawValue { if #available(iOS 14.0, *) { completionHandler([.banner, .list, .sound]) } else { completionHandler([.alert, .sound]) } return } // Otherwise a share notification let category = notification.request.content.categoryIdentifier guard (category == ShareNoticeConstants.categorySuccessIdentifier || category == ShareNoticeConstants.categoryFailureIdentifier), (userInfo.object(forKey: ShareNoticeUserInfoKey.originatedFromAppExtension) as? Bool) == true, let postUploadOpID = userInfo.object(forKey: ShareNoticeUserInfoKey.postUploadOpID) as? String else { return } // If the notification orginated from the share extension, disregard this current notification and resend a new one. ShareExtensionSessionManager.fireUserNotificationIfNeeded(postUploadOpID) completionHandler([]) } private func handleZendeskNotification(userInfo: NSDictionary) { if let type = userInfo.string(forKey: ZendeskUtils.PushNotificationIdentifiers.key), type == ZendeskUtils.PushNotificationIdentifiers.type { ZendeskUtils.handlePushNotification(userInfo) } } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo as NSDictionary let textInputResponse = response as? UNTextInputNotificationResponse // Analytics PushNotificationsManager.shared.trackNotification(with: userInfo) if handleAction(with: response.actionIdentifier, category: response.notification.request.content.categoryIdentifier, threadId: response.notification.request.content.threadIdentifier, userInfo: userInfo, responseText: textInputResponse?.userText) { completionHandler() return } // TODO: // ===== // Refactor both PushNotificationsManager + InteractiveNotificationsManager: // // - InteractiveNotificationsManager should no longer be a singleton. Perhaps we could convert it into a struct. // Plus int should probably be renamed into something more meaningful (and match the new framework's naming) // - New `NotificationsManager` class: // - Would inherit `PushNotificationsManager.handleNotification` // - Would deal with UserNotifications.framework // - Would use InteractiveNotificationsManager! // - Nuke `PushNotificationsManager` // // PushNotificationsManager.shared.handleNotification(userInfo, userInteraction: true) { _ in completionHandler() } } func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) { MeNavigationAction.notificationSettings.perform(router: UniversalLinkRouter.shared) } }
gpl-2.0
4713d213dff7a25d433bac3c21b06b04
40.794586
250
0.6219
5.776188
false
false
false
false
LeeShiYoung/LSYWeibo
Pods/ALCameraViewController/ALCameraViewController/Views/ImageCell.swift
1
2675
// // ImageCell.swift // ALImagePickerViewController // // Created by Alex Littlejohn on 2015/06/09. // Copyright (c) 2015 zero. All rights reserved. // import UIKit import Photos private let w:CGFloat = 30.0 protocol ImageCellDelegate: NSObjectProtocol { func selectAsset(tag: Int) func removeAsset(tag: Int) } class ImageCell: UICollectionViewCell { weak var delegate: ImageCellDelegate? let imageView : UIImageView = { let imageView = UIImageView() imageView.contentMode = .ScaleAspectFill imageView.layer.masksToBounds = true imageView.image = UIImage(named: "placeholder", inBundle: CameraGlobals.shared.bundle, compatibleWithTraitCollection: nil) return imageView }() override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(imageView) contentView.addSubview(selectBtn) selectBtn.frame = CGRect(x: contentView.frame.width - w - 2, y: 2, width: w, height: w) } // MARK: - action @objc private func selectPicture(btn: UIButton) { btn.selected = !btn.selected btn.selected ? delegate?.selectAsset(btn.tag-2000) : delegate?.removeAsset(btn.tag-2000-1) } lazy var selectBtn: UIButton = { let btn = UIButton() btn.setImage(UIImage(named: "compose_guide_check_box_default"), forState: UIControlState.Normal) btn.setImage(UIImage(named: "compose_photo_preview_right"), forState: UIControlState.Selected) btn.addTarget(self, action: #selector(ImageCell.selectPicture(_:)), forControlEvents: UIControlEvents.TouchUpInside) return btn }() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() imageView.frame = bounds } override func prepareForReuse() { super.prepareForReuse() imageView.image = UIImage(named: "placeholder", inBundle: CameraGlobals.shared.bundle, compatibleWithTraitCollection: nil) } func configureWithModel(model: PHAsset) { if tag != 0 { PHImageManager.defaultManager().cancelImageRequest(PHImageRequestID(tag)) } tag = Int(PHImageManager.defaultManager().requestImageForAsset(model, targetSize: contentView.bounds.size, contentMode: .AspectFill, options: nil) { image, info in self.imageView.image = image }) } }
artistic-2.0
24214322bae2664a23cd4e21957990c9
30.104651
171
0.620187
4.908257
false
false
false
false
zhouwude/KeyboardMan
Messages/ViewController.swift
2
6819
// // ViewController.swift // Messages // // Created by NIX on 15/7/25. // Copyright (c) 2015年 nixWork. All rights reserved. // import UIKit import KeyboardMan class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var toolBar: UIView! @IBOutlet weak var toolBarBottomConstraint: NSLayoutConstraint! @IBOutlet weak var textField: UITextField! var messages: [String] = [ "How do you do?", ] let cellID = "cell" let keyboardMan = KeyboardMan() override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = 60 tableView.contentInset.bottom = toolBar.frame.height tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellID) tableView.tableFooterView = UIView() keyboardMan.animateWhenKeyboardAppear = { [weak self] appearPostIndex, keyboardHeight, keyboardHeightIncrement in print("appear \(appearPostIndex), \(keyboardHeight), \(keyboardHeightIncrement)\n") if let strongSelf = self { strongSelf.tableView.contentOffset.y += keyboardHeightIncrement strongSelf.tableView.contentInset.bottom = keyboardHeight + strongSelf.toolBar.frame.height strongSelf.toolBarBottomConstraint.constant = keyboardHeight strongSelf.view.layoutIfNeeded() } } keyboardMan.animateWhenKeyboardDisappear = { [weak self] keyboardHeight in print("disappear \(keyboardHeight)\n") if let strongSelf = self { strongSelf.tableView.contentOffset.y -= keyboardHeight strongSelf.tableView.contentInset.bottom = strongSelf.toolBar.frame.height strongSelf.toolBarBottomConstraint.constant = 0 strongSelf.view.layoutIfNeeded() } } keyboardMan.postKeyboardInfo = { keyboardMan, keyboardInfo in switch keyboardInfo.action { case .Show: print("show \(keyboardMan.appearPostIndex), \(keyboardInfo.height), \(keyboardInfo.heightIncrement)\n") case .Hide: print("hide \(keyboardInfo.height)\n") } /* if let strongSelf = self { let duration = keyboardInfo.animationDuration let curve = keyboardInfo.animationCurve let options = UIViewAnimationOptions(rawValue: curve << 16 | UIViewAnimationOptions.BeginFromCurrentState.rawValue) switch keyboardInfo.action { case .Show: print("show \(keyboardMan.appearPostIndex), \(keyboardInfo.height), \(keyboardInfo.heightIncrement)\n") UIView.animateWithDuration(duration, delay: 0, options: options, animations: { strongSelf.tableView.contentOffset.y += keyboardInfo.heightIncrement strongSelf.tableView.contentInset.bottom = keyboardInfo.height + strongSelf.toolBar.frame.height strongSelf.toolBarBottomConstraint.constant = keyboardInfo.height strongSelf.view.layoutIfNeeded() }, completion: nil) case .Hide: print("hide \(keyboardInfo.height)\n") UIView.animateWithDuration(duration, delay: 0, options: options, animations: { strongSelf.tableView.contentOffset.y -= keyboardInfo.height strongSelf.tableView.contentInset.bottom = strongSelf.toolBar.frame.height strongSelf.toolBarBottomConstraint.constant = 0 strongSelf.view.layoutIfNeeded() }, completion: nil) } } */ } } // MARK: - Actions func sendMessage(textField: UITextField) { guard let message = textField.text else { return } if message.isEmpty { return } // update data source messages.append(message) // insert new row let indexPath = NSIndexPath(forRow: messages.count - 1, inSection: 0) tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) // scroll up a little bit if need let newMessageHeight: CGFloat = tableView.rowHeight let blockedHeight = statusBarHeight + navigationBarHeight + toolBar.frame.height + toolBarBottomConstraint.constant let visibleHeight = tableView.frame.height - blockedHeight let hiddenHeight = tableView.contentSize.height - visibleHeight if hiddenHeight + newMessageHeight > 0 { let contentOffsetYIncrement = hiddenHeight > 0 ? newMessageHeight : hiddenHeight + newMessageHeight print("contentOffsetYIncrement: \(contentOffsetYIncrement)\n") UIView.animateWithDuration(0.2) { self.tableView.contentOffset.y += contentOffsetYIncrement } } // clear text textField.text = "" } } // MARK: - Bar heights extension UIViewController { var statusBarHeight: CGFloat { if let window = view.window { let statusBarFrame = window.convertRect(UIApplication.sharedApplication().statusBarFrame, toView: view) return statusBarFrame.height } else { return 0 } } var navigationBarHeight: CGFloat { if let navigationController = navigationController { return navigationController.navigationBar.frame.height } else { return 0 } } } // MARK: - UITextFieldDelegate extension ViewController: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { sendMessage(textField) return true } } // MARK: - UITableViewDataSource, UITableViewDelegate extension ViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellID)! let message = messages[indexPath.row] cell.textLabel?.text = "\(indexPath.row + 1): " + message return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) textField.resignFirstResponder() } }
mit
35b23d2bdabd2cbb8f2e76e2d4e8f007
28.510823
131
0.630043
5.747892
false
false
false
false
powerytg/Accented
Accented/UI/Common/Components/Stream/Headerless/HeaderlessStreamViewModel.swift
1
2770
// // HeaderlessStreamViewModel.swift // Accented // // Generic photo stream without header, rendering photos in group style // // Created by Tiangong You on 8/25/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit class HeaderlessStreamViewModel: StreamViewModel, PhotoRendererDelegate { private let cardRendererReuseIdentifier = "renderer" required init(stream : StreamModel, collectionView : UICollectionView, flowLayoutDelegate: UICollectionViewDelegateFlowLayout) { super.init(stream: stream, collectionView: collectionView, flowLayoutDelegate: flowLayoutDelegate) } override func registerCellTypes() { collectionView.register(DefaultStreamPhotoCell.self, forCellWithReuseIdentifier: cardRendererReuseIdentifier) } override func createCollectionViewLayout() { layout = HeaderlessStreamLayout() layout.footerReferenceSize = CGSize(width: 50, height: 50) } override func createLayoutTemplateGenerator(_ maxWidth: CGFloat) -> StreamTemplateGenerator { return PhotoGroupTemplateGenarator(maxWidth: maxWidth) } // MARK: - UICollectionViewDelegateFlowLayout override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if !collection.loaded { let loadingCell = collectionView.dequeueReusableCell(withReuseIdentifier: initialLoadingRendererReuseIdentifier, for: indexPath) return loadingCell } else { let group = photoGroups[(indexPath as NSIndexPath).section] let photo = group[(indexPath as NSIndexPath).item] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cardRendererReuseIdentifier, for: indexPath) as! DefaultStreamPhotoCell cell.photo = photo cell.renderer.delegate = self cell.setNeedsLayout() return cell } } override func numberOfSections(in collectionView: UICollectionView) -> Int { if !collection.loaded { return 1 } else { return photoGroups.count } } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if !collection.loaded { return 1 } else { return photoGroups[section].count } } // MARK: - PhotoRendererDelegate func photoRendererDidReceiveTap(_ renderer: PhotoRenderer) { let navContext = DetailNavigationContext(selectedPhoto: renderer.photo!, sourceImageView: renderer.imageView) NavigationService.sharedInstance.navigateToDetailPage(navContext) } }
mit
a8ed7070af0f08102c288efc63718dba
36.418919
150
0.693391
5.605263
false
false
false
false
MidnightPulse/Tabman
Carthage/Checkouts/Pageboy/Sources/PageboyTests/PageboyPropertyTests.swift
1
1373
// // PageboyPropertyTests.swift // Pageboy // // Created by Merrick Sapsford on 22/03/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import XCTest @testable import Pageboy class PageboyPropertyTests: PageboyTests { /// Test that currentViewController property returns correct view controller. func testCorrectCurrentViewControllerReported() { self.dataSource.numberOfPages = 5 self.pageboyViewController.dataSource = self.dataSource self.pageboyViewController.scrollToPage(.next, animated: false) let currentViewController = self.pageboyViewController.currentViewController XCTAssertTrue(currentViewController === self.dataSource.viewControllers[1], "currentViewController property is incorrect following transitions.") } /// Test that setting isScrollEnabled updates internal scroll view correctly. func testIsScrollEnabledUpdates() { self.dataSource.numberOfPages = 5 self.pageboyViewController.dataSource = self.dataSource self.pageboyViewController.isScrollEnabled = false XCTAssertTrue(self.pageboyViewController.pageViewController.scrollView?.isScrollEnabled == false, "isScrollEnabled does not update the internal scrollView correctly.") } }
mit
f0d0380682c1ce8dbb82e769ff5c23f5
36.081081
105
0.710641
6.18018
false
true
false
false
vector-im/vector-ios
Riot/Modules/Room/Views/RemoveJitsiWidget/ArrowsAnimationView.swift
1
4018
// // Copyright 2021 New Vector Ltd // // 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 class ArrowsAnimationView: UIView { private enum Constants { static let numberOfArrows: Int = 3 static let arrowSize: CGSize = CGSize(width: 14, height: 14) static let gradientAnimationKey: String = "gradient" static let gradientRatios: [CGFloat] = [1.0, 0.3, 0.2] } private var gradientLayer: CAGradientLayer! private lazy var gradientAnimation: CABasicAnimation = { let animation = CABasicAnimation(keyPath: "locations") animation.fromValue = [0.0, 0.0, 0.25] animation.toValue = [0.75, 1.0, 1.0] animation.repeatCount = .infinity animation.duration = 1 return animation }() private var theme: Theme = ThemeService.shared().theme private var arrowImageViews: [UIImageView] = [] override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } private func setup() { let arrowImage = Asset.Images.disclosureIcon.image for i in 0..<Constants.numberOfArrows { let totalSpace = frame.width - CGFloat(Constants.numberOfArrows) * Constants.arrowSize.width let oneSpace = totalSpace / CGFloat(Constants.numberOfArrows - 1) let x = CGFloat(i) * (oneSpace + Constants.arrowSize.width) let y = (frame.height - Constants.arrowSize.height) / 2 let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: x, y: y), size: Constants.arrowSize)) imageView.contentMode = .scaleAspectFit imageView.tintColor = theme.tabBarUnselectedItemTintColor imageView.image = arrowImage addSubview(imageView) arrowImageViews.append(imageView) } gradientLayer = CAGradientLayer() gradientLayer.frame = bounds gradientLayer.locations = [0.25, 0.5, 0.75] gradientLayer.startPoint = CGPoint(x: 0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 1, y: 0.5) // this color doesn't have to come from the theme, it's only used as a mask let color = UIColor.black let colors = Constants.gradientRatios.map({ color.withAlphaComponent($0) }) gradientLayer.colors = colors.map({ $0.cgColor }) layer.mask = gradientLayer } override func layoutSubviews() { super.layoutSubviews() gradientLayer.frame = bounds } // MARK: - API var isAnimating: Bool = false { didSet { if isAnimating { if gradientLayer.animation(forKey: Constants.gradientAnimationKey) == nil { gradientLayer.add(gradientAnimation, forKey: Constants.gradientAnimationKey) } } else { if gradientLayer.animation(forKey: Constants.gradientAnimationKey) != nil { gradientLayer.removeAnimation(forKey: Constants.gradientAnimationKey) } } } } } // MARK: - Themable extension ArrowsAnimationView: Themable { func update(theme: Theme) { self.theme = theme arrowImageViews.forEach({ $0.tintColor = theme.tabBarUnselectedItemTintColor }) } }
apache-2.0
63c924261f7a67195a3f84be841067fa
34.245614
104
0.614485
4.732627
false
false
false
false
stardust139/ios-charts
Charts/Classes/Renderers/ChartXAxisRendererBarChart.swift
1
5515
// // ChartXAxisRendererBarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class ChartXAxisRendererBarChart: ChartXAxisRenderer { internal weak var _chart: BarChartView! public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer) self._chart = chart } /// draws the x-labels on the specified y-position internal override func drawLabels(context context: CGContext, pos: CGFloat) { if (_chart.data === nil) { return } let paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle paraStyle.alignment = .Center let labelAttrs = [NSFontAttributeName: _xAxis.labelFont, NSForegroundColorAttributeName: _xAxis.labelTextColor, NSParagraphStyleAttributeName: paraStyle] let barData = _chart.data as! BarChartData let step = barData.dataSetCount let valueToPixelMatrix = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) var labelMaxSize = CGSize() if (_xAxis.isWordWrapEnabled) { labelMaxSize.width = _xAxis.wordWrapWidthPercent * valueToPixelMatrix.a } for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus) { let label = i >= 0 && i < _xAxis.values.count ? _xAxis.values[i] : nil if (label == nil) { continue } position.x = CGFloat(i * step) + CGFloat(i) * barData.groupSpace + barData.groupSpace / 2.0 position.y = 0.0 // consider groups (center label for each group) if (step > 1) { position.x += (CGFloat(step) - 1.0) / 2.0 } position = CGPointApplyAffineTransform(position, valueToPixelMatrix) if (viewPortHandler.isInBoundsX(position.x)) { if (_xAxis.isAvoidFirstLastClippingEnabled) { // avoid clipping of the last if (i == _xAxis.values.count - 1) { let width = label!.sizeWithAttributes(labelAttrs).width if (position.x + width / 2.0 > viewPortHandler.contentRight) { position.x = viewPortHandler.contentRight - (width / 2.0) } } else if (i == 0) { // avoid clipping of the first let width = label!.sizeWithAttributes(labelAttrs).width if (position.x - width / 2.0 < viewPortHandler.contentLeft) { position.x = viewPortHandler.contentLeft + (width / 2.0) } } } drawLabel(context: context, label: label!, xIndex: i, x: position.x, y: pos, align: .Center, attributes: labelAttrs, constrainedToSize: labelMaxSize) } } } private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderGridLines(context context: CGContext) { if (!_xAxis.isDrawGridLinesEnabled || !_xAxis.isEnabled) { return } let barData = _chart.data as! BarChartData let step = barData.dataSetCount CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor) CGContextSetLineWidth(context, _xAxis.gridLineWidth) if (_xAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let valueToPixelMatrix = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for (var i = _minX; i < _maxX; i += _xAxis.axisLabelModulus) { position.x = CGFloat(i * step) + CGFloat(i) * barData.groupSpace - 0.5 position.y = 0.0 position = CGPointApplyAffineTransform(position, valueToPixelMatrix) if (viewPortHandler.isInBoundsX(position.x)) { _gridLineSegmentsBuffer[0].x = position.x _gridLineSegmentsBuffer[0].y = viewPortHandler.contentTop _gridLineSegmentsBuffer[1].x = position.x _gridLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2) } } CGContextRestoreGState(context) } }
apache-2.0
4a015dc11736d38d7cb381fda0530de6
34.818182
165
0.549773
5.454995
false
false
false
false
iceVeryCold/DouYuZhiBo
DYDemo/DYDemo/Classes/Main/Model/AnchorGroup.swift
1
1105
// // AnchorGroup.swift // DYDemo // // Created by 这个夏天有点冷 on 2017/3/17. // Copyright © 2017年 YLT. All rights reserved. // import UIKit class AnchorGroup: NSObject { /// 该组中对应的房间信息 var room_list : [[String : NSObject]]? { didSet{ // 需要查看了解 guard let room_list = room_list else { return } for dict in room_list { anchors.append(AnchorModel.init(dic: dict)) } } } /// 组显示的标题 var tag_name : String = "" /// 组显示的图标 var icon_name : String = "home_header_normal" /// 游戏对应的图标 var icon_url : String = "" /// 定义主播的模型对象数组 lazy var anchors : [AnchorModel] = [AnchorModel]() // MARK:- 构造函数 override init() { } // MARK:- 重载 init(dict : [String : NSObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
mit
078986d48e7c1d432f11099c1868cb08
19.081633
72
0.517276
3.784615
false
false
false
false