repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 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
my-mail-ru/swiftperl
Sources/Perl/Util.swift
1
211
func isStrictSubclass(_ child: AnyClass, of parent: AnyClass) -> Bool { var cur: AnyClass = child while let next = _getSuperclass(cur) { cur = next if cur == parent { return true } } return false }
mit
58026b8cdf48f354bd674df2bb01cd07
20.1
71
0.658768
3.246154
false
false
false
false
superk589/CGSSGuide
DereGuide/Toolbox/EventInfo/Model/EventTrend.swift
2
3957
// // EventTrend.swift // DereGuide // // Created by zzk on 2017/4/2. // Copyright © 2017 zzk. All rights reserved. // import Foundation import SwiftyJSON extension EventTrend { var date: Date { return startDate.toDate() } var dateString: String { return DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .none) } } class EventTrend : NSObject, NSCoding { var endDate : String! var eventId : Int! var id : Int! var liveDataIds : [Int]! var startDate : String! lazy var lives: [CGSSLive] = { return self.liveDataIds.compactMap { var result: CGSSLive? let semaphore = DispatchSemaphore.init(value: 0) CGSSGameResource.shared.master.getLives(liveId: $0, callback: { (lives) in result = lives.first semaphore.signal() }) semaphore.wait() return result } }() // lazy var lives: [CGSSLive] = { // self.liveDataIds. // var results = [CGSSLive]() // let group = DispatchGroup.init() // for liveId in self.liveDataIds { // group.enter() // CGSSGameResource.shared.master.getLives(liveId: liveId, callback: { (lives) in // results.append(contentsOf: lives) // group.leave() // }) // } // // group.wait() // return results // }() /** * Instantiate the instance using the passed json values to set the properties values */ init(fromJson json: JSON!) { if json.isEmpty { return } endDate = json["end_date"].stringValue eventId = json["event_id"].intValue id = json["id"].intValue self.liveDataIds = [Int]() var i = 1 while json["live_data_id_\(i)"] != JSON.null { self.liveDataIds.append(json["live_data_id_\(i)"].intValue) i += 1 } startDate = json["start_date"].stringValue } /** * Returns all the available property values in the form of NSDictionary object where the key is the approperiate json key and the value is the value of the corresponding property */ func toDictionary() -> NSDictionary { let dictionary = NSMutableDictionary() if endDate != nil { dictionary["end_date"] = endDate } if eventId != nil { dictionary["event_id"] = eventId } if id != nil { dictionary["id"] = id } if liveDataIds != nil { dictionary["live_data_ids"] = liveDataIds } if startDate != nil { dictionary["start_date"] = startDate } return dictionary } /** * NSCoding required initializer. * Fills the data from the passed decoder */ required init(coder aDecoder: NSCoder) { endDate = aDecoder.decodeObject(forKey: "end_date") as? String eventId = aDecoder.decodeObject(forKey: "event_id") as? Int id = aDecoder.decodeObject(forKey: "id") as? Int liveDataIds = aDecoder.decodeObject(forKey: "live_data_ids") as? [Int] startDate = aDecoder.decodeObject(forKey: "start_date") as? String } /** * NSCoding required method. * Encodes mode properties into the decoder */ func encode(with aCoder: NSCoder) { if endDate != nil{ aCoder.encode(endDate, forKey: "end_date") } if eventId != nil{ aCoder.encode(eventId, forKey: "event_id") } if id != nil{ aCoder.encode(id, forKey: "id") } if liveDataIds != nil{ aCoder.encode(liveDataIds, forKey: "live_data_ids") } if startDate != nil{ aCoder.encode(startDate, forKey: "start_date") } } }
mit
c849c376c30a5397af26d55691ceaf3a
27.460432
183
0.545248
4.332968
false
false
false
false
esttorhe/eidolon
Kiosk/App/Networking/ArtsyAPI.swift
2
12621
import Foundation import ReactiveCocoa import Moya enum ArtsyAPI { case XApp case XAuth(email: String, password: String) case TrustToken(number: String, auctionPIN: String) case SystemTime case Ping case Me case MyCreditCards case CreatePINForBidder(bidderID: String) case FindBidderRegistration(auctionID: String, phone: String) case RegisterToBid(auctionID: String) case Artwork(id: String) case Artist(id: String) case Auctions case AuctionListings(id: String, page: Int, pageSize: Int) case AuctionInfo(auctionID: String) case AuctionInfoForArtwork(auctionID: String, artworkID: String) case ActiveAuctions case MyBiddersForAuction(auctionID: String) case MyBidPositionsForAuctionArtwork(auctionID: String, artworkID: String) case PlaceABid(auctionID: String, artworkID: String, maxBidCents: String) case UpdateMe(email: String, phone: String, postCode: String, name: String) case CreateUser(email: String, password: String, phone: String, postCode: String, name: String) case RegisterCard(stripeToken: String) case BidderDetailsNotification(auctionID: String, identifier: String) case LostPasswordNotification(email: String) case FindExistingEmailRegistration(email: String) } extension ArtsyAPI : MoyaTarget { var path: String { switch self { case .XApp: return "/api/v1/xapp_token" case .XAuth: return "/oauth2/access_token" case AuctionInfo(let id): return "/api/v1/sale/\(id)" case Auctions: return "/api/v1/sales" case AuctionListings(let id, _, _): return "/api/v1/sale/\(id)/sale_artworks" case AuctionInfoForArtwork(let auctionID, let artworkID): return "/api/v1/sale/\(auctionID)/sale_artwork/\(artworkID)" case SystemTime: return "/api/v1/system/time" case Ping: return "/api/v1/system/ping" case RegisterToBid: return "/api/v1/bidder" case MyCreditCards: return "/api/v1/me/credit_cards" case CreatePINForBidder(let bidderID): return "/api/v1/bidder/\(bidderID)/pin" case ActiveAuctions: return "/api/v1/sales" case Me: return "/api/v1/me" case UpdateMe: return "/api/v1/me" case CreateUser: return "/api/v1/user" case MyBiddersForAuction: return "/api/v1/me/bidders" case MyBidPositionsForAuctionArtwork: return "/api/v1/me/bidder_positions" case Artwork(let id): return "/api/v1/artwork/\(id)" case Artist(let id): return "/api/v1/artist/\(id)" case FindBidderRegistration: return "/api/v1/bidder" case PlaceABid: return "/api/v1/me/bidder_position" case RegisterCard: return "/api/v1/me/credit_cards" case TrustToken: return "/api/v1/me/trust_token" case BidderDetailsNotification: return "/api/v1/bidder/bidding_details_notification" case LostPasswordNotification: return "/api/v1/users/send_reset_password_instructions" case FindExistingEmailRegistration: return "/api/v1/user" } } var base: String { return AppSetup.sharedState.useStaging ? "https://stagingapi.artsy.net" : "https://api.artsy.net" } var baseURL: NSURL { return NSURL(string: base)! } var parameters: [String: AnyObject] { switch self { case XAuth(let email, let password): return [ "client_id": APIKeys.sharedKeys.key ?? "", "client_secret": APIKeys.sharedKeys.secret ?? "", "email": email, "password": password, "grant_type": "credentials" ] case XApp: return ["client_id": APIKeys.sharedKeys.key ?? "", "client_secret": APIKeys.sharedKeys.secret ?? ""] case Auctions: return ["is_auction": "true"] case RegisterToBid(let auctionID): return ["sale_id": auctionID] case MyBiddersForAuction(let auctionID): return ["sale_id": auctionID] case PlaceABid(let auctionID, let artworkID, let maxBidCents): return [ "sale_id": auctionID, "artwork_id": artworkID, "max_bid_amount_cents": maxBidCents ] case TrustToken(let number, let auctionID): return ["number": number, "auction_pin": auctionID] case CreateUser(let email, let password,let phone,let postCode, let name): return [ "email": email, "password": password, "phone": phone, "name": name, "location": [ "postal_code": postCode ] ] case UpdateMe(let email, let phone,let postCode, let name): return [ "email": email, "phone": phone, "name": name, "location": [ "postal_code": postCode ] ] case RegisterCard(let token): return ["provider": "stripe", "token": token] case FindBidderRegistration(let auctionID, let phone): return ["sale_id": auctionID, "number": phone] case BidderDetailsNotification(let auctionID, let identifier): return ["sale_id": auctionID, "identifier": identifier] case LostPasswordNotification(let email): return ["email": email] case FindExistingEmailRegistration(let email): return ["email": email] case AuctionListings(_, let page, let pageSize): return ["size": pageSize, "page": page] case ActiveAuctions: return ["is_auction": true, "live": true] case MyBidPositionsForAuctionArtwork(let auctionID, let artworkID): return ["sale_id": auctionID, "artwork_id": artworkID] default: return [:] } } var method: Moya.Method { switch self { case .LostPasswordNotification, .CreateUser, .PlaceABid, .RegisterCard, .RegisterToBid, .CreatePINForBidder: return .POST case .FindExistingEmailRegistration: return .HEAD case .UpdateMe, .BidderDetailsNotification: return .PUT default: return .GET } } var sampleData: NSData { switch self { case XApp: return stubbedResponse("XApp") case XAuth: return stubbedResponse("XAuth") case TrustToken: return stubbedResponse("XAuth") case Auctions: return stubbedResponse("Auctions") case AuctionListings: return stubbedResponse("AuctionListings") case SystemTime: return stubbedResponse("SystemTime") case CreatePINForBidder: return stubbedResponse("CreatePINForBidder") case ActiveAuctions: return stubbedResponse("ActiveAuctions") case MyCreditCards: return stubbedResponse("MyCreditCards") case RegisterToBid: return stubbedResponse("RegisterToBid") case MyBiddersForAuction: return stubbedResponse("MyBiddersForAuction") case Me: return stubbedResponse("Me") case UpdateMe: return stubbedResponse("Me") case CreateUser: return stubbedResponse("Me") // This API returns a 302, so stubbed response isn't valid case FindBidderRegistration: return stubbedResponse("Me") case PlaceABid: return stubbedResponse("CreateABid") case Artwork: return stubbedResponse("Artwork") case Artist: return stubbedResponse("Artist") case AuctionInfo: return stubbedResponse("AuctionInfo") case RegisterCard: return stubbedResponse("RegisterCard") case BidderDetailsNotification: return stubbedResponse("RegisterToBid") case LostPasswordNotification: return stubbedResponse("ForgotPassword") case FindExistingEmailRegistration: return stubbedResponse("ForgotPassword") case AuctionInfoForArtwork: return stubbedResponse("AuctionInfoForArtwork") case MyBidPositionsForAuctionArtwork: return stubbedResponse("MyBidPositionsForAuctionArtwork") case Ping: return stubbedResponse("Ping") } } } // MARK: - Provider setup func endpointResolver() -> ((endpoint: Endpoint<ArtsyAPI>) -> (NSURLRequest)) { return { (endpoint: Endpoint<ArtsyAPI>) -> (NSURLRequest) in let request: NSMutableURLRequest = endpoint.urlRequest.mutableCopy() as! NSMutableURLRequest request.HTTPShouldHandleCookies = false return request } } class ArtsyProvider<T where T: MoyaTarget>: ReactiveCocoaMoyaProvider<T> { typealias OnlineSignalClosure = () -> RACSignal // Closure that returns a signal which completes once the app is online. let onlineSignal: OnlineSignalClosure init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEndpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil, onlineSignal: OnlineSignalClosure = connectedToInternetSignal) { self.onlineSignal = onlineSignal super.init(endpointClosure: endpointClosure, endpointResolver: endpointResolver, stubBehavior: stubBehavior, networkActivityClosure: networkActivityClosure) } } struct Provider { private static var endpointsClosure = { (target: ArtsyAPI) -> Endpoint<ArtsyAPI> in var endpoint: Endpoint<ArtsyAPI> = Endpoint<ArtsyAPI>(URL: url(target), sampleResponse: .Success(200, {target.sampleData}), method: target.method, parameters: target.parameters) // Sign all non-XApp token requests switch target { case .XApp: return endpoint case .XAuth: return endpoint default: return endpoint.endpointByAddingHTTPHeaderFields(["X-Xapp-Token": XAppToken().token ?? ""]) } } static func APIKeysBasedStubBehaviour(target: ArtsyAPI) -> Moya.StubbedBehavior { return APIKeys.sharedKeys.stubResponses ? .Immediate : .NoStubbing } // init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEnpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil, onlineSignal: OnlineSignalClosure = connectedToInternetSignal) { static func DefaultProvider() -> ArtsyProvider<ArtsyAPI> { return ArtsyProvider(endpointClosure: endpointsClosure, endpointResolver: endpointResolver(), stubBehavior: APIKeysBasedStubBehaviour) } static func StubbingProvider() -> ArtsyProvider<ArtsyAPI> { return ArtsyProvider(endpointClosure: endpointsClosure, endpointResolver: endpointResolver(), stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, onlineSignal: { RACSignal.empty() }) } private struct SharedProvider { static var instance = Provider.DefaultProvider() } static var sharedProvider: ArtsyProvider<ArtsyAPI> { get { return SharedProvider.instance } set (newSharedProvider) { SharedProvider.instance = newSharedProvider } } } // MARK: - Provider support func stubbedResponse(filename: String) -> NSData! { @objc class TestClass: NSObject { } let bundle = NSBundle(forClass: TestClass.self) let path = bundle.pathForResource(filename, ofType: "json") return NSData(contentsOfFile: path!) } private extension String { var URLEscapedString: String { return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())! } } func url(route: MoyaTarget) -> String { return route.baseURL.URLByAppendingPathComponent(route.path).absoluteString }
mit
ea2f2503e53b65e0ab8a31a4d518f7e1
30.5525
364
0.630774
4.903263
false
false
false
false
OneBusAway/onebusaway-iphone
Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/Views/CalendarDayCell.swift
2
2564
/** Copyright (c) Facebook, Inc. and its affiliates. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 IGListKit import UIKit final class CalendarDayCell: UICollectionViewCell { lazy fileprivate var label: UILabel = { let view = UILabel() view.backgroundColor = .clear view.textAlignment = .center view.textColor = .black view.font = .boldSystemFont(ofSize: 16) view.layer.borderWidth = 2 view.clipsToBounds = true self.contentView.addSubview(view) return view }() lazy fileprivate var dotsLabel: UILabel = { let view = UILabel() view.backgroundColor = .clear view.textAlignment = .center view.textColor = .red view.font = .boldSystemFont(ofSize: 30) self.contentView.addSubview(view) return view }() var text: String? { get { return label.text } set { label.text = newValue } } var dots: String? { get { return dotsLabel.text } set { dotsLabel.text = newValue } } override func layoutSubviews() { super.layoutSubviews() let bounds = contentView.bounds let half = bounds.height / 2 label.frame = bounds label.layer.cornerRadius = half dotsLabel.frame = CGRect(x: 0, y: half - 10, width: bounds.width, height: half) } } extension CalendarDayCell: ListBindable { func bindViewModel(_ viewModel: Any) { guard let viewModel = viewModel as? DayViewModel else { return } label.text = viewModel.day.description label.layer.borderColor = viewModel.today ? UIColor.red.cgColor : UIColor.clear.cgColor label.backgroundColor = viewModel.selected ? UIColor.red.withAlphaComponent(0.3) : UIColor.clear var dots = "" for _ in 0..<viewModel.appointments { dots += "." } dotsLabel.text = dots } }
apache-2.0
574fb369c50e26c07678bfacafbfffcc
28.471264
104
0.637285
4.704587
false
false
false
false
wordpress-mobile/AztecEditor-iOS
Aztec/Classes/TextKit/HTMLStorage.swift
2
5792
import Foundation import UIKit // MARK: - NSTextStorage Implementation: Automatically colorizes all of the present HTML Tags. // open class HTMLStorage: NSTextStorage { /// Internal Storage /// private var textStore = NSMutableAttributedString(string: "", attributes: nil) fileprivate var textStoreString = "" /// Document's Font /// open var font: UIFont /// Color to be applied over HTML text /// open var textColor = Styles.defaultTextColor /// Color to be applied over HTML Comments /// open var commentColor = Styles.defaultCommentColor /// Color to be applied over HTML Tags /// open var tagColor = Styles.defaultTagColor /// Color to be applied over Quotes within HTML Tags /// open var quotedColor = Styles.defaultQuotedColor // MARK: - Initializers public override init() { // Note: // iOS 11 has changed the way Copy + Paste works. As far as we can tell, upon Paste, the system // instantiates a new UITextView stack, and renders it on top of the one in use. // This (appears) to be the cause of a glitch in which the pasted text would temporarily appear out // of phase, on top of the "pre paste UI". // // We're adding a ridiculosly small defaultFont here, in order to force the "Secondary" UITextView // not to render anything. // // Ref. https://github.com/wordpress-mobile/AztecEditor-iOS/issues/771 // font = UIFont.systemFont(ofSize: 4) super.init() } public init(defaultFont: UIFont) { font = defaultFont super.init() } required public init?(coder aDecoder: NSCoder) { fatalError() } required public init(itemProviderData data: Data, typeIdentifier: String) throws { fatalError("init(itemProviderData:typeIdentifier:) has not been implemented") } // MARK: - Overriden Methods override open var string: String { return textStoreString } private func replaceTextStoreString(_ range: NSRange, with string: String) { let utf16String = textStoreString.utf16 let startIndex = utf16String.index(utf16String.startIndex, offsetBy: range.location) let endIndex = utf16String.index(startIndex, offsetBy: range.length) textStoreString.replaceSubrange(startIndex..<endIndex, with: string) } override open func attributes(at location: Int, effectiveRange range: NSRangePointer?) -> [NSAttributedString.Key : Any] { guard textStore.length != 0 else { return [:] } return textStore.attributes(at: location, effectiveRange: range) } override open func setAttributes(_ attrs: [NSAttributedString.Key : Any]?, range: NSRange) { beginEditing() textStore.setAttributes(attrs, range: range) edited(.editedAttributes, range: range, changeInLength: 0) endEditing() } override open func replaceCharacters(in range: NSRange, with str: String) { beginEditing() textStore.replaceCharacters(in: range, with: str) replaceTextStoreString(range, with: str) edited([.editedAttributes, .editedCharacters], range: range, changeInLength: str.utf16.count - range.length) colorizeHTML() endEditing() } override open func replaceCharacters(in range: NSRange, with attrString: NSAttributedString) { beginEditing() textStore.replaceCharacters(in: range, with: attrString) replaceTextStoreString(range, with: attrString.string) edited([.editedAttributes, .editedCharacters], range: range, changeInLength: attrString.length - range.length) colorizeHTML() endEditing() } } // MARK: - Private Helpers // private extension HTMLStorage { /// Colorizes all of the HTML Tags contained within this Storage /// func colorizeHTML() { let fullStringRange = rangeOfEntireString addAttribute(.foregroundColor, value: textColor, range: fullStringRange) addAttribute(.font, value: font, range: fullStringRange) let tags = RegExes.html.matches(in: string, options: [], range: fullStringRange) for tag in tags { addAttribute(.foregroundColor, value: tagColor, range: tag.range) let quotes = RegExes.quotes.matches(in: string, options: [], range: tag.range) for quote in quotes { addAttribute(.foregroundColor, value: quotedColor, range: quote.range) } } let comments = RegExes.comments.matches(in: string, options: [], range: fullStringRange) for comment in comments { addAttribute(.foregroundColor, value: commentColor, range: comment.range) } edited(.editedAttributes, range: fullStringRange, changeInLength: 0) } } // MARK: - Constants // extension HTMLStorage { /// Regular Expressions used to match HTML /// private struct RegExes { static let comments = try! NSRegularExpression(pattern: "<!--[^>]+-->", options: .caseInsensitive) static let html = try! NSRegularExpression(pattern: "<[^>]+>", options: .caseInsensitive) static let quotes = try! NSRegularExpression(pattern: "\".*?\"", options: .caseInsensitive) } /// Default Styles /// public struct Styles { static let defaultTextColor = UIColor.black static let defaultCommentColor = UIColor.lightGray static let defaultTagColor = UIColor(red: 0x00/255.0, green: 0x75/255.0, blue: 0xB6/255.0, alpha: 0xFF/255.0) static let defaultQuotedColor = UIColor(red: 0x6E/255.0, green: 0x96/255.0, blue: 0xB1/255.0, alpha: 0xFF/255.0) } }
mpl-2.0
def84c2eaedeece25be47d01c9857e8d
31.909091
126
0.653315
4.626198
false
false
false
false
marcusellison/lil-twitter
lil-twitter/TweetDetailViewController.swift
1
3908
// // TweetDetailViewController.swift // lil-twitter // // Created by Marcus J. Ellison on 5/22/15. // Copyright (c) 2015 Marcus J. Ellison. All rights reserved. // import UIKit class TweetDetailViewController: UIViewController { @IBOutlet weak var thumbImageView: UIImageView! @IBOutlet weak var retweetUsernameLabel: UILabel! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var createdAtLabel: UILabel! @IBOutlet weak var tweetDescriptionLabel: UILabel! @IBOutlet weak var screennameLabel: UILabel! @IBOutlet weak var replyImageView: UIImageView! @IBOutlet weak var replyButton: UIButton! @IBOutlet weak var retweetButton: UIButton! @IBOutlet weak var favoriteButton: UIButton! @IBOutlet weak var retweetsCountLabel: UILabel! @IBOutlet weak var favoritesCountLabel: UILabel! var tweet: Tweet! override func viewDidLoad() { super.viewDidLoad() if tweet.favorited! { favoriteButton.selected = true } else { favoriteButton.selected = false } if tweet.retweeted! { retweetButton.selected = true } else { retweetButton.selected = false } thumbImageView.layer.cornerRadius = 4 thumbImageView.clipsToBounds = true thumbImageView.setImageWithURL(tweet.imageURL) replyImageView.image = UIImage(named: "reply") userNameLabel.text = tweet.user?.name tweetDescriptionLabel.text = tweet.text createdAtLabel.text = "\(tweet.createdAt!)" screennameLabel.text = "@\(tweet.user!.screenname!)" favoritesCountLabel.text = "\(tweet.favoritesCount!)" retweetsCountLabel.text = "\(tweet.retweetsCount!)" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onFavorite(sender: AnyObject) { TwitterClient.sharedInstance.favorite(tweet.tweetIDString!, completion: { (tweet, error) -> () in if error == nil { println("Tweet favorited") self.favoritesCountLabel.text = "\(self.tweet.favoritesCount! + 1)" self.favoriteButton.selected = true // (self.delegate?.budgieDetailsActionsCell!(self, didChangeFavoriteStatus: !(self.tweet.isFavorited!))) } else { println(("favoriting error")) } }) } @IBAction func onRetweet(sender: AnyObject) { TwitterClient.sharedInstance.retweet(tweet, completion: { (tweet, error) -> () in if error == nil { println("Successful retweet!") self.retweetsCountLabel.text = "\(self.tweet.retweetsCount! + 1)" self.retweetButton.selected = true // (self.delegate?.budgieDetailsActionsCell!(self, didChangeReTweetedStatus: !(self.tweet.isRetweeted!))) } else { println(("Error retweeting!")) } }) } @IBAction func onReply(sender: AnyObject) { performSegueWithIdentifier("replyTweet", sender: sender) } // 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?) { if segue.identifier == "replyTweet" { let replyViewController = segue.destinationViewController as! ReplyViewController replyViewController.tweet = tweet } // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } }
mit
49f435c9272ed5879c9af0bcee352abb
31.840336
137
0.617451
5.288227
false
false
false
false
sajeel/AutoScout
AutoScoutAPI/AutoScoutAPI.swift
1
4791
// // AutoScoutAPI.swift // AutoScout // // Created by Sajjeel Khilji on 5/21/17. // Copyright © 2017 Saj. All rights reserved. // import Foundation import Alamofire import ObjectMapper import AlamofireObjectMapper open class AutoScoutAPI: AutoScoutAPIProtocol { // MARK: Private constants fileprivate static let parameterNameMake = "make" fileprivate static let urlPathNameIndex = "index" fileprivate static let badServerResponseError = NSError(domain: NSURLErrorDomain, code: NSURLErrorBadServerResponse, userInfo: nil) internal static let baseServerUrl = URL(string: "http://sumamo.de/iOS-TechChallange/api/")! // MARK: Public properties open fileprivate(set) var resultQueue: OperationQueue public init(queue: OperationQueue) { self.resultQueue = queue } // MARK: Private members private func callCompletionHandler<T>(completionHandler: @escaping (T) -> (), object: T) { self.resultQueue.addOperation { completionHandler(object) } } open func loadCars(_ carType: CarsRequestType, completionHandler: @escaping (CarsResponse) -> ()) -> AutoScoutAPICancelable{ //since make is not appear as the parameter but the part of the URL, so unfortunatly i have to drop this // diddn't like the API design let url = type(of:self).baseServerUrl.appendingPathComponent("\(type(of: self).urlPathNameIndex)/\(type(of: self).parameterNameMake)=\(carType.description)") return self.performCarsListRequest( url, requestType: carType, filterCarsHandler: { (cars: [Car]?) in cars?.filter { $0.isValid() } }, completionHandler: completionHandler ) } open func saveIntoFav(_ carType: CarsRequestType, completionHandler: ()) -> Car?{ return nil } open func getFav(_ carType: CarsRequestType, completionHandler: ()) -> Car?{ return nil } open func deleteFav(_ carType: CarsRequestType, completionHandler: ()) -> Bool{ return false } // MARK: Internal API Requests //internal func performCarsListRequest<T: Mappable>(_ url: URL, internal func performCarsListRequest<T: Mappable>(_ url: URL,requestType: CarsRequestType,filterCarsHandler: @escaping ([T]?) -> [Car]?, completionHandler: @escaping (CarsResponse) -> Void ) -> AutoScoutAPICancelable { //assert(requestType.rawValue.isEmpty , "requestType cannot be nil") // since there make is part of the URL but not the parameter, so i have to drop this, and pass nil in the DataRequest let defaultError = type(of: self).badServerResponseError var urlRequest = URLRequest(url: url) urlRequest.httpMethod = "POST" let params: [String: Any] = [ type(of: self).parameterNameMake: requestType.description ] // do { // urlRequest.httpBody = try JSONSerialization.data(withJSONObject: params, options: []) // } catch { // // No-op // } //implement the cache policy to ignore cache responses urlRequest.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") //let dataRequest = Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding(options: []), headers: nil).responseObject(completionHandler: { let dataRequest = Alamofire.request(urlRequest).responseObject(completionHandler: { [weak self] (apiResponse: DataResponse<ApiResponse>) -> Void in guard apiResponse.result.isSuccess else { let carsResponse: CarsResponse = .error(apiResponse.result.error ?? defaultError) self?.callCompletionHandler(completionHandler: completionHandler, object: carsResponse) return } let apiR = apiResponse.result.value let listOfCars:[T] = (apiR?.cars)! as! [T] guard let validCars = filterCarsHandler(listOfCars), validCars.count > 0 else { let carsResponse: CarsResponse = .error(apiResponse.result.error ?? defaultError) self?.callCompletionHandler(completionHandler: completionHandler, object: carsResponse) return } let carsSuccessResponse: CarsResponse = .success(validCars) self?.callCompletionHandler(completionHandler: completionHandler, object: carsSuccessResponse) }) return dataRequest } }
gpl-3.0
ccf532bd2d9d9a8afe2bde3b3b80b973
35.287879
222
0.633612
5.036803
false
false
false
false
yanif/circator
MetabolicCompassWatchExtension/MealTimesInterfaceController.swift
1
1500
// // MealTimesInterfaceController.swift // Circator // // Created by Mariano on 4/19/16. // Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved. // import WatchKit import Foundation struct mealTypeVariable { var mealType: String } var mealTypebyButton = mealTypeVariable(mealType:"to be named") class MealTimesInterfaceController: WKInterfaceController { @IBOutlet var dinnerButton: WKInterfaceButton! @IBOutlet var breakfastButton: WKInterfaceButton! @IBOutlet var lunchButton: WKInterfaceButton! @IBOutlet var snackButton: WKInterfaceButton! override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) } override func willActivate() { super.willActivate() } override func didDeactivate() { super.didDeactivate() } @IBAction func onDinner() { mealTypebyButton.mealType = "Dinner" pushControllerWithName("MealInterfaceController", context: self) } @IBAction func onLunch() { mealTypebyButton.mealType = "Lunch" pushControllerWithName("MealInterfaceController", context: self) } @IBAction func onBreakfast() { mealTypebyButton.mealType = "Breakfast" pushControllerWithName("MealInterfaceController", context: self) } @IBAction func onSnack() { mealTypebyButton.mealType = "Snack" pushControllerWithName("MealInterfaceController", context: self) } }
apache-2.0
e5a7a3a49f91468b65c7c97918830d6c
26.254545
72
0.687125
4.835484
false
false
false
false
NoryCao/SwiftExtension
SwiftExtension/UIViewController+QSExtension.swift
1
1719
// // UIViewController+QSExtension.swift // SwiftExtension // // Created by caonongyun on 2017/7/17. // Copyright © 2017年 QS. All rights reserved. // import Foundation import UIKit typealias AlertCallback = (_ action:UIAlertAction)->Void extension UIViewController{ //MARK: - alert func alert(with title:String?,message:String?,okTitle:String?){ self.alert(with: title, message: message, okTitle: okTitle, cancelTitle: nil, okAction: nil, cancelAction: nil) } func alert(with title:String?,message:String?,okTitle:String?,okAction:AlertCallback?){ self.alert(with: title, message: message, okTitle: okTitle, cancelTitle: nil, okAction: okAction, cancelAction: nil) } func alert(with title:String?,message:String?,okTitle:String?,cancelTitle:String?,okAction:AlertCallback?){ self.alert(with: title, message: message, okTitle: okTitle, cancelTitle: cancelTitle, okAction: okAction, cancelAction: nil) } func alert(with title:String?,message:String?,okTitle:String?,cancelTitle:String?,okAction:AlertCallback?,cancelAction:AlertCallback?){ let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let ok = UIAlertAction(title: okTitle, style: .default) { (alertAction) in if let action = okAction { action(alertAction) } } let cancel = UIAlertAction(title: cancelTitle, style: .default) { (alertAction) in if let action = cancelAction { action(alertAction) } } alert.addAction(ok) alert.addAction(cancel) self.present(alert, animated: true, completion: nil) } }
mit
6e18b7454053f51790abf00197ff86d1
37.133333
139
0.670163
4.377551
false
false
false
false
frankcjw/CJWUtilsS
CJWUtilsS/QPLib/UI/QPGridView.swift
1
4480
// // QPGridView.swift // CJWUtilsS // // Created by Frank on 10/9/16. // Copyright © 2016 cen. All rights reserved. // import UIKit public class QPGridView: UIView { var gridCount = 0 var column = 2 public var customViews: [UIView] = [] override public func updateConstraints() { super.updateConstraints() // var view = self // view.leadingAlign(self, predicate: "10") // view.trailingAlign(self, predicate: "-10") // view.topAlign(self, predicate: "10") // view.bottomAlign(self, predicate: "-10") // let hei = gridCount * 101 // view.heightConstrain("\(hei)") // view.backgroundColor = UIColor.yellowColor() // let tmpPadding = 0 let padding = 4 gridContainerView.topAlign(self, predicate: "\(padding)") gridContainerView.bottomAlign(self, predicate: "-\(padding)") gridContainerView.leadingAlign(self, predicate: "\(padding)") gridContainerView.trailingAlign(self, predicate: "-\(padding)") var horizanReferenceView = customViews.first! var verticalReferenceView = customViews.first! let wwwScale: CGFloat = CGFloat(1) / CGFloat(column) let view = gridContainerView for grid in grids { let index = grids.indexOf(grid)! let customView = customViews[index] let scale: CGFloat = CGFloat(1) / CGFloat(column * 2) let columnIndex = index % column let indexFloat: CGFloat = CGFloat(columnIndex + 1) * 2 - 1 let predicateX: CGFloat = indexFloat * scale * 2 if index == 0 { grid.topAlign(view, predicate: "0") horizanReferenceView = grid verticalReferenceView = grid if grids.count == 1 { grid.bottomAlign(view, predicate: "0") } } else { if index % column == 0 { grid.topConstrain(verticalReferenceView, predicate: "0") verticalReferenceView = grid horizanReferenceView = grid } else { grid.centerY(horizanReferenceView) horizanReferenceView = grid } if index == gridCount - 1 { grid.bottomAlign(view, predicate: "0") } } grid.centerX(grid.superview!, predicate: "*\(predicateX)") grid.width(grid.superview!, predicate: "*\(wwwScale)") if index != 0 { grid.width(horizanReferenceView) } // if let predicate = delegate?.heightPredicateForView?() { // grid.heightConstrain(predicate) // } else { // grid.aspectRatio() // } if let heightConstrain = gridHeightConstrain() { grid.heightConstrain(heightConstrain) } else { grid.aspectRatio() } let customViewSuperView = customView.superview! customView.leadingAlign(customViewSuperView, predicate: "\(padding)") customView.trailingAlign(customViewSuperView, predicate: "-\(padding)") customView.topAlign(customViewSuperView, predicate: "\(padding)") customView.bottomAlign(customViewSuperView, predicate: "-\(padding)") } } public typealias GridSelectionBlock = (index: Int) -> () func onViewSelected(gesture: UIGestureRecognizer) { if let tag = gesture.view?.tag { self.onSelectBlock?(index: tag) } } var onSelectBlock: GridSelectionBlock? public func addTarget(block: GridSelectionBlock) { self.onSelectBlock = block } var heightConstrain: String? public func gridHeightConstrain() -> String? { return heightConstrain } var grids: [UIView] = [] let gridContainerView = UIView() func setup() { // self.addSubview(view) if gridCount > 0 { addSubview(gridContainerView) for index in 0 ... gridCount - 1 { let grid = UIView() grids.append(grid) gridContainerView.addSubview(grid) // TODO: let userCustomView = customView(index) userCustomView.tag = index userCustomView.addTapGesture(self, action: "onViewSelected:") customViews.append(userCustomView) grid.addSubview(userCustomView) } } } convenience init () { self.init(frame: CGRect.zero) setup() } public override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } public convenience init (count: Int, column: Int) { self.init(frame: CGRect.zero) self.gridCount = count self.column = column setup() } public convenience init (count: Int, column: Int, heightConstrain: String) { self.init(frame: CGRect.zero) self.heightConstrain = heightConstrain self.gridCount = count self.column = column setup() } public func customView(index: Int) -> UIView { return UIView() } public func numberOfColum() -> Int { return 2 } }
mit
68ad377d2071ad4767371394d480d9d7
23.342391
77
0.684305
3.480186
false
false
false
false
sealgair/MusicKit
MusicKit/ChordName.swift
2
4912
// Copyright (c) 2015 Ben Guo. All rights reserved. import Foundation extension PitchSet { /// Normalizes the pitch set by deduping and collapsing to within an octave /// while maintaining the root. mutating func normalize() { dedupe() collapse() } } extension Chord { /// Returns the name of the chord if found. public static func name(pitchSet: PitchSet) -> String? { if let desc = descriptor(pitchSet) { let rootName = desc.root.description let quality = desc.quality.description if desc.root == desc.bass { return "\(rootName)\(quality)" } else { let bassName = desc.bass.description return "\(rootName)\(quality)/\(bassName)" } } return nil } /// Returns an optional `ChordDescriptor`. public static func descriptor(pitchSet: PitchSet) -> ChordDescriptor? { var pitchSet = pitchSet pitchSet.normalize() let count = pitchSet.count let gamutCount = pitchSet.gamut().count // early return if: // - less than a dyad after normalization // - one or more pitch is chroma-less if count < 2 || count != gamutCount { return nil } let bass = pitchSet[0] let bassChromaOpt = bass.chroma // pitch set with bass removed var bassRemoved = pitchSet bassRemoved.remove(bass) // dyads if count == 2 { return _descriptor(pitchSet, qualities: ChordQuality.Dyads) } // triads else if count == 3 { return _descriptor(pitchSet, qualities: ChordQuality.Triads) } // Tetrads, Pentads, Hexads, Heptads else if count > 3 && count < 8 { var fullQs = [ChordQuality]() var fullUnalteredQs = [ChordQuality]() var slashQs = [ChordQuality]() if count == 4 { fullQs = ChordQuality.Tetrads fullUnalteredQs = ChordQuality.UnalteredTetrads slashQs = ChordQuality.Triads } else if count == 5 { fullQs = ChordQuality.Pentads fullUnalteredQs = ChordQuality.UnalteredPentads slashQs = ChordQuality.Tetrads } else if count == 6 { fullQs = ChordQuality.Hexads fullUnalteredQs = ChordQuality.UnalteredHexads slashQs = ChordQuality.Pentads } else if count == 7 { fullQs = ChordQuality.Heptads fullUnalteredQs = ChordQuality.UnalteredHeptads slashQs = ChordQuality.Hexads } // no-slash let fullOpt = _descriptor(pitchSet, qualities: fullQs) // unaltered, no-slash, root position -> return if let full = fullOpt { if fullUnalteredQs.contains(full.quality) && full.bass == full.root { return full } } // try to simplify chord by slashing let noBassOpt = _descriptor(bassRemoved, qualities: slashQs) var slashNoBassOpt: ChordDescriptor? = nil if let noBass = noBassOpt { slashNoBassOpt = bassChromaOpt.map { ChordDescriptor(root: noBass.root, quality: noBass.quality, bass: $0) } } return slashNoBassOpt ?? fullOpt } return nil } /// Returns an optional `ChordDescriptor`. static func _descriptor(pitchSet: PitchSet, qualities: [ChordQuality]) -> ChordDescriptor? { let count = pitchSet.count if count < 1 { return nil } let bass = pitchSet.first()! let bassChromaOpt = bass.chroma let indices = pitchSet.semitoneIndices() // check root position chords for quality in qualities { let _indices = MKUtil.collapse(MKUtil.semitoneIndices(quality.intervals)) if _indices == indices { return bassChromaOpt.map { ChordDescriptor(root: $0, quality: quality, bass: $0) } } } // check inversions for quality in qualities { let _indices = MKUtil.collapse(MKUtil.semitoneIndices(quality.intervals)) for i in 1..<count { let inversion = MKUtil.zero(MKUtil.invert(_indices, n: UInt(i))) if inversion == indices { if let rootChroma = pitchSet[count - i].chroma { return bassChromaOpt.map { ChordDescriptor(root: rootChroma, quality: quality, bass: $0) } } } } } return nil } }
mit
b549a426d960a1d6d5a0faafd65dabc7
33.836879
89
0.536034
4.655924
false
false
false
false
Jnosh/swift
test/decl/protocol/special/coding/class_codable_computed_vars.swift
55
1480
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown // Classes with computed members should get synthesized conformance to Codable, // but their lazy and computed members should be skipped as part of the // synthesis. class ClassWithComputedMembers : Codable { var x: Int = 1 lazy var y: Double = .pi var z: String { return "foo" } // These lines have to be within the ClassWithComputedMembers type because // CodingKeys should be private. func foo() { // They should receive a synthesized CodingKeys enum. let _ = ClassWithComputedMembers.CodingKeys.self // The enum should have a case for each of the vars. let _ = ClassWithComputedMembers.CodingKeys.x // Lazy vars should not be part of the CodingKeys enum. let _ = ClassWithComputedMembers.CodingKeys.y // expected-error {{type 'ClassWithComputedMembers.CodingKeys' has no member 'y'}} // Computed vars should not be part of the CodingKeys enum. let _ = ClassWithComputedMembers.CodingKeys.z // expected-error {{type 'ClassWithComputedMembers.CodingKeys' has no member 'z'}} } } // They should receive synthesized init(from:) and an encode(to:). let _ = ClassWithComputedMembers.init(from:) let _ = ClassWithComputedMembers.encode(to:) // The synthesized CodingKeys type should not be accessible from outside the // class. let _ = ClassWithComputedMembers.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
apache-2.0
84a807b1c3409c066509a3a085414c1a
40.111111
133
0.739189
4.391691
false
false
false
false
ormaa/Bluetooth-LE-IOS-Swift
Central Manager/CentralManager/Singleton.swift
1
894
//import UIKit import Foundation //Model singleton so that we can refer to this from throughout the app. let appControllerSingletonGlobal = Singleton() // this class is a singleton // class Singleton: NSObject { class func sharedInstance() -> Singleton { return appControllerSingletonGlobal } // used by BLE stack let serialQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.default) //DispatchQueue(label: "my serial queue") // Be careful. those class cannot use appController, because it would be a cyclic redundance let bluetoothController = BluetoothController() let tools = Tools() // App restore after IOS killed it, and bluetooth status has changed : device switch on, or advertise something. var appRestored = false var centralManagerToRestore: String? // logger let logger = Log() }
mit
d26898be62930caeadfc19e924f33c8b
24.542857
119
0.697987
4.994413
false
false
false
false
Pearapps/SampleTodoApp
frontend/frontend/ApplicationFlowController.swift
1
1262
// // ApplicationFlowController.swift // frontend // // Created by Kenneth Parker Ackerson on 8/30/16. // Copyright © 2016 Kenneth Ackerson. All rights reserved. // import UIKit final class ApplicationFlowController { let window = UIWindow(frame: UIScreen.mainScreen().bounds) private let URLSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) private var todoFlowController: TodoListFlowController? func start() { let navigation = UINavigationController() window.rootViewController = navigation todoFlowController = TodoListFlowController(fetcher: BackendFetcher(session: URLSession, URL: NSURL(string: "http://localhost:3030/todos") ?? NSURL(), converter: TodoConverter(), dispatcher: MainThreadAsyncDispatcher()), navigationController: navigation, tableView: UITableView(), URLSession: URLSession) todoFlowController?.start(false) window.makeKeyAndVisible() todoFlowController?.refresh() } }
apache-2.0
9ffc743fc9e8dd3936e7478401e538e4
34.055556
113
0.601903
6.401015
false
true
false
false
NocturneZX/TTT-Pre-Internship-Exercises
Swift/TwitterApp/TwitterApp/TimelineTableViewController.swift
1
8490
// // TimelineTableViewController.swift // SwifferApp // // Created by TurnToTech on 29/06/14. // Copyright (c) 2014 TurnToTech. All rights reserved. // import UIKit class TimelineTableViewController: UITableViewController { var timelineData:NSMutableArray! = NSMutableArray() override init(style: UITableViewStyle) { super.init(style: style) // Custom initialization } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } @IBAction func loadData(){ timelineData.removeAllObjects() var findTimelineData:PFQuery = PFQuery(className: "Tweets") findTimelineData.findObjectsInBackgroundWithBlock{ (objects:[AnyObject]!, error:NSError!)->Void in if error == nil{ for object in objects{ let tweet:PFObject = object as PFObject self.timelineData.addObject(tweet) } let array:NSArray = self.timelineData.reverseObjectEnumerator().allObjects self.timelineData = NSMutableArray(array: array) self.tableView.reloadData() } } } override func viewDidAppear(animated: Bool) { self.loadData() if PFUser.currentUser() == nil{ var loginAlert:UIAlertController = UIAlertController(title: "Sign Up / Login", message: "Please sign up or login", preferredStyle: UIAlertControllerStyle.Alert) loginAlert.addTextFieldWithConfigurationHandler({ textfield in textfield.placeholder = "Your username" }) loginAlert.addTextFieldWithConfigurationHandler({ textfield in textfield.placeholder = "Your password" textfield.secureTextEntry = true }) loginAlert.addAction(UIAlertAction(title: "Login", style: UIAlertActionStyle.Default, handler: { alertAction in let textFields:NSArray = loginAlert.textFields! let usernameTextfield:UITextField = textFields.objectAtIndex(0) as UITextField let passwordTextfield:UITextField = textFields.objectAtIndex(1) as UITextField PFUser.logInWithUsernameInBackground(usernameTextfield.text, password: passwordTextfield.text){ (user:PFUser!, error:NSError!)->Void in if user != nil{ println("Login successfull") }else{ println("Login failed") } } })) loginAlert.addAction(UIAlertAction(title: "Sign Up", style: UIAlertActionStyle.Default, handler: { alertAction in let textFields:NSArray = loginAlert.textFields! let usernameTextfield:UITextField = textFields.objectAtIndex(0) as UITextField let passwordTextfield:UITextField = textFields.objectAtIndex(1) as UITextField var tweeter:PFUser = PFUser() tweeter.username = usernameTextfield.text tweeter.password = passwordTextfield.text tweeter.signUpInBackgroundWithBlock{ (success:Bool!, error:NSError!)->Void in if error == nil{ println("Sign Up successfull") }else{ let errorString = error.localizedDescription println(errorString) } } })) self.presentViewController(loginAlert, animated: true, completion: nil) } } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // #pragma mark - Table view data source override func numberOfSectionsInTableView(tableView: UITableView?) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return timelineData.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:TweetTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as TweetTableViewCell let tweet:PFObject = self.timelineData.objectAtIndex(indexPath.row) as PFObject cell.tweetTextView.alpha = 0 cell.timestampLabel.alpha = 0 cell.usernameLabel.alpha = 0 cell.tweetTextView.text = tweet.objectForKey("content") as String var dataFormatter:NSDateFormatter = NSDateFormatter() dataFormatter.dateFormat = "MMM d, yyyy HH:mm" cell.timestampLabel.text = dataFormatter.stringFromDate(tweet.createdAt) var findTweeter:PFQuery = PFUser.query() findTweeter.whereKey("objectId", equalTo: tweet.objectForKey("tweeter").objectId) findTweeter.findObjectsInBackgroundWithBlock{ (objects:[AnyObject]!, error:NSError!)->Void in if error == nil{ let user:PFUser = (objects as NSArray).lastObject as PFUser cell.usernameLabel.text = user.username UIView.animateWithDuration(0.5, animations: { cell.tweetTextView.alpha = 1 cell.timestampLabel.alpha = 1 cell.usernameLabel.alpha = 1 }) } } return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView?, canEditRowAtIndexPath indexPath: NSIndexPath?) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView?, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath?) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView?, moveRowAtIndexPath fromIndexPath: NSIndexPath?, toIndexPath: NSIndexPath?) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView?, canMoveRowAtIndexPath indexPath: NSIndexPath?) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
gpl-2.0
c74c5c6cd49468264042993f0e0a9a91
35.753247
172
0.588928
6.121125
false
false
false
false
cleven1/CLScrollPageView
CLScrollPageView/ScrollPageView/CLScrollPageView.swift
1
5401
// // CLScrollPageView.swift // CLScrollPageView // // Created by cleven on 2016/10/22. // Copyright © 2016年 cleven. All rights reserved. // import UIKit class CLScrollPageView: UIView { //MARK: 私有属性 fileprivate var selectButton:UIButton = UIButton() //设置标题 fileprivate var titleArray:[String] //设置页面 fileprivate var pageArray:[UIViewController] //MARK: 构造方法 init(frame:CGRect,titleArray:[String],pageArray:[UIViewController]){ self.titleArray = titleArray self.pageArray = pageArray super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: 懒加载 fileprivate lazy var titleScrollView:UIScrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width:UIScreen.main.bounds.width , height: 40)) fileprivate lazy var pageScrollView:UIScrollView = UIScrollView(frame: .zero) } extension CLScrollPageView { //初始化UI fileprivate func setupUI(){ backgroundColor = UIColor.white //titleScrollView titleScrollView.backgroundColor = UIColor.darkGray titleScrollView.showsHorizontalScrollIndicator = false titleScrollView.bounces = false addSubview(titleScrollView) //pageScrollView let maxY = titleScrollView.frame.maxY pageScrollView.frame = CGRect(x: 0, y: maxY, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - maxY) pageScrollView.showsHorizontalScrollIndicator = true pageScrollView.isPagingEnabled = true pageScrollView.delegate = self pageScrollView.bounces = false addSubview(pageScrollView) //MARK: 设置数据 let margin:CGFloat = 10 var width:CGFloat = 0 //计算titleArray文字的宽度 var textWidth:CGFloat = 0 let textFont:CGFloat = 17.5 //17号字宽度17.5 for str in titleArray { textWidth += CGFloat(str.characters.count) * textFont + margin * 2 } for i in (0..<titleArray.count){ //title let titleButton:UIButton = UIButton(title: titleArray[i], titleColor: UIColor.black) titleScrollView.addSubview(titleButton) titleButton.addTarget(self, action: #selector(self.titleButtonClick(button:)), for: .touchUpInside) //判断传进的title文字宽度,设置frame if (textWidth < UIScreen.main.bounds.width) { titleButton.frame = CGRect(x: width , y: 5.0, width: UIScreen.main.bounds.width / CGFloat(titleArray.count), height: 40) width += titleButton.bounds.size.width }else{ titleButton.frame = CGRect(x: width , y: 5.0, width: titleButton.bounds.size.width + margin, height: 40) width += titleButton.bounds.size.width + margin } titleButton.tag = i + 1000 //默认选中第一个 if i == 0 { titleButtonClick(button: titleButton) } //页面 let vc:UIViewController = pageArray[i] pageScrollView.addSubview(vc.view) vc.view.frame = bounds.offsetBy(dx: CGFloat(i) * UIScreen.main.bounds.width, dy: 0) } titleScrollView.contentSize = CGSize(width: Int(width), height: 0) pageScrollView.contentSize = CGSize(width: pageArray.count * Int(UIScreen.main.bounds.width), height: 0) } //MARK: 监听方法 @objc private func titleButtonClick(button:UIButton){ selectButton.setTitleColor(UIColor.black, for: .normal) button.setTitleColor(UIColor.red, for: .normal) selectButton = button //滚动到指定的位置 pageScrollView.setContentOffset(CGPoint(x: (button.tag - 1000) * Int(UIScreen.main.bounds.width), y: 0), animated: true) setUptitleButtonCenter(button: button) } //设置标题按钮居中 fileprivate func setUptitleButtonCenter(button:UIButton){ var offsetX:CGFloat = button.center.x - UIScreen.main.bounds.width * 0.5 if offsetX < 0 { offsetX = 0 } //最大的偏移量 let maxX:CGFloat = titleScrollView.contentSize.width - UIScreen.main.bounds.width if offsetX > maxX { offsetX = maxX } titleScrollView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true) } } //MARK: scrollView代理方法 extension CLScrollPageView:UIScrollViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let page = scrollView.contentOffset.x / scrollView.bounds.width let titleButton = self.viewWithTag(Int(page)+1000) as! UIButton selectButton.setTitleColor(UIColor.black, for: .normal) titleButton.setTitleColor(UIColor.red, for: .normal) selectButton = titleButton //滚动标题居中 setUptitleButtonCenter(button: titleButton) } }
mit
f1502bb7b3f64a9404b82041896bbcf9
30.587879
142
0.603223
4.848372
false
false
false
false
HenvyLuk/BabyGuard
BabyGuard/CVCalendar/CVCalendarMonthContentViewController.swift
1
17355
// // CVCalendarMonthContentViewController.swift // CVCalendar Demo // // Created by Eugene Mozharovsky on 12/04/15. // Copyright (c) 2015 GameApp. All rights reserved. // import UIKit public final class CVCalendarMonthContentViewController: CVCalendarContentViewController { private var monthViews: [Identifier : MonthView] public override init(calendarView: CalendarView, frame: CGRect) { monthViews = [Identifier : MonthView]() super.init(calendarView: calendarView, frame: frame) initialLoad(presentedMonthView.date) } public init(calendarView: CalendarView, frame: CGRect, presentedDate: NSDate) { monthViews = [Identifier : MonthView]() super.init(calendarView: calendarView, frame: frame) presentedMonthView = MonthView(calendarView: calendarView, date: presentedDate) presentedMonthView.updateAppearance(scrollView.bounds) initialLoad(presentedDate) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Load & Reload public func initialLoad(date: NSDate) { insertMonthView(getPreviousMonth(date), withIdentifier: previous) insertMonthView(presentedMonthView, withIdentifier: presented) insertMonthView(getFollowingMonth(date), withIdentifier: following) presentedMonthView.mapDayViews { dayView in if self.calendarView.shouldAutoSelectDayOnMonthChange && self.matchedDays(dayView.date, Date(date: date)) { self.calendarView.coordinator.flush() self.calendarView.touchController.receiveTouchOnDayView(dayView) dayView.selectionView?.removeFromSuperview() } } calendarView.presentedDate = CVDate(date: presentedMonthView.date) } public func reloadMonthViews() { for (identifier, monthView) in monthViews { monthView.frame.origin.x = CGFloat(indexOfIdentifier(identifier)) * scrollView.frame.width monthView.removeFromSuperview() scrollView.addSubview(monthView) } } // MARK: - Insertion public func insertMonthView(monthView: MonthView, withIdentifier identifier: Identifier) { let index = CGFloat(indexOfIdentifier(identifier)) monthView.frame.origin = CGPoint(x: scrollView.bounds.width * index, y: 0) monthViews[identifier] = monthView scrollView.addSubview(monthView) } public func replaceMonthView(monthView: MonthView, withIdentifier identifier: Identifier, animatable: Bool) { var monthViewFrame = monthView.frame monthViewFrame.origin.x = monthViewFrame.width * CGFloat(indexOfIdentifier(identifier)) monthView.frame = monthViewFrame monthViews[identifier] = monthView if animatable { scrollView.scrollRectToVisible(monthViewFrame, animated: false) } } // MARK: - Load management public func scrolledLeft() { if let presentedMonth = monthViews[presented], let followingMonth = monthViews[following] { if pageLoadingEnabled { pageLoadingEnabled = false monthViews[previous]?.removeFromSuperview() replaceMonthView(presentedMonth, withIdentifier: previous, animatable: false) replaceMonthView(followingMonth, withIdentifier: presented, animatable: true) insertMonthView(getFollowingMonth(followingMonth.date), withIdentifier: following) self.calendarView.delegate?.didShowNextMonthView?(followingMonth.date) } } } public func scrolledRight() { if let previous = monthViews[previous], let presented = monthViews[presented] { if pageLoadingEnabled { pageLoadingEnabled = false monthViews[following]?.removeFromSuperview() replaceMonthView(previous, withIdentifier: self.presented, animatable: true) replaceMonthView(presented, withIdentifier: following, animatable: false) insertMonthView(getPreviousMonth(previous.date), withIdentifier: self.previous) self.calendarView.delegate?.didShowPreviousMonthView?(previous.date) } } } // MARK: - Override methods public override func updateFrames(rect: CGRect) { super.updateFrames(rect) for monthView in monthViews.values { monthView.reloadViewsWithRect(rect != CGRect.zero ? rect : scrollView.bounds) } reloadMonthViews() if let presented = monthViews[presented] { if scrollView.frame.height != presented.potentialSize.height { updateHeight(presented.potentialSize.height, animated: false) } scrollView.scrollRectToVisible(presented.frame, animated: false) } } public override func performedDayViewSelection(dayView: DayView) { if dayView.isOut && calendarView.shouldScrollOnOutDayViewSelection { if dayView.date.day > 20 { let presentedDate = dayView.monthView.date calendarView.presentedDate = Date(date: self.dateBeforeDate(presentedDate)) presentPreviousView(dayView) } else { let presentedDate = dayView.monthView.date calendarView.presentedDate = Date(date: self.dateAfterDate(presentedDate)) presentNextView(dayView) } } } public override func presentPreviousView(view: UIView?) { if presentationEnabled { presentationEnabled = false guard let extra = monthViews[following], presented = monthViews[presented], previous = monthViews[previous] else { return } UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.prepareTopMarkersOnMonthView(presented, hidden: true) extra.frame.origin.x += self.scrollView.frame.width presented.frame.origin.x += self.scrollView.frame.width previous.frame.origin.x += self.scrollView.frame.width self.replaceMonthView(presented, withIdentifier: self.following, animatable: false) self.replaceMonthView(previous, withIdentifier: self.presented, animatable: false) self.presentedMonthView = previous self.updateLayoutIfNeeded() }) { _ in extra.removeFromSuperview() self.insertMonthView(self.getPreviousMonth(previous.date), withIdentifier: self.previous) //self.updateSelection() self.presentationEnabled = true for monthView in self.monthViews.values { self.prepareTopMarkersOnMonthView(monthView, hidden: false) } } } } public override func presentNextView(view: UIView?) { if presentationEnabled { presentationEnabled = false guard let extra = monthViews[previous], presented = monthViews[presented], following = monthViews[following] else { return } UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.prepareTopMarkersOnMonthView(presented, hidden: true) extra.frame.origin.x -= self.scrollView.frame.width presented.frame.origin.x -= self.scrollView.frame.width following.frame.origin.x -= self.scrollView.frame.width self.replaceMonthView(presented, withIdentifier: self.previous, animatable: false) self.replaceMonthView(following, withIdentifier: self.presented, animatable: false) self.presentedMonthView = following self.updateLayoutIfNeeded() }) { _ in extra.removeFromSuperview() self.insertMonthView(self.getFollowingMonth(following.date), withIdentifier: self.following) //self.updateSelection() self.presentationEnabled = true for monthView in self.monthViews.values { self.prepareTopMarkersOnMonthView(monthView, hidden: false) } } } } public override func updateDayViews(hidden: Bool) { setDayOutViewsVisible(hidden) } private var togglingBlocked = false public override func togglePresentedDate(date: NSDate) { let presentedDate = Date(date: date) guard let presentedMonth = monthViews[presented], selectedDate = calendarView.coordinator.selectedDayView?.date else { return } if !matchedDays(selectedDate, presentedDate) && !togglingBlocked { if !matchedMonths(presentedDate, selectedDate) { togglingBlocked = true monthViews[previous]?.removeFromSuperview() monthViews[following]?.removeFromSuperview() insertMonthView(getPreviousMonth(date), withIdentifier: previous) insertMonthView(getFollowingMonth(date), withIdentifier: following) let currentMonthView = MonthView(calendarView: calendarView, date: date) currentMonthView.updateAppearance(scrollView.bounds) currentMonthView.alpha = 0 insertMonthView(currentMonthView, withIdentifier: presented) presentedMonthView = currentMonthView calendarView.presentedDate = Date(date: date) UIView.animateWithDuration(0.8, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { presentedMonth.alpha = 0 currentMonthView.alpha = 1 }) { _ in presentedMonth.removeFromSuperview() self.selectDayViewWithDay(presentedDate.day, inMonthView: currentMonthView) self.togglingBlocked = false self.updateLayoutIfNeeded() } } else { if let currentMonthView = monthViews[presented] { selectDayViewWithDay(presentedDate.day, inMonthView: currentMonthView) } } } } } // MARK: - Month management extension CVCalendarMonthContentViewController { public func getFollowingMonth(date: NSDate) -> MonthView { let firstDate = calendarView.manager.monthDateRange(date).monthStartDate let components = Manager.componentsForDate(firstDate) components.month += 1 let newDate = NSCalendar.currentCalendar().dateFromComponents(components)! let frame = scrollView.bounds let monthView = MonthView(calendarView: calendarView, date: newDate) monthView.updateAppearance(frame) return monthView } public func getPreviousMonth(date: NSDate) -> MonthView { let firstDate = calendarView.manager.monthDateRange(date).monthStartDate let components = Manager.componentsForDate(firstDate) components.month -= 1 let newDate = NSCalendar.currentCalendar().dateFromComponents(components)! let frame = scrollView.bounds let monthView = MonthView(calendarView: calendarView, date: newDate) monthView.updateAppearance(frame) return monthView } } // MARK: - Visual preparation extension CVCalendarMonthContentViewController { public func prepareTopMarkersOnMonthView(monthView: MonthView, hidden: Bool) { monthView.mapDayViews { dayView in dayView.topMarker?.hidden = hidden } } public func setDayOutViewsVisible(visible: Bool) { for monthView in monthViews.values { monthView.mapDayViews { dayView in if dayView.isOut { if !visible { dayView.alpha = 0 dayView.hidden = false } UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { dayView.alpha = visible ? 0 : 1 }, completion: { _ in if visible { dayView.alpha = 1 dayView.hidden = true dayView.userInteractionEnabled = false } else { dayView.userInteractionEnabled = true } }) } } } } public func updateSelection() { let coordinator = calendarView.coordinator if let selected = coordinator.selectedDayView { for (index, monthView) in monthViews { if indexOfIdentifier(index) != 1 { monthView.mapDayViews { dayView in if dayView == selected { dayView.setDeselectedWithClearing(true) coordinator.dequeueDayView(dayView) } } } } } if let presentedMonthView = monthViews[presented] { self.presentedMonthView = presentedMonthView calendarView.presentedDate = Date(date: presentedMonthView.date) if let selected = coordinator.selectedDayView, selectedMonthView = selected.monthView where !matchedMonths(Date(date: selectedMonthView.date), Date(date: presentedMonthView.date)) && calendarView.shouldAutoSelectDayOnMonthChange { let current = Date(date: NSDate()) let presented = Date(date: presentedMonthView.date) if matchedMonths(current, presented) { selectDayViewWithDay(current.day, inMonthView: presentedMonthView) } else { selectDayViewWithDay(Date(date: calendarView.manager .monthDateRange(presentedMonthView.date).monthStartDate).day, inMonthView: presentedMonthView) } } } } public func selectDayViewWithDay(day: Int, inMonthView monthView: CVCalendarMonthView) { let coordinator = calendarView.coordinator monthView.mapDayViews { dayView in if dayView.date.day == day && !dayView.isOut { if let selected = coordinator.selectedDayView where selected != dayView { //self.calendarView.didSelectDayView(dayView) } coordinator.performDayViewSingleSelection(dayView) } } } } // MARK: - UIScrollViewDelegate extension CVCalendarMonthContentViewController { public func scrollViewDidScroll(scrollView: UIScrollView) { if scrollView.contentOffset.y != 0 { scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: 0) } let page = Int(floor((scrollView.contentOffset.x - scrollView.frame.width / 2) / scrollView.frame.width) + 1) if currentPage != page { currentPage = page } lastContentOffset = scrollView.contentOffset.x } public func scrollViewWillBeginDragging(scrollView: UIScrollView) { if let presented = monthViews[presented] { prepareTopMarkersOnMonthView(presented, hidden: true) } } public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { if pageChanged { switch direction { case .Left: scrolledLeft() case .Right: scrolledRight() default: break } } updateSelection() updateLayoutIfNeeded() pageLoadingEnabled = true direction = .None } public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate { let rightBorder = scrollView.frame.width if scrollView.contentOffset.x <= rightBorder { direction = .Right } else { direction = .Left } } for monthView in monthViews.values { prepareTopMarkersOnMonthView(monthView, hidden: false) } } }
apache-2.0
9b3c65e2148ab921181ddce50154e06a
36.97593
99
0.590896
6.336254
false
false
false
false
OatmealCode/Oatmeal
Pod/Classes/Extensions/Swift/Date.swift
1
1844
//// //// Date.swift //// Cent //// //// Created by Ankur Patel on 6/30/14. //// Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved. //// // //import Foundation // //public extension NSDate { // // /// Returns a new Date given the year month and day // /// // /// :param year // /// :param month // /// :param day // /// :return Date // public class func from(year year: Int, month: Int, day: Int) -> NSDate? { // let c = NSDateComponents() // c.year = year // c.month = month // c.day = day // // if let gregorian = NSCalendar(identifier: NSCalendarIdentifierGregorian) { // return gregorian.dateFromComponents(c) // } else { // return .None // } // } // // /// Returns a new Date given the unix timestamp // /// // /// :param unix timestamp // /// :return Date // public class func from(unix unix: Double) -> NSDate { // return NSDate(timeIntervalSince1970: unix) // } // // /// Parses the date based on the format and return a new Date // /// // /// :param dateStr String version of the date // /// :param format By default it is year month day // /// :return Date // public class func parse(dateStr: String, format: String = "yyyy-MM-dd") -> NSDate { // let dateFmt = NSDateFormatter() // dateFmt.timeZone = NSTimeZone.defaultTimeZone() // dateFmt.dateFormat = format // return dateFmt.dateFromString(dateStr)! // } // // /// Returns the unix timestamp of the date passed in or // /// the current unix timestamp // /// // /// :param date // /// :return Double // public class func unix(date: NSDate = NSDate()) -> Double { // return date.timeIntervalSince1970 as Double // } //} // //public typealias Date = NSDate
mit
07fd8e120b3f7bc5634b4c0c25e26c97
28.741935
89
0.566161
3.770961
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/PullToRefresher/PullToRefresh/UIScrollView+PullToRefresh.swift
4
2984
// // Created by Anastasiya Gorban on 4/14/15. // Copyright (c) 2015 Yalantis. All rights reserved. // // Licensed under the MIT license: http://opensource.org/licenses/MIT // Latest version can be found at https://github.com/Yalantis/PullToRefresh // import Foundation import UIKit import ObjectiveC private var topPullToRefreshKey: UInt8 = 0 private var bottomPullToRefreshKey: UInt8 = 0 public extension UIScrollView { fileprivate(set) var topPullToRefresh: PullToRefresh? { get { return objc_getAssociatedObject(self, &topPullToRefreshKey) as? PullToRefresh } set { objc_setAssociatedObject(self, &topPullToRefreshKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate(set) var bottomPullToRefresh: PullToRefresh? { get { return objc_getAssociatedObject(self, &bottomPullToRefreshKey) as? PullToRefresh } set { objc_setAssociatedObject(self, &bottomPullToRefreshKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public func addPullToRefresh(_ pullToRefresh: PullToRefresh, action: @escaping () -> ()) { pullToRefresh.scrollView = self pullToRefresh.action = action var originY: CGFloat let view = pullToRefresh.refreshView switch pullToRefresh.position { case .top: if let previousPullToRefresh = topPullToRefresh { removePullToRefresh(previousPullToRefresh) } topPullToRefresh = pullToRefresh originY = -view.frame.size.height case .bottom: if let previousPullToRefresh = bottomPullToRefresh{ removePullToRefresh(previousPullToRefresh) } bottomPullToRefresh = pullToRefresh originY = contentSize.height } view.frame = CGRect(x: 0, y: originY, width: frame.width, height: view.frame.height) addSubview(view) sendSubview(toBack: view) } func removePullToRefresh(_ pullToRefresh: PullToRefresh) { switch pullToRefresh.position { case .top: topPullToRefresh?.refreshView.removeFromSuperview() topPullToRefresh = nil case .bottom: bottomPullToRefresh?.refreshView.removeFromSuperview() bottomPullToRefresh = nil } } func startRefreshing(at position: Position) { switch position { case .top: topPullToRefresh?.startRefreshing() case .bottom: bottomPullToRefresh?.startRefreshing() } } func endRefreshing(at position: Position) { switch position { case .top: topPullToRefresh?.endRefreshing() case .bottom: bottomPullToRefresh?.endRefreshing() } } }
mit
ca4ca1eaff841a819a7bc30d8821e692
29.44898
113
0.608579
5.475229
false
false
false
false
fxm90/GradientProgressBar
Example/Pods/SnapshotTesting/Sources/SnapshotTesting/Snapshotting/UIBezierPath.swift
1
1741
#if os(iOS) || os(tvOS) import UIKit extension Snapshotting where Value == UIBezierPath, Format == UIImage { /// A snapshot strategy for comparing bezier paths based on pixel equality. public static var image: Snapshotting { return .image() } /// A snapshot strategy for comparing bezier paths based on pixel equality. /// /// - Parameter precision: The percentage of pixels that must match. public static func image(precision: Float = 1, scale: CGFloat = 1) -> Snapshotting { return SimplySnapshotting.image(precision: precision, scale: scale).pullback { path in let bounds = path.bounds let format: UIGraphicsImageRendererFormat if #available(iOS 11.0, tvOS 11.0, *) { format = UIGraphicsImageRendererFormat.preferred() } else { format = UIGraphicsImageRendererFormat.default() } format.scale = scale return UIGraphicsImageRenderer(bounds: bounds, format: format).image { ctx in path.fill() } } } } @available(iOS 11.0, tvOS 11.0, *) extension Snapshotting where Value == UIBezierPath, Format == String { /// A snapshot strategy for comparing bezier paths based on pixel equality. public static var elementsDescription: Snapshotting { Snapshotting<CGPath, String>.elementsDescription.pullback { path in path.cgPath } } /// A snapshot strategy for comparing bezier paths based on pixel equality. /// /// - Parameter numberFormatter: The number formatter used for formatting points. public static func elementsDescription(numberFormatter: NumberFormatter) -> Snapshotting { Snapshotting<CGPath, String>.elementsDescription( numberFormatter: numberFormatter ).pullback { path in path.cgPath } } } #endif
mit
d37a8a468a6e9828b948d826ad9b2efc
36.847826
92
0.71166
4.863128
false
false
false
false
dobnezmi/EmotionNote
EmotionNote/Charts/Renderers/YAxisRendererRadarChart.swift
1
8123
// // YAxisRendererRadarChart.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class YAxisRendererRadarChart: YAxisRenderer { fileprivate weak var chart: RadarChartView? public init(viewPortHandler: ViewPortHandler?, yAxis: YAxis?, chart: RadarChartView?) { super.init(viewPortHandler: viewPortHandler, yAxis: yAxis, transformer: nil) self.chart = chart } open override func computeAxisValues(min yMin: Double, max yMax: Double) { guard let axis = axis as? YAxis else { return } let labelCount = axis.labelCount let range = abs(yMax - yMin) if labelCount == 0 || range <= 0 { axis.entries = [Double]() return } // Find out how much spacing (in yValue space) between axis values var rawInterval = range / Double(labelCount) if rawInterval.isInfinite { rawInterval = range > 0.0 && !range.isInfinite ? range : 1.0 } var interval = ChartUtils.roundToNextSignificant(number: Double(rawInterval)) // If granularity is enabled, then do not allow the interval to go below specified granularity. // This is used to avoid repeated values when rounding values for display. if axis.isGranularityEnabled { interval = interval < axis.granularity ? axis.granularity : interval } // Normalize interval let intervalMagnitude = ChartUtils.roundToNextSignificant(number: pow(10.0, floor(log10(interval)))) let intervalSigDigit = Int(interval / intervalMagnitude) if intervalSigDigit > 5 { // Use one order of magnitude higher, to avoid intervals like 0.9 or // 90 interval = floor(10 * intervalMagnitude) } let centeringEnabled = axis.isCenterAxisLabelsEnabled var n = centeringEnabled ? 1 : 0 // force label count if axis.isForceLabelsEnabled { let step = Double(range) / Double(labelCount - 1) // Ensure stops contains at least n elements. axis.entries.removeAll(keepingCapacity: true) axis.entries.reserveCapacity(labelCount) var v = yMin for _ in 0 ..< labelCount { axis.entries.append(v) v += step } n = labelCount } else { // no forced count var first = interval == 0.0 ? 0.0 : ceil(yMin / interval) * interval if centeringEnabled { first -= interval } let last = interval == 0.0 ? 0.0 : ChartUtils.nextUp(floor(yMax / interval) * interval) if interval != 0.0 { for _ in stride(from: first, through: last, by: interval) { n += 1 } } n += 1 // Ensure stops contains at least n elements. axis.entries.removeAll(keepingCapacity: true) axis.entries.reserveCapacity(labelCount) var f = first var i = 0 while i < n { if f == 0.0 { // Fix for IEEE negative zero case (Where value == -0.0, and 0.0 == -0.0) f = 0.0 } axis.entries.append(Double(f)) f += interval i += 1 } } // set decimals if interval < 1 { axis.decimals = Int(ceil(-log10(interval))) } else { axis.decimals = 0 } if centeringEnabled { axis.centeredEntries.reserveCapacity(n) axis.centeredEntries.removeAll() let offset = (axis.entries[1] - axis.entries[0]) / 2.0 for i in 0 ..< n { axis.centeredEntries.append(axis.entries[i] + offset) } } axis._axisMinimum = axis.entries[0] axis._axisMaximum = axis.entries[n-1] axis.axisRange = abs(axis._axisMaximum - axis._axisMinimum) } open override func renderAxisLabels(context: CGContext) { guard let yAxis = axis as? YAxis, let chart = chart else { return } if !yAxis.isEnabled || !yAxis.isDrawLabelsEnabled { return } let labelFont = yAxis.labelFont let labelTextColor = yAxis.labelTextColor let center = chart.centerOffsets let factor = chart.factor let labelCount = yAxis.entryCount let labelLineHeight = yAxis.labelFont.lineHeight for j in 0 ..< labelCount { if j == labelCount - 1 && yAxis.isDrawTopYLabelEntryEnabled == false { break } let r = CGFloat(yAxis.entries[j] - yAxis._axisMinimum) * factor let p = ChartUtils.getPosition(center: center, dist: r, angle: chart.rotationAngle) let label = yAxis.getFormattedLabel(j) ChartUtils.drawText( context: context, text: label, point: CGPoint(x: p.x + 10.0, y: p.y - labelLineHeight), align: .left, attributes: [ NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor ]) } } open override func renderLimitLines(context: CGContext) { guard let yAxis = axis as? YAxis, let chart = chart, let data = chart.data else { return } var limitLines = yAxis.limitLines if limitLines.count == 0 { return } context.saveGState() let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = chart.factor let center = chart.centerOffsets for i in 0 ..< limitLines.count { let l = limitLines[i] if !l.isEnabled { continue } context.setStrokeColor(l.lineColor.cgColor) context.setLineWidth(l.lineWidth) if l.lineDashLengths != nil { context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } let r = CGFloat(l.limit - chart.chartYMin) * factor context.beginPath() for j in 0 ..< (data.maxEntryCountSet?.entryCount ?? 0) { let p = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(j) + chart.rotationAngle) if j == 0 { context.move(to: CGPoint(x: p.x, y: p.y)) } else { context.addLine(to: CGPoint(x: p.x, y: p.y)) } } context.closePath() context.strokePath() } context.restoreGState() } }
apache-2.0
da380822300afaa7f9eea9433b9dc4bd
27.907473
125
0.484919
5.408123
false
false
false
false
rhodgkins/RDHCommonCrypto
RDHCommonCrypto/CryptoError.swift
1
2717
// // CryptoError.swift // RDHCommonCrypto // // Created by Richard Hodgkins on 15/09/2014. // Copyright (c) 2014 Rich Hodgkins. All rights reserved. // import Foundation let RDHCommonCryptoErrorDomain = "RDHCommonCryptoErrorDomain" extension RDHStatus { func error() -> NSError? { var message: String? = nil switch (self) { case .Success: return nil case .ParameterError: message = "Illegal parameter value." case .BufferTooSmall: message = "Insufficent buffer provided for specified operation." case .MemoryFailure: message = "Memory allocation failure." case .AlignmentError: message = "Input size was not aligned properly." case .DecodeError: message = "Input data did not decode or decrypt properly." case .Unimplemented: message = "Function not implemented for the current algorithm." case .Overflow: message = nil case .RandomNumberGeneratorFailure: message = nil case .Unknown: message = nil } return NSError(domain: RDHCommonCryptoErrorDomain, code: Int(self.toRaw()), userInfo: (message != nil) ? [NSLocalizedDescriptionKey : message!] : nil) } static func fromInt(intStatus: CCStatus) -> RDHStatus { return fromRaw(intStatus) ?? .Unknown } /// Closure that converts a crypto operation status static func statusForOperation(block: () -> CCStatus) -> RDHStatus { let intStatus = block() return RDHStatus.fromInt(intStatus) } } /// Checks if the the operation was succesful and then trims the data to the needed size. If there was an error success will be false with a error func cleanUpOutData(dataOut: NSMutableData!, movedOutLength dataOutMoved: UInt, forResultStatus status: RDHStatus) -> (success: Bool, error: NSError?) { var success = false var error: NSError? = nil if status == RDHStatus.Success { // Fix data to final length dataOut.length = Int(dataOutMoved) success = true } else if status == RDHStatus.BufferTooSmall { // dataOutMoved now contains the needed size dataOut.length = Int(dataOutMoved) } else { error = status.error() // Clear any out data dataOut.length = 0 } return (success, error) }
mit
c9a13e3480beab353511fa81a5615630
30.229885
158
0.565329
5.390873
false
false
false
false
Eonil/SQLite3
Sources/LowLevel/Core.Debug.swift
2
1541
// // Core.swift // EonilSQLite3 // // Created by Hoon H. on 9/17/14. // // import Foundation extension Core { static func log<T>(@autoclosure object:()->T) { if Debug.mode && Debug.useCoreLogging { println(object()) } } struct LeakDetector { enum TargetObjectType { case db case stmt } static var theDetector = LeakDetector() mutating func registerInstance(inst:COpaquePointer, of type:TargetObjectType) { if Debug.mode || Test.mode { precondition(inst != nil) precondition(find(instanceListForType[type]!, inst) == nil) instanceListForType[type]!.append(inst) } } mutating func unregisterInstance(inst:COpaquePointer, of type:TargetObjectType) { if Debug.mode || Test.mode { precondition(inst != nil) let idx = find(instanceListForType[type]!, inst) precondition(idx != nil) instanceListForType[type]!.removeAtIndex(idx!) } } var allInstancesByTypes:Dictionary<TargetObjectType,[COpaquePointer]> { get { return instanceListForType } } func countAllInstances() -> Int { if Debug.mode || Test.mode { let a1 = map(instanceListForType.values, { (v:[COpaquePointer]) -> (Int) in return v.count }) let a2 = reduce(a1, 0, +) return a2 } else { Core.Common.crash(message: "Unsupported feature on RELEASE build. Do not try to call this on RELEASE build.") } } private var instanceListForType = [ TargetObjectType.db: [COpaquePointer](), TargetObjectType.stmt: [COpaquePointer](), ] } }
mit
b6d84c30c1783d6c73336d5a9de966d5
18.75641
113
0.663206
3.35
false
false
false
false
hmtinc/Z80-Swift
Source/macros.swift
1
8626
// // macros.swift // Z80-Swift // // Created by Harsh Mistry on 2017-12-15. // Copyright © 2017 Harsh Mistry. All rights reserved. // import Foundation enum Fl : uint8 { case C = 0x01 case N = 0x02 case PV = 0x04 case H = 0x10 case Z = 0x40 case S = 0x80 case None = 0x00 case All = 0xD7 } //Register References let B = 0, C = 1, D = 2, E = 3, H = 4, L = 5, F = 6, A = 7, Bp = 8 let Cp = 9, Dp = 10, Ep = 11, Hp = 12, Lp = 13, Fp = 14, Ap = 15 let I = 16, R = 17, IX = 18, IY = 20, SP = 22, PC = 24 //16 Bit Registers func Hl (_ registers : [UInt8] ) -> UInt16 { return UInt16(registers[L] + (registers[H] << 8))} func Sp (_ registers : [UInt8] ) -> UInt16 { return UInt16(registers[SP + 1] + (registers[SP] << 8))} func Ix (_ registers : [UInt8] ) -> UInt16 { return UInt16(registers[IX + 1] + (registers[IX] << 8))} func Iy (_ registers : [UInt8] ) -> UInt16 { return UInt16(registers[IY + 1] + (registers[IY] << 8))} func Bc (_ registers : [UInt8] ) -> UInt16 { return UInt16((registers[B] << 8) + registers[C] )} func De (_ registers : [UInt8] ) -> UInt16 { return UInt16((registers[D] << 8) + registers[E] )} func Pc (_ registers : [UInt8] ) -> UInt16 { return UInt16(registers[PC + 1] + (registers[PC] << 8))} //Helper functions func swapRegisters(_ r1 : Int, _ r2 : Int, _ registers : inout [uint8] ){ let temp = registers[r1] registers[r1] = registers[r2] registers[r2] = temp } func fetch(_ registers : inout [uint8], _ mem : inout [uint8]) -> uint8 { var pc = Pc(registers) let returnVal = mem[Int(pc)] pc = pc + 1 registers[PC] = uint8(pc >> 8) registers[PC + 1] = uint8(pc & 0xFF) return returnVal } func fetch16(_ registers : inout [uint8], _ mem : inout [uint8]) -> uint16 { return uint16(fetch(&registers, &mem) + (fetch(&registers, &mem) << 8)) } func jumpCond(_ condition : uint8, _ registers : inout [uint8] ) -> Bool{ var value : uint8 let cond = condition & 0xFE switch (cond){ case 0 : value = Fl.Z.rawValue case 2 : value = Fl.C.rawValue case 4 : value = Fl.PV.rawValue case 6 : value = Fl.S.rawValue default : return false } return ((registers[F] & value) > 0) == ((condition & 1) == 1) } func Parity(_ val : uint16, _ registers : inout [uint8]) -> Bool{ var parity = true; var tempVal = val; while (tempVal > 0){ if ((tempVal & 1) == 1) { parity = !parity} tempVal = tempVal >> 1 } return parity } func dec(_ b : uint8, _ registers : inout [uint8]) -> UInt8 { let sum = b &- 1 var f = uint8(registers[F] & 0x28) if((sum & 0x80) > 0) {f = UInt8(f | 0x80)} if(sum == 0) {f = UInt8(f | 0x40)} if((b & 0x0F) == 0) {f = UInt8(f | 0x10)} if(b == 0x80) {f = UInt8(f | 0x04)} f = uint8(f | 0x02) registers[F] = f return UInt8(sum) } func Inc(_ b : uint8, _ registers : inout [uint8]) -> UInt8 { let sum = b &+ 1 var f = uint8(registers[F] & 0x28) if((sum & 0x80) > 0) {f = UInt8(f | 0x80)} if(sum == 0) {f = UInt8(f | 0x40)} if((b & 0x0F) == 0) {f = UInt8(f | 0x10)} if(b == 0x80) {f = UInt8(f | 0x04)} f = uint8(f | 0x02) if(sum > 0xFF) { f = UInt8(f | 0x01)} registers[F] = f return UInt8(sum) } func Cmp(_ b : uint8, _ registers : inout [uint8]){ let a = registers[A] let diff = a &- b var f = UInt8(registers[F] & 0x28) if ((diff & 0x80) > 0) { f = UInt8(f | 0x80)} if (diff == 0) { f = UInt8(f | 0x40) } if ((a & 0xF) < (b & 0xF)){ f = UInt8(f | 0x10)} if ((a > 0x80 && b > 0x80 && diff > 0) || (a < 0x80 && b < 0x80 && diff < 0)){f = UInt8(f | 0x04)} f = UInt8(f | 0x02) if (diff > 0xFF){ f = UInt8(f | 0x01) } registers[F] = f } func xor(_ b : uint8, _ registers : inout [uint8]) { let a = registers[A]; let res = a ^ b registers[A] = res var f = uint8(registers[F] & 0x28) if((res & 0x80) > 0) {f |= UInt8(Fl.S.rawValue)} if(res == 0) {f |= UInt8(Fl.Z.rawValue)} if(Parity(uint16(res), &registers)) {f |= UInt8(Fl.PV.rawValue)} registers[F] = f } func or(_ b : uint8, _ registers : inout [uint8]) { let a = registers[A]; let res = UInt8(a | b) registers[A] = res var f = uint8(registers[F] & 0x28) if((res & 0x80) > 0) {f |= UInt8(Fl.S.rawValue)} if(res == 0) {f |= UInt8(Fl.Z.rawValue)} if(Parity(uint16(res), &registers)) {f |= UInt8(Fl.PV.rawValue)} registers[F] = f } func and(_ b : uint8, _ registers : inout [uint8]) { let a = registers[A]; let res = UInt8(a & b) registers[A] = res var f = uint8(registers[F] & 0x28) if((res & 0x80) > 0) {f |= UInt8(Fl.S.rawValue)} if(res == 0) {f |= UInt8(Fl.Z.rawValue)} f |= uint8(Fl.H.rawValue) if(Parity(uint16(res), &registers)) {f |= UInt8(Fl.PV.rawValue)} registers[F] = f } func sbc (_ b : uint8, _ registers : inout [uint8]){ let a = registers[A] let c = uint8(registers[F] & 0x01) let diff = a &- b &- c var f = uint8(registers[F] & 0x28) if((diff & 0x80) > 0) {f |= uint8(Fl.S.rawValue)} if(diff == 0) {f |= UInt8(Fl.Z.rawValue)} if((a & 0xF) < (b & 0xF) + c) {f |= UInt8(Fl.H.rawValue)} if((a >= 0x80 && b >= 0x80 && diff > 0) || ( a < 0x80 && b < 0x80 && diff < 0)) { f |= UInt8(Fl.PV.rawValue) } f |= uint8(Fl.N.rawValue) if(diff > 0xFF) { f |= UInt8(Fl.C.rawValue)} registers[F] = f } func sub (_ b : uint8, _ registers : inout [uint8]){ let a = registers[A] let diff = a &- b var f = uint8(registers[F] & 0x28) if((diff & 0x80) > 0) {f |= uint8(Fl.S.rawValue)} if(diff == 0) {f |= UInt8(Fl.Z.rawValue)} if((a & 0xF) < (b & 0xF)) {f |= UInt8(Fl.H.rawValue)} if((a >= 0x80 && b >= 0x80 && diff > 0) || ( a < 0x80 && b < 0x80 && diff < 0)) { f |= UInt8(Fl.PV.rawValue) } f |= uint8(Fl.N.rawValue) if(diff > 0xFF) { f |= UInt8(Fl.C.rawValue)} registers[F] = f } func adc (_ b : uint8, _ registers : inout [uint8]){ let a = registers[A] let c = uint8(registers[F] & Fl.C.rawValue) let diff = a &+ b &+ c var f = uint8(registers[F] & 0x28) if((diff & 0x80) > 0) {f |= uint8(Fl.S.rawValue)} if(diff == 0) {f |= UInt8(Fl.Z.rawValue)} if((a & 0xF + b & 0xF) > 0xF) {f |= UInt8(Fl.H.rawValue)} if((a >= 0x80 && b >= 0x80 && diff > 0) || ( a < 0x80 && b < 0x80 && diff < 0)) { f |= UInt8(Fl.PV.rawValue) } f = uint8(f & ~uint8(Fl.N.rawValue)) if(diff > 0xFF) { f |= UInt8(Fl.C.rawValue)} registers[F] = f } func add (_ b : uint8, _ registers : inout [uint8]){ let a = registers[A] let diff = a &+ b registers[A] = uint8(diff) var f = uint8(registers[F] & 0x28) if((diff & 0x80) > 0) {f |= uint8(Fl.S.rawValue)} if(diff == 0) {f |= UInt8(Fl.Z.rawValue)} if((a & 0xF + b & 0xF) > 0xF) {f |= UInt8(Fl.H.rawValue)} if((a >= 0x80 && b >= 0x80 && diff > 0) || ( a < 0x80 && b < 0x80 && diff < 0)) { f |= UInt8(Fl.PV.rawValue) } if(diff > 0xFF) { f |= UInt8(Fl.C.rawValue)} registers[F] = f } func add(_ val1 : uint16, _ val2 : uint16, _ registers : inout [uint8]) -> uint16 { let sum = val1 &+ val2 var f = uint8(registers[F] & uint8(Fl.H.rawValue | Fl.N.rawValue | Fl.C.rawValue)) if ((val1 & 0x0FFF) + (val2 & 0x0FFF) > 0x0FFF){ f |= uint8(Fl.H.rawValue) } if(sum > 0xFFFF){ f |= uint8(Fl.C.rawValue) } registers[F] = f return uint16(sum) } func addHl (_ val : uint16, _ registers : inout [uint8]){ let sum = add(Hl(registers), val, &registers) registers[H] = uint8(sum >> 8) registers[L] = uint8(sum & 0xFF) } func stallCpu(_ time : Int, _ registers : inout [uint8]) { let oneTick = 0.25 let sleepTime = oneTick * Double(time) registers[R] = uint8((time + 3) / 4) usleep(uint32(sleepTime)) } func pushPairSp(_ reg1 : Int, _ reg2 : Int, _ registers : inout [uint8], _ mem : inout [uint8]){ var address = Int(Sp(registers)) address -= 1 mem[address] = registers[reg1] address -= 1 mem[address] = registers[reg2] registers[SP + 1] = uint8(address & 0xFF) registers[SP] = uint8(address >> 8) stallCpu(11, &registers) } func popPairSp(_ reg1 : Int, _ reg2 : Int, _ registers : inout [uint8], _ mem : inout [uint8]){ var address = Int(Sp(registers)) registers[reg2] = mem[address] address += 1 registers[reg1] = mem[address] address += 1 registers[SP + 1] = uint8(address & 0xFF) registers[SP] = uint8(address >> 8) stallCpu(10, &registers) }
mit
c92077ba317cf725a6ee6c18e9295883
30.593407
102
0.540638
2.651399
false
false
false
false
CartoDB/mobile-ios-samples
AdvancedMap.Swift/Feature Demo/MainView.swift
1
2778
// // MainView.swift // Feature Demo // // Created by Aare Undo on 16/06/2017. // Copyright © 2017 CARTO. All rights reserved. // import Foundation import UIKit class MainView: UIScrollView { weak var galleryDelegate: GalleryDelegate? var views: [GalleryRow] = [GalleryRow]() convenience init() { self.init(frame: CGRect.zero) backgroundColor = Colors.fromRgba(red: 250, green: 250, blue: 250, alpha: 255) let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.tapped(_:))) addGestureRecognizer(recognizer) } @objc func tapped(_ sender: UITapGestureRecognizer) { let location = sender.location(in: self) for view in views { if (view.frame.contains(location)) { galleryDelegate?.galleryItemClick(item: view) } } } override func layoutSubviews() { var itemsInRow: CGFloat = 2 if (frame.width > frame.height) { itemsInRow = 3 if (frame.width > 1000) { itemsInRow = 4 } } else if (frame.width > 700) { itemsInRow = 3 } let padding: CGFloat = 5 var counter: CGFloat = 0 var x = padding var y = padding let w = (frame.width - (itemsInRow + 1) * padding) / itemsInRow let h = w for view in views { let xWithoutPadding = (counter.truncatingRemainder(dividingBy: itemsInRow) * w) let multipliedXPadding = ((counter.truncatingRemainder(dividingBy: itemsInRow) + 1) * padding) x = xWithoutPadding + multipliedXPadding let yWithoutPadding = h * ((CGFloat)((Int)(counter / itemsInRow))) let multipliedYPadding = padding * ((CGFloat)((Int)(counter / itemsInRow))) + padding y = yWithoutPadding + multipliedYPadding view.frame = CGRect(x: x, y: y, width: w, height: h) counter += 1; if (Int(counter) == views.count) { contentSize = CGSize(width: frame.width, height: y + h + padding) } } } func addRows(rows: [Sample]) { views.removeAll() for view in subviews { if let row = view as? GalleryRow { row.removeFromSuperview() } } for row in rows { let view = GalleryRow() view.update(sample: row) addSubview(view) views.append(view) } } }
bsd-2-clause
03bc2e92e854c8df518272057524783e
26.49505
106
0.507022
4.923759
false
false
false
false
brave/browser-ios
Client/Frontend/Browser/BrowserLocationView.swift
1
16623
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import Shared import SnapKit import XCGLogger private let log = Logger.browserLogger protocol BrowserLocationViewDelegate { func browserLocationViewDidTapLocation(_ browserLocationView: BrowserLocationView) func browserLocationViewDidLongPressLocation(_ browserLocationView: BrowserLocationView) func browserLocationViewDidTapReaderMode(_ browserLocationView: BrowserLocationView) /// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied @discardableResult func browserLocationViewDidLongPressReaderMode(_ browserLocationView: BrowserLocationView) -> Bool func browserLocationViewLocationAccessibilityActions(_ browserLocationView: BrowserLocationView) -> [UIAccessibilityCustomAction]? func browserLocationViewDidTapReload(_ browserLocationView: BrowserLocationView) func browserLocationViewDidTapStop(_ browserLocationView: BrowserLocationView) } struct BrowserLocationViewUX { static let HostFontColor = BraveUX.GreyJ static let BaseURLFontColor = BraveUX.GreyG static let BaseURLPitch = 0.75 static let HostPitch = 1.0 static let LocationContentInset = 8 static let Themes: [String: Theme] = { var themes = [String: Theme]() // TODO: Currently fontColor theme adjustments are being overriden by the textColor. // This should be cleaned up. var theme = Theme() theme.URLFontColor = BraveUX.LocationBarTextColor_URLBaseComponent theme.hostFontColor = BraveUX.LocationBarTextColor_URLHostComponent theme.textColor = BraveUX.LocationBarTextColor theme.backgroundColor = BraveUX.LocationBarBackgroundColor themes[Theme.NormalMode] = theme theme = Theme() theme.URLFontColor = BraveUX.LocationBarTextColor_URLBaseComponent theme.hostFontColor = .white theme.textColor = .white theme.backgroundColor = BraveUX.LocationBarBackgroundColor_PrivateMode themes[Theme.PrivateMode] = theme return themes }() } class BrowserLocationView: UIView { var delegate: BrowserLocationViewDelegate? var longPressRecognizer: UILongPressGestureRecognizer! var tapRecognizer: UITapGestureRecognizer! // Variable colors should be overwritten by theme @objc dynamic var baseURLFontColor: UIColor = BrowserLocationViewUX.BaseURLFontColor { didSet { updateTextWithURL() } } @objc dynamic var hostFontColor: UIColor = BrowserLocationViewUX.HostFontColor { didSet { updateTextWithURL() } } // The color of the URL after it has loaded @objc dynamic var fullURLFontColor: UIColor = BraveUX.LocationBarTextColor { didSet { updateTextWithURL() // Reset placeholder text, which will auto-adjust based on this new color self.urlTextField.attributedPlaceholder = self.placeholder } } var url: URL? { didSet { let wasHidden = lockImageView.isHidden lockImageView.isHidden = url?.scheme != "https" if wasHidden != lockImageView.isHidden { UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } updateTextWithURL() setNeedsUpdateConstraints() } } var readerModeState: ReaderModeState { get { return readerModeButton.readerModeState } set (newReaderModeState) { if newReaderModeState != self.readerModeButton.readerModeState { let wasHidden = readerModeButton.isHidden self.readerModeButton.readerModeState = newReaderModeState readerModeButton.isHidden = (newReaderModeState == ReaderModeState.Unavailable) if wasHidden != readerModeButton.isHidden { UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } UIView.animate(withDuration: 0.1, animations: { () -> Void in if newReaderModeState == ReaderModeState.Unavailable { self.readerModeButton.alpha = 0.0 } else { self.readerModeButton.alpha = 1.0 } self.setNeedsUpdateConstraints() self.layoutIfNeeded() }) } } } /// Returns constant placeholder text with current URL color var placeholder: NSAttributedString { let placeholderText = Strings.Search_or_enter_address return NSAttributedString(string: placeholderText, attributes: [NSAttributedStringKey.foregroundColor: self.fullURLFontColor.withAlphaComponent(0.5)]) } lazy var urlTextField: UITextField = { let urlTextField = DisplayTextField() self.longPressRecognizer.delegate = self urlTextField.addGestureRecognizer(self.longPressRecognizer) self.tapRecognizer.delegate = self urlTextField.addGestureRecognizer(self.tapRecognizer) urlTextField.keyboardAppearance = .dark urlTextField.attributedPlaceholder = self.placeholder urlTextField.accessibilityIdentifier = "url" urlTextField.accessibilityActionsSource = self urlTextField.font = UIConstants.DefaultChromeFont return urlTextField }() fileprivate lazy var lockImageView: UIImageView = { let lockImageView = UIImageView(image: UIImage(named: "lock_verified")?.withRenderingMode(.alwaysTemplate)) lockImageView.tintColor = BraveUX.Green lockImageView.isHidden = true lockImageView.isAccessibilityElement = true lockImageView.contentMode = UIViewContentMode.center lockImageView.accessibilityLabel = Strings.Secure_connection return lockImageView }() fileprivate lazy var readerModeButton: ReaderModeButton = { let readerModeButton = ReaderModeButton(frame: CGRect.zero) readerModeButton.isHidden = true readerModeButton.addTarget(self, action: #selector(BrowserLocationView.SELtapReaderModeButton), for: .touchUpInside) readerModeButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(BrowserLocationView.SELlongPressReaderModeButton(_:)))) readerModeButton.isAccessibilityElement = true readerModeButton.accessibilityLabel = Strings.Reader_View readerModeButton.accessibilityCustomActions = [UIAccessibilityCustomAction(name: Strings.Add_to_Reading_List, target: self, selector: #selector(BrowserLocationView.SELreaderModeCustomAction))] return readerModeButton }() let stopReloadButton = UIButton() func stopReloadButtonIsLoading(_ isLoading: Bool) { stopReloadButton.isSelected = isLoading stopReloadButton.accessibilityLabel = isLoading ? Strings.Stop : Strings.Reload } @objc func didClickStopReload() { if stopReloadButton.accessibilityLabel == Strings.Stop { delegate?.browserLocationViewDidTapStop(self) } else { delegate?.browserLocationViewDidTapReload(self) } } // Prefixing with brave to distinguish from progress view that firefox has (which we hide) var braveProgressView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat(URLBarViewUX.LocationHeight))) override init(frame: CGRect) { super.init(frame: frame) stopReloadButton.accessibilityIdentifier = "BrowserToolbar.stopReloadButton" stopReloadButton.setImage(UIImage.templateImageNamed("reload"), for: .normal) stopReloadButton.setImage(UIImage.templateImageNamed("stop"), for: .selected) // Setup the state dependent visuals stopReloadButtonIsLoading(false) stopReloadButton.addTarget(self, action: #selector(BrowserLocationView.didClickStopReload), for: UIControlEvents.touchUpInside) longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(BrowserLocationView.SELlongPressLocation(_:))) tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(BrowserLocationView.SELtapLocation(_:))) addSubview(urlTextField) addSubview(lockImageView) addSubview(readerModeButton) addSubview(stopReloadButton) braveProgressView.accessibilityLabel = "braveProgressView" braveProgressView.backgroundColor = PrivateBrowsing.singleton.isOn ? BraveUX.ProgressBarDarkColor : BraveUX.ProgressBarColor braveProgressView.layer.cornerRadius = BraveUX.TextFieldCornerRadius braveProgressView.layer.masksToBounds = true self.addSubview(braveProgressView) self.sendSubview(toBack: braveProgressView) } override var accessibilityElements: [Any]! { get { return [lockImageView, urlTextField, readerModeButton].filter { !$0.isHidden } } set { super.accessibilityElements = newValue } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateConstraints() { lockImageView.snp.makeConstraints { make in make.centerY.equalTo(self) make.left.equalTo(self).offset(BrowserLocationViewUX.LocationContentInset) make.width.equalTo(self.lockImageView.intrinsicContentSize.width) } readerModeButton.snp.makeConstraints { make in make.right.equalTo(stopReloadButton.snp.left).inset(-16) make.centerY.equalTo(self) make.width.equalTo(18) make.height.equalTo(17) } stopReloadButton.snp.makeConstraints { make in make.right.equalTo(self).inset(BrowserLocationViewUX.LocationContentInset) make.centerY.equalTo(self) make.width.equalTo(16) make.height.equalTo(15) } urlTextField.snp.remakeConstraints { make in make.top.bottom.equalTo(self) if lockImageView.isHidden { make.left.equalTo(self).offset(BrowserLocationViewUX.LocationContentInset) } else { make.left.equalTo(self.lockImageView.snp.right).offset(BrowserLocationViewUX.LocationContentInset-3) } if readerModeButton.isHidden { make.right.equalTo(self.stopReloadButton.snp.left) } else { make.right.equalTo(self.readerModeButton.snp.left).inset(-8) } } super.updateConstraints() } @objc func SELtapReaderModeButton() { delegate?.browserLocationViewDidTapReaderMode(self) } @objc func SELlongPressReaderModeButton(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.began { delegate?.browserLocationViewDidLongPressReaderMode(self) } } @objc func SELlongPressLocation(_ recognizer: UITapGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.began { delegate?.browserLocationViewDidLongPressLocation(self) } } @objc func SELtapLocation(_ recognizer: UITapGestureRecognizer) { delegate?.browserLocationViewDidTapLocation(self) } @objc func SELreaderModeCustomAction() -> Bool { return delegate?.browserLocationViewDidLongPressReaderMode(self) ?? false } fileprivate func updateTextWithURL() { if url == nil { urlTextField.text = "" return } if let httplessURL = url?.absoluteDisplayString, let baseDomain = url?.baseDomain { var urlString = httplessURL // remove https:// (the scheme) from the url when displaying if let scheme = url?.scheme, let range = urlString.range(of: "\(scheme)://") { urlString = urlString.replacingCharacters(in: range, with: "") } // color url path let attributedString = NSMutableAttributedString(string: urlString) let nsRange = NSMakeRange(0, urlString.count) attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: baseURLFontColor, range: nsRange) attributedString.colorSubstring(baseDomain, withColor: hostFontColor) attributedString.addAttribute(NSAttributedStringKey(rawValue: UIAccessibilitySpeechAttributePitch), value: NSNumber(value: BrowserLocationViewUX.BaseURLPitch), range: nsRange) attributedString.pitchSubstring(baseDomain, withPitch: BrowserLocationViewUX.HostPitch) urlTextField.attributedText = attributedString } else { // If we're unable to highlight the domain, just use the URL as is. urlTextField.text = url?.absoluteString } // postAsyncToMain(0.1) { // self.urlTextField.textColor = self.fullURLFontColor // } } } extension BrowserLocationView: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { // If the longPressRecognizer is active, fail all other recognizers to avoid conflicts. return gestureRecognizer == longPressRecognizer } } extension BrowserLocationView: AccessibilityActionsSource { func accessibilityCustomActionsForView(_ view: UIView) -> [UIAccessibilityCustomAction]? { if view === urlTextField { return delegate?.browserLocationViewLocationAccessibilityActions(self) } return nil } } extension BrowserLocationView: Themeable { func applyTheme(_ themeName: String) { guard let theme = BrowserLocationViewUX.Themes[themeName] else { log.error("Unable to apply unknown theme \(themeName)") return } guard let textColor = theme.textColor, let fontColor = theme.URLFontColor, let hostColor = theme.hostFontColor else { log.warning("Theme \(themeName) is missing one of required color values") return } urlTextField.textColor = textColor baseURLFontColor = fontColor hostFontColor = hostColor fullURLFontColor = textColor stopReloadButton.tintColor = textColor readerModeButton.tintColor = textColor backgroundColor = theme.backgroundColor } } private class ReaderModeButton: UIButton { override init(frame: CGRect) { super.init(frame: frame) tintColor = BraveUX.ActionButtonTintColor setImage(UIImage(named: "reader")!.withRenderingMode(.alwaysTemplate), for: .normal) setImage(UIImage(named: "reader_active"), for: UIControlState.selected) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var _readerModeState: ReaderModeState = ReaderModeState.Unavailable var readerModeState: ReaderModeState { get { return _readerModeState; } set (newReaderModeState) { _readerModeState = newReaderModeState switch _readerModeState { case .Available: self.isEnabled = true self.isSelected = false case .Unavailable: self.isEnabled = false self.isSelected = false case .Active: self.isEnabled = true self.isSelected = true } } } } private class DisplayTextField: UITextField { weak var accessibilityActionsSource: AccessibilityActionsSource? override var accessibilityCustomActions: [UIAccessibilityCustomAction]? { get { return accessibilityActionsSource?.accessibilityCustomActionsForView(self) } set { super.accessibilityCustomActions = newValue } } fileprivate override var canBecomeFirstResponder : Bool { return false } }
mpl-2.0
8e1aed4d6ee6297f19780fc7c1f1f60a
40.044444
200
0.682729
5.915658
false
false
false
false
daggmano/photo-management-studio
src/Client/OSX/Photo Management Studio/Photo Management Studio/JobResponseObject.swift
1
894
// // JobResponseObject.swift // Photo Management Studio // // Created by Darren Oster on 3/03/2016. // Copyright © 2016 Darren Oster. All rights reserved. // import Foundation class JobResponseObject : NSObject, JsonProtocol { internal private(set) var jobId: String? internal private(set) var status: String? init(jobId: String, status: String) { self.jobId = jobId self.status = status } required init(json: [String: AnyObject]) { self.jobId = json["jobId"] as? String self.status = json["status"] as? String } func toJSON() -> [String: AnyObject] { var result = [String: AnyObject]() if let jobId = self.jobId { result["jobId"] = jobId } if let status = self.status { result["status"] = status } return result } }
mit
f907a66d92c3d320bde9e9541a603b0e
23.135135
55
0.574468
4.272727
false
false
false
false
PonyGroup/PonyChatUI-Swift
PonyChatUI/Classes/User Interface/Presenter/MainPresenter.swift
1
1141
// // MainPresenter.swift // PonyChatUIProject // // Created by 崔 明辉 on 15/10/27. // // import Foundation extension PonyChatUI.UserInterface { public class MainPresenter { public let interactor = MainInteractor() weak var userInterface: MainViewController? init() { interactor.delegate = self } func insertMessage(count: Int) { if let userInterface = userInterface { userInterface.tableViewInsertRows(count) } } func appendMessage(count: Int) { if let userInterface = userInterface { dispatch_async(dispatch_get_main_queue(), { () -> Void in userInterface.tableViewAppendRows(count) }) } } func removeMessage(atIndex: Int) { if let userInterface = userInterface { dispatch_async(dispatch_get_main_queue(), { () -> Void in userInterface.tableViewRemoveRow(atIndex) }) } } } }
mit
1c28be0dfaa612ffcf4680d0d1c5ccb9
23.695652
73
0.514537
5.353774
false
false
false
false
everald/JetPack
Sources/Extensions/Swift/Dictionary.swift
1
1617
public extension Dictionary { public func filterAsDictionary(includeElement: (_ key: Key, _ value: Value) throws -> Bool) rethrows -> [Key : Value] { var filteredDictionary = [Key : Value]() for (key, value) in self where try includeElement(key, value) { filteredDictionary[key] = value } return filteredDictionary } public mutating func filterInPlace(includeElement: (_ key: Key, _ value: Value) throws -> Bool) rethrows { for (key, value) in self where !(try includeElement(key, value)) { self[key] = nil } } public func mapAsDictionary<K, V>(transform: (_ key: Key, _ value: Value) throws -> (K, V)) rethrows -> [K : V] { var mappedDictionary = [K : V](minimumCapacity: count) for (key, value) in self { let (mappedKey, mappedValue) = try transform(key, value) mappedDictionary[mappedKey] = mappedValue } return mappedDictionary } public func mapAsDictionaryNotNil<K, V>(transform: (_ key: Key, _ value: Value) throws -> (K?, V?)) rethrows -> [K : V] { var mappedDictionary = [K : V](minimumCapacity: count) for (key, value) in self { let (mappedKey, mappedValue) = try transform(key, value) if let mappedKey = mappedKey, let mappedValue = mappedValue { mappedDictionary[mappedKey] = mappedValue } } return mappedDictionary } public mutating func mapInPlace(transform: (_ value: Value) throws -> Value) rethrows { for (key, value) in self { self[key] = try transform(value) } } mutating func updateValues(_ fromDictionary: [Key : Value]) { for (key, value) in fromDictionary { updateValue(value, forKey: key) } } }
mit
c8f8ffe758caf1e7c33b361c27316337
26.40678
122
0.672851
3.455128
false
false
false
false
material-components/material-components-ios
components/List/examples/BaseCellExample.swift
2
5398
// Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import MaterialComponents.MaterialList import MaterialComponents.MaterialShadowElevations import MaterialComponents.MaterialContainerScheme class BaseCellExample: UIViewController { private let arbitraryCellHeight: CGFloat = 75 fileprivate let baseCellIdentifier: String = "baseCellIdentifier" fileprivate let numberOfCells: Int = 100 var containerScheme: MDCContainerScheming = MDCContainerScheme() private lazy var collectionView: UICollectionView = { return UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) }() private var collectionViewLayout: UICollectionViewFlowLayout { return collectionView.collectionViewLayout as! UICollectionViewFlowLayout } private var collectionViewEstimatedCellSize: CGSize { return CGSize( width: collectionView.bounds.size.width - 20, height: arbitraryCellHeight) } override func viewDidLoad() { super.viewDidLoad() parent?.automaticallyAdjustsScrollViewInsets = false automaticallyAdjustsScrollViewInsets = false setUpCollectionView() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() positionCollectionView() } func setUpCollectionView() { collectionViewLayout.estimatedItemSize = collectionViewEstimatedCellSize collectionViewLayout.minimumInteritemSpacing = 5 collectionViewLayout.minimumLineSpacing = 5 collectionView.backgroundColor = containerScheme.colorScheme.backgroundColor collectionView.register(MDCBaseCell.self, forCellWithReuseIdentifier: baseCellIdentifier) collectionView.delegate = self collectionView.dataSource = self view.addSubview(collectionView) } func positionCollectionView() { var originX = view.bounds.origin.x var originY = view.bounds.origin.y var width = view.bounds.size.width var height = view.bounds.size.height originX += view.safeAreaInsets.left originY += view.safeAreaInsets.top width -= (view.safeAreaInsets.left + view.safeAreaInsets.right) height -= (view.safeAreaInsets.top + view.safeAreaInsets.bottom) let frame = CGRect(x: originX, y: originY, width: width, height: height) collectionView.frame = frame collectionViewLayout.estimatedItemSize = collectionViewEstimatedCellSize collectionViewLayout.invalidateLayout() collectionView.reloadData() } } extension BaseCellExample: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) { guard let cell = collectionView.cellForItem(at: indexPath) as? MDCBaseCell else { fatalError() } cell.elevation = ShadowElevation(rawValue: 10) } func collectionView( _ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath ) { guard let cell = collectionView.cellForItem(at: indexPath) as? MDCBaseCell else { fatalError() } cell.elevation = ShadowElevation(rawValue: 0) } } extension BaseCellExample: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView( _ collectionView: UICollectionView, numberOfItemsInSection section: Int ) -> Int { return numberOfCells } static let colorNames: [String] = [ "Red", "Green", "Blue", "Orange", "Yellow", "Brown", "Cyan", "Purple", ] static let colorNameToColorMap: [String: UIColor] = [ "Red": .red, "Green": .green, "Blue": .blue, "Orange": .orange, "Yellow": .yellow, "Brown": .brown, "Cyan": .cyan, "Purple": .purple, ] func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath ) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell( withReuseIdentifier: baseCellIdentifier, for: indexPath) as? MDCBaseCell else { fatalError() } cell.layer.borderColor = containerScheme.colorScheme.onBackgroundColor.cgColor let styleIndex = indexPath.row % BaseCellExample.colorNames.count let colorName = BaseCellExample.colorNames[styleIndex] let backgroundColor = BaseCellExample.colorNameToColorMap[colorName] cell.accessibilityLabel = colorName cell.isAccessibilityElement = true cell.backgroundColor = backgroundColor cell.layer.borderWidth = 1 cell.inkColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1) return cell } } // MARK: Catalog By Convention extension BaseCellExample { @objc class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["List Items", "MDCBaseCell Example (Swift)"], "description": "MDCBaseCell Example (Swift)", "primaryDemo": true, "presentable": true, ] } }
apache-2.0
4b98bba12c99a01a28f18dc71365f589
33.382166
100
0.742682
5.030755
false
false
false
false
hamilyjing/JJSwiftNetwork
Service/JJSService.swift
1
2466
// // JJSService.swift // JJSwiftNetwork // // Created by JJ on 3/3/17. // Copyright © 2017 jianjing. All rights reserved. // import UIKit open class JJSService: NSObject { open func startRequest(request: JJSNetworkRequest, successAction: ((JJSNetworkBaseObjectProtocol, JJSNetworkRequest) -> Void)? = nil, failAcction: ((Error, JJSNetworkRequest) -> Void)? = nil) { request.successCompletionBlock = { baseRequest in let object = request.currentResponseObject(baseRequest.filterResponseString())! successAction?(object, request) self.handleResponseResult(success: true, object: object, request: request) } request.failureCompletionBlock = { baseRequest in let error = request.responseError failAcction?(error!, request) self.handleResponseResult(success: false, object:nil, request: request) } request.start() } open func responseCallBack(success: Bool, object: JJSNetworkBaseObjectProtocol?, request: JJSNetworkRequest) { var result: JJSResult<JJSNetworkBaseObjectProtocol> if success { result = JJSResult<JJSNetworkBaseObjectProtocol>.success(object!) } else { result = JJSResult<JJSNetworkBaseObjectProtocol>.failure(request.responseError!) } request.responseCallback?(result, request.otherInfo) } open func postResponseNotification(success: Bool, object: JJSNetworkBaseObjectProtocol?, request: JJSNetworkRequest) { var userInfo = [String: Any]() userInfo["success"] = success userInfo["identity"] = request.identity userInfo["parameter"] = request.httpParameters userInfo["object"] = object userInfo["error"] = request.responseError userInfo["otherInfo"] = request.otherInfo let notificationName = "\(self.classForCoder)_\(request.identity != nil ? request.identity! : request.buildRequestURL())" NotificationCenter.default.post(name: NSNotification.Name(rawValue: notificationName), object: self, userInfo: userInfo) } open func handleResponseResult(success: Bool, object: JJSNetworkBaseObjectProtocol?, request: JJSNetworkRequest) { responseCallBack(success: success, object: object, request: request) postResponseNotification(success: success, object: object, request: request) } }
mit
1575f19c1a68d2c33669482fb3274388
41.5
197
0.674239
4.767892
false
false
false
false
alltheflow/copypasta
CopyPasta/AppDelegate.swift
1
1800
// // AppDelegate.swift // CopyPasta // // Created by Agnes Vasarhelyi on 29/10/15. // Copyright © 2015 Agnes Vasarhelyi. All rights reserved. // import AppKit @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-2) let popover = NSPopover() var popoverTransiencyMonitor: AnyObject? func applicationDidFinishLaunching(aNotification: NSNotification) { statusItem.button!.image = NSImage(named: "pasta_icon") statusItem.button!.action = Selector("togglePopover:") let mainViewController = MainViewController(nibName: "MainViewController", bundle: nil) popover.behavior = .Semitransient popover.contentViewController = mainViewController } func applicationWillTerminate(aNotification: NSNotification) { } // MARK: popover actions func togglePopover(sender: AnyObject?) { if popover.shown { closePopover(sender) } else { openPopover(sender) } } func openPopover(sender: AnyObject?) { popover.showRelativeToRect(statusItem.button!.bounds, ofView: statusItem.button!, preferredEdge: .MinY) guard popoverTransiencyMonitor == nil else { return } popoverTransiencyMonitor = NSEvent.addGlobalMonitorForEventsMatchingMask([.RightMouseDownMask, .LeftMouseDownMask]) { _ in self.closePopover(sender) } } func closePopover(sender: AnyObject?) { popover.performClose(sender) guard let monitor = popoverTransiencyMonitor else { return } NSEvent.removeMonitor(monitor) popoverTransiencyMonitor = nil } }
mit
3c229fb1024a33916bf3f2f4630a8d7e
27.555556
130
0.658699
5.096317
false
false
false
false
tkach/SimpleRedditClient
SimpleRedditClient/Common/Services/DateFormatter/DateFormatter.swift
1
676
// // Created by Alexander Tkachenko on 9/10/17. // import Foundation final class DateFormatter { private lazy var formatter: DateComponentsFormatter = { let formatter = DateComponentsFormatter() formatter.unitsStyle = .full formatter.maximumUnitCount = 1 formatter.allowedUnits = [.year, .month, .day, .hour, .minute, .second] return formatter }() func formattedDate(date: Date) -> String { let now = Date() guard let timeString = formatter.string(from: date, to: now) else { return "" } let ago = "DateFormatter.Ago".localized() return timeString + " " + ago } }
mit
d3e78fe40b3d3c8e1fdecdd2684f85b4
27.166667
79
0.612426
4.506667
false
false
false
false
jhliberty/GitLabKit
GitLabKit/Project.swift
1
5074
// // Project.swift // GitLabKit // // Copyright (c) 2015 orih. 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 import Mantle public class Project: GitLabModel, Fetchable, Creatable, Editable, Deletable { public var id: NSNumber? public var descriptionText: String? // "description" as a property name is not allowed by compiler public var defaultBranch: String? public var _isPublic: NSNumber? public var isPublic: Bool { get { return _isPublic? != nil ? _isPublic!.boolValue : false } set { _isPublic = NSNumber(bool: newValue)} } public var visibilityLevel: NSNumber? public var sshUrlToRepo: String? public var httpUrlToRepo: String? public var webUrl: String? public var owner: User? public var name: String? public var nameWithNamespace: String? public var path: String? public var pathWithNamespace: String? public var _issuesEnabled: NSNumber? public var issuesEnabled: Bool { get { return _issuesEnabled? != nil ? _issuesEnabled!.boolValue : false } set { _issuesEnabled = NSNumber(bool: newValue)} } public var _mergeRequestsEnabled: NSNumber? public var mergeRequestsEnabled: Bool { get { return _mergeRequestsEnabled? != nil ? _mergeRequestsEnabled!.boolValue : false } set { _mergeRequestsEnabled = NSNumber(bool: newValue)} } public var _wikiEnabled: NSNumber? public var wikiEnabled: Bool { get { return _wikiEnabled? != nil ? _wikiEnabled!.boolValue : false } set { _wikiEnabled = NSNumber(bool: newValue)} } public var _snippetsEnabled: NSNumber? public var snippetsEnabled: Bool { get { return _snippetsEnabled? != nil ? _snippetsEnabled!.boolValue : false } set { _snippetsEnabled = NSNumber(bool: newValue)} } public var createdAt: NSDate? public var lastActivityAt: NSDate? public var namespace: Namespace? public var _archived: NSNumber? public var archived: Bool { get { return _archived? != nil ? _archived!.boolValue : false } set { _archived = NSNumber(bool: newValue)} } public override class func JSONKeyPathsByPropertyKey() -> [NSObject : AnyObject]! { var baseKeys: [NSObject : AnyObject] = super.JSONKeyPathsByPropertyKey() var newKeys: [NSObject : AnyObject] = [ "id" : "id", "descriptionText" : "description", "defaultBranch" : "default_branch", "_isPublic" : "public", "visibilityLevel" : "visibility_level", "sshUrlToRepo" : "ssh_url_to_repo", "httpUrlToRepo" : "http_url_to_repo", "webUrl" : "web_url", "owner" : "owner", "name" : "name", "nameWithNamespace" : "name_with_namespace", "path" : "path", "pathWithNamespace" :"path_with_namespace", "_issuesEnabled" : "issues_enabled", "_mergeRequestsEnabled" : "merge_requests_enabled", "_wikiEnabled" : "wiki_enabled", "_snippetsEnabled" : "snippets_enabled", "createdAt" : "created_at", "lastActivityAt" : "last_activity_at", "namespace" : "namespace", "_archived" : "archived" ] return baseKeys + newKeys } class func ownerJSONTransformer() -> NSValueTransformer { return ModelUtil<User>.transformer() } class func namespaceJSONTransformer() -> NSValueTransformer { return ModelUtil<Namespace>.transformer() } class func createdAtJSONTransformer() -> NSValueTransformer { return dateTimeTransformer } class func lastActivityAtJSONTransformer() -> NSValueTransformer { return dateTimeTransformer } }
mit
888ff199a5528f46e459e6a4626fcbf9
42.75
102
0.630863
4.55885
false
false
false
false
fgulan/letter-ml
project/LetterML/Frameworks/framework/Source/Operations/OpeningFilter.swift
9
447
public class OpeningFilter: OperationGroup { public var radius:UInt { didSet { erosion.radius = radius dilation.radius = radius } } let erosion = Erosion() let dilation = Dilation() public override init() { radius = 1 super.init() self.configureGroup{input, output in input --> self.erosion --> self.dilation --> output } } }
mit
5f3f07bf110ed54e25727c2b58090dac
22.578947
63
0.530201
4.515152
false
true
false
false
savelii/BSON
Sources/Document.swift
1
16876
// // Document.swift // BSON // // Created by Robbert Brandsma on 19-05-16. // // import Foundation public protocol StringVariant { var bsonStringBinary: [UInt8] { get } } extension StaticString: StringVariant { public var bsonStringBinary: [UInt8] { var keyData = [UInt8](repeating: 0, count: self.utf8CodeUnitCount) memcpy(&keyData, self.utf8Start, keyData.count) return keyData } } extension String: StringVariant { public var bsonStringBinary: [UInt8] { return [UInt8](self.utf8) } } public protocol _DocumentProtocolForArrayAdditions { var bytes: [UInt8] { get } init(data: [UInt8]) init(data: ArraySlice<UInt8>) func validate() -> Bool } extension Document : _DocumentProtocolForArrayAdditions {} public typealias IndexIterationElement = (key: String, value: ValueConvertible) extension Array where Element : _DocumentProtocolForArrayAdditions { /// The combined data for all documents in the array public var bytes: [UInt8] { return self.map { $0.bytes }.reduce([], +) } public init(bsonBytes data: Data, validating: Bool = false) { var buffer = [UInt8](repeating: 0, count: data.count) data.copyBytes(to: &buffer, count: buffer.count) self.init(bsonBytes: buffer, validating: validating) } public init(bsonBytes bytes: [UInt8], validating: Bool = false) { var array = [Element]() var position = 0 let byteCount = bytes.count documentLoop: while byteCount >= position + 5 { let length = Int(bytes[position..<position+4].makeInt32()) guard length > 0 else { // invalid break } guard byteCount >= position + length else { break documentLoop } let document = Element(data: [UInt8](bytes[position..<position+length])) if validating { if document.validate() { array.append(document) } } else { array.append(document) } position += length } self = array } } public enum ElementType : UInt8 { case double = 0x01 case string = 0x02 case document = 0x03 case arrayDocument = 0x04 case binary = 0x05 case objectId = 0x07 case boolean = 0x08 case utcDateTime = 0x09 case nullValue = 0x0A case regex = 0x0B case javascriptCode = 0x0D case javascriptCodeWithScope = 0x0F case int32 = 0x10 case timestamp = 0x11 case int64 = 0x12 case decimal128 = 0x13 case minKey = 0xFF case maxKey = 0x7F } /// `Document` is a collection type that uses a BSON document as storage. /// As such, it can be stored in a file or instantiated from BSON data. /// /// Documents behave partially like an array, and partially like a dictionary. /// For general information about BSON documents, see http://bsonspec.org/spec.html public struct Document : Collection, ExpressibleByDictionaryLiteral, ExpressibleByArrayLiteral { internal var storage: [UInt8] internal var _count: Int? = nil internal var invalid = false internal var elementPositions = [Int]() internal var isArray: Bool = false // MARK: - Initialization from data /// Initializes this Doucment with binary `Foundation.Data` /// /// - parameters data: the `Foundation.Data` that's being used to initialize this`Document` public init(data: Foundation.Data) { var byteArray = [UInt8](repeating: 0, count: data.count) data.copyBytes(to: &byteArray, count: byteArray.count) self.init(data: byteArray) } /// Initializes this Doucment with an `Array` of `Byte`s - I.E: `[Byte]` /// /// - parameters data: the `[Byte]` that's being used to initialize this `Document` public init(data: [UInt8]) { guard data.count > 4 else { self.storage = [5,0,0,0] self.invalid = true return } let length = Int(data[0...3].makeInt32()) guard length <= data.count, data.last == 0x00 else { self.storage = [5,0,0,0] self.invalid = true return } storage = Array(data[0..<Swift.max(length - 1, 0)]) elementPositions = buildElementPositionsCache() isArray = validatesAsArray() } /// Initializes this Doucment with an `Array` of `Byte`s - I.E: `[Byte]` /// /// - parameters data: the `[Byte]` that's being used to initialize this `Document` public init(data: ArraySlice<UInt8>) { guard data.count > 4 else { self.storage = [5,0,0,0] self.invalid = true return } storage = Array(data[data.startIndex..<data.endIndex.advanced(by: -1)]) var length: UInt32 = 0 memcpy(&length, &storage, 4) guard numericCast(length) <= data.count, data.last == 0x00 else { self.storage = [5,0,0,0] self.invalid = true return } elementPositions = buildElementPositionsCache() isArray = self.validatesAsArray() } /// Initializes an empty `Document` public init() { // the empty document is 5 bytes long. storage = [5,0,0,0] } // MARK: - Initialization from Swift Types & Literals /// Initializes this `Document` as a `Dictionary` using an existing Swift `Dictionary` /// /// - parameter elements: The `Dictionary`'s generics used to initialize this must be a `String` key and `Value` for the value public init(dictionaryElements elements: [(StringVariant, ValueConvertible?)]) { storage = [5,0,0,0] for (key, value) in elements { guard let value = value?.makeBSONPrimitive() else { continue } // Append the key-value pair // Add element to positions cache elementPositions.append(storage.endIndex) // Type identifier storage.append(value.typeIdentifier) // Key storage.append(contentsOf: key.bsonStringBinary) // Key null terminator storage.append(0x00) // Value let data = value.makeBSONBinary() storage.append(contentsOf: data) } updateDocumentHeader() isArray = false } /// Initializes this `Document` as a `Dictionary` using a `Dictionary` literal /// /// - parameter elements: The `Dictionary` used to initialize this must use `String` for key and `Value` for values public init(dictionaryLiteral elements: (StringVariant, ValueConvertible?)...) { self.init(dictionaryElements: elements) } /// Initializes this `Document` as an `Array` using an `Array` literal /// /// - parameter elements: The `Array` literal used to initialize the `Document` must be a `[Value]` public init(arrayLiteral elements: ValueConvertible?...) { self.init(array: elements) } /// Initializes this `Document` as an `Array` using an `Array` /// /// - parameter elements: The `Array` used to initialize the `Document` must be a `[Value]` public init(array elements: [ValueConvertible?]) { storage = [5,0,0,0] for (index, value) in elements.enumerated() { guard let value = value?.makeBSONPrimitive() else { continue } // Append the values // Add element to positions cache elementPositions.append(storage.endIndex) // Type identifier storage.append(value.typeIdentifier) // Key storage.append(contentsOf: "\(index)".utf8) // Key null terminator storage.append(0x00) // Value storage.append(contentsOf: value.makeBSONBinary()) } updateDocumentHeader() isArray = true } // MARK: - Manipulation & Extracting values public typealias Index = DocumentIndex /// Appends a Key-Value pair to this `Document` where this `Document` acts like a `Dictionary` /// /// TODO: Analyze what should happen with `Array`-like documents and this function /// TODO: Analyze what happens when you append with a duplicate key /// /// - parameter value: The `Value` to append /// - parameter key: The key in the key-value pair public mutating func append(_ value: ValueConvertible, forKey key: String) { let value = value.makeBSONPrimitive() // We're going to insert the element before the Document null terminator elementPositions.append(storage.endIndex) // Append the key-value pair // Type identifier storage.append(value.typeIdentifier) // Key storage.append(contentsOf: key.utf8) // Key null terminator storage.append(0x00) // Value storage.append(contentsOf: value.makeBSONBinary()) // Increase the bytecount updateDocumentHeader() isArray = false } /// Appends a Key-Value pair to this `Document` where this `Document` acts like a `Dictionary` /// /// TODO: Analyze what should happen with `Array`-like documents and this function /// TODO: Analyze what happens when you append with a duplicate key /// /// - parameter value: The `Value` to append /// - parameter key: The key in the key-value pair internal mutating func append(_ value: ValueConvertible, forKey key: [UInt8]) { let value = value.makeBSONPrimitive() // We're going to insert the element before the Document null terminator elementPositions.append(storage.endIndex) // Append the key-value pair // Type identifier storage.append(value.typeIdentifier) // Key storage.append(contentsOf: key) // Key null terminator storage.append(0x00) // Value storage.append(contentsOf: value.makeBSONBinary()) // Increase the bytecount updateDocumentHeader() isArray = false } /// Appends a `Value` to this `Document` where this `Document` acts like an `Array` /// /// TODO: Analyze what should happen with `Dictionary`-like documents and this function /// /// - parameter value: The `Value` to append public mutating func append(_ value: ValueConvertible) { let value = value.makeBSONPrimitive() let key = "\(self.count)" // We're going to insert the element before the Document null terminator elementPositions.append(storage.endIndex) // Append the key-value pair // Type identifier storage.append(value.typeIdentifier) // Key storage.append(contentsOf: key.utf8) // Key null terminator storage.append(0x00) // Value storage.append(contentsOf: value.makeBSONBinary()) // Increase the bytecount updateDocumentHeader() } /// Appends the convents of `otherDocument` to `self` overwriting any keys in `self` with the `otherDocument` equivalent in the case of duplicates public mutating func append(contentsOf otherDocument: Document) { if self.validatesAsArray() && otherDocument.validatesAsArray() { self = Document(array: self.arrayValue + otherDocument.arrayValue) } else { self += otherDocument } } /// Updates this `Document`'s storage to contain the proper `Document` length header internal mutating func updateDocumentHeader() { // One extra byte for the missing null terminator in the storage var count = Int32(storage.count + 1) memcpy(&storage, &count, 4) } // MARK: - Collection /// The first `Index` in this `Document`. Can point to nothing when the `Document` is empty public var startIndex: DocumentIndex { return DocumentIndex(byteIndex: 4) } /// The last `Index` in this `Document`. Can point to nothing whent he `Document` is empty public var endIndex: DocumentIndex { var thisIndex = 4 for element in self.makeKeyIterator() { thisIndex = element.startPosition } return DocumentIndex(byteIndex: thisIndex) } /// Creates an iterator that iterates over all key-value pairs public func makeIterator() -> AnyIterator<IndexIterationElement> { let keys = self.makeKeyIterator() return AnyIterator { guard let key = keys.next() else { return nil } guard let string = String(bytes: key.keyData[0..<key.keyData.endIndex-1], encoding: String.Encoding.utf8) else { return nil } guard let value = self.getValue(atDataPosition: key.dataPosition, withType: key.type) else { return nil } return IndexIterationElement(key: string, value: value) } } /// Fetches the next index /// /// - parameter i: The `Index` to advance public func index(after i: DocumentIndex) -> DocumentIndex { var position = i.byteIndex guard let type = ElementType(rawValue: storage[position]) else { fatalError("Invalid type found in Document when finding the next key at position \(position)") } position += 1 while storage[position] != 0 { position += 1 } position += 1 let length = getLengthOfElement(withDataPosition: position, type: type) // Return the position of the byte after the value return DocumentIndex(byteIndex: position + length) } /// Finds the key-value pair for the given key and removes it /// /// - parameter key: The `key` in the key-value pair to remove /// /// - returns: The `Value` in the pair if there was any @discardableResult public mutating func removeValue(forKey key: String) -> ValueConvertible? { guard let meta = getMeta(forKeyBytes: [UInt8](key.utf8)) else { return nil } let val = getValue(atDataPosition: meta.dataPosition, withType: meta.type) let length = getLengthOfElement(withDataPosition: meta.dataPosition, type: meta.type) guard meta.dataPosition + length <= storage.count else { return nil } storage.removeSubrange(meta.elementTypePosition..<meta.dataPosition + length) let removedLength = (meta.dataPosition + length) - meta.elementTypePosition for (index, element) in elementPositions.enumerated() where element > meta.elementTypePosition { elementPositions[index] = elementPositions[index] - removedLength } if let index = elementPositions.index(of: meta.elementTypePosition) { elementPositions.remove(at: index) } updateDocumentHeader() return val } // MARK: - Files /// Writes this `Document` to a file. Usually for debugging purposes /// /// - parameter path: The path to write this to public func write(toFile path: String) throws { var myData = storage let nsData = NSData(bytes: &myData, length: myData.count) try nsData.write(toFile: path) } } public struct DocumentIndex : Comparable { // The byte index is the very start of the element, the element type internal var byteIndex: Int internal init(byteIndex: Int) { self.byteIndex = byteIndex } public static func ==(lhs: DocumentIndex, rhs: DocumentIndex) -> Bool { return lhs.byteIndex == rhs.byteIndex } public static func <(lhs: DocumentIndex, rhs: DocumentIndex) -> Bool { return lhs.byteIndex < rhs.byteIndex } } extension Sequence where Iterator.Element == Document { /// Converts a sequence of Documents to an array of documents in BSON format public func makeDocument() -> Document { var combination = [] as Document for doc in self { combination.append(doc) } return combination } }
mit
bc5a92611d491dc9453975880453b63d
32.285996
150
0.592795
4.655448
false
false
false
false
alpascual/DigitalWil
FrostedSidebar/FrostedSidebar.swift
1
18663
// // FrostedSidebar.swift // CustomStuff // // Created by Evan Dekhayser on 7/9/14. // Copyright (c) 2014 Evan Dekhayser. All rights reserved. // import UIKit import QuartzCore public protocol FrostedSidebarDelegate{ func sidebar(sidebar: FrostedSidebar, willShowOnScreenAnimated animated: Bool) func sidebar(sidebar: FrostedSidebar, didShowOnScreenAnimated animated: Bool) func sidebar(sidebar: FrostedSidebar, willDismissFromScreenAnimated animated: Bool) func sidebar(sidebar: FrostedSidebar, didDismissFromScreenAnimated animated: Bool) func sidebar(sidebar: FrostedSidebar, didTapItemAtIndex index: Int) func sidebar(sidebar: FrostedSidebar, didEnable itemEnabled: Bool, itemAtIndex index: Int) } var sharedSidebar: FrostedSidebar? public class FrostedSidebar: UIViewController { //MARK: Public Properties public var width: CGFloat = 145.0 public var showFromRight: Bool = false public var animationDuration: CGFloat = 0.25 public var itemSize: CGSize = CGSize(width: 90.0, height: 90.0) public var tintColor: UIColor = UIColor(white: 0.2, alpha: 0.73) public var itemBackgroundColor: UIColor = UIColor(white: 1, alpha: 0.25) public var borderWidth: CGFloat = 2 public var delegate: FrostedSidebarDelegate? = nil public var actionForIndex: [Int : ()->()] = [:] public var selectedIndices: NSMutableIndexSet = NSMutableIndexSet() //Only one of these properties can be used at a time. If one is true, the other automatically is false public var isSingleSelect: Bool = false{ didSet{ if isSingleSelect{ calloutsAlwaysSelected = false } } } public var calloutsAlwaysSelected: Bool = false{ didSet{ if calloutsAlwaysSelected{ isSingleSelect = false selectedIndices = NSMutableIndexSet(indexesInRange: NSRange(location: 0,length: images.count) ) } } } //MARK: Private Properties private var contentView: UIScrollView = UIScrollView() private var blurView: UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Dark)) //private var blurView: UIView = UIView() private var dimView: UIView = UIView() private var tapGesture: UITapGestureRecognizer? = nil private var images: [UIImage] = [] private var borderColors: [UIColor]? = nil private var itemViews: [CalloutItem] = [] //MARK: Public Methods public init(itemImages: [UIImage], colors: [UIColor]?, selectedItemIndices: NSIndexSet?){ contentView.alwaysBounceHorizontal = false contentView.alwaysBounceVertical = true contentView.bounces = true contentView.clipsToBounds = false contentView.showsHorizontalScrollIndicator = false contentView.showsVerticalScrollIndicator = false if (colors != nil){ assert(itemImages.count == colors!.count, "If item color are supplied, the itemImages and colors arrays must be of the same size.") } //(selectedIndices = selectedItemIndices ? NSMutableIndexSet(indexSet: selectedItemIndices!) : NSMutableIndexSet() != nil) borderColors = colors images = itemImages for (index, image) in enumerate(images){ let view = CalloutItem(index: index) view.clipsToBounds = true view.imageView.image = image contentView.addSubview(view) itemViews.append(view) if (borderColors != nil){ if selectedIndices.containsIndex(index){ let color = borderColors![index] view.layer.borderColor = color.CGColor } } else{ view.layer.borderColor = UIColor.clearColor().CGColor } } super.init(nibName: nil, bundle: nil) } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // contentView.alwaysBounceHorizontal = false // contentView.alwaysBounceVertical = true // contentView.bounces = true // contentView.clipsToBounds = false // contentView.showsHorizontalScrollIndicator = false // contentView.showsVerticalScrollIndicator = false // } public override func loadView() { super.loadView() view.backgroundColor = UIColor.clearColor() view.addSubview(dimView) view.addSubview(blurView) view.addSubview(contentView) tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:") view.addGestureRecognizer(tapGesture!) } public override func shouldAutorotate() -> Bool { return true } public override func supportedInterfaceOrientations() -> Int { return Int(UIInterfaceOrientationMask.All.rawValue) } public override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { super.willAnimateRotationToInterfaceOrientation(toInterfaceOrientation, duration: duration) if isViewLoaded(){ dismissAnimated(false, completion: nil) } } public func showInViewController(viewController: UIViewController, animated: Bool){ if let bar = sharedSidebar{ bar.dismissAnimated(false, completion: nil) } delegate?.sidebar(self, willShowOnScreenAnimated: animated) sharedSidebar = self addToParentViewController(viewController, callingAppearanceMethods: true) view.frame = viewController.view.bounds dimView.backgroundColor = UIColor.blackColor() dimView.alpha = 0 dimView.frame = view.bounds let parentWidth = view.bounds.size.width var contentFrame = view.bounds contentFrame.origin.x = showFromRight ? parentWidth : -width contentFrame.size.width = width contentView.frame = contentFrame contentView.contentOffset = CGPoint(x: 0, y: 0) layoutItems() var blurFrame = CGRect(x: showFromRight ? view.bounds.size.width : 0, y: 0, width: 0, height: view.bounds.size.height) blurView.frame = blurFrame blurView.contentMode = showFromRight ? UIViewContentMode.TopRight : UIViewContentMode.TopLeft blurView.clipsToBounds = true view.insertSubview(blurView, belowSubview: contentView) contentFrame.origin.x = showFromRight ? parentWidth - width : 0 blurFrame.origin.x = contentFrame.origin.x blurFrame.size.width = width let animations: () -> () = { self.contentView.frame = contentFrame self.blurView.frame = blurFrame self.dimView.alpha = 0.25 } let completion: (Bool) -> Void = { finished in if finished{ self.delegate?.sidebar(self, didShowOnScreenAnimated: animated) } } if animated{ UIView.animateWithDuration(NSTimeInterval(animationDuration), delay: 0, options: UIViewAnimationOptions(rawValue: UInt(kNilOptions))!, animations: animations, completion: completion) } else{ animations() completion(true) } for (index, item) in enumerate(itemViews){ item.layer.transform = CATransform3DMakeScale(0.3, 0.3, 1) item.alpha = 0 item.originalBackgroundColor = itemBackgroundColor item.layer.borderWidth = borderWidth animateSpringWithView(item, idx: index, initDelay: animationDuration) } } public func dismissAnimated(animated: Bool, completion: ((Bool) -> Void)?){ let completionBlock: (Bool) -> Void = {finished in self.removeFromParentViewControllerCallingAppearanceMethods(true) self.delegate?.sidebar(self, didDismissFromScreenAnimated: true) self.layoutItems() if (completion != nil){ completion!(finished) } } delegate?.sidebar(self, willDismissFromScreenAnimated: animated) if animated{ let parentWidth = view.bounds.size.width var contentFrame = contentView.frame contentFrame.origin.x = showFromRight ? parentWidth : -width var blurFrame = blurView.frame blurFrame.origin.x = showFromRight ? parentWidth : 0 blurFrame.size.width = 0 UIView.animateWithDuration(NSTimeInterval(animationDuration), delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { self.contentView.frame = contentFrame self.blurView.frame = blurFrame self.dimView.alpha = 0 }, completion: completionBlock) } else{ completionBlock(true) } } //MARK: Private Classes private class CalloutItem: UIView{ var imageView: UIImageView = UIImageView() var itemIndex: Int var originalBackgroundColor:UIColor? { didSet{ self.backgroundColor = originalBackgroundColor } } init(index: Int){ imageView.backgroundColor = UIColor.clearColor() imageView.contentMode = UIViewContentMode.ScaleAspectFit itemIndex = index super.init(frame: CGRect.zeroRect) addSubview(imageView) } required init(coder aDecoder: NSCoder) { imageView.backgroundColor = UIColor.clearColor() imageView.contentMode = UIViewContentMode.ScaleAspectFit itemIndex = 0 super.init(frame: CGRect.zeroRect) addSubview(imageView) } override func layoutSubviews() { super.layoutSubviews() let inset: CGFloat = bounds.size.height/2 imageView.frame = CGRect(x: 0, y: 0, width: inset, height: inset) imageView.center = CGPoint(x: inset, y: inset) } override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) { super.touchesBegan(touches, withEvent: event) var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 let darkenFactor: CGFloat = 0.3 var darkerColor: UIColor if (originalBackgroundColor?.getRed(&r, green: &g, blue: &b, alpha: &a) != nil){ darkerColor = UIColor(red: max(r - darkenFactor, 0), green: max(g - darkenFactor, 0), blue: max(b - darkenFactor, 0), alpha: a) } else if (originalBackgroundColor?.getWhite(&r, alpha: &a) != nil){ darkerColor = UIColor(white: max(r - darkenFactor, 0), alpha: a) } else{ darkerColor = UIColor.clearColor() assert(false, "Item color should be RBG of White/Alpha in order to darken the button") } backgroundColor = darkerColor } override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) { super.touchesEnded(touches, withEvent: event) backgroundColor = originalBackgroundColor } override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) { super.touchesCancelled(touches, withEvent: event) backgroundColor = originalBackgroundColor } } //MARK: Private Methods private func animateSpringWithView(view: CalloutItem, idx: Int, initDelay: CGFloat){ let delay: NSTimeInterval = NSTimeInterval(initDelay) + NSTimeInterval(idx) * 0.1 UIView.animateWithDuration(0.5, delay: delay, usingSpringWithDamping: 10.0, initialSpringVelocity: 50.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { view.layer.transform = CATransform3DIdentity view.alpha = 1 }, completion: nil) } @objc private func handleTap(recognizer: UITapGestureRecognizer){ let location = recognizer.locationInView(view) if !CGRectContainsPoint(contentView.frame, location){ dismissAnimated(true, completion: nil) } else{ let tapIndex = indexOfTap(recognizer.locationInView(contentView)) if (tapIndex != nil){ didTapItemAtIndex(tapIndex!) } } } private func didTapItemAtIndex(index: Int){ let didEnable = !selectedIndices.containsIndex(index) if (borderColors != nil){ let stroke = borderColors![index] let item = itemViews[index] if didEnable{ if isSingleSelect{ selectedIndices.removeAllIndexes() for (index, item) in enumerate(itemViews){ item.layer.borderColor = UIColor.clearColor().CGColor } } item.layer.borderColor = stroke.CGColor var borderAnimation = CABasicAnimation(keyPath: "borderColor") borderAnimation.fromValue = UIColor.clearColor().CGColor borderAnimation.toValue = stroke.CGColor borderAnimation.duration = 0.5 item.layer.addAnimation(borderAnimation, forKey: nil) selectedIndices.addIndex(index) } else{ if !isSingleSelect{ if !calloutsAlwaysSelected{ item.layer.borderColor = UIColor.clearColor().CGColor selectedIndices.removeIndex(index) } } } let pathFrame = CGRect(x: -CGRectGetMidX(item.bounds), y: -CGRectGetMidY(item.bounds), width: item.bounds.size.width, height: item.bounds.size.height) let path = UIBezierPath(roundedRect: pathFrame, cornerRadius: item.layer.cornerRadius) let shapePosition = view.convertPoint(item.center, fromView: contentView) let circleShape = CAShapeLayer() circleShape.path = path.CGPath circleShape.position = shapePosition circleShape.fillColor = UIColor.clearColor().CGColor circleShape.opacity = 0 circleShape.strokeColor = stroke.CGColor circleShape.lineWidth = borderWidth view.layer.addSublayer(circleShape) let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.fromValue = NSValue(CATransform3D: CATransform3DIdentity) scaleAnimation.toValue = NSValue(CATransform3D: CATransform3DMakeScale(2.5, 2.5, 1)) let alphaAnimation = CABasicAnimation(keyPath: "opacity") alphaAnimation.fromValue = 1 alphaAnimation.toValue = 0 let animation = CAAnimationGroup() animation.animations = [scaleAnimation, alphaAnimation] animation.duration = 0.5 animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) circleShape.addAnimation(animation, forKey: nil) } if let action = actionForIndex[index]{ action() } delegate?.sidebar(self, didTapItemAtIndex: index) delegate?.sidebar(self, didEnable: didEnable, itemAtIndex: index) } private func layoutSubviews(){ let x = showFromRight ? parentViewController!.view.bounds.size.width - width : 0 contentView.frame = CGRect(x: x, y: 0, width: width, height: parentViewController!.view.bounds.size.height) blurView.frame = contentView.frame layoutItems() } private func layoutItems(){ let leftPadding: CGFloat = (width - itemSize.width) / 2 let topPadding: CGFloat = leftPadding for (index, item) in enumerate(itemViews){ let idx: CGFloat = CGFloat(index) let frame = CGRect(x: leftPadding, y: topPadding*idx + itemSize.height*idx + topPadding, width:itemSize.width, height: itemSize.height) item.frame = frame item.layer.cornerRadius = frame.size.width / 2 item.layer.borderColor = UIColor.clearColor().CGColor item.alpha = 0 if selectedIndices.containsIndex(index){ if (borderColors != nil){ item.layer.borderColor = borderColors![index].CGColor } } } let itemCount = CGFloat(itemViews.count) contentView.contentSize = CGSizeMake(0, itemCount * (itemSize.height + topPadding) + topPadding) } private func indexOfTap(location: CGPoint) -> Int? { var index: Int? for (idx, item) in enumerate(itemViews){ if CGRectContainsPoint(item.frame, location){ index = idx break } } return index } private func addToParentViewController(viewController: UIViewController, callingAppearanceMethods: Bool){ if (parentViewController != nil){ removeFromParentViewControllerCallingAppearanceMethods(callingAppearanceMethods) } if callingAppearanceMethods{ beginAppearanceTransition(true, animated: false) } viewController.addChildViewController(self) viewController.view.addSubview(self.view) didMoveToParentViewController(self) if callingAppearanceMethods{ endAppearanceTransition() } } private func removeFromParentViewControllerCallingAppearanceMethods(callAppearanceMethods: Bool){ if callAppearanceMethods{ beginAppearanceTransition(false, animated: false) } willMoveToParentViewController(nil) view.removeFromSuperview() removeFromParentViewController() if callAppearanceMethods{ endAppearanceTransition() } } }
mit
cef58a6d7a20797404f0cce53d0fbe52
41.036036
194
0.608637
5.502064
false
false
false
false
box/box-ios-sdk
Sources/Modules/AuthModuleDispatcher.swift
1
1003
// // AuthModuleDispatcher.swift // BoxSDK // // Created by Daniel Cech on 13/06/2019. // Copyright © 2019 Box. All rights reserved. // import Foundation class AuthModuleDispatcher { let authQueue = ThreadSafeQueue<AuthActionTuple>(completionQueue: DispatchQueue.main) var active = false static var current = 1 func start(action: @escaping AuthActionClosure) { let currentId = AuthModuleDispatcher.current AuthModuleDispatcher.current += 1 authQueue.enqueue((id: currentId, action: action)) { if !self.active { self.active = true self.processAction() } } } func processAction() { authQueue.dequeue { [weak self] action in if let unwrappedAction = action { unwrappedAction.action { self?.processAction() } } else { self?.active = false } } } }
apache-2.0
4094c9f5eb171f0059ed507859c13537
22.857143
89
0.558882
4.794258
false
false
false
false
arslan2012/Lazy-Hackintosh-Image-Generator
LazyHackintoshGenerator/FileDropZone.swift
1
6365
import Cocoa protocol FileDropZoneProtocol: class { func didReceiveInstaller(_ filePath: String) func didReceiveExtra(_ filePath: String) } class FileDropZone: NSImageView { weak var viewDelegate: FileDropZoneProtocol? let icnSize = NSMakeSize(CGFloat(100), CGFloat(100)) var icn: NSImage? { return nil } var fileTypes: [String] { return [] } var isDirectories: Bool { return false } var droppedFilePath = "" var fileTypeIsOk = false required init?(coder: NSCoder) { super.init(coder: coder) registerForDraggedTypes([NSPasteboard.PasteboardType(kUTTypeFileURL as String), NSPasteboard.PasteboardType(kUTTypeItem as String)]) icn!.size = self.icnSize self.image = icn } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) } override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { if checkExtension(sender) == true { self.fileTypeIsOk = true return .copy } else { self.fileTypeIsOk = false return NSDragOperation() } } override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation { if self.fileTypeIsOk { return .copy } else { return NSDragOperation() } } override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { if let board = sender.draggingPasteboard.propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")) as? NSArray { if let imagePath = board[0] as? String { self.droppedFilePath = imagePath return true } } return false } func checkExtension(_ drag: NSDraggingInfo) -> Bool { if let board = drag.draggingPasteboard.propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")) as? NSArray, let path = board[0] as? String { let url = URL(fileURLWithPath: path) if self.isDirectories { let suffix = url.lastPathComponent var isDirectory: ObjCBool = ObjCBool(false) FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) for ext in self.fileTypes { if isDirectory.boolValue && suffix.caseInsensitiveCompare(ext) == ComparisonResult.orderedSame { return true } } } else { let suffix = url.pathExtension for ext in self.fileTypes { if ext.lowercased() == suffix { return true } } } } return false } } class InstallerDrop: FileDropZone { override var icn: NSImage? { return NSImage(named: NSImage.Name("image"))! } override var fileTypes: [String] { return ["dmg", "app"] } override func draggingEnded(_ sender: NSDraggingInfo) { if self.fileTypeIsOk && self.droppedFilePath != "" { viewDelegate!.didReceiveInstaller(self.droppedFilePath) let icn = NSImage(named: NSImage.Name("icon-osx")) icn?.size = self.icnSize self.image = icn } } override func mouseDown(with theEvent: NSEvent) { let clickCount = theEvent.clickCount if clickCount > 1 { DispatchQueue.main.async(execute: { let myFiledialog = NSOpenPanel() myFiledialog.prompt = "Open" myFiledialog.worksWhenModal = true myFiledialog.allowsMultipleSelection = false myFiledialog.resolvesAliases = true myFiledialog.title = "#Image Title#".localized() myFiledialog.message = "#Image Msg#".localized() myFiledialog.allowedFileTypes = ["dmg", "app"] myFiledialog.runModal() if let URL = myFiledialog.url { let Path = URL.path if Path != "" { self.viewDelegate!.didReceiveInstaller(Path) let icn = NSImage(named: NSImage.Name("icon-osx")) icn?.size = self.icnSize self.image = icn } } }) } } } class ExtraDrop: FileDropZone { override var icn: NSImage? { return NSImage(named: NSImage.Name("drive"))! } override var fileTypes: [String] { return ["extra"] } override var isDirectories: Bool { return true } override func draggingEnded(_ sender: NSDraggingInfo) { if self.droppedFilePath != "" && self.fileTypeIsOk { viewDelegate!.didReceiveExtra(self.droppedFilePath) let icn = NSImage(named: NSImage.Name("Chameleon")) icn?.size = self.icnSize self.image = icn } } override func mouseDown(with theEvent: NSEvent) { let clickCount = theEvent.clickCount if clickCount > 1 { DispatchQueue.main.async(execute: { let myFiledialog = NSOpenPanel() myFiledialog.prompt = "Open" myFiledialog.worksWhenModal = true myFiledialog.allowsMultipleSelection = true myFiledialog.canChooseDirectories = true myFiledialog.canChooseFiles = false myFiledialog.resolvesAliases = true myFiledialog.title = "#Extra Title#".localized() myFiledialog.message = "#Extra Msg#".localized() myFiledialog.allowedFileTypes = ["extra"] myFiledialog.runModal() if let URL = myFiledialog.url { let Path = URL.path if Path != "" && URL.lastPathComponent.caseInsensitiveCompare("extra") == ComparisonResult.orderedSame { self.viewDelegate!.didReceiveExtra(Path) let icn = NSImage(named: NSImage.Name("Chameleon")) icn?.size = self.icnSize self.image = icn } } }) } } }
agpl-3.0
ecfc9ae6257ce4201799e79133b1037a
33.22043
148
0.555381
5.083866
false
false
false
false
planvine/Line-Up-iOS-SDK
Pod/Classes/Extensions/NSNumber.swift
1
1506
/** * Copyright (c) 2016 Line-Up * * 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 extension NSNumber { func formatTotal() -> String{ if self == 0 { return "0.00" } else { if rint(self.doubleValue) == self { return "\(Int(self.doubleValue)).00" } else { let s2 = String(format: "%.2f",self.doubleValue) return"\(s2)" } } } }
mit
6308a07585003ba1209cc7eab618b4d0
38.657895
80
0.675299
4.536145
false
false
false
false
gregomni/swift
test/SILGen/type_lowering_subst_function_type_conditional_conformance.swift
3
2385
// RUN: %target-swift-emit-silgen %s | %FileCheck %s enum E<T : P> { case a(T.X) } struct S<T> {} protocol P { associatedtype X } extension S : P where T : P { typealias X = T.X } func foo<T : P>(_ x: E<S<T>>) { // Ensure that the lowered substituted SIL function type for `() -> E<S<T>>` // preserves the T: P constraint necessary to allow for `S<T>` to substitute // into `E<T: P>` bar({ return x }) } // CHECK-LABEL: {{^}}sil {{.*}} @${{.*}}3bar // CHECK-SAME: @substituted <τ_0_0, τ_0_1, τ_0_2 where τ_0_0 == S<τ_0_1>, τ_0_1 : P, τ_0_1 == τ_0_2> () -> @out E<S<τ_0_1>> for <S<T>, T, T> func bar<T: P>(_: () -> E<S<T>>) {} // --- protocol Q: P { associatedtype Y } enum E2<T: Q> { case a(T.Y) } struct S2<T: P>: P { typealias X = T.X } extension S2: Q where T: Q { typealias Y = T.Y } func foo2<T : Q>(_ x: E2<S2<T>>) { bar2({ return x }) } // CHECK-LABEL: {{^}}sil {{.*}} @${{.*}}4bar2 // CHECK-SAME: @substituted <τ_0_0, τ_0_1, τ_0_2 where τ_0_0 == S2<τ_0_1>, τ_0_1 : Q, τ_0_1 == τ_0_2> () -> @out E2<S2<τ_0_1>> for <S2<T>, T, T> func bar2<T: Q>(_: () -> E2<S2<T>>) {} protocol P1 { associatedtype Element associatedtype Index } struct S3<Base> where Base: P1, Base.Element: P1 { let x: Base.Element.Index } struct S4<Base> where Base : P1, Base.Element: P1 { // CHECK-LABEL: {{^}}sil {{.*}} @${{.*}}2S4{{.*}}3foo{{.*}}F : // CHECK: @callee_guaranteed @substituted <τ_0_0, τ_0_1 where τ_0_0 : P1, τ_0_0 == τ_0_1, τ_0_0.Element : P1> (@in_guaranteed S3<τ_0_0>) -> () for <Base, Base> func foo(index: S3<Base>?) { _ = index.map({ _ = $0 }) } } struct T0<X> {} extension T0: P1 where X: P1 { typealias Element = X.Element typealias Index = T0<X.Index> } struct T1<X, Y>: P1 where X: P1 { typealias Element = Y typealias Index = X.Index } struct T2<X> where X: P1, X.Element: P1 { let field: X.Element.Index } struct T3<X> where X: P1 { func callee(_: T2<T1<X, T0<X>>>) {} // CHECK-LABEL: {{^}}sil {{.*}}2T3{{.*}}6caller{{.*}}F : // CHECK: @callee_guaranteed @substituted <τ_0_0, τ_0_1, τ_0_2, τ_0_3, τ_0_4, τ_0_5 where τ_0_0 == T1<τ_0_1, T0<τ_0_4>>, τ_0_1 : P1, τ_0_1 == τ_0_3, τ_0_2 == T0<τ_0_4>, τ_0_4 : P1, τ_0_4 == τ_0_5> (T2<T1<τ_0_1, T0<τ_0_4>>>) -> () for <T1<X, T0<X>>, X, T0<X>, X, X, X> func caller() { _ = { (x: T2<T1<X, T0<X>>>) in callee(x) } } }
apache-2.0
1c9b7283b8bc0fa4e3d6028a263d594e
23.385417
269
0.532678
2.204331
false
false
false
false
mlavergn/swiftutil
Sources/diskstore.swift
1
9945
// DiskStore maintains a data store on disk // // - author: Marc Lavergne <[email protected]> // - copyright: 2017 Marc Lavergne. All rights reserved. // - license: MIT import Foundation // MARK: - DiskStoreEntry /// DiskStoreEntry keys private enum DiskStoreEntryKeys: String { case id case created case values } /// /// DiskStoreEntry can be persisted via DiskStore /// public class DiskStoreEntry: NSObject, NSCoding { let id: String let created: Date var values: [AnyHashable: Any] init(id: String? = nil, created: Date? = nil, values: [String: Any] = [:]) { self.id = id ?? NSUUID().uuidString self.created = created ?? Date() self.values = values super.init() } public required init(coder decoder: NSCoder) { self.id = decoder.decodeObject(forKey: DiskStoreEntryKeys.id.rawValue) as? String ?? NSUUID().uuidString self.created = decoder.decodeObject(forKey: DiskStoreEntryKeys.created.rawValue) as? Date ?? Date() self.values = decoder.decodeObject(forKey: DiskStoreEntryKeys.values.rawValue) as? [AnyHashable: Any] ?? [:] } public func encode(with coder: NSCoder) { coder.encode(id, forKey: DiskStoreEntryKeys.id.rawValue) coder.encode(created, forKey: DiskStoreEntryKeys.created.rawValue) coder.encode(values, forKey: DiskStoreEntryKeys.values.rawValue) } } // MARK: - DiskStore /// DiskStore errors enum DiskStoreError: Error { case failedToArchiveDataStore case failedToUnarchiveDataStore case failedToFindApplicationSupportPath case failedToReadApplicationSupportPath case failedToWriteApplicationSupportPath } /// DiskStore keys private enum DiskStoreKeys: String { case dataset case timestamp } /// /// DiskStore persists DiskStoreEntries to disk while allowing for updates /// public class DiskStore: NSObject, NSCoding { private var dataset: [String: DiskStoreEntry] private var memoryTimestamp: Date = Date.distantPast /// Name under the Application Support folder for dataset static private let storeFile = "com.example.Dataset.plist" let diskStoreNotification = Notification.Name(storeFile) /// Construct the data path, creating any required directories private static let storeDirectoryBaseURL: URL = { let paths = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true) var pathRoot: String if let pathApplicationSupport = paths.last { pathRoot = pathApplicationSupport } else { // we should never wind up barring a fundamental change in iOS pathRoot = ("~/Library/Application Support" as NSString).expandingTildeInPath Log.warn(DiskStoreError.failedToFindApplicationSupportPath) } var pathURL = URL(fileURLWithPath: pathRoot, isDirectory: true) // trying is quicker than checking in this case try? FileManager.default.createDirectory(at: pathURL, withIntermediateDirectories: true, attributes: nil) pathURL.appendPathComponent(storeFile) return pathURL }() // init is offered for convenience override convenience init() { let disk = DiskStore.read() self.init(dataset: disk.dataset) self.memoryTimestamp = disk.memoryTimestamp } // designated initializer private init(dataset: [String: DiskStoreEntry]) { self.dataset = dataset self.memoryTimestamp = DiskStore.diskTimestamp() super.init() NotificationCenter.default.addObserver(self, selector: #selector(DiskStore.handleNotification), name: diskStoreNotification, object: nil) } // designated de-initializer deinit { NotificationCenter.default.removeObserver(self, name: diskStoreNotification, object: nil) } /// Describe the contents of the DiskStore override public var description: String { return "\(self.memoryTimestamp): \(self.dataset)" } // MARK: - NSCoding required public init(coder decoder: NSCoder) { if let dataset = decoder.decodeObject(forKey: DiskStoreKeys.dataset.rawValue) as? [String: DiskStoreEntry] { self.dataset = dataset self.memoryTimestamp = DiskStore.diskTimestamp() } else { self.dataset = [:] self.memoryTimestamp = Date.distantPast } } public func encode(with coder: NSCoder) { coder.encode(self.dataset, forKey: DiskStoreKeys.dataset.rawValue) } // MARK: - Synchronization @objc func handleNotification(withNotification notification: NSNotification) { let newCheckpoint = notification.userInfo?[DiskStoreKeys.timestamp.rawValue] as? Date ?? DiskStore.diskTimestamp() if self.memoryTimestamp != newCheckpoint { sync() } } /// Sync the in-memory contents from the disk truth private func sync() { if self.memoryTimestamp < DiskStore.diskTimestamp() { let latest = DiskStore.read() self.dataset = latest.dataset self.memoryTimestamp = latest.memoryTimestamp } } /// Commits the in-memory contents to the disk and notifies any copies /// /// - Returns: true if successfully persisted, otherwise false private func commit() -> Bool { // are we missing an update if self.memoryTimestamp < DiskStore.diskTimestamp() { sync() return false } // we're good, write let result = DiskStore.write(self) if result { self.memoryTimestamp = DiskStore.diskTimestamp() NotificationCenter.default.post(name: diskStoreNotification, object: nil, userInfo: nil) } return result } // MARK: - Disk IO /// The last modified date of the persisted store /// /// - Returns: Date of the current persisted store last modification private static func diskTimestamp() -> Date { let resourceValues = try? DiskStore.storeDirectoryBaseURL.resourceValues(forKeys: [.contentModificationDateKey]) guard let checkpoint = resourceValues?.contentModificationDate else { return Date.distantPast } return checkpoint } /// Reads the store from disk /// /// - Returns: DiskStore instance from disk private static func read() -> DiskStore { let reachable = (try? storeDirectoryBaseURL.checkResourceIsReachable()) ?? false if reachable { guard let dataset = NSKeyedUnarchiver.unarchiveObject(withFile: storeDirectoryBaseURL.path) as? DiskStore else { Log.error(DiskStoreError.failedToUnarchiveDataStore) /// we failed to read, potential corruption, delete any existing file try? FileManager.default.removeItem(at: storeDirectoryBaseURL) let store = DiskStore(dataset: [:]) _ = write(store) store.memoryTimestamp = DiskStore.diskTimestamp() return store } dataset.memoryTimestamp = DiskStore.diskTimestamp() return dataset } else { Log.error(DiskStoreError.failedToReadApplicationSupportPath) } return DiskStore(dataset: [:]) } /// Write the store to disk /// We take a persimistic view of the write. We write to a tmp file /// and await a success before synchronously moving the file into /// place /// /// - Parameter store: DataStore to persist to disk /// - Returns: true if write was successful, otherwise false @discardableResult private static func write(_ store: DiskStore) -> Bool { var pathURL = DiskStore.storeDirectoryBaseURL pathURL.appendPathExtension(".tmp") let result = NSKeyedArchiver.archiveRootObject(store, toFile: pathURL.path) if result { do { try _ = FileManager.default.replaceItemAt(DiskStore.storeDirectoryBaseURL, withItemAt: pathURL, options: [.usingNewMetadataOnly]) } catch { Log.error(DiskStoreError.failedToWriteApplicationSupportPath) try? FileManager.default.removeItem(at: pathURL) return false } } else { Log.error(DiskStoreError.failedToArchiveDataStore) try? FileManager.default.removeItem(at: pathURL) } return result } // MARK: - Features /// Sets an entry in the store /// /// - Parameters: /// - entry: DiskStoreEntry to set /// - attempts: Maximum number of attempts to persist the change /// - Returns: true is successfully persisted, otherwise false @discardableResult func set(_ entry: DiskStoreEntry, _ attempts: Int = 3) -> Bool { self.dataset[entry.id] = entry if !commit() { if attempts == 0 { return false } else { return set(entry, attempts - 1) } } return true } /// Deletes the given entry from the store /// /// - Parameters: /// - entry: DiskStoreEntry to remove /// - attempts: Maximum number of attempts to persist the change /// - Returns: true is successfully persisted, otherwise false func remove(_ entry: DiskStoreEntry, _ attempts: Int = 3) -> Bool { self.dataset[entry.id] = nil if !commit() { if attempts == 0 { return false } else { return remove(entry, attempts - 1) } } return true } /// Returns the current snapshot of the disk store entry /// /// - Parameter entryId: UUID for the entry /// - Returns: DiskStoreEntry instance if found, otherwise nil func findForID(_ entryId: String) -> DiskStoreEntry? { return self.dataset[entryId] } }
mit
ff7f6f9b9e4326c6cc954cb6d840fbe8
33.651568
145
0.644947
4.82767
false
false
false
false
AlexeyGolovenkov/DocGenerator
GRMustache.swift/Tests/Public/DocumentationTests/MustacheRenderableGuideTests.swift
1
8530
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // 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 XCTest import Mustache class MustacheRenderableGuideTests: XCTestCase { func testExample1() { let render = { (info: RenderingInfo) -> Rendering in switch info.tag.type { case .Variable: return Rendering("I'm rendering a {{ variable }} tag.") case .Section: return Rendering("I'm rendering a {{# section }}...{{/ }} tag.") } } var rendering = try! Template(string: "{{.}}").render(Box(render)) XCTAssertEqual(rendering, "I&apos;m rendering a {{ variable }} tag.") rendering = try! Template(string: "{{#.}}{{/}}").render(Box(render)) XCTAssertEqual(rendering, "I&apos;m rendering a {{# section }}...{{/ }} tag.") } func textExample2() { let render = { (info: RenderingInfo) -> Rendering in return Rendering("Arthur & Cie") } let rendering = try! Template(string: "{{.}}|{{{.}}}").render(Box(render)) XCTAssertEqual(rendering, "Arthur &amp; Cie|Arthur & Cie") } func textExample3() { let render = { (info: RenderingInfo) -> Rendering in let rendering = try! info.tag.render(info.context) return Rendering("<strong>\(rendering.string)</strong>", rendering.contentType) } let box = Box([ "strong": Box(render), "name": Box("Arthur")]) let rendering = try! Template(string: "{{#strong}}{{name}}{{/strong}}").render(box) XCTAssertEqual(rendering, "<strong>Arthur</strong>") } func textExample4() { let render = { (info: RenderingInfo) -> Rendering in let rendering = try! info.tag.render(info.context) return Rendering(rendering.string + rendering.string, rendering.contentType) } let box = Box(["twice": Box(render)]) let rendering = try! Template(string: "{{#twice}}Success{{/twice}}").render(box) XCTAssertEqual(rendering, "SuccessSuccess") } func textExample5() { let render = { (info: RenderingInfo) -> Rendering in let template = try! Template(string: "<a href=\"{{url}}\">\(info.tag.innerTemplateString)</a>") return try template.render(info.context) } let box = Box([ "link": Box(render), "name": Box("Arthur"), "url": Box("/people/123")]) let rendering = try! Template(string: "{{# link }}{{ name }}{{/ link }}").render(box) XCTAssertEqual(rendering, "<a href=\"/people/123\">Arthur</a>") } func testExample6() { let repository = TemplateRepository(templates: [ "movieLink": "<a href=\"{{url}}\">{{title}}</a>", "personLink": "<a href=\"{{url}}\">{{name}}</a>"]) let link1 = Box(try! repository.template(named: "movieLink")) let item1 = Box([ "title": Box("Citizen Kane"), "url": Box("/movies/321"), "link": link1]) let link2 = Box(try! repository.template(named: "personLink")) let item2 = Box([ "name": Box("Orson Welles"), "url": Box("/people/123"), "link": link2]) let box = Box(["items": Box([item1, item2])]) let rendering = try! Template(string: "{{#items}}{{link}}{{/items}}").render(box) XCTAssertEqual(rendering, "<a href=\"/movies/321\">Citizen Kane</a><a href=\"/people/123\">Orson Welles</a>") } func testExample7() { struct Person : MustacheBoxable { let firstName: String let lastName: String var mustacheBox: MustacheBox { let keyedSubscript = { (key: String) -> MustacheBox in switch key { case "firstName": return Box(self.firstName) case "lastName": return Box(self.lastName) default: return Box() } } let render = { (info: RenderingInfo) -> Rendering in let template = try! Template(named: "Person", bundle: NSBundle(forClass: MustacheRenderableGuideTests.self)) let context = info.context.extendedContext(Box(self)) return try template.render(context) } return MustacheBox( value: self, keyedSubscript: keyedSubscript, render: render) } } struct Movie : MustacheBoxable { let title: String let director: Person var mustacheBox: MustacheBox { let keyedSubscript = { (key: String) -> MustacheBox in switch key { case "title": return Box(self.title) case "director": return Box(self.director) default: return Box() } } let render = { (info: RenderingInfo) -> Rendering in let template = try! Template(named: "Movie", bundle: NSBundle(forClass: MustacheRenderableGuideTests.self)) let context = info.context.extendedContext(Box(self)) return try template.render(context) } return MustacheBox( value: self, keyedSubscript: keyedSubscript, render: render) } } let director = Person(firstName: "Orson", lastName: "Welles") let movie = Movie(title:"Citizen Kane", director: director) let template = try! Template(string: "{{ movie }}") let rendering = try! template.render(Box(["movie": Box(movie)])) XCTAssertEqual(rendering, "Citizen Kane by Orson Welles") } func testExample8() { let listFilter = { (box: MustacheBox, info: RenderingInfo) -> Rendering in guard let items = box.arrayValue else { return Rendering("") } var buffer = "<ul>" for item in items { let itemContext = info.context.extendedContext(item) let itemRendering = try! info.tag.render(itemContext) buffer += "<li>\(itemRendering.string)</li>" } buffer += "</ul>" return Rendering(buffer, .HTML) } let template = try! Template(string: "{{#list(nav)}}<a href=\"{{url}}\">{{title}}</a>{{/}}") template.baseContext = template.baseContext.extendedContext(Box(["list": Box(Filter(listFilter))])) let item1 = Box([ "url": "http://mustache.github.io", "title": "Mustache"]) let item2 = Box([ "url": "http://github.com/groue/GRMustache.swift", "title": "GRMustache.swift"]) let box = Box(["nav": Box([item1, item2])]) let rendering = try! template.render(box) XCTAssertEqual(rendering, "<ul><li><a href=\"http://mustache.github.io\">Mustache</a></li><li><a href=\"http://github.com/groue/GRMustache.swift\">GRMustache.swift</a></li></ul>") } }
mit
49ace2612e7537160bcb20320c123372
41.432836
187
0.545316
4.740967
false
false
false
false
benlangmuir/swift
test/SILGen/toplevel.swift
9
3989
// RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle %s | %FileCheck %s // RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle -enable-experimental-async-top-level %s | %FileCheck %s func markUsed<T>(_ t: T) {} func trap() -> Never { fatalError() } // CHECK-LABEL: sil [ossa] @main // CHECK: bb0({{%.*}} : $Int32, {{%.*}} : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): // CHECK-NOT: @async_Main // -- initialize x // CHECK: alloc_global @$s8toplevel1xSiv // CHECK: [[X:%[0-9]+]] = global_addr @$s8toplevel1xSivp : $*Int // CHECK: integer_literal $Builtin.IntLiteral, 999 // CHECK: store {{.*}} to [trivial] [[X]] var x = 999 func print_x() { markUsed(x) } // -- assign x // CHECK: integer_literal $Builtin.IntLiteral, 0 // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X]] : $*Int // CHECK: assign {{.*}} to [[WRITE]] // CHECK: [[PRINT_X:%[0-9]+]] = function_ref @$s8toplevel7print_xyyF : // CHECK: apply [[PRINT_X]] x = 0 print_x() // <rdar://problem/19770775> Deferred initialization of let bindings rejected at top level in playground // CHECK: alloc_global @$s8toplevel5countSiv // CHECK: [[COUNTADDR:%[0-9]+]] = global_addr @$s8toplevel5countSivp : $*Int // CHECK-NEXT: [[COUNTMUI:%[0-9]+]] = mark_uninitialized [var] [[COUNTADDR]] : $*Int let count: Int // CHECK: cond_br if x == 5 { count = 0 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE:bb[0-9]+]] } else { count = 10 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE]] } // CHECK: [[MERGE]]: // CHECK: load [trivial] [[COUNTMUI]] markUsed(count) var y : Int func print_y() { markUsed(y) } // -- assign y // CHECK: alloc_global @$s8toplevel1ySiv // CHECK: [[Y1:%[0-9]+]] = global_addr @$s8toplevel1ySivp : $*Int // CHECK: [[Y:%[0-9]+]] = mark_uninitialized [var] [[Y1]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[Y]] // CHECK: assign {{.*}} to [[WRITE]] // CHECK: [[PRINT_Y:%[0-9]+]] = function_ref @$s8toplevel7print_yyyF y = 1 print_y() // -- treat 'guard' vars as locals // CHECK-LABEL: function_ref toplevel.A.__allocating_init // CHECK: switch_enum {{%.+}} : $Optional<A>, case #Optional.some!enumelt: [[SOME_CASE:.+]], case #Optional.none! // CHECK: [[SOME_CASE]]([[VALUE:%.+]] : @owned $A): // CHECK: store [[VALUE]] to [init] [[BOX:%.+]] : $*A // CHECK-NOT: destroy_value // CHECK: [[SINK:%.+]] = function_ref @$s8toplevel8markUsedyyxlF // CHECK-NOT: destroy_value // CHECK: apply [[SINK]]<A>({{%.+}}) class A {} guard var a = Optional(A()) else { trap() } markUsed(a) // CHECK: alloc_global @$s8toplevel21NotInitializedIntegerSiv // CHECK-NEXT: [[VARADDR:%[0-9]+]] = global_addr @$s8toplevel21NotInitializedIntegerSiv // CHECK-NEXT: [[VARMUI:%[0-9]+]] = mark_uninitialized [var] [[VARADDR]] : $*Int // CHECK-NEXT: mark_function_escape [[VARMUI]] : $*Int // <rdar://problem/21753262> Bug in DI when it comes to initialization of global "let" variables let NotInitializedInteger : Int func fooUsesUninitializedValue() { _ = NotInitializedInteger } fooUsesUninitializedValue() NotInitializedInteger = 10 fooUsesUninitializedValue() // Test initialization of variables captured by top-level defer. // CHECK: alloc_global @$s8toplevel9uninitVarSiv // CHECK-NEXT: [[UNINIADDR:%[0-9]+]] = global_addr @$s8toplevel9uninitVarSiv // CHECK-NEXT: [[UNINIMUI:%[0-9]+]] = mark_uninitialized [var] [[UNINIADDR]] : $*Int // CHECK-NEXT: mark_function_escape [[UNINIMUI]] : $*Int var uninitVar: Int defer { print(uninitVar) } // CHECK: [[RET:%[0-9]+]] = struct $Int32 // CHECK: return [[RET]] // CHECK-LABEL: sil hidden [ossa] @$s8toplevel7print_xyyF // CHECK-LABEL: sil hidden [ossa] @$s8toplevel7print_yyyF // CHECK: sil hidden [ossa] @$s8toplevel13testGlobalCSESiyF // CHECK-NOT: global_addr // CHECK: %0 = global_addr @$s8toplevel1xSivp : $*Int // CHECK-NOT: global_addr // CHECK: return func testGlobalCSE() -> Int { // We should only emit one global_addr in this function. return x + x }
apache-2.0
e435dae0ea401c410ffaaf038b380e3b
27.905797
115
0.643269
3.118843
false
false
false
false
ZekeSnider/Jared
Pods/Telegraph/Sources/Transport/URI.swift
1
2461
// // URI.swift // Telegraph // // Created by Yvo van Beek on 2/5/17. // Copyright © 2017 Building42. All rights reserved. // import Foundation public struct URI { private var components: URLComponents /// Creates a URI from the provided path, query string. public init(path: String = "/", query: String? = nil) { self.components = URLComponents() self.path = path self.query = query } /// Creates a URI from URLComponents. Takes only the path, query string. public init(components: URLComponents) { self.init(path: components.path, query: components.query) } /// Creates a URI from the provided URL. Takes only the path, query string and fragment. public init?(url: URL) { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil } self.init(components: components) } /// Creates a URI from the provided string. Takes only the path, query string and fragment. public init?(_ string: String) { guard let components = URLComponents(string: string) else { return nil } self.init(components: components) } } public extension URI { /// The path of the URI (e.g. /index.html). Always starts with a slash. var path: String { get { return components.path } set { components.path = newValue.hasPrefix("/") ? newValue : "/\(newValue)" } } /// The query string of the URI (e.g. lang=en&page=home). Does not contain a question mark. var query: String? { get { return components.query } set { components.query = newValue } } /// The query string items of the URI as an array. var queryItems: [URLQueryItem]? { get { return components.queryItems } set { components.queryItems = newValue } } } public extension URI { /// Returns a URI indicating the root. static let root = URI(path: "/") /// Returns the part of the path that doesn't overlap. /// For example '/files/today' with argument '/files' returns 'today'. func relativePath(from path: String) -> String? { var result = self.path // Remove the part of the path that overlaps guard let range = result.range(of: path) else { return nil } result = result.replacingCharacters(in: range, with: "") // Remove leading slash if result.hasPrefix("/") { result.remove(at: result.startIndex) } return result } } extension URI: CustomStringConvertible { public var description: String { return components.description } }
apache-2.0
e2acf31d0ff0141ae253ef9e9fb5bd14
28.638554
102
0.677642
4.066116
false
false
false
false
duanlunming/imageHandle
GPUImage-Swift/examples/iOS/FilterShowcase/FilterShowcaseSwift/FilterView/Views/LMTreeTableView.swift
2
11937
// // LMTreeTableView.swift // FilterShowcase // // Created by wzkj on 2017/1/13. // Copyright © 2017年 Cell Phone. All rights reserved. // import UIKit class LMTreeNode { static let NODE_TYPE_G: Int = 0 //表示该节点不是叶子节点 static let NODE_TYPE_N: Int = 1 //表示节点为叶子节点 var type: Int? var desc: String? // 对于多种类型的内容,需要确定其内容 var id: String? var pId: String? var name: String? var level: Int? var isExpand: Bool = false var icon: String? var children: [LMTreeNode] = [] var parent: LMTreeNode? init (desc: String?, id:String? , pId: String? , name: String?) { self.desc = desc self.id = id self.pId = pId self.name = name } //是否为根节点 func isRoot() -> Bool{ return parent == nil } //判断父节点是否打开 func isParentExpand() -> Bool { if parent == nil { return false } return (parent?.isExpand)! } //是否是叶子节点 func isLeaf() -> Bool { return children.count == 0 } //获取level,用于设置节点内容偏左的距离 func getLevel() -> Int { return parent == nil ? 0 : (parent?.getLevel())!+1 } //设置展开 func setExpand(isExpand: Bool) { self.isExpand = isExpand if !isExpand { var i = 0; while i < children.count { children[i].setExpand(isExpand: isExpand) i += 1 } } } } private let instance: LMTreeNodeHelper = LMTreeNodeHelper() class LMTreeNodeHelper{ // 单例模式 final class var sharedInstance: LMTreeNodeHelper { return instance } //传入普通节点,转换成排序后的Node func getSortedNodes(groups: NSMutableArray, defaultExpandLevel: Int) -> [LMTreeNode] { var result: [LMTreeNode] = [] let nodes = convetData2Node(groups: groups) let rootNodes = getRootNodes(nodes: nodes) for item in rootNodes{ addNode(nodes: &result, node: item, defaultExpandLeval: defaultExpandLevel, currentLevel: 1) } return result } //过滤出所有可见节点 func filterVisibleNode(nodes: [LMTreeNode]) -> [LMTreeNode] { var result: [LMTreeNode] = [] for item in nodes { if item.isRoot() || item.isParentExpand() { setNodeIcon(node: item) result.append(item) } } return result } //将数据转换成书节点 func convetData2Node(groups: NSMutableArray) -> [LMTreeNode] { var nodes: [LMTreeNode] = [] var node: LMTreeNode var desc: String? var id: String? var pId: String? var label: String? for item in groups { let itemInfo = item as! Dictionary<String, String> desc = itemInfo["description"] id = itemInfo["id"] pId = itemInfo["pid"] label = itemInfo["name"] node = LMTreeNode(desc: desc, id: id, pId: pId, name: label) nodes.append(node) } /** * 设置Node间,父子关系;让每两个节点都比较一次,即可设置其中的关系 */ var n: LMTreeNode var m: LMTreeNode for i in 0..<nodes.count { n = nodes[i] for j in i+1..<nodes.count { m = nodes[j] if m.pId == n.id { n.children.append(m) m.parent = n } else if n.pId == m.id { m.children.append(n) n.parent = m } } } for item in nodes { setNodeIcon(node: item) } return nodes } // 获取根节点集 func getRootNodes(nodes: [LMTreeNode]) -> [LMTreeNode] { var root: [LMTreeNode] = [] for item in nodes { if item.isRoot() { root.append(item) } } return root } //把一个节点的所有子节点都挂上去 func addNode( nodes: inout [LMTreeNode], node: LMTreeNode, defaultExpandLeval: Int, currentLevel: Int) { nodes.append(node) if defaultExpandLeval >= currentLevel { node.setExpand(isExpand: true) } if node.isLeaf() { return } var i = 0 while i<node.children.count { addNode(nodes: &nodes, node: node.children[i], defaultExpandLeval: defaultExpandLeval, currentLevel: currentLevel+1) i+=1 } } // 设置节点图标 func setNodeIcon(node: LMTreeNode) { if node.children.count > 0 { node.type = LMTreeNode.NODE_TYPE_G if node.isExpand { // 设置icon为向下的箭头 node.icon = "tree_ex.png" } else if !node.isExpand { // 设置icon为向右的箭头 node.icon = "tree_ec.png" } } else { node.type = LMTreeNode.NODE_TYPE_N } } } class LMTreeNodeTableViewCell: UITableViewCell { private var _node:LMTreeNode? var node: LMTreeNode? { get { return _node } set { _node = newValue if _node != nil { if _node?.type == LMTreeNode.NODE_TYPE_G { self.imageView?.image = UIImage(named: (_node?.icon)!) self.imageView?.contentMode = .center }else{ self.imageView?.image = nil } self.textLabel?.text = _node?.name self.detailTextLabel?.text = _node?.desc let indentLevel : Int = Int((self.node?.getLevel())!) + 1 /*if self.responds(to: #selector(setter: UIView.layoutMargins)) { var margins : UIEdgeInsets = self.layoutMargins margins.left = 60 * insets self.layoutMargins = margins }else */ self.indentationLevel = indentLevel self.indentationWidth = 0 if self.responds(to: #selector(setter: UITableViewCell.separatorInset)) { var sepInset : UIEdgeInsets = self.separatorInset sepInset.left = CGFloat(16 * indentLevel) self.separatorInset = sepInset } self.setNeedsDisplay() } } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style:.subtitle, reuseIdentifier: reuseIdentifier) let accessoryImageView:UIImageView = UIImageView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 20, height: 20))) accessoryImageView.image = #imageLiteral(resourceName: "Lambeau.jpg") self.accessoryView = accessoryImageView self.selectionStyle = .none } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class LMTreeTable : UITableView,UITableViewDelegate,UITableViewDataSource { var mAllNodes: [LMTreeNode]? //所有的node var mNodes: [LMTreeNode]? //可见的node let NODE_CELL_ID: String = "nodecell" static var sharedInstance : LMTreeTable { struct Static { static let instance : LMTreeTable = LMTreeTable(frame: CGRect.zero, withData: LMTreeNodeHelper.sharedInstance.getSortedNodes(groups: NSMutableArray(contentsOfFile: Bundle.main.path(forResource: "DataSources", ofType: "plist")!)!, defaultExpandLevel: 0)) } return Static.instance } init(frame: CGRect, withData data: [LMTreeNode]) { super.init(frame: frame, style: .grouped) self.register(LMTreeNodeTableViewCell.self, forCellReuseIdentifier: NODE_CELL_ID) self.delegate = self self.dataSource = self mAllNodes = data mNodes = LMTreeNodeHelper.sharedInstance.filterVisibleNode(nodes: mAllNodes!) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:LMTreeNodeTableViewCell = tableView.dequeueReusableCell(withIdentifier: NODE_CELL_ID) as! LMTreeNodeTableViewCell let node: LMTreeNode = mNodes![indexPath.row] // if node.type == LMTreeNode.NODE_TYPE_G { // cell.imageView?.contentMode = .center // cell.imageView?.image = UIImage(named: (node.icon)!) // }else{ // cell.imageView?.image = nil // } // // cell.textLabel?.text = node.name // cell.detailTextLabel?.text = node.desc cell.node = node // cell.background.bounds.origin.x = -20.0 * CGFloat(node.getLevel()) return cell } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (mNodes?.count)! } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44.0 } /* 设置缩进 func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int { let node: LMTreeNode = mNodes![indexPath.row] return Int(node.getLevel()) } */ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let parentNode = mNodes![indexPath.row] let startPosition = indexPath.row+1 var endPosition = startPosition if parentNode.isLeaf() {// 点击的节点为叶子节点 // do something return } expandOrCollapse(count: &endPosition, node: parentNode) mNodes = LMTreeNodeHelper.sharedInstance.filterVisibleNode(nodes: mAllNodes!) //更新可见节点 //修正indexpath var indexPathArray :[IndexPath] = [] var tempIndexPath: IndexPath? for i in startPosition..<endPosition { tempIndexPath = IndexPath(row: i, section: 0) indexPathArray.append(tempIndexPath!) } self.beginUpdates() // 插入和删除节点的动画 if parentNode.isExpand { self.insertRows(at: indexPathArray as [IndexPath], with: .bottom) } else { self.deleteRows(at: indexPathArray as [IndexPath], with: .top) } self.endUpdates() //更新被选组节点 //self.reloadRows(at: [indexPath as IndexPath], with: .none) } //展开或者关闭某个节点 func expandOrCollapse( count: inout Int, node: LMTreeNode) { if node.isExpand { //如果当前节点是开着的,需要关闭节点下的所有子节点 closedChildNode(count: &count,node: node) } else { //如果节点是关着的,打开当前节点即可 count += node.children.count node.setExpand(isExpand: true) } } //关闭某个节点和该节点的所有子节点 func closedChildNode( count:inout Int, node: LMTreeNode) { if node.isLeaf() { return } if node.isExpand { node.isExpand = false for item in node.children { //关闭子节点 count += 1 // 计算子节点数加一 closedChildNode(count: &count, node: item) } } } }
bsd-3-clause
84c9c559330e464102263309ecee650d
30.597765
265
0.546322
4.350769
false
false
false
false
IBM-MIL/BluePic
BluePic-iOS/BluePic/ViewModels/ProfileViewModel.swift
1
9570
/** * Copyright IBM Corporation 2015 * * 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 class ProfileViewModel: NSObject { //array that holds all that pictures that are displayed in the collection view var pictureDataArray = [Picture]() //callback used to tell the ProfileViewController when to refresh its collection view var refreshVCCallback : (()->())! //state variable to keep try of if the view model has receieved data from cloudant yet var hasRecievedDataFromCloudant = false //constant that represents the number of sections in the collection view let kNumberOfSectionsInCollectionView = 1 //constant that represents the height of the info view in the collection view cell that shows the photos caption and photographer name let kCollectionViewCellInfoViewHeight : CGFloat = 60 //constant that represents the limit of how big the colection view cell height can be let kCollectionViewCellHeightLimit : CGFloat = 480 //constant that represents a value added to the height of the EmptyFeedCollectionViewCell when its given a size in the sizeForItemAtIndexPath method, this value allows the collection view to scroll let kEmptyFeedCollectionViewCellBufferToAllowForScrolling : CGFloat = 1 //constant that represents the number of cells in the collection view when there is no photos let kNumberOfCellsWhenUserHasNoPhotos = 1 /** Method called upon init, it sets up the callback to refresh the profile collection view - parameter refreshVCCallback: (()->()) - returns: */ init(refreshVCCallback : (()->())){ super.init() self.refreshVCCallback = refreshVCCallback DataManagerCalbackCoordinator.SharedInstance.addCallback(handleDataManagerNotifications) getPictureObjects() } /** Method handles notifications when there are DataManagerNotifications, it passes DataManagerNotifications to the Profile VC - parameter dataManagerNotification: DataManagerNotification */ func handleDataManagerNotifications(dataManagerNotification : DataManagerNotification){ if (dataManagerNotification == DataManagerNotification.UserDecidedToPostPhoto){ getPictureObjects() } if (dataManagerNotification == DataManagerNotification.CloudantPullDataSuccess){ getPictureObjects() } else if(dataManagerNotification == DataManagerNotification.ObjectStorageUploadImageAndCloudantCreatePictureDocSuccess){ getPictureObjects() } } /** Method adds a locally stored version of the image the user just posted to the pictureDataArray */ func addUsersLastPhotoTakenToPictureDataArrayAndRefreshCollectionView(){ let lastPhotoTaken = CameraDataManager.SharedInstance.lastPictureObjectTaken var lastPhotoTakenArray = [Picture]() lastPhotoTakenArray.append(lastPhotoTaken) pictureDataArray = lastPhotoTakenArray + pictureDataArray callRefreshCallBack() } /** Method gets the picture objects from cloudant based on the facebook unique user id. When this completes it tells the profile view controller to refresh its collection view */ func getPictureObjects(){ pictureDataArray = CloudantSyncDataManager.SharedInstance!.getPictureObjects(FacebookDataManager.SharedInstance.fbUniqueUserID!) hasRecievedDataFromCloudant = true dispatch_async(dispatch_get_main_queue()) { self.callRefreshCallBack() } } /** method repulls for new data from cloudant */ func repullForNewData(){ do { try CloudantSyncDataManager.SharedInstance!.pullFromRemoteDatabase() } catch { print("repullForNewData error: \(error)") DataManagerCalbackCoordinator.SharedInstance.sendNotification(DataManagerNotification.CloudantPullDataFailure) } } /** Method returns the number of sections in the collection view - returns: Int */ func numberOfSectionsInCollectionView() -> Int { return kNumberOfSectionsInCollectionView } /** Method returns the number of items in a section - parameter section: Int - returns: Int */ func numberOfItemsInSection(section : Int) -> Int { if(pictureDataArray.count == 0 && hasRecievedDataFromCloudant == true) { return kNumberOfCellsWhenUserHasNoPhotos } else { return pictureDataArray.count } } /** Method returns the size for item at indexPath - parameter indexPath: NSIndexPath - parameter collectionView: UICollectionView - parameter heightForEmptyProfileCollectionViewCell: CGFloat - returns: CGSize */ func sizeForItemAtIndexPath(indexPath : NSIndexPath, collectionView : UICollectionView, heightForEmptyProfileCollectionViewCell : CGFloat) -> CGSize { if(pictureDataArray.count == 0) { return CGSize(width: collectionView.frame.width, height: heightForEmptyProfileCollectionViewCell + kEmptyFeedCollectionViewCellBufferToAllowForScrolling) } else{ let picture = pictureDataArray[indexPath.row] if let width = picture.width, let height = picture.height { let ratio = height / width var height = collectionView.frame.width * ratio if(height > kCollectionViewCellHeightLimit){ height = kCollectionViewCellHeightLimit } return CGSize(width: collectionView.frame.width, height: height + kCollectionViewCellInfoViewHeight) } else{ return CGSize(width: collectionView.frame.width, height: collectionView.frame.width + kCollectionViewCellInfoViewHeight) } } } /** Method sets up the collection view cell for indexPath. If the pictureDataArray.count is equal to 0 then we return an instance EmptyfeedCollectionviewCell - parameter indexPath: NSIndexPath - parameter collectionView: UICollectionViewCell - returns: UICollectionViewCell */ func setUpCollectionViewCell(indexPath : NSIndexPath, collectionView : UICollectionView) -> UICollectionViewCell { if(pictureDataArray.count == 0){ let cell: EmptyFeedCollectionViewCell cell = collectionView.dequeueReusableCellWithReuseIdentifier("EmptyFeedCollectionViewCell", forIndexPath: indexPath) as! EmptyFeedCollectionViewCell return cell } else{ let cell: ProfileCollectionViewCell cell = collectionView.dequeueReusableCellWithReuseIdentifier("ProfileCollectionViewCell", forIndexPath: indexPath) as! ProfileCollectionViewCell let picture = pictureDataArray[indexPath.row] cell.setupData(picture.url, image: picture.image, displayName: picture.displayName, timeStamp: picture.timeStamp, fileName: picture.fileName ) cell.layer.shouldRasterize = true cell.layer.rasterizationScale = UIScreen.mainScreen().scale return cell } } /** Method sets up the section header for the indexPath parameter - parameter indexPath: NSIndexPath - parameter kind: String - parameter collectionView: UICollectionView - returns: TripDetailSupplementaryView */ func setUpSectionHeaderViewForIndexPath(indexPath : NSIndexPath, kind: String, collectionView : UICollectionView) -> ProfileHeaderCollectionReusableView { let header : ProfileHeaderCollectionReusableView header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "ProfileHeaderCollectionReusableView", forIndexPath: indexPath) as! ProfileHeaderCollectionReusableView header.setupData(FacebookDataManager.SharedInstance.fbUserDisplayName, numberOfShots: pictureDataArray.count, profilePictureURL : FacebookDataManager.SharedInstance.getUserFacebookProfilePictureURL()) return header } /** Method tells the profile view controller to reload its collectionView */ func callRefreshCallBack(){ if let callback = refreshVCCallback { callback() } } }
apache-2.0
744a921fb85196543ffede8ff84b7477
33.927007
208
0.658203
6.103316
false
false
false
false
andrewcb/KFPopupSelector
KFPopupSelector/KFPopupSelector control/KFPopupSelector.swift
1
9464
// // KFPopupSelector.swift // KFPopupSelector // // Created by acb on 27/05/2015. // Copyright (c) 2015 Kineticfactory. All rights reserved. // import UIKit class KFPopupSelector: UIControl, UIPopoverPresentationControllerDelegate { enum Option { case Text(text:String) func intrinsicWidthWithFont(font: UIFont) -> CGFloat { switch(self) { case Text(let t): return NSString(string:t).boundingRectWithSize(CGSize(width:1000, height:1000), options:.allZeros, attributes:[NSFontAttributeName: font], context:nil).width } } } /** The options the user has to choose from */ var options: [Option] = [] { didSet { updateButtonState() } } /** The currently selected value */ var selectedIndex: Int? = nil { didSet { updateLabel() sendActionsForControlEvents(.ValueChanged) if let index = selectedIndex { itemSelected?(index) } } } /** The text to display on the button if no option is selected */ var unselectedLabelText:String = "--" { didSet { updateLabel() } } /** if true, replace the button's text with the currently selected item */ var displaySelectedValueInLabel: Bool = true /** How the button title is displayed */ enum LabelDecoration { case None case DownwardTriangle func apply(str:String) ->String { switch(self) { case None: return str case DownwardTriangle: return str + " ▾" } } } var labelDecoration: LabelDecoration = .None { didSet { updateLabel() } } /** The behaviour when the list of options is empty */ enum EmptyBehaviour { /** Leave the button enabled; this allows willOpenPopup to be used to dynamically fill the options */ case Enabled /** Disable the button, but display it in a disabled state */ case Disabled /** Hide the button */ case Hidden } var emptyBehaviour: EmptyBehaviour = .Disabled { didSet { updateButtonState() } } func setLabelFont(font: UIFont) { button.titleLabel?.font = font } /** Optional callback called when the user has selected an item */ var itemSelected: ((Int)->())? = nil /** Optional function to call before the popup is opened; this may be used to update the options list. */ var willOpenPopup: (()->())? = nil func updateButtonState() { let empty = options.isEmpty button.enabled = !(empty && emptyBehaviour == .Disabled) button.hidden = empty && emptyBehaviour == .Hidden invalidateIntrinsicContentSize() } func updateLabel() { if selectedIndex != nil && displaySelectedValueInLabel { switch (options[selectedIndex!]) { case .Text(let text): buttonText = text } } else { buttonText = unselectedLabelText } } // -------- The TableViewController used internally in the popover class PopupViewController: UITableViewController { let minWidth: CGFloat = 40.0 var optionsWidth: CGFloat = 40.0 private let tableViewFont = UIFont.systemFontOfSize(15.0) var options: [Option] = [] { didSet { optionsWidth = options.map { $0.intrinsicWidthWithFont(self.tableViewFont) }.reduce(minWidth) { max($0, $1) } } } var itemSelected: ((Int)->())? = nil let KFPopupSelectorCellReuseId = "KFPopupSelectorCell" override var preferredContentSize: CGSize { get { tableView.layoutIfNeeded() return CGSize(width:optionsWidth+32, height:tableView.contentSize.height) } set { println("Cannot set preferredContentSize of this view controller!") } } override func loadView() { super.loadView() tableView.rowHeight = 36.0 tableView.separatorStyle = .None } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) tableView.scrollEnabled = (tableView.contentSize.height > tableView.frame.size.height) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = (tableView.dequeueReusableCellWithIdentifier(KFPopupSelectorCellReuseId) ?? UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: KFPopupSelectorCellReuseId)) as! UITableViewCell switch options[indexPath.row] { case .Text(let text): cell.textLabel?.text = text cell.textLabel?.font = tableViewFont } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { itemSelected?(indexPath.row) } } // -------------------------------- var currentlyPresentedPopup: PopupViewController? = nil private let button = UIButton.buttonWithType(.System) as! UIButton private var buttonText: String? { get { return button.titleForState(.Normal) } set { button.setTitle(newValue.map { self.labelDecoration.apply($0) }, forState: .Normal) invalidateIntrinsicContentSize() } } override func intrinsicContentSize() -> CGSize { return (options.isEmpty && emptyBehaviour == .Hidden) ? CGSizeZero : button.intrinsicContentSize() } private func setupView() { button.setTitle(labelDecoration.apply(unselectedLabelText), forState: .Normal) self.addSubview(button) button.frame = self.bounds button.autoresizingMask = .FlexibleHeight | .FlexibleWidth button.addTarget(self, action: Selector("buttonPressed:"), forControlEvents:.TouchDown) self.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: Selector("dragged:"))) } override init(frame: CGRect) { super.init(frame:frame) setupView() } required init(coder aDecoder: NSCoder) { super.init(coder:aDecoder) setupView() } override func awakeFromNib() { setupView() } private var viewController: UIViewController? { for var next:UIView? = self.superview; next != nil; next = next?.superview { let responder = next?.nextResponder() if let vc = responder as? UIViewController { return vc } } return nil } func dragged(sender: UIPanGestureRecognizer!) { if let tableView = currentlyPresentedPopup?.tableView { switch(sender.state) { case .Changed: if let popupContainer = tableView.superview { let pos = sender.locationInView(tableView) if let ip = tableView.indexPathForRowAtPoint(pos) { tableView.selectRowAtIndexPath(ip, animated: false, scrollPosition: UITableViewScrollPosition.None) } } case .Ended: if let ip = tableView.indexPathForSelectedRow() { currentlyPresentedPopup!.dismissViewControllerAnimated(true){ self.currentlyPresentedPopup = nil self.selectedIndex = ip.row } } default: break } } } func buttonPressed(sender: AnyObject?) { willOpenPopup?() if options.count > 0 { let pvc = PopupViewController(style: UITableViewStyle.Plain) pvc.options = options pvc.itemSelected = { (index:Int) -> () in pvc.dismissViewControllerAnimated(true) { self.currentlyPresentedPopup = nil self.selectedIndex = index } } pvc.modalPresentationStyle = .Popover currentlyPresentedPopup = pvc let pc = pvc.popoverPresentationController pc?.sourceView = self pc?.sourceRect = button.frame pc?.permittedArrowDirections = .Any pc?.delegate = self viewController!.presentViewController(pvc, animated: true) {} } } // MARK: UIPopoverPresentationControllerDelegate func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) { currentlyPresentedPopup = nil } }
mit
3ab58014ddb400937e560c86eee42605
32.553191
217
0.580638
5.7
false
false
false
false
bradleypj823/Swift-GithubToGo
Swift-GithubToGo/ReposViewController.swift
1
2785
// // ReposViewController.swift // Swift-GithubToGo // // Created by Reed Sweeney on 6/6/14. // Copyright (c) 2014 Bradley Johnson. All rights reserved. // import UIKit class ReposViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var networkController : NetworkController? @IBOutlet var tableView : UITableView var myPublicRepos = Repo[]() var myPrivateRepos = Repo[]() init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() var appDelegate = UIApplication.sharedApplication().delegate as AppDelegate self.networkController = appDelegate.networkController self.networkController!.retrieveMyReposWithCompletion() { (repos: Repo[]) in self.seperateIntoPublicAndPrivate(repos) NSOperationQueue.mainQueue().addOperationWithBlock() { () in self.tableView.reloadData() } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfSectionsInTableView(tableView: UITableView!) -> Int { return 2 } func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String! { if (section == 0) { return "My Public Repos" } else { return "My Private Repos" } } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { if section == 0 { return self.myPublicRepos.count } else { return self.myPrivateRepos.count } } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell var repo : Repo if (indexPath.section == 0) { repo = self.myPublicRepos[indexPath.row] } else { repo = self.myPrivateRepos[indexPath.row] as Repo } cell.textLabel.text = repo.name return cell } func seperateIntoPublicAndPrivate( repos : Repo[]) { for repo : Repo in repos { if repo.isPrivate { self.myPrivateRepos += repo } else { self.myPublicRepos += repo } } } }
mit
6911589aea9361a8ac6005a699911f4a
26.574257
132
0.58456
5.335249
false
false
false
false
vitormesquita/Malert
Example/Malert/examples/example4/Example4View.swift
1
1441
// // Example4View.swift // Malert_Example // // Created by Vitor Mesquita on 19/07/2018. // Copyright © 2018 CocoaPods. All rights reserved. // import UIKit class Example4View: UIView { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() applyLayout() } private func applyLayout() { //TODO PUT AN IMAGE imageView.image = UIImage.fromColor(color: UIColor(red:0.91, green:0.12, blue:0.39, alpha:1.0)) titleLabel.font = UIFont.systemFont(ofSize: 24, weight: UIFont.Weight.light) titleLabel.text = "Three Invites" descriptionLabel.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular) descriptionLabel.textColor = UIColor.lightGray descriptionLabel.numberOfLines = 0 descriptionLabel.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sit amet ante ut massa dignissim feugiat. Morbi eu faucibus diam. Nunc et nisl et tellus ultrices blandit. Proin pharetra hendrerit augue sed tempus. Aliquam vel nibh laoreet tortor euismod tempus. Integer et pharetra magna." } class func instantiateFromNib() -> Example4View { return Bundle.main.loadNibNamed("Example4View", owner: nil, options: nil)!.first as! Example4View } }
mit
032775542c20e2bcea6c38a3bdff53a9
36.894737
322
0.693056
4.485981
false
false
false
false
pnhechim/Fiestapp-iOS
Fiestapp/Fiestapp/Common/Enums/EnumFiestasCell.swift
1
443
// // EnumFiestasCell.swift // Fiestapp // // Created by Nicolás Hechim on 31/5/17. // Copyright © 2017 Mint. All rights reserved. // import UIKit enum EnumFiestasCell: String { case Informacion = "InformacionCell", Galeria = "GaleriaCell", MeGustas = "MeGustasCell", Menu = "MenuCell", Regalos = "ListaRegalosCell", Asistencia = "AsistenciaCell", Vestimenta = "VestimentaCell", Musica = "MusicaCell" }
mit
eb92ca4f7af7a67142ba7346d63e5139
21.05
47
0.666667
2.901316
false
false
false
false
SKrotkih/YTLiveStreaming
YTLiveStreaming/String.swift
1
769
import Foundation public extension String { func trim() -> String { return self.trimmingCharacters(in: CharacterSet.whitespaces) } func indexOf(_ string: String) -> String.Index? { return range(of: string, options: .literal, range: nil, locale: nil)?.lowerBound } func urlEncode() -> String { let encodedURL = self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) return encodedURL! } } public func merge(one: [String: String]?, _ two: [String: String]?) -> [String: String]? { var dict: [String: String]? if let one = one { dict = one if let two = two { for (key, value) in two { dict![key] = value } } } else { dict = two } return dict }
mit
ac69bb98381d2b5c397748bdf74eb1c1
23.03125
90
0.598179
4.112299
false
false
false
false
BelkaLab/GaugeView
Pod/Classes/GaugeLayer.swift
1
4211
// .- // `+d/ // -hmm/ // ommmm/ // `mmmmm/ // `mmmmm/ .:+ssyso+-` // `mmmmmsydmmmmmmmmmho. // `mmmmmmh+:---/+ssssyd: // `mmmmmh. / .md- // `mmmmmo..-` .ommo // `mmmmm+..` ./oydmmm/ // `mmmmm/ /dmmmmmmh` // `mmmmm/ `smmmmmmms` // `mmmmm/ `+dmmmmmy+. // :::::. `-::-.` // // GaugeLayer.swift // GaugeLayer // // Created by Luca D'Incà on 18/10/15. // Copyright © 2015 BELKA S.R.L. All rights reserved. // import UIKit class GaugeLayer: CALayer { /// // Class costants /// private let kStartAngle: Float = 0.0 private let kStopAngle: Float = 360.0 /// // Class property /// private var center: CGPoint { return CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height/2) } //Layer propery var startAngle: Float = 0.0 var radius: CGFloat! var thickness: CGFloat! var gaugeBackgroundColor: UIColor! var gaugeColor: UIColor! var animationDuration: Float! //Animated property @NSManaged var stopAngle: Float /// // Class methods /// //MARK: - Init methods override init(layer: Any) { super.init(layer: layer) if ((layer as AnyObject).isKind(of: GaugeLayer.self)) { if let previous = layer as? GaugeLayer { startAngle = previous.startAngle stopAngle = previous.stopAngle radius = previous.radius thickness = previous.thickness gaugeBackgroundColor = previous.gaugeBackgroundColor gaugeColor = previous.gaugeColor } } setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARK: - override func action(forKey event: String) -> CAAction? { if event == "stopAngle" { return createGaugeAnimation(key: event) } return super.action(forKey: event) } override class func needsDisplay(forKey key: String) -> Bool { if (key == "stopAngle") { return true } return super.needsDisplay(forKey: key) } //MARK: - Setup methods private func setup() { self.contentsScale = UIScreen.main.scale } //MARK: - Animation methods private func createGaugeAnimation(key: String) -> CABasicAnimation { let animation = CABasicAnimation(keyPath: key) animation.fromValue = self.presentation()?.value(forKey: key) animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) animation.duration = Double(animationDuration) return animation } //MARK: - Draw methods private func drawGauge(startPoint: CGPoint) -> CGMutablePath { let path = CGMutablePath() path.move(to: startPoint) path.addLine(to: CGPoint(x: (center.x + (radius) * CGFloat(cosf(startAngle))), y: center.y + (radius) * CGFloat(sinf(startAngle)))) path.addArc(center: CGPoint(x: center.x, y: center.y), radius: radius, startAngle: CGFloat(startAngle), endAngle: CGFloat(stopAngle), clockwise: false) path.addLine(to: CGPoint(x: (center.x + CGFloat(radius - thickness) * CGFloat(cosf(stopAngle))), y: center.y + (radius - thickness) * CGFloat(sinf(stopAngle)))) path.addArc(center: CGPoint(x: center.x, y: center.y), radius: (radius - thickness), startAngle: CGFloat(stopAngle), endAngle: CGFloat(startAngle), clockwise: true) return path } override func draw(in ctx: CGContext) { let startPoint = CGPoint(x: (center.x + (radius - thickness) * CGFloat(cosf(startAngle))), y: center.y + (radius - thickness) * CGFloat(sinf(startAngle))) ctx.setShouldAntialias(true) ctx.addArc(center: CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2), radius: radius-(thickness/2), startAngle: 0, endAngle: CGFloat(2.0*CGFloat.pi), clockwise: false) ctx.setLineWidth(thickness) ctx.setLineCap(.round) ctx.setStrokeColor(gaugeBackgroundColor.cgColor) ctx.drawPath(using: .stroke) ctx.addPath(drawGauge(startPoint: startPoint)) ctx.setFillColor(gaugeColor.cgColor) ctx.drawPath(using: .eoFill) } //MARK: - Class helper methods private func convertDegreesToRadius(degrees: CGFloat) -> CGFloat { return ((CGFloat.pi * degrees) / 180.0) } }
mit
534ca30a50798857acfb2c83b183bd95
26.690789
186
0.645046
3.644156
false
false
false
false
andrebocchini/SwiftChattyOSX
Pods/SwiftChatty/SwiftChatty/Requests/Posts/SetPostCategoryRequest.swift
1
708
// // SetPostCategoryRequest.swift // SwiftChatty // // Created by Andre Bocchini on 1/24/16. // Copyright © 2016 Andre Bocchini. All rights reserved. // import Alamofire /// - SeeAlso: http://winchatty.com/v2/readme#_Toc421451678 public struct SetPostCategoryRequest: Request { public let endpoint: ApiEndpoint = .SetPostCategory public var parameters: [String : AnyObject] = [:] public let httpMethod: Alamofire.Method = .POST public let account: Account public init(withAccount account: Account, postId: Int, category: ModerationFlag) { self.account = account self.parameters["postId"] = postId self.parameters["category"] = category.rawValue } }
mit
dac2e8a369031b7ad81b4e8eae1e0fe7
27.28
86
0.700141
4.110465
false
false
false
false
abdullahselek/DragDropUI
DragDropUI/DDGestureRecognizer.swift
1
3576
// // DDGestureRecognizer.swift // DragDropUI // // Copyright © 2016 Abdullah Selek. All rights reserved. // // MIT License // // 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 UIGestureRecognizer { internal class DDClosureWrapper: NSObject { internal let handler: (UIGestureRecognizer) -> Void internal init(handler: @escaping (UIGestureRecognizer) -> Void) { self.handler = handler } } public class DDGestureDelegate: NSObject, UIGestureRecognizerDelegate { static var delegateKey: String = "key" @objc public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return gestureRecognizer.delegate is DDGestureDelegate && otherGestureRecognizer.delegate is DDGestureDelegate } @objc public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return true } @objc public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return true } } private var multiDelegate: DDGestureDelegate { get { return objc_getAssociatedObject(self, &DDGestureDelegate.delegateKey) as! DDGestureDelegate } set { objc_setAssociatedObject(self, &DDGestureDelegate.delegateKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private static var handlerKey: String = "handlerKey" var handler: ((UIGestureRecognizer) -> Void)? { get { guard let closureWrapper = objc_getAssociatedObject(self, &UIGestureRecognizer.handlerKey) as? DDClosureWrapper else { return nil } return closureWrapper.handler } set { guard let gestureHandler = newValue else { return } self.addTarget(self, action: #selector(UIGestureRecognizer.handleAction)) self.multiDelegate = DDGestureDelegate() self.delegate = self.multiDelegate objc_setAssociatedObject(self, &UIGestureRecognizer.handlerKey, DDClosureWrapper(handler: gestureHandler), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } @objc public func handleAction() { guard let handler = self.handler else { return } handler(self) } }
mit
4514ef368126c278b4042e2ef0d28028
39.168539
176
0.691189
5.121777
false
false
false
false
calebd/ReactiveCocoa
ReactiveCocoaTests/CocoaActionSpec.swift
2
1997
import ReactiveSwift import Result import Nimble import Quick import ReactiveCocoa class CocoaActionSpec: QuickSpec { override func spec() { var action: Action<Int, Int, NoError>! #if os(OSX) var cocoaAction: CocoaAction<NSControl>! #else var cocoaAction: CocoaAction<UIControl>! #endif beforeEach { action = Action { value in SignalProducer(value: value + 1) } expect(action.isEnabled.value) == true cocoaAction = CocoaAction(action) { _ in 1 } expect(cocoaAction.isEnabled.value).toEventually(beTruthy()) } #if os(OSX) it("should be compatible with AppKit") { let control = NSControl(frame: NSZeroRect) control.target = cocoaAction control.action = CocoaAction<NSControl>.selector control.performClick(nil) } #elseif os(iOS) it("should be compatible with UIKit") { let control = UIControl(frame: .zero) control.addTarget(cocoaAction, action: CocoaAction<UIControl>.selector, for: .touchDown) control.sendActions(for: .touchDown) } #endif it("should emit changes for enabled") { var values: [Bool] = [] cocoaAction.isEnabled.producer .startWithValues { values.append($0) } expect(values) == [ true ] let result = action.apply(0).first() expect(result?.value) == 1 expect(values).toEventually(equal([ true, false, true ])) _ = cocoaAction } it("should generate KVO notifications for executing") { var values: [Bool] = [] cocoaAction.isExecuting.producer .startWithValues { values.append($0) } expect(values) == [ false ] let result = action.apply(0).first() expect(result?.value) == 1 expect(values).toEventually(equal([ false, true, false ])) _ = cocoaAction } context("lifetime") { it("CocoaAction should not create a retain cycle") { weak var weakAction = action expect(weakAction).notTo(beNil()) action = nil expect(weakAction).toNot(beNil()) cocoaAction = nil expect(weakAction).to(beNil()) } } } }
mit
f818d41ab275d4b48c3b0f83b8ad1c23
23.353659
92
0.674512
3.578853
false
false
false
false
natecook1000/swift
validation-test/stdlib/Algorithm.swift
1
7262
// -*- swift -*- // RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest import StdlibCollectionUnittest import SwiftPrivate var Algorithm = TestSuite("Algorithm") // FIXME(prext): remove this conformance. extension String.UnicodeScalarView : Equatable {} // FIXME(prext): remove this function. public func == ( lhs: String.UnicodeScalarView, rhs: String.UnicodeScalarView) -> Bool { return Array(lhs) == Array(rhs) } // FIXME(prext): move this struct to the point of use. Algorithm.test("min,max") { // Identities are unique in this set. let a1 = MinimalComparableValue(0, identity: 1) let a2 = MinimalComparableValue(0, identity: 2) let a3 = MinimalComparableValue(0, identity: 3) let b1 = MinimalComparableValue(1, identity: 4) let b2 = MinimalComparableValue(1, identity: 5) _ = MinimalComparableValue(1, identity: 6) let c1 = MinimalComparableValue(2, identity: 7) let c2 = MinimalComparableValue(2, identity: 8) let c3 = MinimalComparableValue(2, identity: 9) // 2-arg min() expectEqual(a1.identity, min(a1, b1).identity) expectEqual(a1.identity, min(b1, a1).identity) expectEqual(a1.identity, min(a1, a2).identity) // 2-arg max() expectEqual(c1.identity, max(c1, b1).identity) expectEqual(c1.identity, max(b1, c1).identity) expectEqual(c1.identity, max(c2, c1).identity) // 3-arg min() expectEqual(a1.identity, min(a1, b1, c1).identity) expectEqual(a1.identity, min(b1, a1, c1).identity) expectEqual(a1.identity, min(c1, b1, a1).identity) expectEqual(a1.identity, min(c1, a1, b1).identity) expectEqual(a1.identity, min(a1, a2, a3).identity) expectEqual(a1.identity, min(a1, a2, b1).identity) expectEqual(a1.identity, min(a1, b1, a2).identity) expectEqual(a1.identity, min(b1, a1, a2).identity) // 3-arg max() expectEqual(c1.identity, max(c1, b1, a1).identity) expectEqual(c1.identity, max(a1, c1, b1).identity) expectEqual(c1.identity, max(b1, a1, c1).identity) expectEqual(c1.identity, max(b1, c1, a1).identity) expectEqual(c1.identity, max(c3, c2, c1).identity) expectEqual(c1.identity, max(c2, c1, b1).identity) expectEqual(c1.identity, max(c2, b1, c1).identity) expectEqual(c1.identity, max(b1, c2, c1).identity) // 4-arg min() expectEqual(a1.identity, min(a1, b1, a2, b2).identity) expectEqual(a1.identity, min(b1, a1, a2, b2).identity) expectEqual(a1.identity, min(c1, b1, b2, a1).identity) expectEqual(a1.identity, min(c1, b1, a1, a2).identity) // 4-arg max() expectEqual(c1.identity, max(c2, b1, c1, b2).identity) expectEqual(c1.identity, max(b1, c2, c1, b2).identity) expectEqual(c1.identity, max(a1, b1, b2, c1).identity) expectEqual(c1.identity, max(a1, b1, c2, c1).identity) } Algorithm.test("sorted/strings") { expectEqual( ["Banana", "apple", "cherry"], ["apple", "Banana", "cherry"].sorted()) let s = ["apple", "Banana", "cherry"].sorted() { $0.count > $1.count } expectEqual(["Banana", "cherry", "apple"], s) } // A wrapper around Array<T> that disables any type-specific algorithm // optimizations and forces bounds checking on. struct A<T> : MutableCollection, RandomAccessCollection { typealias Indices = CountableRange<Int> init(_ a: Array<T>) { impl = a } var startIndex: Int { return 0 } var endIndex: Int { return impl.count } func makeIterator() -> Array<T>.Iterator { return impl.makeIterator() } subscript(i: Int) -> T { get { expectTrue(i >= 0 && i < impl.count) return impl[i] } set (x) { expectTrue(i >= 0 && i < impl.count) impl[i] = x } } subscript(r: Range<Int>) -> Array<T>.SubSequence { get { expectTrue(r.lowerBound >= 0 && r.lowerBound <= impl.count) expectTrue(r.upperBound >= 0 && r.upperBound <= impl.count) return impl[r] } set (x) { expectTrue(r.lowerBound >= 0 && r.lowerBound <= impl.count) expectTrue(r.upperBound >= 0 && r.upperBound <= impl.count) impl[r] = x } } var impl: Array<T> } func randomArray() -> A<Int> { let count = Int.random(in: 0 ..< 50) let array = (0 ..< count).map { _ in Int.random(in: .min ... .max) } return A(array) } Algorithm.test("invalidOrderings") { withInvalidOrderings { let a = randomArray() _blackHole(a.sorted(by: $0)) } withInvalidOrderings { var a: A<Int> a = randomArray() let lt = $0 let first = a.first _ = a.partition(by: { !lt($0, first!) }) } /* // FIXME: Disabled due to <rdar://problem/17734737> Unimplemented: // abstraction difference in l-value withInvalidOrderings { var a = randomArray() var pred = $0 _insertionSort(&a, a.indices, &pred) } */ } // The routine is based on http://www.cs.dartmouth.edu/~doug/mdmspe.pdf func makeQSortKiller(_ len: Int) -> [Int] { var candidate: Int = 0 var keys = [Int: Int]() func Compare(_ x: Int, y : Int) -> Bool { if keys[x] == nil && keys[y] == nil { if (x == candidate) { keys[x] = keys.count } else { keys[y] = keys.count } } if keys[x] == nil { candidate = x return true } if keys[y] == nil { candidate = y return false } return keys[x]! > keys[y]! } var ary = [Int](repeating: 0, count: len) var ret = [Int](repeating: 0, count: len) for i in 0..<len { ary[i] = i } ary = ary.sorted(by: Compare) for i in 0..<len { ret[ary[i]] = i } return ret } Algorithm.test("sorted/complexity") { var ary: [Int] = [] // Check performance of sorting an array of repeating values. var comparisons_100 = 0 ary = [Int](repeating: 0, count: 100) ary.sort { comparisons_100 += 1; return $0 < $1 } var comparisons_1000 = 0 ary = [Int](repeating: 0, count: 1000) ary.sort { comparisons_1000 += 1; return $0 < $1 } expectTrue(comparisons_1000/comparisons_100 < 20) // Try to construct 'bad' case for quicksort, on which the algorithm // goes quadratic. comparisons_100 = 0 ary = makeQSortKiller(100) ary.sort { comparisons_100 += 1; return $0 < $1 } comparisons_1000 = 0 ary = makeQSortKiller(1000) ary.sort { comparisons_1000 += 1; return $0 < $1 } expectTrue(comparisons_1000/comparisons_100 < 20) } Algorithm.test("sorted/return type") { let _: Array = ([5, 4, 3, 2, 1] as ArraySlice).sorted() } Algorithm.test("sort3/simple") .forEach(in: [ [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1] ]) { var input = $0 input.sort() expectEqual([1, 2, 3], input) } func isSorted<T>(_ a: [T], by areInIncreasingOrder: (T, T) -> Bool) -> Bool { return !a.dropFirst().enumerated().contains(where: { (offset, element) in areInIncreasingOrder(element, a[offset]) }) } Algorithm.test("sort3/stable") .forEach(in: [ [1, 1, 2], [1, 2, 1], [2, 1, 1], [1, 2, 2], [2, 1, 2], [2, 2, 1], [1, 1, 1] ]) { // decorate with offset, but sort by value var input = Array($0.enumerated()) input._sort3(0, 1, 2) { $0.element < $1.element } // offsets should still be ordered for equal values expectTrue(isSorted(input) { if $0.element == $1.element { return $0.offset < $1.offset } return $0.element < $1.element }) } runAllTests()
apache-2.0
183c1c0254c52c71b7798784356d25a9
27.256809
79
0.627788
3.044864
false
false
false
false
dkeichinger/XLForm
Examples/Swift/Examples/Inputs/InputsFormViewController.swift
16
5687
// // InputsFormViewController.swift // XLForm ( https://github.com/xmartlabs/XLForm ) // // Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. class InputsFormViewController : XLFormViewController { private enum Tags : String { case Name = "name" case Email = "email" case Twitter = "twitter" case Number = "number" case Integer = "integer" case Decimal = "decimal" case Password = "password" case Phone = "phone" case Url = "url" case TextView = "textView" case Notes = "notes" } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.initializeForm() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initializeForm() } func initializeForm() { let form : XLFormDescriptor var section : XLFormSectionDescriptor var row : XLFormRowDescriptor form = XLFormDescriptor(title: "Text Fields") form.assignFirstResponderOnShow = true section = XLFormSectionDescriptor.formSectionWithTitle("TextField Types") section.footerTitle = "This is a long text that will appear on section footer" form.addFormSection(section) // Name row = XLFormRowDescriptor(tag: Tags.Name.rawValue, rowType: XLFormRowDescriptorTypeText, title: "Name") row.required = true section.addFormRow(row) // Email row = XLFormRowDescriptor(tag: Tags.Email.rawValue, rowType: XLFormRowDescriptorTypeEmail, title: "Email") // validate the email row.addValidator(XLFormValidator.emailValidator()) section.addFormRow(row) // Twitter row = XLFormRowDescriptor(tag: Tags.Name.rawValue, rowType: XLFormRowDescriptorTypeTwitter, title: "Twitter") row.disabled = NSNumber(bool: true) row.value = "@no_editable" section.addFormRow(row) // Number row = XLFormRowDescriptor(tag: Tags.Number.rawValue, rowType: XLFormRowDescriptorTypeNumber, title: "Number") section.addFormRow(row) // Integer row = XLFormRowDescriptor(tag: Tags.Integer.rawValue, rowType: XLFormRowDescriptorTypeInteger, title: "Integer") section.addFormRow(row) // Decimal row = XLFormRowDescriptor(tag: Tags.Decimal.rawValue, rowType: XLFormRowDescriptorTypeDecimal, title: "Decimal") section.addFormRow(row) // Password row = XLFormRowDescriptor(tag: Tags.Password.rawValue, rowType: XLFormRowDescriptorTypePassword, title: "Password") section.addFormRow(row) // Phone row = XLFormRowDescriptor(tag: Tags.Phone.rawValue, rowType: XLFormRowDescriptorTypePhone, title: "Phone") section.addFormRow(row) // Url row = XLFormRowDescriptor(tag: Tags.Url.rawValue, rowType: XLFormRowDescriptorTypeURL, title: "Url") section.addFormRow(row) section = XLFormSectionDescriptor.formSection() form.addFormSection(section) // TextView row = XLFormRowDescriptor(tag: Tags.TextView.rawValue, rowType: XLFormRowDescriptorTypeTextView) row.cellConfigAtConfigure["textView.placeholder"] = "TEXT VIEW EXAMPLE" section.addFormRow(row) section = XLFormSectionDescriptor.formSectionWithTitle("TextView With Label Example") form.addFormSection(section) row = XLFormRowDescriptor(tag: Tags.Number.rawValue, rowType: XLFormRowDescriptorTypeTextView, title: "Notes") section.addFormRow(row) self.form = form } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Save, target: self, action: "savePressed:") } func savePressed(button: UIBarButtonItem) { let validationErrors : Array<NSError> = self.formValidationErrors() as! Array<NSError> if (validationErrors.count > 0){ self.showFormValidationError(validationErrors.first) return } self.tableView.endEditing(true) let alertView = UIAlertView(title: "Valid Form", message: "No errors found", delegate: self, cancelButtonTitle: "OK") alertView.show() } }
mit
002472ec3611cb18c8c2347a65192a0a
37.425676
151
0.66485
5.137308
false
false
false
false
rtm-ctrlz/ParrotZik-OSX
CommonFiles/UI/ParrotState.swift
1
2542
// // Parrot.swift // ParrotZik // // Created by Внештатный командир земли on 17/02/15. // Copyright (c) 2015 Внештатный командир земли. All rights reserved. // import Cocoa class ParrotState { var bat: BatteryItem = BatteryItem() var nam: NameItem = NameItem() var ver: VersionItem = VersionItem() var anc: ANCItem = ANCItem() var panc: PhoneANCItem = PhoneANCItem() var lou: LouReedItem = LouReedItem() var item: NSStatusItem var req:ParrotRequestor? = nil init(item: NSStatusItem) { self.item = item self.bat.updateCB = { self.bat.updateStatusItem(self.item) } } func getNotifyRegistrations() -> [(path:String, handler: (NSData,ParrotRequestor) -> Void)] { var result:[(path:String, handler: (NSData,ParrotRequestor) -> Void)] result = self.bat.getNotityRegistrations() return result } func getMenuItems() -> [NSMenuItem] { var result: [NSMenuItem] = [NSMenuItem]() result.extend(self.bat.getMenuItems()) result.extend(self.nam.getMenuItems()) result.extend(self.ver.getMenuItems()) result.extend(self.anc.getMenuItems()) result.extend(self.panc.getMenuItems()) result.extend(self.lou.getMenuItems()) return result } func onConnect(req:ParrotRequestor?) { if req != nil { self.req = req } self.bat.clear() self.nam.clear() self.ver.clear() self.anc.clear() self.panc.clear() self.lou.clear() self.req!.clean() self.req!.pushItem(self.bat) self.req!.pushItem(self.nam) self.req!.pushItem(self.ver) self.req!.pushItem(self.anc) self.req!.pushItem(self.panc) self.req!.pushItem(self.lou) } func onDisconnect() { self.req!.clean() self.bat.clear() self.nam.clear() self.ver.clear() self.anc.clear() self.panc.clear() self.lou.clear() } func updateStatusItem(item: NSStatusItem) { self.bat.updateStatusItem(item) } func forwardMenuItemClick(menuItem: NSMenuItem) { if self.anc.handleItemClick(self, menuItem: menuItem) { return } if self.panc.handleItemClick(self, menuItem: menuItem) { return } if self.lou.handleItemClick(self, menuItem: menuItem) { return } } }
gpl-2.0
5c9f67f5f7d62e338f98ec0d3124b4c9
26.744444
97
0.586138
3.793313
false
false
false
false
oliveroneill/FeedCollectionViewController
Example/FeedCollectionViewController/ColorImageCellData.swift
1
1613
// // CustomImageCellData.swift // FeedCollectionViewController // // Created by Oliver ONeill on 21/12/2016. // import UIKit import ImageFeedCollectionViewController public extension UIImage { convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image?.cgImage else { return nil } self.init(cgImage: cgImage) } } class ColorImageCellData: ImageCellData { var image: UIImage? { didSet { self.imageDidChange?() } } var imageDidChange: (() -> ())? private var color: UIColor = .red private var loadingDelay: Double = 0.1 convenience init(color: UIColor, delay: Double) { self.init(image: UIImage(color: color)) self.color = color self.loadingDelay = delay } override func cellDidBecomeVisible() { // use 0.1 second delay instead of a network request if loadingDelay == 0 { setColor() return } let ms = Int(loadingDelay * 1000) DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(ms)) { [unowned self] in DispatchQueue.main.sync { [unowned self] in self.setColor() } } } func setColor() { self.image = UIImage(color: self.color) } }
mit
1e91318519d1c621910fde7b236123ab
27.298246
99
0.611903
4.480556
false
false
false
false
TongjiUAppleClub/WeCitizens
WeCitizens/ReplyTableViewCell.swift
1
4194
// // ReplyTableViewCell.swift // WeCitizens // // Created by Harold LIU on 2/24/16. // Copyright © 2016 Tongji Apple Club. All rights reserved. // import UIKit import FoldingCell protocol JumpVoiceDelegate { func jumpVoiceDetail(voiceId:String) } class ReplyTableViewCell: FoldingCell,SSRadioButtonControllerDelegate{ //Foreground View var delegate:JumpVoiceDelegate? var voiceId:String? @IBOutlet weak var Back: UIView! @IBOutlet weak var Favatar: UIImageView! @IBOutlet weak var imgContainer: UIView! @IBOutlet weak var ResponseTitle: UILabel! @IBOutlet weak var FAgency: UILabel! @IBOutlet weak var ResponseTime: UILabel! @IBOutlet weak var SupportPercent: UILabel! //Container View //First @IBOutlet weak var CAvatar: UIImageView! @IBOutlet weak var CAgency: UILabel! @IBOutlet weak var CTitle: UILabel! @IBOutlet weak var CContent: UITextView! //Second @IBOutlet weak var CimgContainer: UIView! @IBOutlet weak var CResponseTime: UILabel! @IBOutlet weak var CResponseButton: UIButton! //Third @IBOutlet weak var ThirdView: RotatedView! @IBOutlet weak var EvaluateButton: UIButton! @IBOutlet weak var CheckHistoryButton: UIButton! @IBOutlet var CommentButtons: [SSRadioButton]! // Fourth @IBOutlet weak var SubmitButton: UIButton! @IBOutlet weak var CSupport: UILabel! var radioButtonController:SSRadioButtonsController? override func awakeFromNib() { super.awakeFromNib() configureUI() setButtons() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } override func animationDuration(itemIndex:NSInteger, type:AnimationType)-> NSTimeInterval { // durations count equal it itemCount let durations = [0.33, 0.26, 0.26] // timing animation for each view return durations[itemIndex] } func configureUI() { foregroundView.layer.cornerRadius = 8 Back.layer.cornerRadius = 8 Favatar = UIImageView.lxd_CircleImage(Favatar, borderColor: UIColor.clearColor(), borderWidth: 0) imgContainer.layer.cornerRadius = 5 containerView.layer.cornerRadius = 8 CAvatar = UIImageView.lxd_CircleImage(CAvatar, borderColor: UIColor.clearColor(), borderWidth: 0) CimgContainer.layer.cornerRadius = 5 CContent.backgroundColor = UIColor.clearColor() CResponseButton.layer.borderColor = UIColor.lxd_MainBlueColor().CGColor CResponseButton.layer.borderWidth = 1.3 CResponseButton.layer.cornerRadius = CResponseButton.frame.height/2 SubmitButton.layer.cornerRadius = SubmitButton.frame.height/2 SubmitButton.layer.borderColor = UIColor.lxd_MainBlueColor().CGColor SubmitButton.layer.borderWidth = 1.3 } @IBAction func jumpVoice(sender: AnyObject) { delegate!.jumpVoiceDetail(self.voiceId!) } func drawBarChart(radios:[CGFloat]) { for (index,radio) in radios.enumerate() { let width :CGFloat = 20.0+radio*300 let y:CGFloat = EvaluateButton.layer.frame.origin.y+CGFloat(35*index+64) let frame = CGRect(x: -20, y:y, width:width , height: 20) let barView = UIView(frame: frame) barView.backgroundColor = UIColor.lxd_YellowColor() barView.layer.cornerRadius = barView.frame.size.height/2 var labelFrame = frame labelFrame.size.width -= 10 let markLabel = UILabel(frame: labelFrame) markLabel.text = "\(radio)" markLabel.textColor = UIColor.whiteColor() markLabel.textAlignment = .Right ThirdView.addSubview(barView) ThirdView.addSubview(markLabel) } } func setButtons() { radioButtonController = SSRadioButtonsController() for button in CommentButtons { radioButtonController?.addButton(button) } radioButtonController?.shouldLetDeSelect = true } }
mit
b20d75335e2fcb877ed67376b609119c
31.253846
105
0.663248
4.633149
false
false
false
false
zillachan/actor-platform
actor-apps/app-ios/Actor/Controllers/Conversation/Cells/BubbleLayouts.swift
42
5773
// // Layouts.swift // ActorApp // // Created by Stepan Korshakov on 26.06.15. // Copyright (c) 2015 Actor LLC. All rights reserved. // import Foundation class MessagesLayouting { class func measureHeight(message: AMMessage, group: Bool, setting: CellSetting, layoutCache: LayoutCache) -> CGFloat { var content = message.getContent()! var layout = layoutCache.pick(message.getRid()) if (layout == nil) { // Usually never happens layout = buildLayout(message, layoutCache: layoutCache) layoutCache.cache(message.getRid(), layout: layout!) } var height = layout!.height if content is AMServiceContent { height += AABubbleCell.bubbleTop height += AABubbleCell.bubbleBottom } else { height += (setting.clenchTop ? AABubbleCell.bubbleTopCompact : AABubbleCell.bubbleTop) height += (setting.clenchBottom ? AABubbleCell.bubbleBottomCompact : AABubbleCell.bubbleBottom) } // Sender name let isIn = message.getSenderId() != MSG.myUid() if group && isIn && !(content is AMServiceContent) && !(content is AMPhotoContent) && !(content is AMDocumentContent) { height += CGFloat(20.0) } // Date separator if (setting.showDate) { height += AABubbleCell.dateSize } // New message separator if (setting.showNewMessages) { height += AABubbleCell.newMessageSize } return height } class func buildLayout(message: AMMessage, layoutCache: LayoutCache) -> CellLayout { var content = message.getContent()! var res: CellLayout if (content is AMTextContent) { res = TextCellLayout(message: message) } else if (content is AMPhotoContent) { res = CellLayout(message: message) res.height = AABubbleMediaCell.measureMediaHeight(message) } else if (content is AMServiceContent) { res = CellLayout(message: message) res.height = AABubbleServiceCell.measureServiceHeight(message) } else if (content is AMDocumentContent) { res = CellLayout(message: message) res.height = AABubbleDocumentCell.measureDocumentHeight(message) } else { // Unsupported res = TextCellLayout(message: message) } return res } } class CellSetting { let showNewMessages: Bool let showDate: Bool let clenchTop: Bool let clenchBottom: Bool init(showDate: Bool, clenchTop: Bool, clenchBottom: Bool, showNewMessages: Bool) { self.showDate = showDate self.clenchTop = clenchTop self.clenchBottom = clenchBottom self.showNewMessages = showNewMessages } } class CellLayout: NSObject { var height: CGFloat = 0 var date: String init(message: AMMessage) { self.date = CellLayout.formatDate(Int64(message.getDate())) } class func formatDate(date: Int64) -> String { var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" return dateFormatter.stringFromDate(NSDate(timeIntervalSince1970: NSTimeInterval(Double(date) / 1000.0))) } } class TextCellLayout: CellLayout { private static let stringOutPadding = " \u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}"; private static let stringInPadding = " \u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}"; private static let maxTextWidth = isIPad ? 400 : 210 static let bubbleFont = isIPad ? UIFont(name: "HelveticaNeue", size: 17)! : UIFont(name: "HelveticaNeue", size: 16)! static let bubbleFontUnsupported = isIPad ? UIFont(name: "HelveticaNeue-Italic", size: 17)! : UIFont(name: "HelveticaNeue-Italic", size: 16)! var text: String var isUnsupported: Bool var textSizeWithPadding: CGSize var textSize: CGSize override init(message: AMMessage) { if let content = message.getContent() as? AMTextContent { text = content.getText() isUnsupported = false } else { text = NSLocalizedString("UnsupportedContent", comment: "Unsupported text") isUnsupported = true } // Measure text var measureText = (text + (message.getSenderId() == MSG.myUid() ? TextCellLayout.stringOutPadding : TextCellLayout.stringInPadding)) as NSString; var size = CGSize(width: TextCellLayout.maxTextWidth, height: 0); var style = NSMutableParagraphStyle(); style.lineBreakMode = NSLineBreakMode.ByWordWrapping; var rect = measureText.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: isUnsupported ? TextCellLayout.bubbleFontUnsupported : TextCellLayout.bubbleFont, NSParagraphStyleAttributeName: style], context: nil); textSizeWithPadding = CGSizeMake(round(rect.width), round(rect.height)) rect = text.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: isUnsupported ? TextCellLayout.bubbleFontUnsupported : TextCellLayout.bubbleFont, NSParagraphStyleAttributeName: style], context: nil); textSize = CGSizeMake(round(rect.width), round(rect.height)) super.init(message: message) height = textSizeWithPadding.height + AABubbleCell.bubbleContentTop + AABubbleCell.bubbleContentBottom } }
mit
76abdc74dd5a8fb7dbeaa9ae601b9d85
35.770701
167
0.639356
4.659403
false
false
false
false
kaltura/playkit-ios
Classes/Managers/AppState/AppStateSubject.swift
1
6970
// =================================================================================================== // Copyright (C) 2017 Kaltura Inc. // // Licensed under the AGPLv3 license, unless a different license for a // particular library is specified in the applicable library path. // // You may obtain a copy of the License at // https://www.gnu.org/licenses/agpl-3.0.html // =================================================================================================== import Foundation /// The interface of `AppStateSubject`, allows us to better divide the logic and mock easier. public protocol AppStateSubjectProtocol: AppStateProviderDelegate { associatedtype InstanceType static var shared: InstanceType { get } /// Lock object for synchronizing access. var lock: AnyObject { get } /// The app state events provider. var appStateProvider: AppStateProvider { get } /// The current app state observers. var observers: [AppStateObserver] { get set } /// States whether currently observing. /// - note: when mocking set initial value to false. var isObserving: Bool { get set } } extension AppStateSubjectProtocol { /// Starts observing the app state events func startObservingAppState() { sync { // if not already observing and has more than 0 oberserver then start observing if !isObserving { PKLog.verbose("start observing app state") appStateProvider.addObservers() isObserving = true } } } /// Stops observing the app state events. func stopObservingAppState() { sync { if isObserving { PKLog.verbose("stop observing app state") appStateProvider.removeObservers() isObserving = false } } } /// Adds an observer to inform when state events are posted. public func add(observer: AppStateObservable) { sync { cleanObservers() PKLog.verbose("add observer, \(observer)") // if no observers were available start observing now if observers.count == 0 && !isObserving { startObservingAppState() } observers.append(AppStateObserver(observer)) } } /// Removes an observer to stop being inform when state events are posted. public func remove(observer: AppStateObservable) { sync { cleanObservers() // search for the observer to remove for i in 0..<observers.count { if observers[i].observer === observer { let removedObserver = observers.remove(at: i) PKLog.verbose("removed observer, \(removedObserver)") // if no more observers available stop observing if observers.count == 0 && isObserving { stopObservingAppState() } break } } } } /// Removes all observers and stop observing. func removeAllObservers() { sync { if observers.count > 0 { PKLog.verbose("remove all observers") observers.removeAll() stopObservingAppState() } } } /************************************************************/ // MARK: AppStateProviderDelegate /************************************************************/ public func appStateEventPosted(name: ObservationName) { sync { PKLog.verbose("app state event posted with name: \(name.rawValue)") for appStateObserver in self.observers { if let filteredObservations = appStateObserver.observer?.observations.filter({ $0.name == name }) { for observation in filteredObservations { observation.onObserve() } } } } } // MARK: Private /// synchornized function private func sync(block: () -> ()) { objc_sync_enter(lock) block() objc_sync_exit(lock) } /// remove nil observers from our list private func cleanObservers() { self.observers = self.observers.filter { $0.observer != nil } } } /************************************************************/ // MARK: - AppStateSubject /************************************************************/ /// The `AppStateSubject` class provides a way to add/remove application state observers. /// /// - note: Subject is a class that is both observing and being observered. /// In our case listening to events using the provider and posting using the obervations onObserve. /// /// **For Unit-Testing:** When mocking this object just conform to the `AppStateSubjectProtocol`. /// For firing events to observers manually use `appStateEventPosted(name: ObservationName)` with the observation name. public final class AppStateSubject: AppStateSubjectProtocol { // singleton object and private init to prevent unwanted creation of more objects. public static let shared = AppStateSubject() private init() { self.appStateProvider = AppStateProvider() self.appStateProvider.delegate = self } public let lock: AnyObject = UUID().uuidString as AnyObject public var observers = [AppStateObserver]() public var appStateProvider: AppStateProvider public var isObserving = false } /************************************************************/ // MARK: - Types /************************************************************/ /// Used to specify observation name public typealias ObservationName = Notification.Name // used as typealias in case we will change type in the future. /// represents a single observation with observation name as the type, and a block to perform when observing. public struct NotificationObservation: Hashable { public init(name: ObservationName, onObserve: @escaping () -> Void) { self.name = name self.onObserve = onObserve } public var name: ObservationName public var onObserve: () -> Void public func hash(into hasher: inout Hasher) { hasher.combine(name) } } public func == (lhs: NotificationObservation, rhs: NotificationObservation) -> Bool { return lhs.name.rawValue == rhs.name.rawValue } public class AppStateObserver { weak var observer: AppStateObservable? init(_ observer: AppStateObservable) { self.observer = observer } } /// A type that provides a set of NotificationObservation to observe. /// This interface defines the observations we would want in our class, for example a set of [willTerminate, didEnterBackground etc.] public protocol AppStateObservable: AnyObject { var observations: Set<NotificationObservation> { get } }
agpl-3.0
738e80282839d9187793ac11e07bfee4
35.878307
133
0.576471
5.419907
false
false
false
false
bigtreenono/NSPTools
HeHe/CoreText/SwiftTextKitNotepad-final/SwiftTextKitNotepad/TimeIndicatorView.swift
1
2454
// // TimeIndicatorView.swift // SwiftTextKitNotepad // // Created by Gabriel Hauber on 18/07/2014. // Copyright (c) 2014 Gabriel Hauber. All rights reserved. // import UIKit class TimeIndicatorView: UIView { var label = UILabel() required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(date: NSDate) { super.init(frame: CGRectZero) // Initialization code backgroundColor = UIColor.clearColor() clipsToBounds = false // format and style the date let formatter = NSDateFormatter() formatter.dateFormat = "dd\rMMMM\ryyyy" let formattedDate = formatter.stringFromDate(date) label.text = formattedDate.uppercaseString label.textAlignment = .Center label.textColor = UIColor.whiteColor() label.numberOfLines = 0 addSubview(label) } func updateSize() { // size the label based on the font label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) label.frame = CGRect(x: 0, y: 0, width: Int.max, height: Int.max) label.sizeToFit() // set the frame to be large enough to accomodate the circle that surrounds the text let radius = radiusToSurroundFrame(label.frame) frame = CGRect(x: 0, y: 0, width: radius * 2, height: radius * 2) // center the label within this circle label.center = center // offset the center of this view to ... erm ... can I just draw you a picture? // You know the story - the designer provides a mock-up with some static data, leaving // you to work out the complex calculations required to accomodate the variability of real-world // data. C'est la vie! let padding : CGFloat = 5.0 center = CGPoint(x: center.x + label.frame.origin.x - padding, y: center.y - label.frame.origin.y + padding) } // calculates the radius of the circle that surrounds the label func radiusToSurroundFrame(frame: CGRect) -> CGFloat { return max(frame.width, frame.height) * 0.5 + 25 } func curvePathWithOrigin(origin: CGPoint) -> UIBezierPath { return UIBezierPath(arcCenter: origin, radius: radiusToSurroundFrame(label.frame), startAngle: -180, endAngle: 180, clockwise: true) } override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() CGContextSetShouldAntialias(context, true) let path = curvePathWithOrigin(label.center) UIColor(red: 0.329, green: 0.584, blue: 0.898, alpha: 1).setFill() path.fill() } }
mit
62cf100a59504adf9b0aa135bcac0350
31.72
136
0.699674
3.958065
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/PollResultController.swift
1
16919
// // PollResultController.swift // Telegram // // Created by Mikhail Filimonov on 07.01.2020. // Copyright © 2020 Telegram. All rights reserved. // import Cocoa import TGUIKit import SwiftSignalKit import TelegramCore import Postbox private struct PollResultState : Equatable { let results: PollResultsState? let shouldLoadMore: Data? let poll: TelegramMediaPoll let expandedOptions: [Data: Int] init(results: PollResultsState?, poll: TelegramMediaPoll, shouldLoadMore: Data?, expandedOptions: [Data: Int]) { self.results = results self.poll = poll self.shouldLoadMore = nil self.expandedOptions = expandedOptions } func withUpdatedResults(_ results: PollResultsState?) -> PollResultState { return PollResultState(results: results, poll: self.poll, shouldLoadMore: self.shouldLoadMore, expandedOptions: self.expandedOptions) } func withUpdatedShouldLoadMore(_ shouldLoadMore: Data?) -> PollResultState { return PollResultState(results: self.results, poll: self.poll, shouldLoadMore: shouldLoadMore, expandedOptions: self.expandedOptions) } func withAddedExpandedOption(_ identifier: Data) -> PollResultState { var expandedOptions = self.expandedOptions if let optionState = results?.options[identifier] { expandedOptions[identifier] = optionState.peers.count } return PollResultState(results: self.results, poll: self.poll, shouldLoadMore: self.shouldLoadMore, expandedOptions: expandedOptions) } func withRemovedExpandedOption(_ identifier: Data) -> PollResultState { var expandedOptions = self.expandedOptions expandedOptions.removeValue(forKey: identifier) return PollResultState(results: self.results, poll: self.poll, shouldLoadMore: self.shouldLoadMore, expandedOptions: expandedOptions) } } private func _id_option(_ identifier: Data, _ peerId: PeerId) -> InputDataIdentifier { return InputDataIdentifier("_id_option_\(identifier.base64EncodedString())_\(peerId.toInt64())") } private func _id_load_more(_ identifier: Data) -> InputDataIdentifier { return InputDataIdentifier("_id_load_more_\(identifier.base64EncodedString())") } private func _id_loading_for(_ identifier: Data) -> InputDataIdentifier { return InputDataIdentifier("_id_loading_for_\(identifier.base64EncodedString())") } private func _id_option_header(_ identifier: Data) -> InputDataIdentifier { return InputDataIdentifier("_id_option_header_\(identifier.base64EncodedString())") } private func _id_option_empty(_ index: Int) -> InputDataIdentifier { return InputDataIdentifier("_id_option_empty_\(index)") } private let collapsedResultCount: Int = 10 private let collapsedInitialLimit: Int = 14 private let _id_loading = InputDataIdentifier("_id_loading") private func pollResultEntries(_ state: PollResultState, context: AccountContext, openProfile:@escaping(PeerId)->Void, expandOption: @escaping(Data)->Void, collapseOption: @escaping(Data)->Void) -> [InputDataEntry] { var sectionId: Int32 = 0 var index: Int32 = 0 var entries:[InputDataEntry] = [] entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(.desc(sectionId: sectionId, index: index, text: .plain(state.poll.text), data: InputDataGeneralTextData(color: theme.colors.text, detectBold: true, viewType: .modern(position: .inner, insets: NSEdgeInsetsMake(0, 16, 0, 16)), fontSize: .huge))) index += 1 let poll = state.poll var votes:[Int] = [] for option in poll.options { let count = Int(poll.results.voters?.first(where: {$0.opaqueIdentifier == option.opaqueIdentifier})?.count ?? 0) votes.append(count) } let percents = countNicePercent(votes: votes, total: Int(poll.results.totalVoters ?? 0)) struct Option : Equatable { let option: TelegramMediaPollOption let percent: Int let voters:PollResultsOptionState? let votesCount: Int } var options:[Option] = [] for (i, option) in poll.options.enumerated() { if let voters = state.results?.options[option.opaqueIdentifier], !voters.peers.isEmpty { let votesCount = Int(poll.results.voters?.first(where: {$0.opaqueIdentifier == option.opaqueIdentifier})?.count ?? 0) options.append(Option(option: option, percent: percents[i], voters: voters, votesCount: votesCount)) } else { let votesCount = Int(poll.results.voters?.first(where: {$0.opaqueIdentifier == option.opaqueIdentifier})?.count ?? 0) options.append(Option(option: option, percent: percents[i], voters: nil, votesCount: votesCount)) } } var isEmpty = false if let resultsState = state.results { for (_, optionState) in resultsState.options { if !optionState.hasLoadedOnce { isEmpty = true break } } } for option in options { if option.votesCount > 0 { if option == options.first { entries.append(.sectionId(sectionId, type: .customModern(16))) sectionId += 1 } else { entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 } let text = option.option.text let additionText:String = " — \(option.percent)%" entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_option_header(option.option.opaqueIdentifier), equatable: InputDataEquatable(state), comparable: nil, item: { initialSize, stableId in let collapse:(()->Void)? if state.expandedOptions[option.option.opaqueIdentifier] != nil { collapse = { collapseOption(option.option.opaqueIdentifier) } } else { collapse = nil } return PollResultStickItem(initialSize, stableId: stableId, left: text, additionText: additionText, right: poll.isQuiz ? strings().chatQuizTotalVotesCountable(option.votesCount) : strings().chatPollTotalVotes1Countable(option.votesCount), collapse: collapse, viewType: .textTopItem) })) index += 1 if let optionState = option.voters { let optionExpandedAtCount = state.expandedOptions[option.option.opaqueIdentifier] var peers = optionState.peers let count = optionState.count let displayCount: Int if peers.count > collapsedInitialLimit + 1 { if optionExpandedAtCount != nil { displayCount = peers.count } else { displayCount = collapsedResultCount } } else { if let optionExpandedAtCount = optionExpandedAtCount { if optionExpandedAtCount == collapsedInitialLimit + 1 && optionState.canLoadMore { displayCount = collapsedResultCount } else { displayCount = peers.count } } else { if !optionState.canLoadMore { displayCount = peers.count } else { displayCount = collapsedResultCount } } } peers = Array(peers.prefix(displayCount)) for (i, voter) in peers.enumerated() { if let peer = voter.peer { var viewType = bestGeneralViewType(peers, for: i) if i == peers.count - 1, optionState.canLoadMore { if peers.count == 1 { viewType = .firstItem } else { viewType = .innerItem } } entries.append(InputDataEntry.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_option(option.option.opaqueIdentifier, peer.id), equatable: InputDataEquatable(option), comparable: nil, item: { initialSize, stableId in return ShortPeerRowItem(initialSize, peer: peer, account: context.account, context: context, stableId: stableId, height: 46, photoSize: NSMakeSize(32, 32), inset: NSEdgeInsets(left: 30, right: 30), generalType: .none, viewType: viewType, action: { openProfile(peer.id) }, highlightVerified: true) })) index += 1 } } let remainingCount = count - peers.count if remainingCount > 0 { if optionState.isLoadingMore && state.expandedOptions[option.option.opaqueIdentifier] != nil { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_loading_for(option.option.opaqueIdentifier), equatable: InputDataEquatable(option), comparable: nil, item: { initialSize, stableId in return LoadingTableItem(initialSize, height: 41, stableId: stableId, viewType: .lastItem) })) index += 1 } else { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_load_more(option.option.opaqueIdentifier), equatable: InputDataEquatable(option), comparable: nil, item: { initialSize, stableId in return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().pollResultsLoadMoreCountable(remainingCount), nameStyle: blueActionButton, type: .none, viewType: .lastItem, action: { expandOption(option.option.opaqueIdentifier) }, thumb: GeneralThumbAdditional(thumb: theme.icons.chatSearchUp, textInset: 52, thumbInset: 4)) })) index += 1 } } } else { let displayCount: Int let voterCount = option.votesCount if voterCount > collapsedInitialLimit { displayCount = collapsedResultCount } else { displayCount = voterCount } let remainingCount: Int? if displayCount < voterCount { remainingCount = voterCount - displayCount } else { remainingCount = nil } var display:[Int] = [] for peerIndex in 0 ..< displayCount { display.append(peerIndex) } for peerIndex in display { var viewType = bestGeneralViewType(display, for: peerIndex) if peerIndex == displayCount - 1, remainingCount != nil { if displayCount == 1 { viewType = .firstItem } else { viewType = .innerItem } } entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_option_empty(Int(index)), equatable: nil, comparable: nil, item: { initialSize, stableId in return PeerEmptyHolderItem(initialSize, stableId: stableId, height: 46, photoSize: NSMakeSize(32, 32), viewType: viewType) })) index += 1 } if let remainingCount = remainingCount { entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_load_more(option.option.opaqueIdentifier), equatable: InputDataEquatable(option), comparable: nil, item: { initialSize, stableId in return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().pollResultsLoadMoreCountable(remainingCount), nameStyle: blueActionButton, type: .none, viewType: .lastItem, thumb: GeneralThumbAdditional(thumb: theme.icons.chatSearchUpDisabled, textInset: 52, thumbInset: 4), enabled: false) })) index += 1 } } } } entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 return entries } func PollResultController(context: AccountContext, message: Message, scrollToOption: Data? = nil) -> InputDataModalController { let poll = message.media[0] as! TelegramMediaPoll var scrollToOption = scrollToOption let resultsContext: PollResultsContext = context.engine.messages.pollResults(messageId: message.id, poll: poll) let initialState = PollResultState(results: nil, poll: poll, shouldLoadMore: nil, expandedOptions: [:]) let disposable = MetaDisposable() let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) let updateState: ((PollResultState) -> PollResultState) -> Void = { f in statePromise.set(stateValue.modify (f)) } disposable.set(resultsContext.state.start(next: { results in updateState { $0.withUpdatedResults(results) } })) var openProfile:((PeerId)->Void)? = nil let signal = statePromise.get() |> map { pollResultEntries($0, context: context, openProfile: { peerId in openProfile?(peerId) }, expandOption: { identifier in updateState { $0.withAddedExpandedOption(identifier) } resultsContext.loadMore(optionOpaqueIdentifier: identifier) }, collapseOption: { identifier in updateState { $0.withRemovedExpandedOption(identifier) } }) } |> map { InputDataSignalValue(entries: $0, animated: true) } let controller = InputDataController(dataSignal: signal, title: !poll.isQuiz ? strings().pollResultsTitlePoll : strings().pollResultsTitleQuiz) controller.getBackgroundColor = { theme.colors.background } controller.contextObject = resultsContext let modalController = InputDataModalController(controller) controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: { [weak modalController] in modalController?.close() }) controller.centerModalHeader = ModalHeaderData(title: controller.defaultBarTitle, subtitle: poll.isQuiz ? strings().chatQuizTotalVotesCountable(Int(poll.results.totalVoters ?? 0)) : strings().chatPollTotalVotes1Countable(Int(poll.results.totalVoters ?? 0))) controller.getBackgroundColor = { theme.colors.listBackground } openProfile = { [weak modalController] peerId in context.bindings.rootNavigation().push(PeerInfoController(context: context, peerId: peerId)) modalController?.close() } controller.afterTransaction = { controller in if let scroll = scrollToOption { let item = controller.tableView.item(stableId: InputDataEntryId.custom(_id_option_header(scroll))) if let item = item { controller.tableView.scroll(to: .top(id: item.stableId, innerId: nil, animated: true, focus: .init(focus: true), inset: -10)) scrollToOption = nil } } } controller.didLoaded = { controller, _ in controller.tableView.set(stickClass: PollResultStickItem.self, handler: { _ in }) } // controller.didLoaded = { controller, _ in // controller.tableView.setScrollHandler { position in // switch position.direction { // case .bottom: // let shouldLoadMore = stateValue.with { $0.shouldLoadMore } // if let shouldLoadMore = shouldLoadMore { // resultsContext.loadMore(optionOpaqueIdentifier: shouldLoadMore) // } // break // default: // break // } // } // } return modalController }
gpl-2.0
18a92752b616ec8fc8210c5598cc5d36
42.823834
331
0.587196
5.105946
false
false
false
false
crossroadlabs/Express
Express/ExpressSugar.swift
1
18065
//===--- ExpressSugar.swift -----------------------------------------------===// // //Copyright (c) 2015-2016 Daniel Leping (dileping) // //This file is part of Swift Express. // //Swift Express is free software: you can redistribute it and/or modify //it under the terms of the GNU Lesser General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //Swift Express 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 Lesser General Public License for more details. // //You should have received a copy of the GNU Lesser General Public License //along with Swift Express. If not, see <http://www.gnu.org/licenses/>. // //===----------------------------------------------------------------------===// import Foundation import Future import Regex private func defaultUrlMatcher(path:String, method:String = HttpMethod.Any.rawValue) -> UrlMatcherType { return try! RegexUrlMatcher(method: method, pattern: path) } public extension Express { //sync //we need it to avoid recursion internal func handleInternal<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(method:String, path:String, handler:@escaping (Request<RequestContent>) throws -> Action<ResponseContent>) -> Void { self.handle(matcher: defaultUrlMatcher(path: path, method: method), handler: handler) } func handle<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(method:String, path:String, handler:@escaping (Request<RequestContent>) throws -> Action<ResponseContent>) -> Void { self.handleInternal(method: method, path: path, handler: handler) } func handle<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(method:String, regex:Regex, handler:@escaping (Request<RequestContent>) throws -> Action<ResponseContent>) -> Void { self.handle(matcher: RegexUrlMatcher(method: method, regex: regex), handler: handler) } func all<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(path:String, handler:@escaping (Request<RequestContent>) throws -> Action<ResponseContent>) -> Void { self.handle(method: HttpMethod.Any.rawValue, path: path, handler: handler) } func get<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(path:String, handler:@escaping (Request<RequestContent>) throws -> Action<ResponseContent>) -> Void { self.handle(method: HttpMethod.Get.rawValue, path: path, handler: handler) } func post<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(path:String, handler:@escaping (Request<RequestContent>) throws -> Action<ResponseContent>) -> Void { self.handle(method: HttpMethod.Post.rawValue, path: path, handler: handler) } func put<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(path:String, handler:@escaping (Request<RequestContent>) throws -> Action<ResponseContent>) -> Void { self.handle(method: HttpMethod.Put.rawValue, path: path, handler: handler) } func delete<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(path:String, handler:@escaping (Request<RequestContent>) throws -> Action<ResponseContent>) -> Void { self.handle(method: HttpMethod.Delete.rawValue, path: path, handler: handler) } func patch<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(path:String, handler:@escaping (Request<RequestContent>) throws -> Action<ResponseContent>) -> Void { self.handle(method: HttpMethod.Patch.rawValue, path: path, handler: handler) } //async //we need it to avoid recursion internal func handleInternal<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(method:String, path:String, handler:@escaping (Request<RequestContent>) -> Future<Action<ResponseContent>>) -> Void { handleInternal(matcher: defaultUrlMatcher(path: path, method: method), handler: handler) } func handle<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(method:String, path:String, handler:@escaping (Request<RequestContent>) -> Future<Action<ResponseContent>>) -> Void { handleInternal(method: method, path: path, handler: handler) } func handle<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(method:String, regex:Regex, handler:@escaping(Request<RequestContent>) -> Future<Action<ResponseContent>>) -> Void { self.handle(matcher: RegexUrlMatcher(method: method, regex: regex), handler: handler) } func all<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(path:String, handler:@escaping (Request<RequestContent>) -> Future<Action<ResponseContent>>) -> Void { handle(method: HttpMethod.Any.rawValue, path: path, handler: handler) } func get<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(path:String, handler:@escaping (Request<RequestContent>) -> Future<Action<ResponseContent>>) -> Void { handle(method: HttpMethod.Get.rawValue, path: path, handler: handler) } func post<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(path:String, handler:@escaping (Request<RequestContent>) -> Future<Action<ResponseContent>>) -> Void { handle(method: HttpMethod.Post.rawValue, path: path, handler: handler) } func put<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(path:String, handler:@escaping (Request<RequestContent>) -> Future<Action<ResponseContent>>) -> Void { handle(method: HttpMethod.Put.rawValue, path: path, handler: handler) } func delete<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(path:String, handler:@escaping (Request<RequestContent>) -> Future<Action<ResponseContent>>) -> Void { handle(method: HttpMethod.Delete.rawValue, path: path, handler: handler) } func patch<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(path:String, handler:@escaping (Request<RequestContent>) -> Future<Action<ResponseContent>>) -> Void { handle(method: HttpMethod.Patch.rawValue, path: path, handler: handler) } //action func handle<ResponseContent : FlushableContentType>(method:String, path:String, action:Action<ResponseContent>) -> Void { handle(matcher: defaultUrlMatcher(path: path, method: method), action: action) } func all<ResponseContent : FlushableContentType>(path:String, action:Action<ResponseContent>) -> Void { handle(method: HttpMethod.Any.rawValue, path: path, action: action) } func get<ResponseContent : FlushableContentType>(path:String, action:Action<ResponseContent>) -> Void { handle(method: HttpMethod.Get.rawValue, path: path, action: action) } func post<ResponseContent : FlushableContentType>(path:String, action:Action<ResponseContent>) -> Void { handle(method: HttpMethod.Post.rawValue, path: path, action: action) } func put<ResponseContent : FlushableContentType>(path:String, action:Action<ResponseContent>) -> Void { handle(method: HttpMethod.Put.rawValue, path: path, action: action) } func delete<ResponseContent : FlushableContentType>(path:String, action:Action<ResponseContent>) -> Void { handle(method: HttpMethod.Delete.rawValue, path: path, action: action) } func patch<ResponseContent : FlushableContentType>(path:String, action:Action<ResponseContent>) -> Void { handle(method: HttpMethod.Patch.rawValue, path: path, action: action) } //sync - simple req func handle<ResponseContent : FlushableContentType>(method:String, path:String, handler:@escaping (Request<AnyContent>) throws -> Action<ResponseContent>) -> Void { self.handleInternal(method: method, path: path, handler: handler) } func all<ResponseContent : FlushableContentType>(path:String, handler:@escaping(Request<AnyContent>)throws -> Action<ResponseContent>) -> Void { self.handle(method: HttpMethod.Any.rawValue, path: path, handler: handler) } func get<ResponseContent : FlushableContentType>(path:String, handler:@escaping(Request<AnyContent>) throws -> Action<ResponseContent>) -> Void { self.handle(method: HttpMethod.Get.rawValue, path: path, handler: handler) } func post<ResponseContent : FlushableContentType>(path:String, handler:@escaping(Request<AnyContent>) throws -> Action<ResponseContent>) -> Void { self.handle(method: HttpMethod.Post.rawValue, path: path, handler: handler) } func put<ResponseContent : FlushableContentType>(path:String, handler:@escaping(Request<AnyContent>)throws -> Action<ResponseContent>) -> Void { self.handle(method: HttpMethod.Put.rawValue, path: path, handler: handler) } func delete<ResponseContent : FlushableContentType>(path:String, handler:@escaping(Request<AnyContent>)throws -> Action<ResponseContent>) -> Void { self.handle(method: HttpMethod.Delete.rawValue, path: path, handler: handler) } func patch<ResponseContent : FlushableContentType>(path:String, handler:@escaping(Request<AnyContent>) throws -> Action<ResponseContent>) -> Void { self.handle(method: HttpMethod.Patch.rawValue, path: path, handler: handler) } //async - simple req func handle<ResponseContent : FlushableContentType>(method:String, path:String, handler:@escaping (Request<AnyContent>) -> Future<Action<ResponseContent>>) -> Void { self.handleInternal(method: method, path: path, handler: handler) } func all<ResponseContent : FlushableContentType>(path:String, handler:@escaping(Request<AnyContent>) -> Future<Action<ResponseContent>>) -> Void { self.handle(method: HttpMethod.Any.rawValue, path: path, handler: handler) } func get<ResponseContent : FlushableContentType>(path:String, handler:@escaping(Request<AnyContent>) -> Future<Action<ResponseContent>>) -> Void { self.handle(method: HttpMethod.Get.rawValue, path: path, handler: handler) } func post<ResponseContent : FlushableContentType>(path:String, handler:@escaping(Request<AnyContent>) -> Future<Action<ResponseContent>>) -> Void { self.handle(method: HttpMethod.Post.rawValue, path: path, handler: handler) } func put<ResponseContent : FlushableContentType>(path:String, handler:@escaping(Request<AnyContent>) -> Future<Action<ResponseContent>>) -> Void { self.handle(method: HttpMethod.Put.rawValue, path: path, handler: handler) } func delete<ResponseContent : FlushableContentType>(path:String, handler:@escaping(Request<AnyContent>) -> Future<Action<ResponseContent>>) -> Void { self.handle(method: HttpMethod.Delete.rawValue, path: path, handler: handler) } func patch<ResponseContent : FlushableContentType>(path:String, handler:@escaping(Request<AnyContent>) -> Future<Action<ResponseContent>>) -> Void { self.handle(method: HttpMethod.Patch.rawValue, path: path, handler: handler) } //sync - simple res func handle<RequestContent : ConstructableContentType>(method:String, path:String, handler:@escaping (Request<RequestContent>) throws -> Action<AnyContent>) -> Void { self.handleInternal(method: method, path: path, handler: handler) } func all<RequestContent : ConstructableContentType>(path:String, handler:@escaping (Request<RequestContent>) throws -> Action<AnyContent>) -> Void { self.handle(method: HttpMethod.Any.rawValue, path: path, handler: handler) } func get<RequestContent : ConstructableContentType>(path:String, handler:@escaping (Request<RequestContent>) throws -> Action<AnyContent>) -> Void { self.handle(method: HttpMethod.Get.rawValue, path: path, handler: handler) } func post<RequestContent : ConstructableContentType>(path:String, handler:@escaping (Request<RequestContent>) throws -> Action<AnyContent>) -> Void { self.handle(method: HttpMethod.Post.rawValue, path: path, handler: handler) } func put<RequestContent : ConstructableContentType>(path:String, handler:@escaping (Request<RequestContent>) throws -> Action<AnyContent>) -> Void { self.handle(method: HttpMethod.Put.rawValue, path: path, handler: handler) } func delete<RequestContent : ConstructableContentType>(path:String, handler:@escaping (Request<RequestContent>) throws -> Action<AnyContent>) -> Void { self.handle(method: HttpMethod.Delete.rawValue, path: path, handler: handler) } func patch<RequestContent : ConstructableContentType>(path:String, handler:@escaping (Request<RequestContent>) throws -> Action<AnyContent>) -> Void { self.handle(method: HttpMethod.Patch.rawValue, path: path, handler: handler) } //async - simple res func handle<RequestContent : ConstructableContentType>(method:String, path:String, handler:@escaping (Request<RequestContent>) -> Future<Action<AnyContent>>) -> Void { self.handleInternal(method: method, path: path, handler: handler) } func all<RequestContent : ConstructableContentType>(path:String, handler:@escaping (Request<RequestContent>) -> Future<Action<AnyContent>>) -> Void { self.handle(method: HttpMethod.Any.rawValue, path: path, handler: handler) } func get<RequestContent : ConstructableContentType>(path:String, handler:@escaping (Request<RequestContent>) -> Future<Action<AnyContent>>) -> Void { self.handle(method: HttpMethod.Get.rawValue, path: path, handler: handler) } func post<RequestContent : ConstructableContentType>(path:String, handler:@escaping (Request<RequestContent>) -> Future<Action<AnyContent>>) -> Void { self.handle(method: HttpMethod.Post.rawValue, path: path, handler: handler) } func put<RequestContent : ConstructableContentType>(path:String, handler:@escaping (Request<RequestContent>) -> Future<Action<AnyContent>>) -> Void { self.handle(method: HttpMethod.Put.rawValue, path: path, handler: handler) } func delete<RequestContent : ConstructableContentType>(path:String, handler:@escaping (Request<RequestContent>) -> Future<Action<AnyContent>>) -> Void { self.handle(method: HttpMethod.Delete.rawValue, path: path, handler: handler) } func patch<RequestContent : ConstructableContentType>(path:String, handler:@escaping (Request<RequestContent>) -> Future<Action<AnyContent>>) -> Void { self.handle(method: HttpMethod.Patch.rawValue, path: path, handler: handler) } //sync - simple all func handle(method:String, path:String, handler:@escaping (Request<AnyContent>) throws -> Action<AnyContent>) -> Void { self.handleInternal(method: method, path: path, handler: handler) } func all(path:String, handler:@escaping(Request<AnyContent>) throws -> Action<AnyContent>) -> Void { self.handle(method: HttpMethod.Any.rawValue, path: path, handler: handler) } func get(path:String, handler:@escaping(Request<AnyContent>) throws -> Action<AnyContent>) -> Void { self.handle(method: HttpMethod.Get.rawValue, path: path, handler: handler) } func post(path:String, handler:@escaping(Request<AnyContent>) throws -> Action<AnyContent>) -> Void { self.handle(method: HttpMethod.Post.rawValue, path: path, handler: handler) } func put(path:String, handler:@escaping(Request<AnyContent>) throws -> Action<AnyContent>) -> Void { self.handle(method: HttpMethod.Put.rawValue, path: path, handler: handler) } func delete(path:String, handler:@escaping(Request<AnyContent>) throws -> Action<AnyContent>) -> Void { self.handle(method: HttpMethod.Delete.rawValue, path: path, handler: handler) } func patch(path:String, handler:@escaping(Request<AnyContent>) throws -> Action<AnyContent>) -> Void { self.handle(method: HttpMethod.Patch.rawValue, path: path, handler: handler) } //async - simple all func handle(method:String, path:String, handler:@escaping (Request<AnyContent>) -> Future<Action<AnyContent>>) -> Void { self.handleInternal(method: method, path: path, handler: handler) } func all(path:String, handler:@escaping (Request<AnyContent>) -> Future<Action<AnyContent>>) -> Void { self.handle(method: HttpMethod.Any.rawValue, path: path, handler: handler) } func get(path:String, handler:@escaping (Request<AnyContent>) -> Future<Action<AnyContent>>) -> Void { self.handle(method: HttpMethod.Get.rawValue, path: path, handler: handler) } func post(path:String, handler:@escaping (Request<AnyContent>) -> Future<Action<AnyContent>>) -> Void { self.handle(method: HttpMethod.Post.rawValue, path: path, handler: handler) } func put(path:String, handler:@escaping (Request<AnyContent>) -> Future<Action<AnyContent>>) -> Void { self.handle(method: HttpMethod.Put.rawValue, path: path, handler: handler) } func delete(path:String, handler:@escaping (Request<AnyContent>) -> Future<Action<AnyContent>>) -> Void { self.handle(method: HttpMethod.Delete.rawValue, path: path, handler: handler) } func patch(path:String, handler:@escaping (Request<AnyContent>) -> Future<Action<AnyContent>>) -> Void { self.handle(method: HttpMethod.Patch.rawValue, path: path, handler: handler) } }
gpl-3.0
1ff7a49d326bc63bafa89973afc0f24c
57.462783
233
0.710933
4.654728
false
false
false
false
liscio/EditableProperty
EditableProperty/EditableProperty.swift
1
5479
import ReactiveCocoa import Result /// A property of type `Value` that Editors can propose and commit changes to. /// /// This can be used to implement multi-way bindings, where each "side" of the /// binding is a separate editor that ignores changes made by itself. public final class EditableProperty<Value, ValidationError: ErrorType>: MutablePropertyType { /// The current value of the property, along with information about how that /// value was obtained. public var committedValue: AnyProperty<Committed<Value, ValidationError>> { return AnyProperty(_committedValue) } private let _committedValue: MutableProperty<Committed<Value, ValidationError>> /// Sends any errors that occur during edit validation, from any editor. public let validationErrors: Signal<ValidationError, NoError> private let validationErrorsSink: Signal<ValidationError, NoError>.Observer /// Initializes an editable property that will have the given default /// values while no edits have yet occurred. /// /// If `editsTakePriority` is true, any edits will permanently override /// `defaultValue`. Otherwise, new default values may replace /// user-initiated edits. public init<P: PropertyType where P.Value == Value>(defaultValue: P, editsTakePriority: Bool) { (validationErrors, validationErrorsSink) = Signal<ValidationError, NoError>.pipe() _committedValue = MutableProperty(.DefaultValue(defaultValue.value)) var defaults = defaultValue.producer .map { Committed<Value, ValidationError>.DefaultValue($0) } if editsTakePriority { let hasBeenEdited = _committedValue.producer .filter { $0.isEdit } .map { _ in () } defaults = defaults .takeUntil(hasBeenEdited) } _committedValue <~ defaults } /// Initializes an editable property with the given default value. public convenience init(_ defaultValue: Value) { self.init(defaultValue: ConstantProperty(defaultValue), editsTakePriority: true) } public var value: Value { get { return _committedValue.value.value } set(value) { _committedValue.value = .ExplicitUpdate(value) } } public var producer: SignalProducer<Value, NoError> { return _committedValue.producer .map { $0.value } } /// A signal that will send the property's changes over time, /// then complete when the property has deinitialized. public lazy var signal: Signal<Value, NoError> = { [unowned self] in var extractedSignal: Signal<Value, NoError>! self.producer.startWithSignal { signal, _ in extractedSignal = signal } return extractedSignal }() deinit { validationErrorsSink.sendCompleted() } } /// Attaches an Editor to an EditableProperty, so that any edits will be /// reflected in the property's value once editing has finished and validation /// has succeeded. /// /// If any error occurs during editing or validation, it will be sent along the /// property's `validationErrors` signal. /// /// The binding will automatically terminate when the property is deinitialized. /// /// Returns a disposable which can be used to manually remove the editor from the /// property. public func <~ <Value, ValidationError: ErrorType>(property: EditableProperty<Value, ValidationError>, editor: Editor<Value, ValidationError>) -> Disposable { let validatedEdits = editor.edits .map(liftSignal) // We only care about the latest edit. .flatMap(FlattenStrategy.Latest) { [weak property] editSession -> SignalProducer<Value, NoError> in let sessionCompleted: SignalProducer<(), NoError> = editSession .then(.empty) .flatMapError { _ in .empty } let committedValues = (property?._committedValue.producer ?? .empty) .promoteErrors(ValidationError.self) .takeUntil(sessionCompleted) return combineLatest(committedValues, editSession) // We only care about the result of merging the latest values. .flatMap(FlattenStrategy.Latest) { committed, proposed in return editor.mergeCommittedValue(committed, intoProposedValue: proposed) } // Wait until validation completes, then use the final value for // the property's value. If the signal never sends anything, // don't update the property. .takeLast(1) // If interrupted or errored, just complete (to cancel the edit). .ignoreInterruption() .flatMapError { error in if let property = property { property.validationErrorsSink.sendNext(error) } return .empty } } .map { Committed<Value, ValidationError>.ValidatedEdit($0, editor) } return property._committedValue <~ validatedEdits } /// Lifts a Signal to a SignalProducer. /// /// This is a fundamentally unsafe operation, as no buffering is performed, and /// events may be missed. Use only in contexts where this is acceptable or /// impossible! private func liftSignal<T, Error>(signal: Signal<T, Error>) -> SignalProducer<T, Error> { return SignalProducer { observer, disposable in disposable.addDisposable(signal.observe(observer)) } } private extension Signal { /// Ignores any Interrupted event on the input signal, translating it to /// Completed instead. func ignoreInterruption() -> Signal<Value, Error> { return Signal { observer in return self.observe { event in switch event { case .Interrupted: observer.sendCompleted() default: observer.action(event) } } } } } private extension SignalProducer { func ignoreInterruption() -> SignalProducer<Value, Error> { return lift { $0.ignoreInterruption() } } }
mit
c61dfda7f79ce70328d49fa4f907adff
32.619632
158
0.73298
4.179252
false
false
false
false
wilfreddekok/Antidote
Antidote/ChatListController.swift
1
3776
// 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 protocol ChatListControllerDelegate: class { func chatListController(controller: ChatListController, didSelectChat chat: OCTChat) } class ChatListController: UIViewController { weak var delegate: ChatListControllerDelegate? private let theme: Theme private weak var submanagerChats: OCTSubmanagerChats! private weak var submanagerObjects: OCTSubmanagerObjects! private var placeholderLabel: UILabel! private var tableManager: ChatListTableManager! init(theme: Theme, submanagerChats: OCTSubmanagerChats, submanagerObjects: OCTSubmanagerObjects) { self.theme = theme self.submanagerChats = submanagerChats self.submanagerObjects = submanagerObjects super.init(nibName: nil, bundle: nil) edgesForExtendedLayout = .None title = String(localized: "chats_title") } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { loadViewWithBackgroundColor(theme.colorForType(.NormalBackground)) createTableView() createPlaceholderView() installConstraints() updateViewsVisibility() } override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) tableManager.tableView.setEditing(editing, animated: animated) } } extension ChatListController: ChatListTableManagerDelegate { func chatListTableManager(manager: ChatListTableManager, didSelectChat chat: OCTChat) { delegate?.chatListController(self, didSelectChat: chat) } func chatListTableManager(manager: ChatListTableManager, presentAlertController controller: UIAlertController) { presentViewController(controller, animated: true, completion: nil) } func chatListTableManagerWasUpdated(manager: ChatListTableManager) { updateViewsVisibility() } } private extension ChatListController { func updateViewsVisibility() { navigationItem.leftBarButtonItem = tableManager.isEmpty ? nil : editButtonItem() placeholderLabel.hidden = !tableManager.isEmpty } func createTableView() { let tableView = UITableView() tableView.estimatedRowHeight = 44.0 tableView.backgroundColor = theme.colorForType(.NormalBackground) tableView.sectionIndexColor = theme.colorForType(.LinkText) // removing separators on empty lines tableView.tableFooterView = UIView() view.addSubview(tableView) tableView.registerClass(ChatListCell.self, forCellReuseIdentifier: ChatListCell.staticReuseIdentifier) tableManager = ChatListTableManager(theme: theme, tableView: tableView, submanagerChats: submanagerChats, submanagerObjects: submanagerObjects) tableManager.delegate = self } func createPlaceholderView() { placeholderLabel = UILabel() placeholderLabel.text = String(localized: "chat_no_chats") placeholderLabel.textColor = theme.colorForType(.EmptyScreenPlaceholderText) placeholderLabel.font = UIFont.antidoteFontWithSize(26.0, weight: .Light) view.addSubview(placeholderLabel) } func installConstraints() { tableManager.tableView.snp_makeConstraints { $0.edges.equalTo(view) } placeholderLabel.snp_makeConstraints { $0.center.equalTo(view) $0.size.equalTo(placeholderLabel.sizeThatFits(CGSize(width: CGFloat.max, height: CGFloat.max))) } } }
mpl-2.0
32f97020995d5f66c10cfad904ad5a45
34.28972
151
0.720604
5.208276
false
false
false
false
tjw/swift
test/PCMacro/pc_and_log.swift
2
1846
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground-high-performance -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PCMacroRuntime.swift %t/main.swift %S/../PlaygroundTransform/Inputs/PlaygroundsRuntime.swift // RUN: %target-run %t/main | %FileCheck %s // REQUIRES: executable_test // FIXME: rdar://problem/30234450 PCMacro tests fail on linux in optimized mode // UNSUPPORTED: OS=linux-gnu #sourceLocation(file: "code.exe", line: 15) func foo(_ x: Int) -> Bool { return x == 1 } foo(1) [1,2,3].map(foo) // CHECK: [19:1-19:7] pc before // CHECK-NEXT: [15:1-15:27] pc before // CHECK-NEXT: [15:1-15:27] pc after // CHECK-NEXT: [16:3-16:16] pc before // CHECK-NEXT: [16:3-16:16] pc after // CHECK-NEXT: [16:10-16:11] $builtin_log[='true'] // this next result is unexpected... // CHECK-NEXT: [19:1-19:7] $builtin_log[='true'] // CHECK-NEXT: [19:1-19:7] pc after // now for the array // CHECK-NEXT: [20:1-20:17] pc before // CHECK-NEXT: [15:1-15:27] pc before // CHECK-NEXT: [15:1-15:27] pc after // CHECK-NEXT: [16:3-16:16] pc before // CHECK-NEXT: [16:3-16:16] pc after // this next result is unexpected... // CHECK-NEXT: [16:10-16:11] $builtin_log[='true'] // CHECK-NEXT: [15:1-15:27] pc before // CHECK-NEXT: [15:1-15:27] pc after // CHECK-NEXT: [16:3-16:16] pc before // CHECK-NEXT: [16:3-16:16] pc after // this next result is unexpected... // CHECK-NEXT: [16:10-16:11] $builtin_log[='false'] // CHECK-NEXT: [15:1-15:27] pc before // CHECK-NEXT: [15:1-15:27] pc after // CHECK-NEXT: [16:3-16:16] pc before // CHECK-NEXT: [16:3-16:16] pc after // this next result is unexpected... // CHECK-NEXT: [16:10-16:11] $builtin_log[='false'] // CHECK-NEXT: [20:1-20:17] $builtin_log[='[true, false, false]'] // CHECK-NEXT: [20:1-20:17] pc after
apache-2.0
56da84fa4aed6a116fc3a3f8eb716bf3
37.458333
254
0.657096
2.611033
false
false
false
false
Merlini93/Weibo
Weibo/Weibo/Classes/Main/MainViewController.swift
1
3166
// // MainViewController.swift // Weibo // // Created by 李遨东 on 16/9/8. // Copyright © 2016年 Merlini. All rights reserved. // import UIKit class MainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() tabBar.tintColor = UIColor.orangeColor() let path:String? = NSBundle.mainBundle().pathForResource("MainVCSettings", ofType: "json") if let jsonpath = path { let jsonData = NSData(contentsOfFile: jsonpath) do { let dictArr = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers) // print(dictArr) } catch { print(error) } } addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home") addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center") addChildViewController(NullViewController(), title: "", imageName: "") addChildViewController(DiscoverTableViewController(), title: "广场", imageName: "tabbar_discover") addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile") } private func addChildViewController(childController: UIViewController, title:String, imageName: String) { childController.tabBarItem.image = UIImage(named: imageName) childController.tabBarItem.selectedImage = UIImage(named: "\(imageName)_highlighted") childController.title = title let navi = UINavigationController() navi.addChildViewController(childController) addChildViewController(navi) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) setupComposeBtn() } func setupComposeBtn() { tabBar.addSubview(composeBtn) let width = UIScreen.mainScreen().bounds.size.width / CGFloat(viewControllers!.count) let rect = CGRect(x: 0, y: 0, width: width, height: 49) composeBtn.frame = CGRectOffset(rect, 2 * width, 0) tabBar.bringSubviewToFront(composeBtn) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - lazy private lazy var composeBtn: UIButton = { let btn = UIButton() btn.setImage(UIImage(named:"tabbar_compose_icon_add"), forState: UIControlState.Normal) btn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted) btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted) btn.addTarget(self, action: #selector(composeBtnClick), forControlEvents: UIControlEvents.TouchUpInside) return btn }() func composeBtnClick(sender:UIButton) { print(sender) } }
mit
33d3d4793749874bb9411303455ad96a
38.78481
132
0.665924
5.16092
false
false
false
false
TouchInstinct/LeadKit
Sources/Extensions/DateFormattingService/DateFormattingService+DefaultImplementation.swift
1
5471
// // Copyright (c) 2018 Touch Instinct // // 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 SwiftDate public extension DateFormattingService { func date(from string: String, format: DateFormatType, defaultDate: DateInRegion = Date().inDefaultRegion()) -> DateInRegion { date(from: string, format: format, parsedIn: nil) ?? defaultDate } func date(from string: String, format: DateFormatType, parsedIn: Region?) -> DateInRegion? { let region = parsedIn ?? currentRegion return format.stringToDateFormat.toDate(string, region: region) } func date(from string: String, formats: [DateFormatType], parsedIn: Region?) -> DateInRegion? { let region = parsedIn ?? currentRegion for format in formats { if let parsedDate = format.stringToDateFormat.toDate(string, region: region) { return parsedDate } } return nil } func string(from date: DateRepresentable, format: DateFormatType) -> String { format.dateToStringFormat.toString(date) } func string(from date: DateRepresentable, format: DateFormatType, formattedIn: Region?) -> String { let region = formattedIn ?? currentRegion let dateInFormatterRegion = date.convertTo(region: region) return format.dateToStringFormat.toString(dateInFormatterRegion) } } public extension DateFormattingService where Self: Singleton { /// Method parses date from string in given format with current region. /// If parsing fails - it returns default date in region. /// /// - Parameters: /// - string: String to use for date parsing. /// - format: Format that should be used for date parsing. /// - defaultDate: Default date if formatting will fail. /// - Returns: Date parsed from given string or default date if parsing did fail. static func date(from string: String, format: DateFormatType, defaultDate: DateInRegion = Date().inDefaultRegion()) -> DateInRegion { shared.date(from: string, format: format, defaultDate: defaultDate) } /// Method parses date from string in given format with current region. /// /// - Parameters: /// - string: String to use for date parsing. /// - format: Format that should be used for date parsing. /// - parsedIn: A region that should be used for date parsing. In case of nil defaultRegion will be used. /// - Returns: Date parsed from given string or default date if parsing did fail. static func date(from string: String, format: DateFormatType, parsedIn: Region?) -> DateInRegion? { shared.date(from: string, format: format, parsedIn: parsedIn) } /// Method parses date from string in one of the given formats with current region. /// /// - Parameters: /// - string: String to use for date parsing. /// - formats: Formats that should be used for date parsing. /// - parsedIn: A region that should be used for date parsing. In case of nil defaultRegion will be used. /// - Returns: Date parsed from given string or default date if parsing did fail. static func date(from string: String, formats: [DateFormatType], parsedIn: Region?) -> DateInRegion? { shared.date(from: string, formats: formats, parsedIn: parsedIn) } /// Method format date in given format. /// /// - Parameters: /// - date: Date to format. /// - format: Format that should be used for date formatting. /// - Returns: String that contains formatted date or nil if formatting did fail. static func string(from date: DateRepresentable, format: DateFormatType) -> String { shared.string(from: date, format: format) } /// Method format date in given format for specific region. /// /// - Parameters: /// - date: Date to format. /// - format: Format that should be used for date formatting. /// - formattedIn: A region that should be used for date formatting. In case of nil defaultRegion will be used. /// - Returns: String that contains formatted date or nil if formatting did fail. static func string(from date: DateRepresentable, format: DateFormatType, formattedIn: Region?) -> String { shared.string(from: date, format: format, formattedIn: formattedIn) } }
apache-2.0
6750f8dd57b9da1c83579f7858e7ed25
42.07874
117
0.67739
4.636441
false
false
false
false
vector-im/vector-ios
Riot/Modules/Call/Dialpad/DialpadViewController.swift
1
15951
// File created from simpleScreenTemplate // $ createSimpleScreen.sh Dialpad Dialpad /* Copyright 2020 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 UIKit import libPhoneNumber_iOS @objc protocol DialpadViewControllerDelegate: AnyObject { @objc optional func dialpadViewControllerDidTapCall(_ viewController: DialpadViewController, withPhoneNumber phoneNumber: String) @objc optional func dialpadViewControllerDidTapClose(_ viewController: DialpadViewController) @objc optional func dialpadViewControllerDidTapDigit(_ viewController: DialpadViewController, digit: String) } @objcMembers class DialpadViewController: UIViewController { // MARK: Outlets @IBOutlet private weak var phoneNumberTextFieldTopConstraint: NSLayoutConstraint! { didSet { if !configuration.showsTitle && !configuration.showsCloseButton { phoneNumberTextFieldTopConstraint.constant = 0 } } } @IBOutlet private weak var closeButton: UIButton! { didSet { closeButton.isHidden = !configuration.showsCloseButton } } @IBOutlet private weak var titleLabel: UILabel! { didSet { titleLabel.isHidden = !configuration.showsTitle } } @IBOutlet private weak var phoneNumberTextField: UITextField! { didSet { phoneNumberTextField.text = nil // avoid showing keyboard on text field phoneNumberTextField.inputView = UIView() phoneNumberTextField.inputAccessoryView = UIView() phoneNumberTextField.isUserInteractionEnabled = configuration.editingEnabled } } @IBOutlet private weak var lineView: UIView! @IBOutlet private weak var digitsStackView: UIStackView! @IBOutlet private var digitButtons: [DialpadButton]! @IBOutlet private weak var backspaceButton: DialpadActionButton! { didSet { backspaceButton.type = .backspace backspaceButton.isHidden = !configuration.showsBackspaceButton } } @IBOutlet private weak var callButton: DialpadActionButton! { didSet { callButton.type = .call callButton.isHidden = !configuration.showsCallButton } } @IBOutlet private weak var spaceButton: UIButton! { didSet { spaceButton.isHidden = !configuration.showsBackspaceButton || !configuration.showsCallButton } } // MARK: Private private enum Constants { static let sizeOniPad: CGSize = CGSize(width: 375, height: 667) static let additionalTopInset: CGFloat = 20 static let digitButtonViewDatas: [Int: DialpadButton.ViewData] = [ -2: .init(title: "#", tone: 1211), -1: .init(title: "*", tone: 1210), 0: .init(title: "0", tone: 1200, subtitle: "+"), 1: .init(title: "1", tone: 1201, showsSubtitleSpace: true), 2: .init(title: "2", tone: 1202, subtitle: "ABC"), 3: .init(title: "3", tone: 1203, subtitle: "DEF"), 4: .init(title: "4", tone: 1204, subtitle: "GHI"), 5: .init(title: "5", tone: 1205, subtitle: "JKL"), 6: .init(title: "6", tone: 1206, subtitle: "MNO"), 7: .init(title: "7", tone: 1207, subtitle: "PQRS"), 8: .init(title: "8", tone: 1208, subtitle: "TUV"), 9: .init(title: "9", tone: 1209, subtitle: "WXYZ") ] } private var wasCursorAtTheEnd: Bool = true /// Phone number as formatted private var phoneNumber: String = "" { willSet { if configuration.editingEnabled { wasCursorAtTheEnd = isCursorAtTheEnd() } } didSet { phoneNumberTextField.text = phoneNumber if configuration.editingEnabled && wasCursorAtTheEnd { moveCursorToTheEnd() } } } /// Phone number as non-formatted var rawPhoneNumber: String { return phoneNumber.vc_removingAllWhitespaces() } private var theme: Theme! private var configuration: DialpadConfiguration! // MARK: Public weak var delegate: DialpadViewControllerDelegate? // MARK: - Setup class func instantiate(withConfiguration configuration: DialpadConfiguration = .default) -> DialpadViewController { let viewController = StoryboardScene.DialpadViewController.initialScene.instantiate() viewController.theme = ThemeService.shared().theme viewController.configuration = configuration return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. titleLabel.text = VectorL10n.dialpadTitle self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) // force orientation to portrait if phone if UIDevice.current.isPhone { UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation") } for button in digitButtons { if let viewData = Constants.digitButtonViewDatas[button.tag] { button.render(withViewData: viewData) } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) AnalyticsScreenTracker.trackScreen(.dialpad) } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { // limit orientation to portrait only for phone if UIDevice.current.isPhone { return .portrait } return super.supportedInterfaceOrientations } override var shouldAutorotate: Bool { return false } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { if UIDevice.current.isPhone { return .portrait } return super.preferredInterfaceOrientationForPresentation } // MARK: - Private private func isCursorAtTheEnd() -> Bool { guard let selectedRange = phoneNumberTextField.selectedTextRange else { return true } if !selectedRange.isEmpty { return false } let cursorEndPos = phoneNumberTextField.offset(from: phoneNumberTextField.beginningOfDocument, to: selectedRange.end) return cursorEndPos == phoneNumber.count } private func moveCursorToTheEnd() { guard let cursorPos = phoneNumberTextField.position(from: phoneNumberTextField.beginningOfDocument, offset: phoneNumber.count) else { return } phoneNumberTextField.selectedTextRange = phoneNumberTextField.textRange(from: cursorPos, to: cursorPos) } private func reformatPhoneNumber() { guard configuration.formattingEnabled, let phoneNumberUtil = NBPhoneNumberUtil.sharedInstance() else { // no formatter return } do { // try formatting the number if phoneNumber.hasPrefix("00") { let range = phoneNumber.startIndex..<phoneNumber.index(phoneNumber.startIndex, offsetBy: 2) phoneNumber.replaceSubrange(range, with: "+") } let nbPhoneNumber = try phoneNumberUtil.parse(rawPhoneNumber, defaultRegion: nil) phoneNumber = try phoneNumberUtil.format(nbPhoneNumber, numberFormat: .INTERNATIONAL) } catch { // continue without formatting } } private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.backgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } if theme.identifier == ThemeIdentifier.light.rawValue { titleLabel.textColor = theme.noticeSecondaryColor closeButton.setBackgroundImage(Asset.Images.closeButton.image.vc_tintedImage(usingColor: theme.tabBarUnselectedItemTintColor), for: .normal) } else { titleLabel.textColor = theme.baseTextSecondaryColor closeButton.setBackgroundImage(Asset.Images.closeButton.image.vc_tintedImage(usingColor: theme.baseTextSecondaryColor), for: .normal) } phoneNumberTextField.textColor = theme.textPrimaryColor lineView.backgroundColor = theme.lineBreakColor updateThemesOfAllButtons(in: digitsStackView, with: theme) } private func updateThemesOfAllButtons(in view: UIView, with theme: Theme) { if let button = view as? DialpadButton { button.update(theme: theme) } else { for subview in view.subviews { updateThemesOfAllButtons(in: subview, with: theme) } } } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } private func topSafeAreaInset() -> CGFloat { guard let window = UIApplication.shared.keyWindow else { return Constants.additionalTopInset } return window.safeAreaInsets.top + Constants.additionalTopInset } // MARK: - Actions @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } @IBAction private func closeButtonAction(_ sender: UIButton) { delegate?.dialpadViewControllerDidTapClose?(self) } @IBAction private func digitButtonAction(_ sender: DialpadButton) { guard let digitViewData = Constants.digitButtonViewDatas[sender.tag] else { return } let digit = digitViewData.title defer { delegate?.dialpadViewControllerDidTapDigit?(self, digit: digit) } if configuration.playTones { AudioServicesPlaySystemSound(digitViewData.tone) } if !configuration.editingEnabled { phoneNumber += digit return } if let selectedRange = phoneNumberTextField.selectedTextRange { if isCursorAtTheEnd() { phoneNumber += digit reformatPhoneNumber() return } let cursorStartPos = phoneNumberTextField.offset(from: phoneNumberTextField.beginningOfDocument, to: selectedRange.start) let cursorEndPos = phoneNumberTextField.offset(from: phoneNumberTextField.beginningOfDocument, to: selectedRange.end) phoneNumber.replaceSubrange((phoneNumber.index(phoneNumber.startIndex, offsetBy: cursorStartPos))..<(phoneNumber.index(phoneNumber.startIndex, offsetBy: cursorEndPos)), with: digit) guard let cursorPos = phoneNumberTextField.position(from: phoneNumberTextField.beginningOfDocument, offset: cursorEndPos + digit.count) else { return } reformatPhoneNumber() phoneNumberTextField.selectedTextRange = phoneNumberTextField.textRange(from: cursorPos, to: cursorPos) } else { phoneNumber += digit reformatPhoneNumber() } } @IBAction private func backspaceButtonAction(_ sender: DialpadActionButton) { defer { delegate?.dialpadViewControllerDidTapDigit?(self, digit: "") } if phoneNumber.isEmpty { return } if !configuration.editingEnabled { phoneNumber.removeLast() return } if let selectedRange = phoneNumberTextField.selectedTextRange { let cursorStartPos = phoneNumberTextField.offset(from: phoneNumberTextField.beginningOfDocument, to: selectedRange.start) let cursorEndPos = phoneNumberTextField.offset(from: phoneNumberTextField.beginningOfDocument, to: selectedRange.end) let rangePos: UITextPosition! if selectedRange.isEmpty { // just caret, remove one char from the cursor position if cursorStartPos == 0 { // already at the beginning of the text, no more text to remove here return } phoneNumber.replaceSubrange((phoneNumber.index(phoneNumber.startIndex, offsetBy: cursorStartPos-1))..<(phoneNumber.index(phoneNumber.startIndex, offsetBy: cursorEndPos)), with: "") rangePos = phoneNumberTextField.position(from: phoneNumberTextField.beginningOfDocument, offset: cursorStartPos-1) } else { // really some text selected, remove selected range of text phoneNumber.replaceSubrange((phoneNumber.index(phoneNumber.startIndex, offsetBy: cursorStartPos))..<(phoneNumber.index(phoneNumber.startIndex, offsetBy: cursorEndPos)), with: "") rangePos = phoneNumberTextField.position(from: phoneNumberTextField.beginningOfDocument, offset: cursorStartPos) } reformatPhoneNumber() guard let cursorPos = rangePos else { return } phoneNumberTextField.selectedTextRange = phoneNumberTextField.textRange(from: cursorPos, to: cursorPos) } else { phoneNumber.removeLast() reformatPhoneNumber() } } @IBAction private func callButtonAction(_ sender: DialpadActionButton) { phoneNumber = phoneNumberTextField.text ?? "" delegate?.dialpadViewControllerDidTapCall?(self, withPhoneNumber: rawPhoneNumber) } } // MARK: - CustomSizedPresentable extension DialpadViewController: CustomSizedPresentable { func customSize(withParentContainerSize containerSize: CGSize) -> CGSize { if UIDevice.current.isPhone { return CGSize(width: containerSize.width, height: containerSize.height - topSafeAreaInset()) } return Constants.sizeOniPad } func position(withParentContainerSize containerSize: CGSize) -> CGPoint { let mySize = customSize(withParentContainerSize: containerSize) if UIDevice.current.isPhone { return CGPoint(x: 0, y: topSafeAreaInset()) } return CGPoint(x: (containerSize.width - mySize.width)/2, y: (containerSize.height - mySize.height)/2) } }
apache-2.0
8431f8f9b129bc06752f706dfdadfcd2
38
196
0.618895
5.606678
false
true
false
false
wookay/Look
samples/LookSample/Pods/C4/C4/UI/C4Animation.swift
3
6464
// Copyright © 2014 C4 // // 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 let C4AnimationCompletedEvent = "C4AnimationCompleted" private let C4AnimationCancelledEvent = "C4AnimationCancelled" /// Defines an object that handles the creation of animations for specific actions and keys. public class C4Animation { /// Specifies the supported animation curves. /// /// ```` /// animation.curve = .EaseIn /// ```` public enum Curve { /// A linear animation curve causes an animation to occur evenly over its duration. case Linear /// An ease-out curve causes the animation to begin quickly, and then slow down as it completes. case EaseOut /// An ease-in curve causes the animation to begin slowly, and then speed up as it progresses. case EaseIn /// An ease-in ease-out curve causes the animation to begin slowly, accelerate through the middle of its duration, and then slow again before completing. This is the default curve for most animations. case EaseInOut } /// Determines if the animation plays in the reverse upon completion. public var autoreverses = false /// Specifies the number of times the animation should repeat. public var repeatCount = 0.0 /// If `true` the animation will repeat indefinitely. public var repeats: Bool { get { return repeatCount > 0 } set { if newValue { repeatCount = DBL_MAX } else { repeatCount = 0 } } } /// The duration of the animation, measured in seconds. public var duration: NSTimeInterval = 1 /// The animation curve that the receiver will apply to the changes it is supposed to animate. public var curve: Curve = .Linear private var completionObservers: [AnyObject] = [] private var cancelObservers: [AnyObject] = [] static var stack = [C4Animation]() static var currentAnimation: C4Animation? { return stack.last } ///Intializes an empty animation object. public init() { } deinit { let nc = NSNotificationCenter.defaultCenter() for observer in completionObservers { nc.removeObserver(observer) } for observer in cancelObservers { nc.removeObserver(observer) } } /// Adds a completion observer to an animation. /// /// The completion observer listens for the end of the animation then executes a specified block of code. /// /// - parameter action: a block of code to be executed at the end of an animation. /// /// - returns: the observer object. public func addCompletionObserver(action: () -> Void) -> AnyObject { let nc = NSNotificationCenter.defaultCenter() let observer = nc.addObserverForName(C4AnimationCompletedEvent, object: self, queue: NSOperationQueue.currentQueue(), usingBlock: { notification in action() }) completionObservers.append(observer) return observer } /// Removes a specified observer from an animation. /// /// - parameter observer: the observer object to remove. public func removeCompletionObserver(observer: AnyObject) { let nc = NSNotificationCenter.defaultCenter() nc.removeObserver(observer, name: C4AnimationCompletedEvent, object: self) } /// Posts a completion event. /// /// This method is triggered when an animation completes. This can be used in place of `addCompletionObserver` for objects outside the scope of the context in which the animation is created. public func postCompletedEvent() { dispatch_async(dispatch_get_main_queue()) { NSNotificationCenter.defaultCenter().postNotificationName(C4AnimationCompletedEvent, object: self) } } /// Adds a cancel observer to an animation. /// /// The cancel observer listens for when an animation is canceled then executes a specified block of code. /// /// - parameter action: a block of code to be executed when an animation is canceled. /// /// - returns: the observer object. public func addCancelObserver(action: () -> Void) -> AnyObject { let nc = NSNotificationCenter.defaultCenter() let observer = nc.addObserverForName(C4AnimationCancelledEvent, object: self, queue: NSOperationQueue.currentQueue(), usingBlock: { notification in action() }) cancelObservers.append(observer) return observer } /// Removes a specified cancel observer from an animation. /// /// - parameter observer: the cancel observer object to remove. public func removeCancelObserver(observer: AnyObject) { let nc = NSNotificationCenter.defaultCenter() nc.removeObserver(observer, name: C4AnimationCancelledEvent, object: self) } /// Posts a cancellation event. /// /// This method is triggered when an animation is canceled. This can be used in place of `addCancelObserver` for objects outside the scope of the context in which the animation is created. public func postCancelledEvent() { dispatch_async(dispatch_get_main_queue()) { NSNotificationCenter.defaultCenter().postNotificationName(C4AnimationCancelledEvent, object: self) } } }
mit
ed22718faf858a74b68bd3392a4a8c34
39.905063
208
0.67987
5.006197
false
false
false
false
khawars/KSTokenView
Examples/Examples/ViewControllers/Autolayout.swift
1
2945
// // Autolayout.swift // Examples // // Created by Khawar Shahzad on 01/01/2015. // Copyright (c) 2015 Khawar Shahzad. 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 UIKit class Autolayout: UIViewController { let names: Array<String> = List.names() @IBOutlet weak var tokenView: KSTokenView! override func viewDidLoad() { super.viewDidLoad() tokenView.delegate = self tokenView.promptText = "Top: " tokenView.placeholder = "Type to search" tokenView.descriptionText = "Languages" tokenView.maxTokenLimit = -1 tokenView.searchResultHeight = 100 tokenView.minimumCharactersToSearch = 0 // Show all results without without typing anything tokenView.style = .squared tokenView.returnKeyType(type: .done) } } extension Autolayout: KSTokenViewDelegate { func tokenView(_ tokenView: KSTokenView, performSearchWithString string: String, completion: ((_ results: Array<AnyObject>) -> Void)?) { if (string.isEmpty){ completion!(names as Array<AnyObject>) return } var data: Array<String> = [] for value: String in names { if value.lowercased().range(of: string.lowercased()) != nil { data.append(value) } } completion!(data as Array<AnyObject>) } func tokenView(_ tokenView: KSTokenView, displayTitleForObject object: AnyObject) -> String { return object as! String } func tokenView(_ tokenView: KSTokenView, shouldAddToken token: KSToken) -> Bool { // Restrict adding token based on token text if token.title == "f" { return false } // If user input something, it can be checked // print(tokenView.text) return true } }
mit
b8b02c22344dc56afcddb7a8744fd45e
36.75641
140
0.664516
4.489329
false
false
false
false
khawars/KSTokenView
Examples/Examples/ViewControllers/Horizontal.swift
1
1464
// // Horizontal.swift // Examples // // Created by Khawar Shahzad on 12/13/16. // Copyright © 2016 Khawar Shahzad. All rights reserved. // import UIKit class Horizontal: UIViewController { let names: Array<String> = List.names() @IBOutlet weak var tokenView: KSTokenView! override func viewDidLoad() { super.viewDidLoad() tokenView.delegate = self tokenView.promptText = "Top: " tokenView.placeholder = "Type to search" tokenView.descriptionText = "Languages" tokenView.maxTokenLimit = -1 tokenView.minimumCharactersToSearch = 0 // Show all results without without typing anything tokenView.style = .squared tokenView.direction = .horizontal } } extension Horizontal: KSTokenViewDelegate { func tokenView(_ tokenView: KSTokenView, performSearchWithString string: String, completion: ((_ results: Array<AnyObject>) -> Void)?) { if (string.isEmpty){ completion!(names as Array<AnyObject>) return } var data: Array<String> = [] for value: String in names { if value.lowercased().range(of: string.lowercased()) != nil { data.append(value) } } completion!(data as Array<AnyObject>) } func tokenView(_ tokenView: KSTokenView, displayTitleForObject object: AnyObject) -> String { return object as! String } }
mit
69232cfd1468c71a04a18fcdb9da2d9a
28.857143
140
0.623377
4.41994
false
false
false
false
wei18810109052/CWWeChat
CWWeChat/MainClass/Base/CWTableViewManager/CWTableViewItem.swift
2
1292
// // CWTableViewItem.swift // CWWeChat // // Created by wei chen on 2017/2/11. // Copyright © 2017年 chenwei. All rights reserved. // import UIKit public typealias CWSelectionHandler = (CWTableViewItem) -> () /// cell对应的model public class CWTableViewItem: NSObject { public weak var section: CWTableViewSection? /// 文本 public var title: String /// 副标题 public var subTitle: String? /// cell高度 默认49 public var cellHeight: CGFloat = 0.0 /// 图标的URL public var rightImageURL: URL? /// 是否显示 public var showDisclosureIndicator: Bool = true /// 是否不高亮 public var disableHighlight: Bool = false public var selectionAction: CWSelectionHandler? public var indexPath: IndexPath? { guard let index = section?.items.index(of: self), let section_index = section?.index else { return nil } return IndexPath(row: index, section: section_index) } public init(title: String, subTitle: String? = nil, rightImageURL: URL? = nil) { self.cellHeight = kCWDefaultItemCellHeight self.title = title self.subTitle = subTitle super.init() } }
mit
0b67e16f4f3f1868df17564a06774492
23.82
61
0.611604
4.324042
false
false
false
false
yvzzztrk/SwiftTemplateProject
Project/template/Utilities/NetworkUtility.swift
1
1543
// // NetworkUtility.swift // template // // Created by YAVUZ ÖZTÜRK on 10/02/2017. // Copyright © 2017 Templete Project INC. All rights reserved. // import Foundation typealias JSON = [String : AnyObject] protocol JsonInitializable { init (json: JSON) throws } protocol JsonConvertable { func toJson() -> JSON } enum RouterError: Error, DisplayableErrorType { case DataTypeMismatch case HiddenError //error message is not shown for some cases like 401 var errorMessage: String? { switch self { case .DataTypeMismatch: return Localize.Error.Generic case .HiddenError: return nil } } } protocol DisplayableErrorType { var errorMessage: String? { get } } extension String { func convertToJson () -> JSON { let data = self.data(using: String.Encoding.utf8) let json = try! JSONSerialization.jsonObject(with: data!, options:[JSONSerialization.ReadingOptions.allowFragments]) as! JSON return json } } extension Dictionary where Key : ExpressibleByStringLiteral, Value : AnyObject { func toString() -> String { let data = try! JSONSerialization.data(withJSONObject:self as AnyObject, options: []) let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String return string } } struct Localize { struct Error { static let Generic = NSLocalizedString("A problem occured, please try again.", comment: "A problem occured, please try again.") } }
apache-2.0
8dd3c3d3a58c5aaa3d924da9e1bd4241
24.245902
135
0.674675
4.338028
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/ShareModalController.swift
1
95766
// // ShareModalController.swift // TelegramMac // // Created by keepcoder on 20/12/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import TGUIKit import SwiftSignalKit import TelegramCore import Localization import Postbox import TGModernGrowingTextView import KeyboardKey fileprivate class ShareButton : Control { private var badge: BadgeNode? private var badgeView: View = View() private let shareText = TextView() required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(badgeView) addSubview(shareText) let layout = TextViewLayout(.initialize(string: strings().modalShare.uppercased(), color: .white, font: .normal(.header)), maximumNumberOfLines: 1) layout.measure(width: .greatestFiniteMagnitude) shareText.update(layout) setFrameSize(NSMakeSize(22 + shareText.frame.width + 47, 41)) layer?.cornerRadius = 20 set(background: theme.colors.accent, for: .Hover) set(background: theme.colors.accent, for: .Normal) set(background: theme.colors.accent, for: .Highlight) shareText.backgroundColor = theme.colors.accent needsLayout = true updateCount(0) shareText.userInteractionEnabled = false shareText.isSelectable = false } override func layout() { super.layout() shareText.centerY(x: 22) shareText.setFrameOrigin(22, shareText.frame.minY + 2) badgeView.centerY(x: shareText.frame.maxX + 9) } func updateCount(_ count:Int) -> Void { badge = BadgeNode(.initialize(string: "\(max(count, 1))", color: theme.colors.accent, font: .medium(.small)), .white) badgeView.setFrameSize(badge!.size) badge?.view = badgeView badge?.setNeedDisplay() needsLayout = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } fileprivate class ShareModalView : Control, TokenizedProtocol { let tokenizedView:TokenizedView let basicSearchView: SearchView = SearchView(frame: NSMakeRect(0,0, 260, 30)) let tableView:TableView = TableView() fileprivate let share:ImageButton = ImageButton() fileprivate let dismiss:ImageButton = ImageButton() fileprivate let textView:TGModernGrowingTextView = TGModernGrowingTextView(frame: NSZeroRect) fileprivate let sendButton = ImageButton() fileprivate let emojiButton = ImageButton() fileprivate let actionsContainerView: Control = Control() fileprivate let textContainerView: View = View() fileprivate let bottomSeparator: View = View() fileprivate var sendWithoutSound: (()->Void)? = nil fileprivate var scheduleMessage: (()->Void)? = nil private let topSeparator = View() fileprivate var hasShareMenu: Bool = true { didSet { share.isHidden = !hasShareMenu needsLayout = true } } required init(frame frameRect: NSRect, shareObject: ShareObject) { tokenizedView = TokenizedView(frame: NSMakeRect(0, 0, 300, 30), localizationFunc: { key in return translate(key: key, []) }, placeholderKey: shareObject.searchPlaceholderKey) super.init(frame: frameRect) backgroundColor = theme.colors.background textContainerView.backgroundColor = theme.colors.background actionsContainerView.backgroundColor = theme.colors.background textView.setBackgroundColor(theme.colors.background) addSubview(tokenizedView) addSubview(basicSearchView) addSubview(tableView) addSubview(topSeparator) tokenizedView.delegate = self bottomSeparator.backgroundColor = theme.colors.border topSeparator.backgroundColor = theme.colors.border self.backgroundColor = theme.colors.background dismiss.disableActions() share.disableActions() addSubview(share) addSubview(dismiss) sendButton.contextMenu = { [weak self] in var items:[ContextMenuItem] = [] items.append(ContextMenuItem(strings().chatSendWithoutSound, handler: { self?.sendWithoutSound?() }, itemImage: MenuAnimation.menu_mute.value)) items.append(ContextMenuItem(strings().chatSendScheduledMessage, handler: { self?.scheduleMessage?() }, itemImage: MenuAnimation.menu_schedule_message.value)) if !items.isEmpty { let menu = ContextMenu() for item in items { menu.addItem(item) } return menu } return nil } sendButton.set(image: theme.icons.chatSendMessage, for: .Normal) sendButton.autohighlight = false _ = sendButton.sizeToFit() emojiButton.set(image: theme.icons.chatEntertainment, for: .Normal) _ = emojiButton.sizeToFit() actionsContainerView.addSubview(sendButton) actionsContainerView.addSubview(emojiButton) actionsContainerView.setFrameSize(sendButton.frame.width + emojiButton.frame.width + 40, 50) emojiButton.centerY(x: 0) sendButton.centerY(x: emojiButton.frame.maxX + 20) backgroundColor = theme.colors.background textView.background = theme.colors.background textView.textFont = .normal(.text) textView.textColor = theme.colors.text textView.linkColor = theme.colors.link textView.max_height = 120 textView.setFrameSize(NSMakeSize(0, 34)) textView.setPlaceholderAttributedString(.initialize(string: strings().previewSenderCommentPlaceholder, color: theme.colors.grayText, font: .normal(.text)), update: false) textContainerView.addSubview(textView) addSubview(textContainerView) addSubview(actionsContainerView) addSubview(bottomSeparator) updateLocalizationAndTheme(theme: theme) } override func updateLocalizationAndTheme(theme: PresentationTheme) { super.updateLocalizationAndTheme(theme: theme) let theme = theme as! TelegramPresentationTheme share.set(image: theme.icons.modalShare, for: .Normal) _ = share.sizeToFit() if inForumMode { dismiss.set(image: theme.icons.chatNavigationBack, for: .Normal) } else { dismiss.set(image: theme.icons.modalClose, for: .Normal) } _ = dismiss.sizeToFit(.zero, NSMakeSize(30, 30), thatFit: true) } var searchView: NSView { if hasCaptionView { return tokenizedView } else { return basicSearchView } } var hasCaptionView: Bool = true { didSet { textContainerView.isHidden = !hasCaptionView actionsContainerView.isHidden = !hasCaptionView bottomSeparator.isHidden = !hasCaptionView basicSearchView.isHidden = hasCaptionView tokenizedView.isHidden = !hasCaptionView dismiss.isHidden = hasCaptionView if oldValue != hasCaptionView, hasCaptionView { textContainerView.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) actionsContainerView.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) bottomSeparator.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) basicSearchView.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) tokenizedView.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) dismiss.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } needsLayout = true } } var hasCommentView: Bool = true { didSet { textContainerView.isHidden = !hasCommentView bottomSeparator.isHidden = !hasCommentView actionsContainerView.isHidden = !hasCommentView needsLayout = true } } var hasSendView: Bool = true { didSet { sendButton.isHidden = !hasSendView needsLayout = true } } func applyTransition(_ transition: TableUpdateTransition) { self.tableView.resetScrollNotifies() self.tableView.scroll(to: .up(false)) self.tableView.merge(with: transition) self.tableView.cancelHighlight() } private var forumTopicItems:[ForumTopicItem] = [] private var forumTopicsView: TableView? var inForumMode: Bool { return forumTopicsView != nil } private class ForumTopicArguments { let context: AccountContext let select:(Int64)->Void init(context: AccountContext, select:@escaping(Int64)->Void) { self.context = context self.select = select } } private struct ForumTopicItem : TableItemListNodeEntry { let item: EngineChatList.Item static func < (lhs: ShareModalView.ForumTopicItem, rhs: ShareModalView.ForumTopicItem) -> Bool { return lhs.item.index < rhs.item.index } static func == (lhs: ShareModalView.ForumTopicItem, rhs: ShareModalView.ForumTopicItem) -> Bool { return lhs.item == rhs.item } var stableId: EngineChatList.Item.Id { return item.id } func item(_ arguments: ShareModalView.ForumTopicArguments, initialSize: NSSize) -> TableRowItem { let threadId: Int64? switch item.id { case let .forum(id): threadId = id default: threadId = nil } return SearchTopicRowItem(initialSize, stableId: self.item.id, item: self.item, context: arguments.context, action: { if let threadId = threadId { arguments.select(threadId) } }) } } func appearForumTopics(_ items: [EngineChatList.Item], peerId: PeerId, interactions: SelectPeerInteraction, delegate: TableViewDelegate?, context: AccountContext, animated: Bool) { let arguments = ForumTopicArguments(context: context, select: { threadId in interactions.action(peerId, threadId) }) let mapped:[ForumTopicItem] = items.map { .init(item: $0) } let animated = animated && self.forumTopicsView == nil let tableView = self.forumTopicsView ?? TableView() if tableView.superview == nil { tableView.frame = self.tableView.frame addSubview(tableView) self.forumTopicsView = tableView } tableView.delegate = delegate let (deleteIndices, indicesAndItems, updateIndices) = mergeListsStableWithUpdates(leftList: self.forumTopicItems, rightList: mapped) self.forumTopicItems = mapped tableView.beginTableUpdates() for deleteIndex in deleteIndices.reversed() { tableView.remove(at: deleteIndex) } for indicesAndItem in indicesAndItems { let item = indicesAndItem.1.item(arguments, initialSize: tableView.frame.size) _ = tableView.insert(item: item, at: indicesAndItem.0) } for updateIndex in updateIndices { let item = updateIndex.1.item(arguments, initialSize: tableView.frame.size) tableView.replace(item: item, at: updateIndex.0, animated: false) } tableView.endTableUpdates() if animated { let oneOfThrid = frame.width / 3 tableView.layer?.animatePosition(from: NSMakePoint(oneOfThrid * 2, tableView.frame.minY), to: tableView.frame.origin, duration: 0.35, timingFunction: .spring) self.tableView.layer?.animatePosition(from: tableView.frame.origin, to: NSMakePoint(-oneOfThrid, tableView.frame.minY), duration: 0.35, timingFunction: .spring) } updateLocalizationAndTheme(theme: theme) needsLayout = true } func cancelForum(animated: Bool) { guard let view = self.forumTopicsView else { return } if animated { let oneOfThrid = frame.width / 3 view.layer?.animatePosition(from: tableView.frame.origin, to: NSMakePoint(frame.width, view.frame.minY), duration: 0.35, timingFunction: .spring, removeOnCompletion: false, completion: { [weak view] _ in view?.removeFromSuperview() }) self.tableView.layer?.animatePosition(from: NSMakePoint(-oneOfThrid, tableView.frame.minY), to: tableView.frame.origin, duration: 0.35, timingFunction: .spring) } else { view.removeFromSuperview() } self.forumTopicsView = nil self.forumTopicItems = [] self.tableView.cancelSelection() self.updateLocalizationAndTheme(theme: theme) self.needsLayout = true } func tokenizedViewDidChangedHeight(_ view: TokenizedView, height: CGFloat, animated: Bool) { if !tokenizedView.isHidden { searchView._change(pos: NSMakePoint(10 + (!dismiss.isHidden ? 40 : 0), 10), animated: animated) tableView.change(size: NSMakeSize(frame.width, frame.height - height - 20 - (textContainerView.isHidden ? 0 : textContainerView.frame.height)), animated: animated) tableView.change(pos: NSMakePoint(0, height + 20), animated: animated) topSeparator.change(pos: NSMakePoint(0, searchView.frame.maxY + 10), animated: animated) } } func textViewUpdateHeight(_ height: CGFloat, _ animated: Bool) { CATransaction.begin() textContainerView.change(size: NSMakeSize(frame.width, height + 16), animated: animated) textContainerView.change(pos: NSMakePoint(0, frame.height - textContainerView.frame.height), animated: animated) textView._change(pos: NSMakePoint(10, height == 34 ? 8 : 11), animated: animated) tableView.change(size: NSMakeSize(frame.width, frame.height - searchView.frame.height - 20 - (!textContainerView.isHidden ? 50 : 0)), animated: animated) actionsContainerView.change(pos: NSMakePoint(frame.width - actionsContainerView.frame.width, frame.height - actionsContainerView.frame.height), animated: animated) bottomSeparator.change(pos: NSMakePoint(0, textContainerView.frame.minY), animated: animated) CATransaction.commit() needsLayout = true } var additionHeight: CGFloat { return textView.frame.height + 16 + searchView.frame.height + 20 } fileprivate override func layout() { super.layout() emojiButton.centerY(x: 0) actionsContainerView.setFrameSize((sendButton.isHidden ? 0 : (sendButton.frame.width + 20)) + emojiButton.frame.width + 20, 50) sendButton.centerY(x: emojiButton.frame.maxX + 20) searchView.setFrameSize(frame.width - 10 - (!dismiss.isHidden ? 40 : 0) - (share.isHidden ? 10 : 50), searchView.frame.height) share.setFrameOrigin(frame.width - share.frame.width - 10, 10) dismiss.setFrameOrigin(10, 10) searchView.setFrameOrigin(10 + (!dismiss.isHidden ? 40 : 0), 10) tableView.frame = NSMakeRect(0, searchView.frame.maxY + 10, frame.width, frame.height - searchView.frame.height - 20 - (!textContainerView.isHidden ? 50 : 0)) topSeparator.frame = NSMakeRect(0, searchView.frame.maxY + 10, frame.width, .borderSize) actionsContainerView.setFrameOrigin(frame.width - actionsContainerView.frame.width, frame.height - actionsContainerView.frame.height) textContainerView.setFrameSize(frame.width, textView.frame.height + 16) textContainerView.setFrameOrigin(0, frame.height - textContainerView.frame.height) textView.setFrameSize(NSMakeSize(textContainerView.frame.width - 10 - actionsContainerView.frame.width, textView.frame.height)) textView.setFrameOrigin(10, textView.frame.height == 34 ? 8 : 11) bottomSeparator.frame = NSMakeRect(0, textContainerView.frame.minY, frame.width, .borderSize) forumTopicsView?.frame = tableView.frame } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } } final class ShareAdditionItem { let peer: Peer let status: String? init(peer: Peer, status: String?) { self.peer = peer self.status = status } } final class ShareAdditionItems { let items: [ShareAdditionItem] let topSeparator: String let bottomSeparator: String init(items: [ShareAdditionItem], topSeparator: String, bottomSeparator: String) { self.items = items self.topSeparator = topSeparator self.bottomSeparator = bottomSeparator } } class ShareObject { let additionTopItems:ShareAdditionItems? let context: AccountContext let emptyPerformOnClose: Bool let excludePeerIds: Set<PeerId> let defaultSelectedIds:Set<PeerId> let limit: Int? var withoutSound: Bool = false var scheduleDate: Date? = nil init(_ context:AccountContext, emptyPerformOnClose: Bool = false, excludePeerIds:Set<PeerId> = [], defaultSelectedIds: Set<PeerId> = [], additionTopItems:ShareAdditionItems? = nil, limit: Int? = nil) { self.limit = limit self.context = context self.emptyPerformOnClose = emptyPerformOnClose self.excludePeerIds = excludePeerIds self.additionTopItems = additionTopItems self.defaultSelectedIds = defaultSelectedIds } var multipleSelection: Bool { return true } var hasCaptionView: Bool { return true } var blockCaptionView: Bool { return false } var interactionOk: String { return strings().modalOK } func attributes(_ peerId: PeerId) -> [MessageAttribute] { var attributes:[MessageAttribute] = [] if FastSettings.isChannelMessagesMuted(peerId) || withoutSound { attributes.append(NotificationInfoMessageAttribute(flags: [.muted])) } if let date = scheduleDate { attributes.append(OutgoingScheduleInfoMessageAttribute(scheduleTime: Int32(date.timeIntervalSince1970))) } return attributes } var searchPlaceholderKey: String { return "ShareModal.Search.Placeholder" } var alwaysEnableDone: Bool { return false } func perform(to entries:[PeerId], threadId: MessageId?, comment: ChatTextInputState? = nil) -> Signal<Never, String> { return .complete() } func limitReached() { } var hasLink: Bool { return false } func shareLink() { } func possibilityPerformTo(_ peer:Peer) -> Bool { return peer.canSendMessage(false) && !self.excludePeerIds.contains(peer.id) } } class ShareLinkObject : ShareObject { let link:String init(_ context: AccountContext, link:String) { self.link = link.removingPercentEncoding ?? link super.init(context) } override var hasLink: Bool { return true } override func shareLink() { copyToClipboard(link) } override func perform(to peerIds:[PeerId], threadId: MessageId?, comment: ChatTextInputState? = nil) -> Signal<Never, String> { for peerId in peerIds { var link = self.link if let comment = comment, !comment.inputText.isEmpty { link += "\n\(comment.inputText)" } let attributes:[MessageAttribute] = attributes(peerId) _ = enqueueMessages(account: context.account, peerId: peerId, messages: [EnqueueMessage.message(text: link, attributes: attributes, inlineStickers: [:], mediaReference: nil, replyToMessageId: threadId, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: [])]).start() } return .complete() } } class ShareUrlObject : ShareObject { let url:String init(_ context: AccountContext, url:String) { self.url = url super.init(context) } override var hasLink: Bool { return true } override func shareLink() { copyToClipboard(url) } override func perform(to peerIds:[PeerId], threadId: MessageId?, comment: ChatTextInputState? = nil) -> Signal<Never, String> { for peerId in peerIds { let attributes:[MessageAttribute] = attributes(peerId) let media = TelegramMediaFile(fileId: MediaId.init(namespace: 0, id: 0), partialReference: nil, resource: LocalFileReferenceMediaResource.init(localFilePath: url, randomId: arc4random64()), previewRepresentations: [], videoThumbnails: [], immediateThumbnailData: nil, mimeType: "text/plain", size: nil, attributes: [.FileName(fileName: url.nsstring.lastPathComponent)]) _ = enqueueMessages(account: context.account, peerId: peerId, messages: [EnqueueMessage.message(text: "", attributes: attributes, inlineStickers: [:], mediaReference: AnyMediaReference.standalone(media: media), replyToMessageId: threadId, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: [])]).start() } return .complete() } } class ShareContactObject : ShareObject { let user:TelegramUser init(_ context: AccountContext, user:TelegramUser) { self.user = user super.init(context) } override func perform(to peerIds:[PeerId], threadId: MessageId?, comment: ChatTextInputState? = nil) -> Signal<Never, String> { for peerId in peerIds { if let comment = comment, !comment.inputText.isEmpty { let attributes:[MessageAttribute] = attributes(peerId) _ = enqueueMessages(account: context.account, peerId: peerId, messages: [EnqueueMessage.message(text: comment.inputText, attributes: attributes, inlineStickers: [:], mediaReference: nil, replyToMessageId: threadId, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: [])]).start() } _ = Sender.shareContact(context: context, peerId: peerId, contact: user, replyId: threadId).start() } return .complete() } } class ShareCallbackObject : ShareObject { private let callback:([PeerId])->Signal<Never, NoError> init(_ context: AccountContext, callback:@escaping([PeerId])->Signal<Never, NoError>) { self.callback = callback super.init(context) } override func perform(to peerIds:[PeerId], threadId: MessageId?, comment: ChatTextInputState? = nil) -> Signal<Never, String> { return callback(peerIds) |> mapError { _ in return String() } } } class ShareMessageObject : ShareObject { fileprivate let messageIds:[MessageId] private let message:Message let link:String? private let exportLinkDisposable = MetaDisposable() init(_ context: AccountContext, _ message:Message, _ groupMessages:[Message] = []) { self.messageIds = groupMessages.isEmpty ? [message.id] : groupMessages.map{$0.id} self.message = message var peer = coreMessageMainPeer(message) as? TelegramChannel var messageId = message.id if let author = message.forwardInfo?.author as? TelegramChannel { peer = author messageId = message.forwardInfo?.sourceMessageId ?? message.id } // peer = coreMessageMainPeer(message) as? TelegramChannel // } if let peer = peer, let address = peer.username { switch peer.info { case .broadcast: self.link = "https://t.me/" + address + "/" + "\(messageId.id)" default: self.link = nil } } else { self.link = nil } super.init(context) } override var hasLink: Bool { return link != nil } override func shareLink() { if let link = link { exportLinkDisposable.set(context.engine.messages.exportMessageLink(peerId: messageIds[0].peerId, messageId: messageIds[0]).start(next: { valueLink in if let valueLink = valueLink { copyToClipboard(valueLink) } else { copyToClipboard(link) } })) } } deinit { exportLinkDisposable.dispose() } override func perform(to peerIds:[PeerId], threadId: MessageId?, comment: ChatTextInputState? = nil) -> Signal<Never, String> { let context = self.context let messageIds = self.messageIds var signals: [Signal<[MessageId?], NoError>] = [] let attrs:(PeerId)->[MessageAttribute] = { [weak self] peerId in return self?.attributes(peerId) ?? [] } let date = self.scheduleDate let withoutSound = self.withoutSound for peerId in peerIds { let viewSignal: Signal<PeerId?, NoError> = context.account.postbox.peerView(id: peerId) |> take(1) |> map { peerView in if let cachedData = peerView.cachedData as? CachedChannelData { return cachedData.sendAsPeerId } else { return nil } } signals.append(viewSignal |> mapToSignal { sendAs in let forward: Signal<[MessageId?], NoError> = Sender.forwardMessages(messageIds: messageIds, context: context, peerId: peerId, replyId: threadId, silent: FastSettings.isChannelMessagesMuted(peerId) || withoutSound, atDate: date, sendAsPeerId: sendAs) var caption: Signal<[MessageId?], NoError>? if let comment = comment, !comment.inputText.isEmpty { let parsingUrlType: ParsingType if peerId.namespace != Namespaces.Peer.SecretChat { parsingUrlType = [.Hashtags] } else { parsingUrlType = [.Links, .Hashtags] } var attributes:[MessageAttribute] = [TextEntitiesMessageAttribute(entities: comment.messageTextEntities(parsingUrlType))] attributes += attrs(peerId) if let sendAs = sendAs { attributes.append(SendAsMessageAttribute(peerId: sendAs)) } caption = Sender.enqueue(message: EnqueueMessage.message(text: comment.inputText, attributes: attributes, inlineStickers: [:], mediaReference: nil, replyToMessageId: threadId, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: []), context: context, peerId: peerId) } if let caption = caption { return caption |> then(forward) } else { return forward } }) } return combineLatest(signals) |> castError(String.self) |> ignoreValues } override func possibilityPerformTo(_ peer:Peer) -> Bool { return message.possibilityForwardTo(peer) } } final class ForwardMessagesObject : ShareObject { fileprivate let messageIds: [MessageId] private let disposable = MetaDisposable() init(_ context: AccountContext, messageIds: [MessageId], emptyPerformOnClose: Bool = false) { self.messageIds = messageIds super.init(context, emptyPerformOnClose: emptyPerformOnClose) } deinit { disposable.dispose() } override var multipleSelection: Bool { return false } override func perform(to peerIds: [PeerId], threadId: MessageId?, comment: ChatTextInputState? = nil) -> Signal<Never, String> { if peerIds.count == 1 { let context = self.context let comment = comment != nil ? comment!.inputText.isEmpty ? nil : comment : nil let peers = context.account.postbox.transaction { transaction -> Peer? in for peerId in peerIds { if let peer = transaction.getPeer(peerId) { return peer } } return nil } return combineLatest(context.account.postbox.messagesAtIds(messageIds), peers) |> deliverOnMainQueue |> castError(String.self) |> mapToSignal { messages, peer in let messageIds = messages.map { $0.id } if let peer = peer, peer.isChannel { for message in messages { if message.isPublicPoll { return .fail(strings().pollForwardError) } } } let navigation = self.context.bindings.rootNavigation() if let peerId = peerIds.first { if peerId == context.peerId { if let comment = comment, !comment.inputText.isEmpty { let parsingUrlType: ParsingType if peerId.namespace != Namespaces.Peer.SecretChat { parsingUrlType = [.Hashtags] } else { parsingUrlType = [.Links, .Hashtags] } let attributes:[MessageAttribute] = [TextEntitiesMessageAttribute(entities: comment.messageTextEntities(parsingUrlType))] _ = Sender.enqueue(message: EnqueueMessage.message(text: comment.inputText, attributes: attributes, inlineStickers: [:], mediaReference: nil, replyToMessageId: threadId, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: []), context: context, peerId: peerId).start() } _ = Sender.forwardMessages(messageIds: messageIds, context: context, peerId: context.account.peerId, replyId: threadId).start() if let controller = context.bindings.rootNavigation().controller as? ChatController { controller.chatInteraction.update({$0.withoutSelectionState()}) } delay(0.2, closure: { _ = showModalSuccess(for: context.window, icon: theme.icons.successModalProgress, delay: 1.0).start() }) } else { if let controller = navigation.controller as? ChatController, controller.chatInteraction.peerId == peerId { controller.chatInteraction.update({$0.withoutSelectionState().updatedInterfaceState({$0.withUpdatedForwardMessageIds(messageIds).withUpdatedInputState(comment ?? $0.inputState)})}) } else { let initialAction: ChatInitialAction = .forward(messageIds: messageIds, text: comment, behavior: .automatic) if let threadId = threadId { return ForumUI.openTopic(makeMessageThreadId(threadId), peerId: peerId, context: context, animated: true, addition: true, initialAction: initialAction) |> filter {$0} |> take(1) |> ignoreValues |> castError(String.self) } (navigation.controller as? ChatController)?.chatInteraction.update({ $0.withoutSelectionState() }) var existed: Bool = false navigation.enumerateControllers { controller, _ in if let controller = controller as? ChatController, controller.chatInteraction.peerId == peerId { existed = true } return existed } let newone: ChatController if existed { newone = ChatController(context: context, chatLocation: .peer(peerId), initialAction: initialAction) } else { newone = ChatAdditionController(context: context, chatLocation: .peer(peerId), initialAction: initialAction) } navigation.push(newone) return newone.ready.get() |> filter {$0} |> take(1) |> ignoreValues |> castError(String.self) } } } else { if let controller = navigation.controller as? ChatController { controller.chatInteraction.update({$0.withoutSelectionState().updatedInterfaceState({$0.withUpdatedForwardMessageIds(messageIds)})}) } } return .complete() } } else { let navigation = self.context.bindings.rootNavigation() if let controller = navigation.controller as? ChatController { controller.chatInteraction.update({ $0.withoutSelectionState() }) } let context = self.context let messageIds = self.messageIds var signals: [Signal<[MessageId?], NoError>] = [] let attrs:(PeerId)->[MessageAttribute] = { [weak self] peerId in return self?.attributes(peerId) ?? [] } let date = self.scheduleDate let withoutSound = self.withoutSound for peerId in peerIds { let viewSignal: Signal<PeerId?, NoError> = context.account.postbox.peerView(id: peerId) |> take(1) |> map { peerView in if let cachedData = peerView.cachedData as? CachedChannelData { return cachedData.sendAsPeerId } else { return nil } } signals.append(viewSignal |> mapToSignal { sendAs in let forward: Signal<[MessageId?], NoError> = Sender.forwardMessages(messageIds: messageIds, context: context, peerId: peerId, replyId: threadId, silent: FastSettings.isChannelMessagesMuted(peerId) || withoutSound, atDate: date, sendAsPeerId: sendAs) var caption: Signal<[MessageId?], NoError>? if let comment = comment, !comment.inputText.isEmpty { let parsingUrlType: ParsingType if peerId.namespace != Namespaces.Peer.SecretChat { parsingUrlType = [.Hashtags] } else { parsingUrlType = [.Links, .Hashtags] } var attributes:[MessageAttribute] = [TextEntitiesMessageAttribute(entities: comment.messageTextEntities(parsingUrlType))] attributes += attrs(peerId) if let sendAs = sendAs { attributes.append(SendAsMessageAttribute(peerId: sendAs)) } caption = Sender.enqueue(message: EnqueueMessage.message(text: comment.inputText, attributes: attributes, inlineStickers: [:], mediaReference: nil, replyToMessageId: threadId, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: []), context: context, peerId: peerId) } if let caption = caption { return caption |> then(forward) } else { return forward } }) } return combineLatest(signals) |> castError(String.self) |> ignoreValues } } override var searchPlaceholderKey: String { return "ShareModal.Search.ForwardPlaceholder" } } enum SelectablePeersEntryStableId : Hashable { case plain(PeerId, ChatListIndex) case emptySearch case separator(ChatListIndex) var hashValue: Int { switch self { case let .plain(peerId, _): return peerId.hashValue case .separator(let index): return index.hashValue case .emptySearch: return 0 } } } enum SelectablePeersEntry : Comparable, Identifiable { case secretChat(Peer, PeerId, ChatListIndex, PeerStatusStringResult?, Bool, Bool) case plain(Peer, ChatListIndex, PeerStatusStringResult?, Bool, Bool) case separator(String, ChatListIndex) case emptySearch var stableId: SelectablePeersEntryStableId { switch self { case let .plain(peer, index, _, _, _): return .plain(peer.id, index) case let .secretChat(_, peerId, index, _, _, _): return .plain(peerId, index) case let .separator(_, index): return .separator(index) case .emptySearch: return .emptySearch } } var index:ChatListIndex { switch self { case let .plain(_, id, _, _, _): return id case let .secretChat(_, _, id, _, _, _): return id case let .separator(_, index): return index case .emptySearch: return ChatListIndex(pinningIndex: nil, messageIndex: MessageIndex.absoluteLowerBound()) } } } func <(lhs:SelectablePeersEntry, rhs:SelectablePeersEntry) -> Bool { return lhs.index < rhs.index } func ==(lhs:SelectablePeersEntry, rhs:SelectablePeersEntry) -> Bool { switch lhs { case let .plain(lhsPeer, index, presence, separator, multiple): if case .plain(let rhsPeer, index, presence, separator, multiple) = rhs { return lhsPeer.isEqual(rhsPeer) } else { return false } case let .secretChat(lhsPeer, peerId, index, presence, separator, multiple): if case .secretChat(let rhsPeer, peerId, index, presence, separator, multiple) = rhs { return lhsPeer.isEqual(rhsPeer) } else { return false } case let .separator(text, index): if case .separator(text, index) = rhs { return true } else { return false } case .emptySearch: if case .emptySearch = rhs { return true } else { return false } } } fileprivate func prepareEntries(from:[SelectablePeersEntry]?, to:[SelectablePeersEntry], context: AccountContext, initialSize:NSSize, animated:Bool, multipleSelection: Bool, selectInteraction:SelectPeerInteraction) -> TableUpdateTransition { let (deleted,inserted,updated) = proccessEntries(from, right: to, { entry -> TableRowItem in switch entry { case let .plain(peer, _, presence, drawSeparator, multiple): let color = presence?.status.string.isEmpty == false ? presence?.status.attribute(NSAttributedString.Key.foregroundColor, at: 0, effectiveRange: nil) as? NSColor : nil return ShortPeerRowItem(initialSize, peer: peer, account: context.account, context: context, stableId: entry.stableId, height: 48, photoSize:NSMakeSize(36, 36), statusStyle: ControlStyle(font: .normal(.text), foregroundColor: peer.id == context.peerId ? theme.colors.grayText : color ?? theme.colors.grayText, highlightColor:.white), status: peer.id == context.peerId ? (multipleSelection ? nil : strings().forwardToSavedMessages) : presence?.status.string, drawCustomSeparator: drawSeparator, isLookSavedMessage : peer.id == context.peerId, inset:NSEdgeInsets(left: 10, right: 10), drawSeparatorIgnoringInset: true, interactionType: multiple ? .selectable(selectInteraction) : .plain, action: { if peer.isForum { selectInteraction.openForum(peer.id) } else { selectInteraction.action(peer.id, nil) } }, contextMenuItems: { return .single([ .init(strings().shareModalSelect, handler: { selectInteraction.toggleSelection(peer) }, itemImage: MenuAnimation.menu_select_messages.value) ]) }, highlightVerified: true) case let .secretChat(peer, peerId, _, _, drawSeparator, multiple): return ShortPeerRowItem(initialSize, peer: peer, account: context.account, context: context, peerId: peerId, stableId: entry.stableId, height: 48, photoSize:NSMakeSize(36, 36), titleStyle: ControlStyle(font: .medium(.title), foregroundColor: theme.colors.accent, highlightColor: .white), statusStyle: ControlStyle(font: .normal(.text), foregroundColor: theme.colors.grayText, highlightColor:.white), status: strings().composeSelectSecretChat.lowercased(), drawCustomSeparator: drawSeparator, isLookSavedMessage : peer.id == context.peerId, inset:NSEdgeInsets(left: 10, right: 10), drawSeparatorIgnoringInset: true, interactionType: multiple ? .selectable(selectInteraction) : .plain, action: { selectInteraction.action(peerId, nil) }) case let .separator(text, _): return SeparatorRowItem(initialSize, entry.stableId, string: text) case .emptySearch: return SearchEmptyRowItem(initialSize, stableId: entry.stableId) } }) return TableUpdateTransition(deleted: deleted, inserted: inserted, updated: updated, animated: animated, state: animated ? .none(nil) : .saveVisible(.lower), grouping: true, animateVisibleOnly: false) } class ShareModalController: ModalViewController, Notifable, TGModernGrowingDelegate, TableViewDelegate { private let share:ShareObject private let selectInteractions:SelectPeerInteraction = SelectPeerInteraction() private let search:Promise<SearchState> = Promise() private let forumPeerId:ValuePromise<PeerId?> = ValuePromise(nil, ignoreRepeated: true) private let inSearchSelected:Atomic<[PeerId]> = Atomic(value:[]) private let disposable:MetaDisposable = MetaDisposable() private let exportLinkDisposable:MetaDisposable = MetaDisposable() private let tokenDisposable: MetaDisposable = MetaDisposable() private var contextQueryState: (ChatPresentationInputQuery?, Disposable)? private let inputContextHelper: InputContextHelper private let contextChatInteraction: ChatInteraction private let forumDisposable = MetaDisposable() private let multipleSelection: ValuePromise<Bool> = ValuePromise(false, ignoreRepeated: true) func notify(with value: Any, oldValue: Any, animated: Bool) { if let value = value as? SelectPeerPresentation, let oldValue = oldValue as? SelectPeerPresentation { genericView.hasCaptionView = value.multipleSelection && !share.blockCaptionView genericView.hasSendView = value.multipleSelection && !share.blockCaptionView if value.multipleSelection && !share.blockCaptionView { search.set(combineLatest(genericView.tokenizedView.textUpdater, genericView.tokenizedView.stateValue.get()) |> map { SearchState(state: $1, request: $0)}) } else { search.set(genericView.basicSearchView.searchValue) } self.multipleSelection.set(value.multipleSelection) let added = value.selected.subtracting(oldValue.selected) let removed = oldValue.selected.subtracting(value.selected) let selected = value.selected.filter { $0.namespace._internalGetInt32Value() != ChatListFilterPeerCategories.Namespace } if let limit = self.share.limit, selected.count > limit { DispatchQueue.main.async { [unowned self] in self.selectInteractions.update(animated: true, { current in var current = current for peerId in added { if let peer = current.peers[peerId] { current = current.withToggledSelected(peerId, peer: peer) } } return current }) self.share.limitReached() } return } let tokens:[SearchToken] = added.map { item in let title = item == share.context.account.peerId ? strings().peerSavedMessages : value.peers[item]?.compactDisplayTitle ?? strings().peerDeletedUser return SearchToken(name: title, uniqueId: item.toInt64()) } genericView.tokenizedView.addTokens(tokens: tokens, animated: animated) genericView.sendButton.isEnabled = !value.selected.isEmpty || share.alwaysEnableDone let idsToRemove:[Int64] = removed.map { $0.toInt64() } genericView.tokenizedView.removeTokens(uniqueIds: idsToRemove, animated: animated) self.modal?.interactions?.updateEnables(!value.selected.isEmpty || share.alwaysEnableDone) if value.inputQueryResult != oldValue.inputQueryResult { inputContextHelper.context(with: value.inputQueryResult, for: self.genericView, relativeView: self.genericView.textContainerView, position: .above, selectIndex: nil, animated: animated) } if let (possibleQueryRange, possibleTypes, _) = textInputStateContextQueryRangeAndType(ChatTextInputState(inputText: value.comment.string, selectionRange: value.comment.range.min ..< value.comment.range.max, attributes: []), includeContext: false) { if possibleTypes.contains(.mention) { let peers: [Peer] = value.peers.compactMap { (_, value) in if value.isGroup || value.isSupergroup { return value } else { return nil } } let query = String(value.comment.string[possibleQueryRange]) if let (updatedContextQueryState, updatedContextQuerySignal) = chatContextQueryForSearchMention(chatLocations: peers.map { .peer($0.id) }, .mention(query: query, includeRecent: false), currentQuery: self.contextQueryState?.0, context: share.context) { self.contextQueryState?.1.dispose() var inScope = true var inScopeResult: ((ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult?)? self.contextQueryState = (updatedContextQueryState, (updatedContextQuerySignal |> deliverOnMainQueue).start(next: { [weak self] result in if let strongSelf = self { if Thread.isMainThread && inScope { inScope = false inScopeResult = result } else { strongSelf.selectInteractions.update(animated: animated, { $0.updatedInputQueryResult { previousResult in return result(previousResult) } }) } } })) inScope = false if let inScopeResult = inScopeResult { selectInteractions.update(animated: animated, { $0.updatedInputQueryResult { previousResult in return inScopeResult(previousResult) } }) } } else { selectInteractions.update(animated: animated, { $0.updatedInputQueryResult { _ in return nil } }) } } else { selectInteractions.update(animated: animated, { $0.updatedInputQueryResult { _ in return nil } }) } } else { selectInteractions.update(animated: animated, { $0.updatedInputQueryResult { _ in return nil } }) } } else if let value = value as? ChatPresentationInterfaceState, let oldValue = oldValue as? ChatPresentationInterfaceState { if value.effectiveInput != oldValue.effectiveInput { updateInput(value, prevState: oldValue, animated) } } _ = self.window?.makeFirstResponder(firstResponder()) } private func updateInput(_ state:ChatPresentationInterfaceState, prevState: ChatPresentationInterfaceState, _ animated:Bool = true) -> Void { let textView = genericView.textView if textView.string() != state.effectiveInput.inputText || state.effectiveInput.attributes != prevState.effectiveInput.attributes { textView.animates = false textView.setAttributedString(state.effectiveInput.attributedString, animated:animated) textView.animates = true } let range = NSMakeRange(state.effectiveInput.selectionRange.lowerBound, state.effectiveInput.selectionRange.upperBound - state.effectiveInput.selectionRange.lowerBound) if textView.selectedRange().location != range.location || textView.selectedRange().length != range.length { textView.setSelectedRange(range) } textViewTextDidChangeSelectedRange(range) } func isEqual(to other: Notifable) -> Bool { if let other = other as? ModalViewController { return other == self } return false } fileprivate var genericView:ShareModalView { return self.view as! ShareModalView } override func viewClass() -> AnyClass { return ShareModalView.self } override func initializer() -> NSView { let vz = viewClass() as! ShareModalView.Type return vz.init(frame: NSMakeRect(_frameRect.minX, _frameRect.minY, _frameRect.width, _frameRect.height - bar.height), shareObject: share); } override var modal: Modal? { didSet { modal?.interactions?.updateEnables(false) } } func selectionDidChange(row: Int, item: TableRowItem, byClick: Bool, isNew: Bool) { } func selectionWillChange(row: Int, item: TableRowItem, byClick: Bool) -> Bool { return !selectInteractions.presentation.multipleSelection && !(item is SeparatorRowItem) } func isSelectable(row: Int, item: TableRowItem) -> Bool { return !selectInteractions.presentation.multipleSelection } func findGroupStableId(for stableId: AnyHashable) -> AnyHashable? { return nil } private func invokeShortCut(_ index: Int) { if genericView.tableView.count > index, let item = self.genericView.tableView.item(at: index) as? ShortPeerRowItem { _ = self.genericView.tableView.select(item: item) (item.view as? ShortPeerRowView)?.invokeAction(item, clickCount: 1) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let context = self.share.context self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.genericView.tableView.highlightPrev() return .invoked }, with: self, for: .UpArrow, priority: .modal) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.genericView.tableView.highlightNext() return .invoked }, with: self, for: .DownArrow, priority: .modal) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in guard let `self` = self else {return .rejected} if let highlighted = self.genericView.tableView.highlightedItem() as? ShortPeerRowItem { _ = self.genericView.tableView.select(item: highlighted) (highlighted.view as? ShortPeerRowView)?.invokeAction(highlighted, clickCount: 1) } return .rejected }, with: self, for: .Return, priority: .low) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.selectInteractions.action(context.peerId, nil) return .invoked }, with: self, for: .Zero, priority: self.responderPriority, modifierFlags: [.command]) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.invokeShortCut(0) return .invoked }, with: self, for: .One, priority: self.responderPriority, modifierFlags: [.command]) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.invokeShortCut(1) return .invoked }, with: self, for: .Two, priority: self.responderPriority, modifierFlags: [.command]) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.invokeShortCut(2) return .invoked }, with: self, for: .Three, priority: self.responderPriority, modifierFlags: [.command]) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.invokeShortCut(3) return .invoked }, with: self, for: .Four, priority: self.responderPriority, modifierFlags: [.command]) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.invokeShortCut(4) return .invoked }, with: self, for: .Five, priority: self.responderPriority, modifierFlags: [.command]) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.invokeShortCut(5) return .invoked }, with: self, for: .Six, priority: self.responderPriority, modifierFlags: [.command]) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.invokeShortCut(6) return .invoked }, with: self, for: .Seven, priority: self.responderPriority, modifierFlags: [.command]) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.invokeShortCut(7) return .invoked }, with: self, for: .Eight, priority: self.responderPriority, modifierFlags: [.command]) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.invokeShortCut(8) return .invoked }, with: self, for: .Nine, priority: self.responderPriority, modifierFlags: [.command]) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.genericView.textView.boldWord() return .invoked }, with: self, for: .B, priority: self.responderPriority, modifierFlags: [.command]) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.makeUrl() return .invoked }, with: self, for: .U, priority: self.responderPriority, modifierFlags: [.command]) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.genericView.textView.italicWord() return .invoked }, with: self, for: .I, priority: self.responderPriority, modifierFlags: [.command]) self.window?.set(handler: { [weak self] _ -> KeyHandlerResult in self?.genericView.textView.codeWord() return .invoked }, with: self, for: .K, priority: self.responderPriority, modifierFlags: [.command, .shift]) } private func makeUrl() { let range = self.genericView.textView.selectedRange() guard range.min != range.max, let window = window else { return } var effectiveRange:NSRange = NSMakeRange(NSNotFound, 0) let defaultTag: TGInputTextTag? = genericView.textView.attributedString().attribute(NSAttributedString.Key(rawValue: TGCustomLinkAttributeName), at: range.location, effectiveRange: &effectiveRange) as? TGInputTextTag let defaultUrl = defaultTag?.attachment as? String if effectiveRange.location == NSNotFound || defaultTag == nil { effectiveRange = range } showModal(with: InputURLFormatterModalController(string: genericView.textView.string().nsstring.substring(with: effectiveRange), defaultUrl: defaultUrl, completion: { [weak self] url in self?.genericView.textView.addLink(url, range: effectiveRange) }), for: window) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.window?.removeAllHandlers(for: self) self.contextChatInteraction.remove(observer: self) } override var handleAllEvents: Bool { return true } override var responderPriority: HandlerPriority { return .modal } private func openForum(_ peerId: PeerId, animated: Bool) { let context = share.context let selectInteractions = self.selectInteractions var filter = chatListViewForLocation(chatListLocation: .forum(peerId: peerId), location: .Initial(100, nil), filter: nil, account: context.account) |> filter { !$0.list.isLoading } |> take(1) filter = showModalProgress(signal: filter, for: context.window) let signal: Signal<[EngineChatList.Item], NoError> = combineLatest(filter, self.search.get()) |> map { update, query in let items = update.list.items.reversed().filter { $0.renderedPeer.peer?._asPeer().canSendMessage(true, threadData: $0.threadData) ?? true } if query.request.isEmpty { return items } else { return items.filter { item in let title = item.threadData?.info.title ?? "" return title.lowercased().contains(query.request.lowercased()) } } } |> deliverOnMainQueue forumDisposable.set(signal.start(next: { [weak self] items in self?.genericView.appearForumTopics(items, peerId: peerId, interactions: selectInteractions, delegate: self, context: context, animated: animated) self?.forumPeerId.set(peerId) })) } override func viewDidLoad() { super.viewDidLoad() let initialSize = self.atomicSize.modify({$0}) let request = Promise<ChatListIndexRequest>() let context = self.share.context let share = self.share let selectInteraction = self.selectInteractions selectInteraction.add(observer: self) selectInteractions.update(animated: false, { $0.withUpdatedMultipleSelection(share.multipleSelection) }) if share.multipleSelection { search.set(combineLatest(genericView.tokenizedView.textUpdater, genericView.tokenizedView.stateValue.get()) |> map { SearchState(state: $1, request: $0)}) } else { search.set(genericView.basicSearchView.searchValue) } self.multipleSelection.set(share.multipleSelection) self.notify(with: self.selectInteractions.presentation, oldValue: self.selectInteractions.presentation, animated: false) self.contextChatInteraction.add(observer: self) genericView.tableView.delegate = self let interactions = EntertainmentInteractions(.emoji, peerId: PeerId(0)) interactions.sendEmoji = { [weak self] emoji, _ in self?.genericView.textView.appendText(emoji) _ = self?.window?.makeFirstResponder(self?.genericView.textView.inputView) } emoji.update(with: interactions, chatInteraction: self.contextChatInteraction) genericView.emojiButton.set(handler: { [weak self] control in self?.showEmoji(for: control) }, for: .Hover) genericView.textView.delegate = self genericView.hasShareMenu = self.share.hasLink genericView.dismiss.set(handler: { [weak self] _ in if self?.genericView.inForumMode == true { self?.cancelForum(animated: true) } else { self?.close() } }, for: .Click) let previous:Atomic<[SelectablePeersEntry]?> = Atomic(value: nil) selectInteraction.action = { [weak self] peerId, threadId in guard let `self` = self else { return } let id = threadId != nil ? makeThreadIdMessageId(peerId: peerId, threadId: threadId!) : nil _ = share.perform(to: [peerId], threadId: id, comment: self.contextChatInteraction.presentation.interfaceState.inputState).start(error: { error in alert(for: context.window, info: error) }, completed: { [weak self] in self?.close() }) } selectInteraction.openForum = { [weak self] peerId in self?.openForum(peerId, animated: true) } genericView.share.contextMenu = { [weak self] in let menu = ContextMenu() menu.addItem(ContextMenuItem(strings().modalCopyLink, handler: { if share.hasLink { share.shareLink() self?.show(toaster: ControllerToaster(text: strings().shareLinkCopied), for: 2.0, animated: true) } }, itemImage: MenuAnimation.menu_copy_link.value)) return menu } genericView.sendButton.set(handler: { [weak self] _ in if let strongSelf = self, !selectInteraction.presentation.selected.isEmpty { _ = strongSelf.invoke() } }, for: .SingleClick) genericView.sendWithoutSound = { [weak self] in self?.share.withoutSound = true _ = self?.invoke() } genericView.scheduleMessage = { [weak self] in guard let share = self?.share else { return } let context = share.context let peerId = share.context.peerId showModal(with: DateSelectorModalController(context: context, mode: .schedule(peerId), selectedAt: { date in self?.share.scheduleDate = date _ = self?.invoke() }), for: context.window) } tokenDisposable.set(genericView.tokenizedView.tokensUpdater.start(next: { tokens in let ids = Set(tokens.map({PeerId($0.uniqueId)})) let unselected = selectInteraction.presentation.selected.symmetricDifference(ids) selectInteraction.update( { unselected.reduce($0, { current, value in return current.deselect(peerId: value) })}) })) let previousChatList:Atomic<ChatListView?> = Atomic(value: nil) let defaultItems = context.account.postbox.transaction { transaction -> [Peer] in var peers:[Peer] = [] if let addition = share.additionTopItems { for item in addition.items { if share.defaultSelectedIds.contains(item.peer.id) { peers.append(item.peer) } } } for peerId in share.defaultSelectedIds { if let peer = transaction.getPeer(peerId) { peers.append(peer) } } return peers } let list:Signal<TableUpdateTransition, NoError> = combineLatest(queue: prepareQueue, request.get() |> distinctUntilChanged, search.get() |> distinctUntilChanged, forumPeerId.get(), multipleSelection.get()) |> mapToSignal { location, query, forumPeerId, multipleSelection -> Signal<TableUpdateTransition, NoError> in if query.request.isEmpty || query.state == .None { if !multipleSelection && query.state == .Focus && forumPeerId == nil { return combineLatest(context.account.postbox.loadedPeerWithId(context.peerId), context.engine.peers.recentPeers() |> deliverOnPrepareQueue, context.engine.peers.recentlySearchedPeers() |> deliverOnPrepareQueue) |> map { user, rawTop, recent -> TableUpdateTransition in var entries:[SelectablePeersEntry] = [] let top:[Peer] switch rawTop { case let .peers(peers): top = peers default: top = [] } var contains:[PeerId:PeerId] = [:] var indexId:Int32 = Int32.max let chatListIndex:()-> ChatListIndex = { let index = MessageIndex(id: MessageId(peerId: PeerId(0), namespace: 1, id: indexId), timestamp: indexId) indexId -= 1 return ChatListIndex(pinningIndex: nil, messageIndex: index) } entries.append(.plain(user, ChatListIndex(pinningIndex: 0, messageIndex: MessageIndex(id: MessageId(peerId: PeerId(0), namespace: 0, id: Int32.max), timestamp: Int32.max)), nil, top.isEmpty && recent.isEmpty, multipleSelection)) contains[user.id] = user.id if !top.isEmpty { entries.insert(.separator(strings().searchSeparatorPopular.uppercased(), chatListIndex()), at: 0) var count: Int32 = 0 for peer in top { if contains[peer.id] == nil { if share.possibilityPerformTo(peer) { entries.insert(.plain(peer, chatListIndex(), nil, count < 4, multipleSelection), at: 0) contains[peer.id] = peer.id count += 1 } } if count >= 5 { break } } } if !recent.isEmpty { entries.insert(.separator(strings().searchSeparatorRecent.uppercased(), chatListIndex()), at: 0) for rendered in recent { if let peer = rendered.peer.chatMainPeer { if contains[peer.id] == nil { if share.possibilityPerformTo(peer) { entries.insert(.plain(peer, chatListIndex(), nil, true, multipleSelection), at: 0) contains[peer.id] = peer.id } } } } } entries.sort(by: <) return prepareEntries(from: previous.swap(entries), to: entries, context: context, initialSize: initialSize, animated: true, multipleSelection: multipleSelection, selectInteraction:selectInteraction) } } else { var signal:Signal<(ChatListView,ViewUpdateType), NoError> switch(location) { case let .Initial(count, _): signal = context.account.viewTracker.tailChatListView(groupId: .root, filterPredicate: nil, count: count) |> take(1) case let .Index(index, _): switch index { case let .chatList(index): signal = context.account.viewTracker.aroundChatListView(groupId: .root, filterPredicate: nil, index: index, count: 30) |> take(1) case .forum: signal = .never() } } return signal |> deliverOnPrepareQueue |> mapToSignal { value -> Signal<(ChatListView,ViewUpdateType, [PeerId: PeerStatusStringResult], Peer), NoError> in var peerIds:[PeerId] = [] for entry in value.0.entries { switch entry { case let .MessageEntry(_, _, _, _, _, renderedPeer, _, _, _, _, _): peerIds.append(renderedPeer.peerId) default: break } } _ = previousChatList.swap(value.0) let keys = peerIds.map {PostboxViewKey.peer(peerId: $0, components: .all)} return combineLatest(context.account.postbox.combinedView(keys: keys), context.account.postbox.loadedPeerWithId(context.peerId)) |> map { values, selfPeer in var presences:[PeerId: PeerStatusStringResult] = [:] for value in values.views { if let view = value.value as? PeerView { presences[view.peerId] = stringStatus(for: view, context: context) } } return (value.0, value.1, presences, selfPeer) } |> take(1) } |> deliverOn(prepareQueue) |> take(1) |> map { value -> TableUpdateTransition in var entries:[SelectablePeersEntry] = [] var contains:[PeerId:PeerId] = [:] var offset: Int32 = Int32.max if let additionTopItems = share.additionTopItems { var index = ChatListIndex(pinningIndex: 0, messageIndex: MessageIndex(id: MessageId(peerId: PeerId(0), namespace: 0, id: offset), timestamp: offset)) entries.append(.separator(additionTopItems.topSeparator, index)) offset -= 1 for item in additionTopItems.items { index = ChatListIndex(pinningIndex: 0, messageIndex: MessageIndex(id: MessageId(peerId: PeerId(0), namespace: 0, id: offset), timestamp: offset)) let theme = PeerStatusStringTheme() let status = NSAttributedString.initialize(string: item.status, color: theme.statusColor, font: theme.statusFont) let title = NSAttributedString.initialize(string: item.peer.displayTitle, color: theme.titleColor, font: theme.titleFont) entries.append(.plain(item.peer, index, PeerStatusStringResult(title, status), true, multipleSelection)) offset -= 1 } index = ChatListIndex(pinningIndex: 0, messageIndex: MessageIndex(id: MessageId(peerId: PeerId(0), namespace: 0, id: offset), timestamp: offset)) entries.append(.separator(additionTopItems.bottomSeparator, index)) offset -= 1 } if !share.excludePeerIds.contains(value.3.id) { entries.append(.plain(value.3, ChatListIndex(pinningIndex: 0, messageIndex: MessageIndex(id: MessageId(peerId: PeerId(0), namespace: 0, id: offset), timestamp: offset)), nil, true, multipleSelection)) contains[value.3.id] = value.3.id } for entry in value.0.entries { switch entry { case let .MessageEntry(id, _, _, _, _, renderedPeer, _, _, _, _, _): if let main = renderedPeer.peer { if contains[main.id] == nil { if share.possibilityPerformTo(main) { if let peer = renderedPeer.chatMainPeer { if main.id.namespace == Namespaces.Peer.SecretChat { entries.append(.secretChat(peer, main.id, id, value.2[peer.id], true, multipleSelection)) } else { entries.append(.plain(peer, id, value.2[peer.id], true, multipleSelection)) } } contains[main.id] = main.id } } } default: break } } entries.sort(by: <) return prepareEntries(from: previous.swap(entries), to: entries, context: context, initialSize: initialSize, animated: true, multipleSelection: multipleSelection, selectInteraction:selectInteraction) } } } else if forumPeerId == nil { _ = previousChatList.swap(nil) var all = query.request.transformKeyboard all.insert(query.request.lowercased(), at: 0) all = all.uniqueElements let localPeers = combineLatest(all.map { return context.account.postbox.searchPeers(query: $0) }) |> map { result in return result.reduce([], { return $0 + $1 }) } let remotePeers = Signal<[RenderedPeer], NoError>.single([]) |> then( context.engine.contacts.searchRemotePeers(query: query.request.lowercased()) |> map { $0.0.map {RenderedPeer($0)} + $0.1.map {RenderedPeer($0)} } ) return combineLatest(localPeers, remotePeers) |> map {$0 + $1} |> mapToSignal { peers -> Signal<([RenderedPeer], [PeerId: PeerStatusStringResult], Peer), NoError> in let keys = peers.map {PostboxViewKey.peer(peerId: $0.peerId, components: .all)} return combineLatest(context.account.postbox.combinedView(keys: keys), context.account.postbox.loadedPeerWithId(context.peerId)) |> map { values, selfPeer -> ([RenderedPeer], [PeerId: PeerStatusStringResult], Peer) in var presences:[PeerId: PeerStatusStringResult] = [:] for value in values.views { if let view = value.value as? PeerView { presences[view.peerId] = stringStatus(for: view, context: context) } } return (peers, presences, selfPeer) } |> take(1) } |> deliverOn(prepareQueue) |> map { values -> TableUpdateTransition in var entries:[SelectablePeersEntry] = [] var contains:[PeerId:PeerId] = [:] var i:Int32 = Int32.max if query.request.isSavedMessagesText || values.0.contains(where: {$0.peerId == context.peerId}), !share.excludePeerIds.contains(values.2.id) { let index = MessageIndex(id: MessageId(peerId: PeerId(0), namespace: 0, id: i), timestamp: i) entries.append(.plain(values.2, ChatListIndex(pinningIndex: 0, messageIndex: index), nil, true, multipleSelection)) i -= 1 contains[values.2.id] = values.2.id } for renderedPeer in values.0 { if let main = renderedPeer.peer { if contains[main.id] == nil { if share.possibilityPerformTo(main) { if let peer = renderedPeer.chatMainPeer { let index = MessageIndex(id: MessageId(peerId: PeerId(0), namespace: 0, id: i), timestamp: i) let id = ChatListIndex(pinningIndex: nil, messageIndex: index) i -= 1 if main.id.namespace == Namespaces.Peer.SecretChat { entries.append(.secretChat(peer, main.id, id, values.1[peer.id], true, multipleSelection)) } else { entries.append(.plain(peer, id, values.1[peer.id], true, multipleSelection)) } } contains[main.id] = main.id } } } } if entries.isEmpty { entries.append(.emptySearch) } entries.sort(by: <) return prepareEntries(from: previous.swap(entries), to: entries, context: context, initialSize: initialSize, animated: false, multipleSelection: multipleSelection, selectInteraction:selectInteraction) } } else { return .complete() } } |> deliverOnMainQueue let signal:Signal<TableUpdateTransition, NoError> = defaultItems |> deliverOnMainQueue |> mapToSignal { [weak self] defaultSelected in self?.selectInteractions.update(animated: false, { value in var value = value for peer in defaultSelected { value = value.withToggledSelected(peer.id, peer: peer) } return value }) return list } |> deliverOnMainQueue disposable.set(signal.start(next: { [weak self] transition in self?.genericView.applyTransition(transition) self?.readyOnce() })) request.set(.single(.Initial(100, nil))) } override var canBecomeResponder: Bool { return true } override func becomeFirstResponder() -> Bool? { _ = window?.makeFirstResponder(nil) return false } override func firstResponder() -> NSResponder? { if window?.firstResponder == genericView.textView.inputView { return genericView.textView.inputView } if let event = NSApp.currentEvent { if event.type == .keyDown { switch event.keyCode { case KeyboardKey.UpArrow.rawValue: return window?.firstResponder case KeyboardKey.DownArrow.rawValue: return window?.firstResponder default: break } } } if selectInteractions.presentation.multipleSelection { return genericView.tokenizedView.responder } else { return genericView.basicSearchView.input } } override func returnKeyAction() -> KeyHandlerResult { if let event = NSApp.currentEvent, !FastSettings.checkSendingAbility(for: event) { return .rejected } return invoke() } private func invoke() -> KeyHandlerResult { if !genericView.tokenizedView.query.isEmpty { if !genericView.tableView.isEmpty, let item = genericView.tableView.item(at: 0) as? ShortPeerRowItem { selectInteractions.update({$0.withToggledSelected(item.peer.id, peer: item.peer)}) } return .invoked } if !selectInteractions.presentation.peers.isEmpty || share.alwaysEnableDone { let ids = selectInteractions.presentation.selected let account = share.context.account let peerAndData:Signal<[(TelegramChannel, CachedChannelData?)], NoError> = share.context.account.postbox.transaction { transaction in var result:[(TelegramChannel, CachedChannelData?)] = [] for id in ids { if let peer = transaction.getPeer(id) as? TelegramChannel { result.append((peer, transaction.getPeerCachedData(peerId: id) as? CachedChannelData)) } } return result } |> deliverOnMainQueue let signal = peerAndData |> mapToSignal { peerAndData in return account.postbox.unsentMessageIdsView() |> take(1) |> map { (peerAndData, Set($0.ids.map { $0.peerId })) } } |> deliverOnMainQueue _ = signal.start(next: { [weak self] (peerAndData, unsentIds) in guard let `self` = self else { return } let share = self.share let comment = self.genericView.textView.string() enum ShareFailedTarget { case token case comment } struct ShareFailedReason { let peerId:PeerId let reason: String let target: ShareFailedTarget } var failed:[ShareFailedReason] = [] for (peer, cachedData) in peerAndData { inner: switch peer.info { case let .group(info): if info.flags.contains(.slowModeEnabled) && (peer.adminRights == nil && !peer.flags.contains(.isCreator)) { if let cachedData = cachedData, let validUntil = cachedData.slowModeValidUntilTimestamp { if validUntil > share.context.timestamp { failed.append(ShareFailedReason(peerId: peer.id, reason: slowModeTooltipText(validUntil - share.context.timestamp), target: .token)) } } if !comment.isEmpty { failed.append(ShareFailedReason(peerId: peer.id, reason: strings().slowModeForwardCommentError, target: .comment)) } if unsentIds.contains(peer.id) { failed.append(ShareFailedReason(peerId: peer.id, reason: strings().slowModeMultipleError, target: .token)) } } default: break inner } } if failed.isEmpty { self.genericView.tokenizedView.removeAllFailed(animated: true) _ = share.perform(to: Array(ids), threadId: nil, comment: self.contextChatInteraction.presentation.interfaceState.inputState).start() self.emoji.popover?.hide() self.close() } else { self.genericView.tokenizedView.markAsFailed(failed.map { $0.peerId.toInt64() }, animated: true) let last = failed.last! switch last.target { case .comment: self.genericView.textView.shake() tooltip(for: self.genericView.bottomSeparator, text: last.reason) case .token: self.genericView.tokenizedView.addTooltip(for: last.peerId.toInt64(), text: last.reason) } } }) return .invoked } if share is ForwardMessagesObject { if genericView.tableView.highlightedItem() == nil, !genericView.tableView.isEmpty { let item = genericView.tableView.item(at: 0) if let item = item as? ShortPeerRowItem { item.action() } _ = genericView.tableView.select(item: item) return .invoked } } return .rejected } private func cancelForum(animated: Bool) { self.forumPeerId.set(nil) self.forumDisposable.set(nil) self.genericView.cancelForum(animated: animated) self.genericView.basicSearchView.cancel(animated) } override func escapeKeyAction() -> KeyHandlerResult { if genericView.tableView.highlightedItem() != nil { genericView.tableView.cancelHighlight() return .invoked } if genericView.inForumMode { self.cancelForum(animated: true) return .invoked } if genericView.tokenizedView.state == .Focus { _ = window?.makeFirstResponder(nil) return .invoked } return .rejected } private let emoji: EmojiesController init(_ share:ShareObject) { self.share = share emoji = EmojiesController(share.context) self.contextChatInteraction = ChatInteraction(chatLocation: .peer(PeerId(0)), context: share.context) inputContextHelper = InputContextHelper(chatInteraction: contextChatInteraction) super.init(frame: NSMakeRect(0, 0, 360, 400)) bar = .init(height: 0) contextChatInteraction.movePeerToInput = { [weak self] peer in if let strongSelf = self { let string = strongSelf.genericView.textView.string() let range = strongSelf.genericView.textView.selectedRange() let textInputState = ChatTextInputState(inputText: string, selectionRange: range.min ..< range.max, attributes: chatTextAttributes(from: strongSelf.genericView.textView.attributedString())) strongSelf.contextChatInteraction.update({$0.withUpdatedEffectiveInputState(textInputState)}) if let (range, _, _) = textInputStateContextQueryRangeAndType(textInputState, includeContext: false) { let inputText = textInputState.inputText let name:String = peer.addressName ?? peer.compactDisplayTitle let distance = inputText.distance(from: range.lowerBound, to: range.upperBound) let replacementText = name + " " let atLength = peer.addressName != nil ? 0 : 1 let range = strongSelf.contextChatInteraction.appendText(replacementText, selectedRange: textInputState.selectionRange.lowerBound - distance - atLength ..< textInputState.selectionRange.upperBound) if peer.addressName == nil { let state = strongSelf.contextChatInteraction.presentation.effectiveInput var attributes = state.attributes attributes.append(.uid(range.lowerBound ..< range.upperBound - 1, peer.id.id._internalGetInt64Value())) let updatedState = ChatTextInputState(inputText: state.inputText, selectionRange: state.selectionRange, attributes: attributes) strongSelf.contextChatInteraction.update({$0.withUpdatedEffectiveInputState(updatedState)}) } } } } bar = .init(height: 0) } func showEmoji(for control: Control) { showPopover(for: control, with: emoji) } func textViewHeightChanged(_ height: CGFloat, animated: Bool) { updateSize(frame.width, animated: animated) genericView.textViewUpdateHeight(height, animated) } func textViewEnterPressed(_ event: NSEvent) -> Bool { if FastSettings.checkSendingAbility(for: event) { _ = returnKeyAction() return true } return false } func textViewTextDidChange(_ string: String) { let range = self.genericView.textView.selectedRange() self.selectInteractions.update { $0.withUpdatedComment(.init(string: string, range: range)) } let attributed = genericView.textView.attributedString() let state = ChatTextInputState(inputText: attributed.string, selectionRange: range.location ..< range.location + range.length, attributes: chatTextAttributes(from: attributed)) contextChatInteraction.update({$0.withUpdatedEffectiveInputState(state)}) } func textViewTextDidChangeSelectedRange(_ range: NSRange) { let string = self.genericView.textView.string() self.selectInteractions.update { $0.withUpdatedComment(.init(string: string, range: range)) } let attributed = genericView.textView.attributedString() let state = ChatTextInputState(inputText: attributed.string, selectionRange: range.location ..< range.location + range.length, attributes: chatTextAttributes(from: attributed)) contextChatInteraction.update({$0.withUpdatedEffectiveInputState(state)}) } func textViewDidReachedLimit(_ textView: Any) { genericView.textView.shake() } func textViewDidPaste(_ pasteboard: NSPasteboard) -> Bool { return false } func textViewSize(_ textView: TGModernGrowingTextView!) -> NSSize { return NSMakeSize(frame.width - 40, textView.frame.height) } func textViewIsTypingEnabled() -> Bool { return true } func canTransformInputText() -> Bool { return true } func maxCharactersLimit(_ textView: TGModernGrowingTextView!) -> Int32 { return 1024 } private func updateSize(_ width: CGFloat, animated: Bool) { if let contentSize = self.window?.contentView?.frame.size { self.modal?.resize(with:NSMakeSize(width, min(contentSize.height - 100, genericView.tableView.listHeight + max(genericView.additionHeight, 88))), animated: animated) } } override var modalInteractions: ModalInteractions? { if !share.hasCaptionView { return ModalInteractions(acceptTitle: share.interactionOk, accept: { [weak self] in _ = self?.invoke() }, drawBorder: true, height: 50, singleButton: true) } else { return nil } } override func measure(size: NSSize) { self.modal?.resize(with:NSMakeSize(genericView.frame.width, min(size.height - 100, genericView.tableView.listHeight + max(genericView.additionHeight, 88))), animated: false) } override var dynamicSize: Bool { return true } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } override func close(animationType: ModalAnimationCloseBehaviour = .common) { if self.share.emptyPerformOnClose { _ = self.share.perform(to: [], threadId: nil).start() } super.close(animationType: animationType) } deinit { disposable.dispose() tokenDisposable.dispose() exportLinkDisposable.dispose() forumDisposable.dispose() } }
gpl-2.0
5ca7f3290960929431ca05b6d4b876d5
43.938996
708
0.559066
5.347909
false
false
false
false
mdiep/Tentacle
Sources/Tentacle/RepositoryInfo.swift
1
4860
// // RepositoryInfo.swift // Tentacle // // Created by Romain Pouclet on 2016-08-02. // Copyright © 2016 Matt Diephouse. All rights reserved. // import Foundation public struct RepositoryInfo: CustomStringConvertible, ResourceType, Identifiable { /// The id of the repository public let id: ID<RepositoryInfo> /// The basic informations about the owner of the repository, either an User or an Organization public let owner: UserInfo /// The name of the repository public let name: String /// The name of the repository prefixed with the name of the owner public let nameWithOwner: String /// The description of the repository public let body: String? /// The URL of the repository to load in a browser public let url: URL /// The URL of the homepage for this repository public let homepage: URL? /// Contains true if the repository is private public let isPrivate: Bool /// Contains true if the repository is a fork public let isFork: Bool /// The number of forks of this repository public let forksCount: Int /// The number of users who starred this repository public let stargazersCount: Int /// The number of users watching this repository public let watchersCount: Int /// The number of open issues in this repository public let openIssuesCount: Int /// The date the last push happened at public let pushedAt: Date /// The date the repository was created at public let createdAt: Date /// The date the repository was last updated public let updatedAt: Date public var description: String { return nameWithOwner } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.id = try container.decode(ID.self, forKey: .id) self.owner = try container.decode(UserInfo.self, forKey: .owner) self.name = try container.decode(String.self, forKey: .name) self.nameWithOwner = try container.decode(String.self, forKey: .nameWithOwner) self.body = try container.decodeIfPresent(String.self, forKey: .body) self.url = try container.decode(URL.self, forKey: .url) self.homepage = try? container.decode(URL.self, forKey: .homepage) self.isPrivate = try container.decode(Bool.self, forKey: .isPrivate) self.isFork = try container.decode(Bool.self, forKey: .isFork) self.forksCount = try container.decode(Int.self, forKey: .forksCount) self.stargazersCount = try container.decode(Int.self, forKey: .stargazersCount) self.watchersCount = try container.decode(Int.self, forKey: .watchersCount) self.openIssuesCount = try container.decode(Int.self, forKey: .openIssuesCount) self.pushedAt = try container.decode(Date.self, forKey: .pushedAt) self.createdAt = try container.decode(Date.self, forKey: .createdAt) self.updatedAt = try container.decode(Date.self, forKey: .updatedAt) } public init(id: ID<RepositoryInfo>, owner: UserInfo, name: String, nameWithOwner: String, body: String?, url: URL, homepage: URL?, isPrivate: Bool, isFork: Bool, forksCount: Int, stargazersCount: Int, watchersCount: Int, openIssuesCount: Int, pushedAt: Date, createdAt: Date, updatedAt: Date) { self.id = id self.owner = owner self.name = name self.nameWithOwner = nameWithOwner self.body = body self.url = url self.homepage = homepage self.isPrivate = isPrivate self.isFork = isFork self.forksCount = forksCount self.stargazersCount = stargazersCount self.watchersCount = watchersCount self.openIssuesCount = openIssuesCount self.pushedAt = pushedAt self.createdAt = createdAt self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case id case owner case name case nameWithOwner = "full_name" case body = "description" case url = "html_url" case homepage case isPrivate = "private" case isFork = "fork" case forksCount = "forks_count" case stargazersCount = "stargazers_count" case watchersCount = "watchers_count" case openIssuesCount = "open_issues_count" case pushedAt = "pushed_at" case createdAt = "created_at" case updatedAt = "updated_at" } } extension RepositoryInfo: Hashable { public static func ==(lhs: RepositoryInfo, rhs: RepositoryInfo) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name && lhs.nameWithOwner == rhs.nameWithOwner } public func hash(into hasher: inout Hasher) { id.hash(into: &hasher) nameWithOwner.hash(into: &hasher) } }
mit
a5315303c03b9ff083caa08e256aa7bd
34.992593
298
0.66701
4.353943
false
false
false
false
PlanTeam/BSON
Sources/BSON/Types/Binary.swift
1
3248
import Foundation import NIO public struct Binary: Primitive, Hashable, @unchecked Sendable { public static func == (lhs: Binary, rhs: Binary) -> Bool { return lhs.subType.identifier == rhs.subType.identifier && lhs.storage == rhs.storage } public func hash(into hasher: inout Hasher) { subType.identifier.hash(into: &hasher) storage.withUnsafeReadableBytes { buffer in hasher.combine(bytes: buffer) } } public enum SubType: Sendable { case generic case function case uuid case md5 case userDefined(UInt8) init(_ byte: UInt8) { switch byte { case 0x00: self = .generic case 0x01: self = .function case 0x04: self = .uuid case 0x05: self = .md5 default: self = .userDefined(byte) } } var identifier: UInt8 { switch self { case .generic: return 0x00 case .function: return 0x01 case .uuid: return 0x04 case .md5: return 0x05 case .userDefined(let byte): return byte } } } /// A single byte indicating the data type public var subType: SubType /// The underlying data storage of the Binary instance public private(set) var storage: ByteBuffer /// The data stored public var data: Data { get { return storage.withUnsafeReadableBytes { buffer in let bytes = buffer.bindMemory(to: UInt8.self) return Data(buffer: bytes) } } set { storage = Document.allocator.buffer(capacity: newValue.count) storage.writeBytes(newValue) } } /// Initializes a new Binary from the given ByteBuffer /// /// - parameter buffer: The ByteBuffer to use as storage. The buffer will be sliced. public init(subType: SubType = .generic, buffer: ByteBuffer) { self.subType = subType self.storage = buffer } // TODO: Encode / decode the subtype public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let container = container as? AnySingleValueBSONDecodingContainer { self = try container.decodeBinary() } else { let data = try container.decode(Data.self) self.subType = .generic self.storage = Document.allocator.buffer(capacity: data.count) self.storage.writeBytes(data) } } public func encode(to encoder: Encoder) throws { if encoder is AnyBSONEncoder { let container = encoder.singleValueContainer() if var container = container as? AnySingleValueBSONEncodingContainer { try container.encode(primitive: self) } else { try self.data.encode(to: encoder) } } else { try self.data.encode(to: encoder) } } /// The amount of data, in bytes, stored in this Binary public var count: Int { return storage.readableBytes } }
mit
7b84d2f1e0e939c5861addd8d789f338
30.230769
93
0.566502
4.855007
false
false
false
false
jtbandes/swift
test/IRGen/zero_size_types.swift
3
1206
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-build-swift -Xllvm -sil-disable-pass="Generic Function Specialization" %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s // REQUIRES: executable_test public struct EmptyStruct { } public enum SingleCaseEnum { case A } public struct GenStruct<T> { var t: T } @inline(never) func fail() { fatalError("size/stride mismatch") } @inline(never) public func testit<T>(_ t: T) { if MemoryLayout<T>.size != 0 { fail() } if MemoryLayout<T>.stride != 1 { fail() } if MemoryLayout<GenStruct<T>>.size != 0 { fail() } if MemoryLayout<GenStruct<T>>.stride != 1 { fail() } } // Test size and stride which are loaded from the value witness tables. testit(EmptyStruct()) testit(()) testit(SingleCaseEnum.A) // Test size and stride which are computed as constants in IRGen. if MemoryLayout<()>.size != 0 { fail() } if MemoryLayout<()>.stride != 1 { fail() } if MemoryLayout<EmptyStruct>.size != 0 { fail() } if MemoryLayout<EmptyStruct>.stride != 1 { fail() } if MemoryLayout<SingleCaseEnum>.size != 0 { fail() } if MemoryLayout<SingleCaseEnum>.stride != 1 { fail() } // CHECK: success print("success")
apache-2.0
b0e7acae8cae366963964210208667b8
16.478261
101
0.647595
3.216
false
true
false
false
CoderST/DYZB
DYZB/DYZB/Class/Profile/ViewModel/LocationSubVM.swift
1
1118
// // LocationSubVM.swift // DYZB // // Created by xiudou on 2017/7/14. // Copyright © 2017年 xiudo. All rights reserved. // import UIKit class LocationSubVM: NSObject { } extension LocationSubVM { func upLoadLocationDatas(_ locationString : String ,_ finishCallBack:@escaping ()->(), _ messageCallBack :@escaping (_ message : String)->(), _ failCallBack :@escaping ()->()){ let urlString = "http://capi.douyucdn.cn/api/v1/set_userinfo_custom?aid=ios&client_sys=ios&time=\(Date.getNowDate())&auth=\(AUTH)" let params = ["token" : TOKEN, "location" : locationString] NetworkTools.requestData(.post, URLString: urlString, parameters: params) { (result) in guard let resultDict = result as? [String : Any] else { return } guard let error = resultDict["error"] as? Int else{ return } guard let data = resultDict["data"] as? String else { return } if error != 0 { messageCallBack(data) return } finishCallBack() } } }
mit
7c67d7efd53f9a626e3dd06c8357ba8c
31.794118
180
0.580269
4.338521
false
false
false
false
dev-gao/GYPageViewController
GYPageViewController/Classes/UIViewController+ChildController.swift
1
2199
// // UIViewController+ChildController.swift // PreciousMetals // // Created by GaoYu on 16/5/29. // Copyright © 2016年 Dev-GY. All rights reserved. // import UIKit extension UIViewController { func gy_addChildViewController(viewController:UIViewController) { self.gy_addChildViewController(viewController,frame: self.view.bounds) } func gy_addChildViewController(viewController:UIViewController,inView:UIView,withFrame:CGRect) { self.gy_addChildViewController(viewController) { (superViewController,childViewController) in childViewController.view.frame = withFrame; if inView.subviews.contains(viewController.view) == false { inView.addSubview(viewController.view) } } } func gy_addChildViewController(viewController:UIViewController,frame:CGRect) { self.gy_addChildViewController(viewController) { (superViewController,childViewController) in childViewController.view.frame = frame; if superViewController.view.subviews.contains(viewController.view) == false { superViewController.view.addSubview(viewController.view) } } } func gy_addChildViewController(viewController:UIViewController, setSubViewAction:((superViewController:UIViewController,childViewController:UIViewController) -> Void)?) { if self.childViewControllers.contains(viewController) == false { self.addChildViewController(viewController) } setSubViewAction?(superViewController:self,childViewController: viewController) if self.childViewControllers.contains(viewController) == false { viewController.didMoveToParentViewController(self) } } func gy_removeFromParentViewControllerOnly() { self.willMoveToParentViewController(nil) self.removeFromParentViewController() } func gy_removeFromParentViewController() { self.willMoveToParentViewController(nil) self.view.removeFromSuperview() self.removeFromParentViewController() } }
mit
1019185e5f344e7a1436ac2d8f224ad1
36.220339
141
0.684882
5.733681
false
false
false
false
mluisbrown/iCalendar
Sources/iCalendar/EventValue.swift
1
901
// // EventValue.swift // iCalendar // // Created by Michael Brown on 26/05/2017. // Copyright © 2017 iCalendar. All rights reserved. // import Foundation protocol DateOrString {} extension String: DateOrString {} extension Date: DateOrString {} protocol EventValueRepresentable { var textValue: String? { get } var dateValue: Date? { get } } struct EventValue<T>: EventValueRepresentable where T: DateOrString { let value: T var textValue: String? { return value as? String } var dateValue: Date? { return value as? Date } } func ==(lhs: EventValueRepresentable, rhs: EventValueRepresentable) -> Bool { return lhs.dateValue == rhs.dateValue || lhs.textValue == rhs.textValue } func ==(lhs: (String, EventValueRepresentable), rhs: (String, EventValueRepresentable)) -> Bool { return lhs.0 == rhs.0 && lhs.1 == rhs.1 }
mit
c1fb223b9a2ce7898e55a66ffc1c5484
20.95122
97
0.664444
3.846154
false
false
false
false
marcelganczak/swift-js-transpiler
test/weheartswift/dictionaries-1.swift
1
718
var code = [ "a" : "b", "b" : "c", "c" : "d", "d" : "e", "e" : "f", "f" : "g", "g" : "h", "h" : "i", "i" : "j", "j" : "k", "k" : "l", "l" : "m", "m" : "n", "n" : "o", "o" : "p", "p" : "q", "q" : "r", "r" : "s", "s" : "t", "t" : "u", "u" : "v", "v" : "w", "w" : "x", "x" : "y", "y" : "z", "z" : "a" ] var message = "hello world" var encodedMessage = "" for char in message.characters { var character = "\(char)" if let encodedChar = code[character] { // letter encodedMessage += encodedChar } else { // space encodedMessage += character } } print(encodedMessage)
mit
071926b116d011d6350a586d5e874a93
14.630435
42
0.346797
2.484429
false
false
false
false
hlprmnky/tree-hugger-ios
Pods/SwiftHamcrest/Hamcrest/Descriptions.swift
1
1543
import Foundation func describe<T>(value: T) -> String { if let stringArray = value as? [String] { return joinDescriptions(stringArray.map {describe($0)}) } if let string = value as? String { return "\"\(string)\"" } return toString(value) } func describeAddress<T: AnyObject>(object: T) -> String { return NSString(format: "%p", unsafeBitCast(object, Int.self)) as String } func describeMismatch<T>(value: T, description: String, mismatchDescription: String?) -> String { return "GOT: " + describeActualValue(value, mismatchDescription) + ", EXPECTED: \(description)" } func describeActualValue<T>(value: T, mismatchDescription: String?) -> String { return describe(value) + (mismatchDescription != nil ? " (\(mismatchDescription!))" : "") } func joinDescriptions(descriptions: [String]) -> String { return joinStrings(descriptions) } func joinDescriptions(descriptions: [String?]) -> String? { let notNil = filterNotNil(descriptions) return notNil.isEmpty ? nil : joinStrings(notNil) } func joinMatcherDescriptions<T>(matchers: [Matcher<T>], prefix: String = "all of") -> String { if matchers.count == 1 { return matchers[0].description } else { return prefix + " " + joinDescriptions(matchers.map({$0.description})) } } private func joinStrings(strings: [String]) -> String { switch (strings.count) { case 0: return "none" case 1: return strings[0] default: return "[" + join(", ", strings) + "]" } }
mit
283a7b68db99989962e515c519b5ad25
29.27451
99
0.65068
3.946292
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Settings/ChangingDetails/Views/ValueValidationCell.swift
1
3354
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit /** * A cell to show a value validation in the settings. */ class ValueValidationCell: UITableViewCell { let label: UILabel = { let label = UILabel() label.font = AuthenticationStepController.errorMessageFont label.textAlignment = .left label.numberOfLines = 0 return label }() /// The initial validation to use. let initialValidation: ValueValidation // MARK: - Initialization /// Creates the cell with the default validation to display. init(initialValidation: ValueValidation) { self.initialValidation = initialValidation super.init(style: .default, reuseIdentifier: nil) setupViews() createConstraints() updateValidation(initialValidation) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupViews() { selectionStyle = .none backgroundColor = .clear contentView.addSubview(label) } private func createConstraints() { label.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -(24 + ValidatedTextField.ConfirmButtonWidth)), label.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8), label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8), contentView.heightAnchor.constraint(greaterThanOrEqualToConstant: 56) ]) } // MARK: - Content /// Updates the label for the displayed validation. func updateValidation(_ validation: ValueValidation?) { switch validation { case .info(let infoText)?: label.accessibilityIdentifier = "validation-rules" label.text = infoText label.textColor = UIColor.Team.placeholderColor case .error(let error, let showVisualFeedback)?: if !showVisualFeedback { // If we do not want to show an error (eg if all the text was deleted, // use the initial info return updateValidation(initialValidation) } label.accessibilityIdentifier = "validation-failure" label.text = error.errorDescription label.textColor = UIColor.from(scheme: .errorIndicator, variant: .dark) case nil: updateValidation(initialValidation) } } }
gpl-3.0
5e6ebb32edd4c1386b7623e632ec8e30
33.22449
138
0.672033
5.097264
false
false
false
false
wireapp/wire-ios
Wire-iOS Tests/App Lock/Tests/AppLockModuleInteractorTests.swift
1
10133
// // Wire // Copyright (C) 2021 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import XCTest @testable import Wire final class AppLockModuleInteractorTests: XCTestCase { private var sut: AppLockModule.Interactor! private var presenter: AppLockModule.MockPresenter! private var session: AppLockModule.MockSession! private var appLock: AppLockModule.MockAppLockController! private var authenticationType: AppLockModule.MockAuthenticationTypeDetector! private var applicationStateProvider: AppLockModule.MockApplicationStateProvider! override func setUp() { super.setUp() presenter = .init() session = .init() appLock = .init() authenticationType = .init() applicationStateProvider = .init() session.appLockController = appLock sut = .init(session: session, authenticationType: authenticationType, applicationStateProvider: applicationStateProvider) sut.presenter = presenter } override func tearDown() { sut = nil presenter = nil session = nil appLock = nil authenticationType = nil applicationStateProvider = nil super.tearDown() } // MARK: - Initiate authentication func test_InitiateAuthentication_NeedsToCreateCustomPasscode_Required() { // Given appLock.isCustomPasscodeSet = false appLock.requireCustomPasscode = true // When sut.executeRequest(.initiateAuthentication(requireActiveApp: false)) // Then XCTAssertEqual(presenter.results, [.customPasscodeCreationNeeded(shouldInform: false)]) } func test_InitiaAuthentication_NeedsToCreateCustomPasscode_NotRequired() { // Given appLock.isCustomPasscodeSet = false appLock.requireCustomPasscode = false authenticationType.current = .unavailable // When sut.executeRequest(.initiateAuthentication(requireActiveApp: false)) // Then XCTAssertEqual(presenter.results, [.customPasscodeCreationNeeded(shouldInform: false)]) } func test_InitiaAuthentication_NeedsToCreatePasscode_InformingUserOfConfigChange() { // Given appLock.isCustomPasscodeSet = false appLock.requireCustomPasscode = true appLock.needsToNotifyUser = true // When sut.executeRequest(.initiateAuthentication(requireActiveApp: false)) // Then XCTAssertEqual(presenter.results, [.customPasscodeCreationNeeded(shouldInform: true)]) } func test_InitiateAuthentication_DoesNotNeedToCreateCustomPasscode() { // Given appLock.isCustomPasscodeSet = true // When sut.executeRequest(.initiateAuthentication(requireActiveApp: false)) // Then XCTAssertEqual(presenter.results, [.readyForAuthentication(shouldInform: false)]) } func test_InitiateAuthentication_DoesNotNeedToCreateCustomPasscode_InformingUserOfConfigChange() { // Given appLock.isCustomPasscodeSet = true appLock.needsToNotifyUser = true // When sut.executeRequest(.initiateAuthentication(requireActiveApp: false)) // Then XCTAssertEqual(presenter.results, [.readyForAuthentication(shouldInform: true)]) } func test_InitiateAuthentication_DoesNotNeedToCreateCustomPasscode_WhenDatabaseIsLocked() { // Given session.lock = .database appLock.isCustomPasscodeSet = false authenticationType.current = .unavailable // When sut.executeRequest(.initiateAuthentication(requireActiveApp: false)) // Then XCTAssertEqual(presenter.results, [.readyForAuthentication(shouldInform: false)]) } func test_InitiateAuthentication_SessionIsAlreadyUnlocked() { // Given session.lock = .none // When sut.executeRequest(.initiateAuthentication(requireActiveApp: false)) // Then XCTAssertEqual(appLock.methodCalls.evaluateAuthentication.count, 0) XCTAssertEqual(appLock.methodCalls.open.count, 1) } func test_InitiateAuthentication_RequireActiveApp_ReturnsNothingIfAppIsInBackground() { // Given applicationStateProvider.applicationState = .background appLock.isCustomPasscodeSet = true // When sut.executeRequest(.initiateAuthentication(requireActiveApp: true)) // Then XCTAssertEqual(presenter.results, []) } func test_InitiateAuthentication_NeedsToCreateCustomPasscodeAndRequireActiveApp_ReturnsNothingIfAppIsInBackground() { // Given applicationStateProvider.applicationState = .background appLock.isCustomPasscodeSet = false appLock.requireCustomPasscode = true // When sut.executeRequest(.initiateAuthentication(requireActiveApp: true)) // Then XCTAssertEqual(presenter.results, []) } // MARK: - Evaluate authentication func test_EvaluateAuthentication_SessionIsAlreadyUnlocked() { // Given session.lock = .none // When sut.executeRequest(.evaluateAuthentication) XCTAssertTrue(waitForGroupsToBeEmpty([sut.dispatchGroup])) // Then XCTAssertEqual(appLock.methodCalls.evaluateAuthentication.count, 0) XCTAssertEqual(appLock.methodCalls.open.count, 1) } func test_EvaluateAuthentication_ScreenLock() { // Given session.lock = .screen appLock.requireCustomPasscode = false // When sut.executeRequest(.evaluateAuthentication) XCTAssertTrue(waitForGroupsToBeEmpty([sut.dispatchGroup])) // Then XCTAssertEqual(appLock.methodCalls.evaluateAuthentication.count, 1) let preference = appLock.methodCalls.evaluateAuthentication[0].preference XCTAssertEqual(preference, .deviceThenCustom) } func test_EvaluateAuthentication_ScreenLock_RequireCustomPasscode() { // Given session.lock = .screen appLock.requireCustomPasscode = true // When sut.executeRequest(.evaluateAuthentication) XCTAssertTrue(waitForGroupsToBeEmpty([sut.dispatchGroup])) // Then XCTAssertEqual(appLock.methodCalls.evaluateAuthentication.count, 1) let preference = appLock.methodCalls.evaluateAuthentication[0].preference XCTAssertEqual(preference, .customOnly) } func test_EvaluateAuthentication_DatabaseLock() { // Given session.lock = .database // When sut.executeRequest(.evaluateAuthentication) XCTAssertTrue(waitForGroupsToBeEmpty([sut.dispatchGroup])) // Then XCTAssertEqual(appLock.methodCalls.evaluateAuthentication.count, 1) let preference = appLock.methodCalls.evaluateAuthentication[0].preference XCTAssertEqual(preference, .deviceOnly) } func test_EvaluateAuthentication_Granted() { // Given session.lock = .database appLock._authenticationResult = .granted // When sut.executeRequest(.evaluateAuthentication) XCTAssertTrue(waitForGroupsToBeEmpty([sut.dispatchGroup])) // Then XCTAssertEqual(session.methodCalls.unlockDatabase.count, 1) XCTAssertEqual(appLock.methodCalls.open.count, 1) } // @SF.Locking @SF.Storage @TSFI.FS-IOS @TSFI.Enclave-IOS @S0.1 // Check that database and screen is not unlocked when user denies authentication func test_EvaluateAuthentication_Denied() { // Given session.lock = .database appLock._authenticationResult = .denied authenticationType.current = .faceID // When sut.executeRequest(.evaluateAuthentication) XCTAssertTrue(waitForGroupsToBeEmpty([sut.dispatchGroup])) // Then XCTAssertEqual(session.methodCalls.unlockDatabase.count, 0) XCTAssertEqual(appLock.methodCalls.open.count, 0) XCTAssertEqual(presenter.results, [.authenticationDenied(.faceID)]) } func test_EvaluateAuthentication_NeedCustomPasscode() { // Given session.lock = .screen appLock._authenticationResult = .needCustomPasscode // When sut.executeRequest(.evaluateAuthentication) XCTAssertTrue(waitForGroupsToBeEmpty([sut.dispatchGroup])) // Then XCTAssertEqual(session.methodCalls.unlockDatabase.count, 0) XCTAssertEqual(appLock.methodCalls.open.count, 0) XCTAssertEqual(presenter.results, [.customPasscodeNeeded]) } // @SF.Locking @SF.Storage @TSFI.FS-IOS @TSFI.Enclave-IOS @S0.1 // Check that database and screen is not unlocked if user disables all authentication types func test_EvaluateAuthentication_Unavailable() { // Given session.lock = .screen appLock._authenticationResult = .unavailable // When sut.executeRequest(.evaluateAuthentication) XCTAssertTrue(waitForGroupsToBeEmpty([sut.dispatchGroup])) // Then XCTAssertEqual(session.methodCalls.unlockDatabase.count, 0) XCTAssertEqual(appLock.methodCalls.open.count, 0) XCTAssertEqual(presenter.results, [.authenticationUnavailable]) } // MARK: - Open app lock func test_ItOpensAppLock() { // When sut.executeRequest(.openAppLock) // Then XCTAssertEqual(appLock.methodCalls.open.count, 1) } }
gpl-3.0
14a489d204485959ec63efd2cb0b4fd9
31.899351
121
0.68795
5.109934
false
true
false
false
dboyliao/NumSwift
NumSwift/Source/Signal/Hilbert.swift
1
3263
// // Dear maintainer: // // When I wrote this code, only I and God // know what it was. // Now, only God knows! // // So if you are done trying to 'optimize' // this routine (and failed), // please increment the following counter // as warning to the next guy: // // var TotalHoursWastedHere = 0 // // Reference: http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered import Accelerate /** Compute the analytic signal, using the Hilbert transform. (1D signal) - Note: the implementation of the fft is limited to process signal with length of power of 2. That is, the signal you pass in may be truncated to shorter signals. #### References: 1. Wikipedia, "Analytic signal". http://en.wikipedia.org/wiki/Analytic_signal - Parameters: - x: array of the signal. - Returns: a tuple consists of the real part and the imaginary part of the analytic signal. */ public func hilbert(_ x:[Double]) -> (realp:[Double], imagp:[Double]) { let signal = [Double](x) let zeros = [Double](repeating: 0.0, count: signal.count) var coef_sig = fft(signal, imagp:zeros) let N_fft = coef_sig.realp.count // Setup the step function `U` in the hilbert transform. // Represent as an array. var step_fun = [Double](repeating: 0.0, count: N_fft) step_fun[0] = 1.0 step_fun[N_fft/2] = 1.0 var two = 2.0 vDSP_vfillD(&two, &(step_fun[1]), 1, vDSP_Length(N_fft/2 - 1)) var output_realp = [Double](repeating: 0.0, count: N_fft) var output_imagp = [Double](repeating: 0.0, count: N_fft) vDSP_vmulD(&(coef_sig.realp), 1, &step_fun, 1, &output_realp, 1, vDSP_Length(N_fft)) vDSP_vmulD(&(coef_sig.imagp), 1, &step_fun, 1, &output_imagp, 1, vDSP_Length(N_fft)) return ifft(output_realp, imagp:output_imagp) } /** Compute the analytic signal, using the Hilbert transform. (1D signal) - Note: the implementation of the fft is limited to process signal with length of power of 2. That is, the signal you pass in may be truncated to shorter signals. #### References: 1. Wikipedia, "Analytic signal". http://en.wikipedia.org/wiki/Analytic_signal - Parameters: - x: array of the signal. - Returns: a tuple consists of the real part and the imaginary part of the analytic signal. */ public func hilbert(_ x:[Float]) -> (realp:[Float], imagp:[Float]) { let signal = [Float](x) let zeros = [Float](repeating: 0.0, count: signal.count) var coef_sig = fft(signal, imagp:zeros) let N_fft = coef_sig.realp.count // Setup the step function `U` in the hilbert transform. // Represent as an array. var step_fun = [Float](repeating: 0.0, count: N_fft) step_fun[0] = Float(1.0) step_fun[N_fft/2] = Float(1.0) var two = Float(2.0) vDSP_vfill(&two, &(step_fun[1]), 1, vDSP_Length(N_fft/2 - 1)) var output_realp = [Float](repeating: 0.0, count: N_fft) var output_imagp = [Float](repeating: 0.0, count: N_fft) vDSP_vmul(&(coef_sig.realp), 1, &step_fun, 1, &output_realp, 1, vDSP_Length(N_fft)) vDSP_vmul(&(coef_sig.imagp), 1, &step_fun, 1, &output_imagp, 1, vDSP_Length(N_fft)) return ifft(output_realp, imagp:output_imagp) }
mit
39a78135c67bba774ad32d158cd0956d
31.63
121
0.650935
3.17104
false
false
false
false
imzyf/99-projects-of-swift
026-safe-area/026-safe-area/UIView/AttachedSafeAreaController.swift
1
1745
// // AttachedSafeareaControllerViewController.swift // 026-safe-area // // Created by moma on 2018/3/29. // Copyright © 2018年 yifans. All rights reserved. // import UIKit class AttachedSafeAreaController: UIViewController { let topSubview = CustomView() let bottomSubview = CustomView() override func viewDidLoad() { super.viewDidLoad() view.addSubview(topSubview) view.addSubview(bottomSubview) view.backgroundColor = .lightGray let tap = UITapGestureRecognizer(target: self, action: #selector(close)) topSubview.addGestureRecognizer(tap) topSubview.isUserInteractionEnabled = true } @objc func close() { dismiss(animated: true, completion: nil) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if #available(iOS 11.0, *) { topSubview.frame.origin.x = view.safeAreaInsets.left topSubview.frame.origin.y = view.safeAreaInsets.top topSubview.frame.size.width = view.bounds.width - view.safeAreaInsets.left - view.safeAreaInsets.right topSubview.frame.size.height = 200 bottomSubview.translatesAutoresizingMaskIntoConstraints = false bottomSubview.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true bottomSubview.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true bottomSubview.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true bottomSubview.heightAnchor.constraint(equalToConstant: 200).isActive = true } else { } } }
mit
d2115f1e5cd8da5fc8b05a33529d4883
34.55102
114
0.67566
4.991404
false
false
false
false
jeanpimentel/HonourBridge
HonourBridge/HonourBridge/Honour/Library/Rules/Email.swift
1
1013
// // Email.swift // Honour // // Created by Jean Pimentel on 5/19/15. // Copyright (c) 2015 Honour. All rights reserved. // import Foundation public class Email : Rule { public override func validate(value: String) -> Bool { if count(value) == 0 { return false } var range = NSMakeRange(0, count(value)) var error: NSError? var detector: NSDataDetector = NSDataDetector(types: NSTextCheckingType.Link.rawValue, error: &error)! if error != nil { return false } if let result = detector.firstMatchInString(value, options: NSMatchingOptions.Anchored, range: range) { if result.URL!.scheme != "mailto" { return false } if !NSEqualRanges(result.range, range) { return false } if value.hasPrefix("mailto") { return false } return true } return false } }
mit
9db6c456f17bd00718e9d53f2ba18a69
20.574468
111
0.538993
4.711628
false
false
false
false
leo-lp/LPIM
LPIM/Common/LPFileLocationHelper.swift
1
4152
// // LPFileLocationHelper.swift // LPIM // // Created by lipeng on 2017/6/17. // Copyright © 2017年 lipeng. All rights reserved. // public let kImageExt = "jpg" private let kRDVideo = "video" private let kRDImage = "image" import Foundation //#import <sys/stat.h> struct LPFileLocationHelper { static var appDocumentPath: String? = { guard let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { return nil } let appKey = LPConfig.shared.appKey let appDocumentPath = "\(path)/\(appKey)/" if !FileManager.default.fileExists(atPath: appDocumentPath) { do { try FileManager.default.createDirectory(atPath: appDocumentPath, withIntermediateDirectories: false, attributes: nil) assert(FileManager.default.fileExists(atPath: appDocumentPath)) var fileURL = URL(fileURLWithPath: appDocumentPath) var resourceValues = URLResourceValues() resourceValues.isExcludedFromBackup = true try fileURL.setResourceValues(resourceValues) } catch { log.error(error) return nil } } return appDocumentPath }() //+ (NSString *)getAppTempPath; //+ (NSString *)userDirectory; //+ (NSString *)genFilenameWithExt:(NSString *)ext; //+ (NSString *)filepathForVideo:(NSString *)filename; //+ (NSString *)filepathForImage:(NSString *)filename; } //+ (NSString *)getAppTempPath //{ // return NSTemporaryDirectory(); //} // //+ (NSString *)userDirectory //{ // NSString *documentPath = [NTESFileLocationHelper getAppDocumentPath]; // NSString *userID = [NIMSDK sharedSDK].loginManager.currentAccount; // if ([userID length] == 0) // { // DDLogError(@"Error: Get User Directory While UserID Is Empty"); // } // NSString* userDirectory= [NSString stringWithFormat:@"%@%@/",documentPath,userID]; // if (![[NSFileManager defaultManager] fileExistsAtPath:userDirectory]) // { // [[NSFileManager defaultManager] createDirectoryAtPath:userDirectory // withIntermediateDirectories:NO // attributes:nil // error:nil]; // // } // return userDirectory; //} // //+ (NSString *)resourceDir: (NSString *)resouceName //{ // NSString *dir = [[NTESFileLocationHelper userDirectory] stringByAppendingPathComponent:resouceName]; // if (![[NSFileManager defaultManager] fileExistsAtPath:dir]) // { // [[NSFileManager defaultManager] createDirectoryAtPath:dir // withIntermediateDirectories:NO // attributes:nil // error:nil]; // } // return dir; //} // // //+ (NSString *)filepathForVideo:(NSString *)filename //{ // return [NTESFileLocationHelper filepathForDir:RDVideo // filename:filename]; //} // //+ (NSString *)filepathForImage:(NSString *)filename //{ // return [NTESFileLocationHelper filepathForDir:RDImage // filename:filename]; //} // //+ (NSString *)genFilenameWithExt:(NSString *)ext //{ // CFUUIDRef uuid = CFUUIDCreate(nil); // NSString *uuidString = (__bridge_transfer NSString*)CFUUIDCreateString(nil, uuid); // CFRelease(uuid); // NSString *uuidStr = [[uuidString stringByReplacingOccurrencesOfString:@"-" withString:@""] lowercaseString]; // NSString *name = [NSString stringWithFormat:@"%@",uuidStr]; // return [ext length] ? [NSString stringWithFormat:@"%@.%@",name,ext]:name; //} // // //#pragma mark - 辅助方法 //+ (NSString *)filepathForDir:(NSString *)dirname // filename:(NSString *)filename //{ // return [[NTESFileLocationHelper resourceDir:dirname] stringByAppendingPathComponent:filename]; //} // //@end
mit
24acf4ae0233ae0b19e91e2f6954feba
32.395161
133
0.591645
4.737986
false
false
false
false
jdspoone/Recipinator
RecipeBook/CoreDataController.swift
1
6617
/* Written by Jeff Spooner */ import CoreData class CoreDataController: NSObject { private let managedObjectContext: NSManagedObjectContext var documentsDirectory: URL { return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! } var dataStoreType: String { return NSSQLiteStoreType } var dataStoreURL: URL { return documentsDirectory.appendingPathComponent("RecipeBook.sqlite") } var temporaryDataStoreURL: URL { return documentsDirectory.appendingPathComponent("TemporaryRecipeBook.sqlite") } var finalManagedObjectModel: NSManagedObjectModel { return NSManagedObjectModel(contentsOf: Bundle.main.url(forResource: "RecipeBook", withExtension: "momd")!)! } var managedObjectModelURLs: [URL] { // Initialize an empty array var urls = [URL]() // Get the path of the momd directory let momdURL = Bundle.main.url(forResource: "RecipeBook", withExtension: "momd")! do { // Get the names of the the files inside the momd directory let contents = try FileManager.default.contentsOfDirectory(atPath: momdURL.path) // Iterate over those file names for path in contents { // We're only interested in .mom files let suffixArray = Array(path.utf16.suffix(4)) if String(utf16CodeUnits: suffixArray, count: suffixArray.count) == ".mom" { // Construct a URL from the given path, and add it to the array of URLs let url = URL(fileURLWithPath: path, relativeTo: momdURL) urls.append(url) } } } catch let e { fatalError("error: \(e)") } return urls } // MARK: - override init() { self.managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) super.init() } func getDestinationModelAndMappingModel(for sourceModel: NSManagedObjectModel) -> (NSManagedObjectModel, NSMappingModel)? { // Iterate over the managed object model urls for url in managedObjectModelURLs { // Create a managed object model from the url let destinationModel = NSManagedObjectModel(contentsOf: url)! // Attempt to get a custom mapping model between the source and destination models // We're operating on the assumption that there is AT MOST 1 mapping model for any given source managed object model if let mappingModel = NSMappingModel(from: [Bundle.main], forSourceModel: sourceModel, destinationModel: destinationModel) { // If we're successful, return the destination model return (destinationModel, mappingModel) } } return nil } func migrateIteratively() throws { do { // Get the persistent store's metadata var sourceMetadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(ofType: dataStoreType, at: dataStoreURL, options: nil) // Determine if we need to migrate let compatible = finalManagedObjectModel.isConfiguration(withName: nil, compatibleWithStoreMetadata: sourceMetadata) // If a migration is needed if compatible == false { // Repeat while a migration is needed repeat { // Get the source model let sourceModel = NSManagedObjectModel.mergedModel(from: [Bundle.main], forStoreMetadata: sourceMetadata)! // Attempt to get the destination model and mapping model let (destinationModel, mappingModel) = getDestinationModelAndMappingModel(for: sourceModel)! // Create a migration manager let migrationManager = NSMigrationManager(sourceModel: sourceModel, destinationModel: destinationModel) // Ensure there is no file at the temporary data store url if FileManager.default.fileExists(atPath: temporaryDataStoreURL.path) { try FileManager.default.removeItem(at: temporaryDataStoreURL) } // Migrate the datastore try migrationManager.migrateStore(from: dataStoreURL, sourceType: NSSQLiteStoreType, options: nil, with: mappingModel, toDestinationURL: temporaryDataStoreURL, destinationType: NSSQLiteStoreType, destinationOptions: nil) // Move the migrated datastore to from the temporary location to the primary location try FileManager.default.removeItem(at: dataStoreURL) try FileManager.default.moveItem(at: temporaryDataStoreURL, to: dataStoreURL) // Update the source metadata sourceMetadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(ofType: dataStoreType, at: dataStoreURL, options: nil) } while finalManagedObjectModel.isConfiguration(withName: nil, compatibleWithStoreMetadata: sourceMetadata) == false } } // Throw any caught errors catch let e { throw e } } func getManagedObjectContext() -> NSManagedObjectContext { // If the managed object context's persistent store coordinator is nil if managedObjectContext.persistentStoreCoordinator == nil { // Create a persistent store coordinator let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: finalManagedObjectModel) do { // Conditionally clear the data store if ProcessInfo().arguments.contains("--clean") { if FileManager.default.fileExists(atPath: dataStoreURL.path) { try FileManager.default.removeItem(at: dataStoreURL) } } // If there is a file at the datastore path if FileManager.default.fileExists(atPath: dataStoreURL.path) { // Attempt iterative migration try migrateIteratively() } // Attempt to add the persistent store try persistentStoreCoordinator.addPersistentStore(ofType: dataStoreType, configurationName: nil, at: dataStoreURL, options: nil) } catch let e { fatalError("error: \(e)") } // Attach the persistent store coordinator to the managed object context managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator } // Return the managed object context return managedObjectContext } }
mit
0f35124a22c0e135b0522469c0412ef1
34.767568
234
0.654677
5.699397
false
false
false
false
toggl/superday
teferi/UI/Modules/On Boarding/OnboardingPage2.swift
1
6069
import UIKit class OnboardingPage2 : OnboardingPage { @IBOutlet private weak var textView: UIView! @IBOutlet private weak var timelineView: UIView! private var editedTimeSlot : TimeSlotEntity! private var timelineCells : [TimelineCell]! private var editedCell : TimelineCell! private var editView : EditTimeSlotView! private var touchCursor : UIImageView! private lazy var timeSlotEntities : [TimeSlotEntity] = { return [ self.viewModel.timeSlotEntity(withCategory:.friends, from:"10:30", to: "11:00"), self.viewModel.timeSlotEntity(withCategory:.work, from:"11:00", to: "11:55") ] }() private let editIndex = 1 private let editTo = Category.commute required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder, nextButtonText: "Ok, got it") } override func viewDidLoad() { super.viewDidLoad() let slot = timeSlotEntities[editIndex] editedTimeSlot = slot.with(category: editTo) initAnimatedTitleText(textView) timelineCells = initAnimatingTimeline(with: timeSlotEntities, in: timelineView) editView = EditTimeSlotView(categoryProvider: OnboardingCategoryProvider(withFirstCategory: editTo)) editView.isUserInteractionEnabled = false timelineView.addSubview(editView) editView.constrainEdges(to: timelineView) editedCell = createTimelineCell(for: editedTimeSlot) editedCell.alpha = 0 touchCursor = UIImageView(image: Asset.icCursor.image) touchCursor.alpha = 0 } override func startAnimations() { timelineCells[editIndex].addSubview(editedCell) editedCell.snp.makeConstraints { make in make.edges.equalToSuperview() } editedCell.contentView.snp.makeConstraints { make in make.edges.equalToSuperview() } timelineView.addSubview(touchCursor) setCursorPosition(toX: 100, y: 200) DelayedSequence.start() .then {t in animateTitleText(textView, duration: 0.5, delay: t)} .after(0.3) {t in animateTimeline(timelineCells, delay: t)} .after(0.9, showCursor) .after(0.3, moveCursorToCell) .after(0.6, tapCursor) .after(0.2, openEditView) .after(0.8, moveCursorToCategory) .after(0.5, tapCursor) .after(0.2, onTappedEditCategory) .after(0.3, closeEditView) .after(0.15, hideCursor) .after(0.5, changeTimeSlot) } private func openEditView(delay: TimeInterval) { Timer.schedule(withDelay: delay) { let cell = self.timelineCells[self.editIndex] let item = cell.slotTimelineItem! let origin = cell.categoryCircle.convert(cell.categoryCircle.center, to: self.timelineView) self.editView.onEditBegan(point: origin, timeSlotEntities: item.timeSlotEntities) } } private func closeEditView(delay : TimeInterval) { Timer.schedule(withDelay: delay) { self.editView.hide() } } private func changeTimeSlot(delay: TimeInterval) { UIView.scheduleAnimation(withDelay: delay, duration: 0.4) { self.editedCell.alpha = 1 } } private func showCursor(delay: TimeInterval) { UIView.scheduleAnimation(withDelay: delay, duration: 0.2, options: .curveEaseOut) { self.touchCursor.alpha = 1 } } private func hideCursor(delay: TimeInterval) { UIView.scheduleAnimation(withDelay: delay, duration: 0.2, options: .curveEaseIn) { self.touchCursor.alpha = 0 } } private func moveCursorToCell(delay : TimeInterval) { moveCursor(to: { let view = self.timelineCells[self.editIndex].categoryCircle! return view.convert(view.center, to: self.editView) }, offset: CGPoint(x: -16, y: -8), delay: delay) } private func moveCursorToCategory(delay: TimeInterval) { moveCursor(to: { let view = self.editView.getIcon(forCategory: self.editTo)! return view.convert(view.center, to: nil) }, offset: CGPoint(x: 0, y: 0), delay: delay) } private func moveCursor(to getPoint: @escaping () -> CGPoint, offset: CGPoint, delay: TimeInterval) { UIView.scheduleAnimation(withDelay: delay, duration: 0.45, options: .curveEaseInOut) { let point = getPoint() self.setCursorPosition(toX: point.x + offset.x, y: point.y + offset.y) } } private func setCursorPosition(toX x: CGFloat, y: CGFloat) { let frame = touchCursor.frame.size let w = frame.width let h = frame.height touchCursor.frame = CGRect(x: x - w / 2, y: y - h / 2, width: w, height: h) } private func tapCursor(delay : TimeInterval) { UIView.scheduleAnimation(withDelay: delay, duration: 0.125, options: .curveEaseOut) { self.touchCursor.transform = CGAffineTransform.init(scaleX: 0.8, y: 0.8) } UIView.scheduleAnimation(withDelay: delay + 0.15, duration: 0.125, options: .curveEaseIn) { self.touchCursor.transform = CGAffineTransform.init(scaleX: 1, y: 1) } } private func onTappedEditCategory(delay : TimeInterval) { Timer.schedule(withDelay: delay) { let view = self.editView.getIcon(forCategory: self.editTo)! UIView.scheduleAnimation(withDelay: 0, duration: 0.15, options: .curveEaseOut) { view.alpha = 0.6 } UIView.scheduleAnimation(withDelay: 0.15, duration: 0.15, options: .curveEaseIn) { view.alpha = 1 } } } }
bsd-3-clause
2cd8c3cf37ef18f518ff9740af6516bd
31.983696
108
0.601747
4.375631
false
false
false
false
LeoMobileDeveloper/MDTable
MDTableExample/MenuTableViewController.swift
1
3130
// // MenuTableViewController.swift // MDTableExample // // Created by Leo on 2017/7/4. // Copyright © 2017年 Leo Huang. All rights reserved. // import UIKit class MenuTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
63cbbc743a3d904848bd25bdfa4b5c3e
31.915789
136
0.670611
5.327087
false
false
false
false
netease-app/NIMSwift
Example/NIMSwift/Classes/IM/Notification/IMNewFriendController.swift
1
6014
// // IMNewFriendController.swift // NIMSwift // // 新的朋友页面 // // Created by 衡成飞 on 6/14/17. // Copyright © 2017 qianwang365. All rights reserved. // import UIKit class IMNewFriendController: UIViewController,UITableViewDataSource,UITableViewDelegate { @IBOutlet weak var tableView:UITableView! let maxNotificationCount:Int = 1000 var notifications:[NIMSystemNotification]? // var shouldMarkAsRead:Bool = false deinit { NIMSDK.shared().systemNotificationManager.markAllNotificationsAsRead() } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "新的朋友" self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "清空", style: .plain, target: self, action: #selector(clearAll)) self.tableView.tableFooterView = UIView() let system = NIMSDK.shared().systemNotificationManager system.add(self) notifications = system.fetchSystemNotifications(nil, limit: maxNotificationCount) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NIMSDK.shared().systemNotificationManager.markAllNotificationsAsRead() } func clearAll(){ NIMSDK.shared().systemNotificationManager.deleteAllNotifications() notifications?.removeAll() self.tableView.reloadData() } // MARK: - UITableViewDataSource,UITableViewDelegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let n = notifications?.count { return n } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! IMNewFriendCell let m = notifications![indexPath.row] cell.setupUI(m) cell.acceptHandler = { self.view.showHUDProgress() if m.type == .friendAdd { let request = NIMUserRequest() request.userId = m.sourceID! request.operation = .verify NIMSDK.shared().userManager.requestFriend(request, completion: { (error) in self.view.hiddenAllMessage() if error == nil { self.view.showHUDMsg(msg: "验证成功") m.handleStatus = IMNotificationHandleType.OK.rawValue }else{ print(error!) self.view.showHUDMsg(msg: "验证失败,请重试") } self.tableView.reloadData() }) }else if m.type == .teamApply{ NIMSDK.shared().teamManager.passApply(toTeam: m.targetID!, userId: m.sourceID!, completion: { (error, status) in self.view.hideHUDMsg() if error == nil { m.handleStatus = IMNotificationHandleType.OK.rawValue }else{ print(error!) self.view.showHUDMsg(msg: "添加失败,请重试") } self.tableView.reloadData() }) }else if m.type == .teamInvite{ NIMSDK.shared().teamManager.acceptInvite(withTeam: m.targetID!, invitorId: m.sourceID!, completion: { (error) in self.view.hideHUDMsg() if error == nil { m.handleStatus = IMNotificationHandleType.OK.rawValue }else{ print(error!) self.view.showHUDMsg(msg: "添加失败,请重试") } self.tableView.reloadData() }) } } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let deleteAction = UITableViewRowAction(style: .default, title: "删除", handler: {action in let noti = self.notifications![indexPath.row] self.notifications!.remove(at: indexPath.row) NIMSDK.shared().systemNotificationManager.delete(noti) tableView.deleteRows(at: [indexPath], with: .fade) }) return [deleteAction] } } //系统通知回调 extension IMNewFriendController:NIMSystemNotificationManagerDelegate{ func onReceive(_ notification: NIMSystemNotification) { //先遍历当前列表中,是否已存在 if notifications != nil { //添加好友请求 if notification.type == .friendAdd { let isEmpty = notifications!.filter{$0.sourceID == notification.sourceID}.isEmpty if isEmpty { notifications?.insert(notification, at: 0) self.tableView.reloadData() } }else if notification.type == .teamApply { let isEmpty = notifications!.filter{$0.sourceID == notification.sourceID}.isEmpty if isEmpty { notifications?.insert(notification, at: 0) self.tableView.reloadData() } } }else{ notifications = [] notifications?.append(notification) } } }
mit
9e34ed7f822c3bc973ce3988aa68b789
35.240741
135
0.562596
5.22331
false
false
false
false
Where2Go/swiftsina
GZWeibo05/AppDelegate.swift
1
2750
// // AppDelegate.swift // GZWeibo05 // // Created by zhangping on 15/10/26. // Copyright © 2015年 zhangping. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { setupAppearance() // 打开数据库 CZSQLiteManager.sharedManager print(CZUserAccount.loadAccount()) // 创建window window = UIWindow(frame: UIScreen.mainScreen().bounds) let tabbar = CZMainViewController() // ?: 如果?前面的变量有值才执行后的代码 // window?.rootViewController = tabbar window?.rootViewController = defaultController() // window?.rootViewController = CZNewFeatureViewController() // print(isNewVersion()) // 称为主窗口并显示 window?.makeKeyAndVisible() return true } private func defaultController() -> UIViewController { // 判断是否登录 // 每次判断都需要 == nil if !CZUserAccount.userLogin() { return CZMainViewController() } // 判断是否是新版本 return isNewVersion() ? CZNewFeatureViewController() : CZWelcomeViewController() } /// 判断是否是新版本 private func isNewVersion() -> Bool { // 获取当前的版本号 let versionString = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String let currentVersion = Double(versionString)! print("currentVersion: \(currentVersion)") // 获取到之前的版本号 let sandboxVersionKey = "sandboxVersionKey" let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey) print("sandboxVersion: \(sandboxVersion)") // 保存当前版本号 NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandboxVersionKey) NSUserDefaults.standardUserDefaults().synchronize() // 对比 return currentVersion > sandboxVersion } // MARK: - 切换根控制器 /** 切换根控制器 - parameter isMain: true: 表示切换到MainViewController, false: welcome */ func switchRootController(isMain: Bool) { window?.rootViewController = isMain ? CZMainViewController() : CZWelcomeViewController() } private func setupAppearance() { // 尽早设置 UINavigationBar.appearance().tintColor = UIColor.orangeColor() } }
apache-2.0
8556cf68d2c006e8bc60c05938783f2a
28.453488
127
0.632846
5.400853
false
false
false
false
gaoleegin/SwiftLianxi
dispatch_group_enter的练习/dispatch_group_enter的练习/ViewController.swift
1
5327
// // ViewController.swift // dispatch_group_enter的练习 // // Created by 高李军 on 15/10/31. // Copyright © 2015年 DamaiPlayBusinessPhone. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //建立一个 dispatch_group,可以减痛一组异步任务完成以后,统一得到通知 let group = dispatch_group_create() //进入群组 dispatch_group_enter(group) //离开群组 dispatch_group_leave(group) //监听群组调度 dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in //执行回调 } //创建一个group let group1 = dispatch_group_create() dispatch_group_enter(group1) dispatch_group_leave(group1) dispatch_group_notify(group1, dispatch_get_main_queue()) { () -> Void in //执行回调 } /* // 3. 监听群组调度 dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in println("图片缓存完成+加载数据 \(NSHomeDirectory())") // 执行回调 completion(statuses: statuses) */ let group2 = dispatch_group_create() dispatch_group_enter(group2) dispatch_group_leave(group2) dispatch_group_notify(group2, dispatch_get_main_queue()) { () -> Void in //所有的block完成后的回调 } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } /* // 建立一个 dispatch_group,可以监听一组异步任务完成后,统一得到通知 let group = dispatch_group_create() // 遍历微博数据数组 for s in statuses as [Status]! { // 没有图片继续循环 if s.pictureURLs == nil { continue } // 遍历图片 url 数组,下载图像 for url in s.pictureURLs! { // downloadImageWithURL 本身会下载图片,并且完成缓存 // 回调参数,通常是有 UI 交互才会使用的 // 1> 进入群组 dispatch_group_enter(group) // SDWebImage 下载图像前,会检查本地是否存在图片缓存,如果存在,会直接返回,不会去网络上加载 // 速度快,效率高! // 如果要判断服务器的图片是否更改,可以使用 RefreshCached 选项 SDWebImageManager.sharedManager().downloadImageWithURL(url, options: nil, progress: nil, completed: { (_, _, _, _, _) in // 2> 离开群组,一定要放在 block 的最后一句,表示异步真正执行完成 dispatch_group_leave(group) }) } } // 3. 监听群组调度 dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in println("图片缓存完成+加载数据 \(NSHomeDirectory())") // 执行回调 completion(statuses: statuses) }) */ //OC版的dispatch_group_enter的异步执行 /* #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } /** $ man dispatch_group_enter void dispatch_group_async(dispatch_group_t group, dispatch_queue_t queue, dispat ch_block_t block) { dispatch_retain(group); dispatch_group_enter(group); dispatch_async(queue, ^{ block(); dispatch_group_leave(group); dispatch_release(group); }); } */ - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { // 1. 创建一个群组 dispatch_group_t group1 = dispatch_group_create(); dispatch_group_t group = dispatch_group_create(); dispatch_queue_t q = dispatch_get_global_queue(0, 0); // 2. 异步任务 - 需要注意 enter & leave 成对出现! // 群组准备监听后续异步方法的执行,打了一个标记 dispatch_group_enter(group); dispatch_async(q, ^{ [NSThread sleepForTimeInterval:0.5]; NSLog(@"1.--%@", [NSThread currentThread]); // block 的最后一句,宣告任务完成,取消在群组中的标记 dispatch_group_leave(group); }); dispatch_group_enter(group); dispatch_async(q, ^{ [NSThread sleepForTimeInterval:0.5]; NSLog(@"2.--%@", [NSThread currentThread]); // block 的最后一句,宣告任务完成,取消在群组中的标记 dispatch_group_leave(group); }); // 3. 监听任务执行,当 group 中所有标记都没有的时候,得到通知 dispatch_group_notify(group, dispatch_get_main_queue(), ^{ NSLog(@"完成回调 %@", [NSThread currentThread]); }); } - (void)groupDemo { // 1. 创建一个群组 dispatch_group_t group = dispatch_group_create(); dispatch_queue_t q = dispatch_get_global_queue(0, 0); // 2. 异步任务 dispatch_group_async(group, q, ^{ [NSThread sleepForTimeInterval:0.5]; NSLog(@"1.--%@", [NSThread currentThread]); }); dispatch_group_async(group, q, ^{ [NSThread sleepForTimeInterval:0.8]; NSLog(@"2.--%@", [NSThread currentThread]); }); // 3. 监听任务执行 dispatch_group_notify(group, dispatch_get_main_queue(), ^{ NSLog(@"完成回调 %@", [NSThread currentThread]); }); } @end */
apache-2.0
e9be95d706c0489347e77504e761f219
19.589862
120
0.640107
3.324405
false
false
false
false
vojto/NiceKit
NiceKit/NiceField.swift
1
4900
// // NiceField.swift // NiceKit // // Created by Vojtech Rinik on 6/30/17. // Copyright © 2017 Vojtech Rinik. All rights reserved. // import Cocoa import AppKit import Cartography open class NiceField: NSView, NSTextFieldDelegate { public let field = NSTextField() public var textColor = NiceColors.lightText { didSet { updateStyle() }} public var borderColor = NiceColors.lightBorder { didSet { updateStyle() }} public var editingBackgroundColor = NiceColors.lightBorder { didSet { updateStyle() }} open var width: CGFloat { return 80.0 } let marginSide = CGFloat(4.0) var widthConstraint: NSLayoutConstraint? public var stringValue: String { get { return field.stringValue } set { field.stringValue = newValue } } public var onChange: ((String) -> ())? override public init(frame frameRect: NSRect) { super.init(frame: frameRect) setup() } required public init?(coder: NSCoder) { super.init(coder: coder) setup() } open func setup() { layer = CALayer() wantsLayer = true layer?.actions = ["borderWidth": NSNull()] layer?.borderWidth = 0 layer?.borderColor = borderColor.cgColor layer?.cornerRadius = 3.0 layer?.anchorPoint = CGPoint(x: 0.5, y: 0.5) field.isBordered = false field.isSelectable = false field.isEditable = false field.backgroundColor = NSColor.clear field.font = NSFont.systemFont(ofSize: 12) // field.drawsBackground = false field.stringValue = "wtf" field.focusRingType = .none field.setContentCompressionResistancePriority(.required, for: .horizontal) field.delegate = self include(field, insets: NSEdgeInsets(top: 4.0, left: marginSide, bottom: 4.0, right: marginSide)) constrain(self) { view in self.widthConstraint = (view.width == width) } widthConstraint?.isActive = false } func updateStyle() { field.textColor = self.textColor layer?.borderColor = self.borderColor.cgColor } var trackingArea: NSTrackingArea? override open func updateTrackingAreas() { if let area = trackingArea { removeTrackingArea(area) } trackingArea = NSTrackingArea(rect: bounds, options: [NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeInKeyWindow], owner: self, userInfo: nil) self.addTrackingArea(trackingArea!) } var isEditing: Bool = false override open func mouseEntered(with event: NSEvent) { if !isEditing { layer?.borderWidth = 1 } } override open func mouseExited(with event: NSEvent) { layer?.borderWidth = 0 } override open func mouseDown(with event: NSEvent) { startEditing() } open func startEditing() { layer?.backgroundColor = self.editingBackgroundColor.cgColor layer?.borderWidth = 0 field.isEditable = true field.textColor = self.textColor widthConstraint?.isActive = true widthConstraint?.constant = width NSAnimationContext.runAnimationGroup({ context in context.duration = 0.15 context.allowsImplicitAnimation = true self.layoutSubtreeIfNeeded() }, completionHandler: nil) window?.makeFirstResponder(field) isEditing = true field.currentEditor()?.moveToEndOfLine(nil) } override open func controlTextDidEndEditing(_ obj: Notification) { self.finishEditing() } open func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { if commandSelector == #selector(NSResponder.insertNewline(_:)) { self.finishEditing() return true } else if commandSelector == #selector(NSResponder.cancelOperation(_:)) { self.finishEditing() return true } else if commandSelector == #selector(NSResponder.insertTab(_:)) { self.finishEditing() return true } return false } open func finishEditing() { window?.makeFirstResponder(nil) field.isEditable = false field.isSelectable = false field.textColor = self.textColor let width = field.intrinsicContentSize.width + marginSide * 2 widthConstraint?.constant = width layer?.backgroundColor = nil NSAnimationContext.runAnimationGroup({ context in context.duration = 0.15 context.allowsImplicitAnimation = true self.layoutSubtreeIfNeeded() self.onChange?(field.stringValue) }, completionHandler: nil) isEditing = false } }
mit
9f2069b3fdcd6afd0922d4a2e1f43c8f
26.216667
178
0.625026
5.119122
false
false
false
false
Fenrikur/ef-app_ios
EurofurenceTests/Test Doubles/FakeAuthenticationService.swift
1
2258
import EurofurenceModel class FakeAuthenticationService: AuthenticationService { enum AuthState { case loggedIn(User) case loggedOut } fileprivate(set) var authState: AuthState class func loggedInService(_ user: User = .random) -> FakeAuthenticationService { return FakeAuthenticationService(authState: .loggedIn(user)) } class func loggedOutService() -> FakeAuthenticationService { return FakeAuthenticationService(authState: .loggedOut) } init(authState: AuthState) { self.authState = authState } fileprivate var observers = [AuthenticationStateObserver]() func add(_ observer: AuthenticationStateObserver) { observers.append(observer) switch authState { case .loggedIn(let user): observer.userDidLogin(user) case .loggedOut: observer.userDidLogout() } } private(set) var authStateDeterminedCount = 0 func determineAuthState(completionHandler: @escaping (AuthState) -> Void) { completionHandler(authState) authStateDeterminedCount += 1 } private(set) var capturedRequest: LoginArguments? fileprivate var capturedCompletionHandler: ((LoginResult) -> Void)? func login(_ arguments: LoginArguments, completionHandler: @escaping (LoginResult) -> Void) { capturedRequest = arguments capturedCompletionHandler = completionHandler } private(set) var wasToldToLogout = false private(set) var capturedLogoutHandler: ((LogoutResult) -> Void)? func logout(completionHandler: @escaping (LogoutResult) -> Void) { wasToldToLogout = true capturedLogoutHandler = completionHandler } } extension FakeAuthenticationService { func fulfillRequest() { capturedCompletionHandler?(.success(.random)) } func failRequest() { capturedCompletionHandler?(.failure) } func notifyObserversUserDidLogin(_ user: User = User(registrationNumber: 42, username: "")) { authState = .loggedIn(user) observers.forEach { $0.userDidLogin(user) } } func notifyObserversUserDidLogout() { authState = .loggedOut observers.forEach { $0.userDidLogout() } } }
mit
b7aaa1941987ef2906935e67cb066def
27.582278
97
0.678034
5.190805
false
false
false
false