repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
SASAbus/SASAbus-ios
SASAbus/Controller/EcoPoints/EcoPointsViewController.swift
1
3339
import UIKit class EcoPointsViewController: MasterViewController { @IBOutlet var loginContainer: UIView! @IBOutlet var contentContainer: UIView! var ecoPointsController: EcoPointsTabViewController! var isLoginActive: Bool = false init() { super.init(nibName: "EcoPointsViewController", title: "Eco Points") } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() let loginNib = UINib(nibName: "LoginViewController", bundle: nil) let loginViewController = loginNib.instantiate(withOwner: self)[0] as! LoginViewController loginViewController.parentVC = self let ecoPointsNib = UINib(nibName: "EcoPointsTabViewController", bundle: nil) ecoPointsController = ecoPointsNib.instantiate(withOwner: self)[0] as! EcoPointsTabViewController ecoPointsController.parentVC = self addChildController(loginViewController, container: loginContainer) addChildController(ecoPointsController, container: contentContainer) if !AuthHelper.isLoggedIn() { isLoginActive = true Log.warning("User is not logged in") loginContainer.isHidden = false contentContainer.isHidden = true } else { loginContainer.isHidden = true contentContainer.isHidden = false ecoPointsController.showButton() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationItem.rightBarButtonItem = nil if !AuthHelper.isLoggedIn() { isLoginActive = true Log.warning("User is not logged in") loginContainer.isHidden = false loginContainer.alpha = 1 contentContainer.isHidden = true } else { ecoPointsController.showButton() } if isLoginActive, let navController = self.navigationController { navController.navigationBar.tintColor = UIColor.white navController.navigationBar.barTintColor = Color.loginBackground } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if isLoginActive, let navController = self.navigationController { navController.navigationBar.tintColor = UIColor.white navController.navigationBar.barTintColor = Theme.orange } } func loginComplete(completion: @escaping () -> Void?) { isLoginActive = false UIView.animate(withDuration: 0.25, animations: { self.loginContainer.alpha = 0 self.contentContainer.alpha = 1 if let navController = self.navigationController { navController.navigationBar.tintColor = UIColor.white navController.navigationBar.barTintColor = Theme.orange } // Cannot load profile earlier because auth token is not set self.ecoPointsController.profileViewController.parseProfile() }, completion: { _ in self.loginContainer.isHidden = true self.contentContainer.isHidden = false self.ecoPointsController.showButton() completion() }) } }
gpl-3.0
da052a0ebb82865d2ffacbc93fa16ba6
29.633028
105
0.650794
5.57429
false
false
false
false
WeHUD/app
weHub-ios/Gzone_App/Gzone_App/PageGamesViewController.swift
1
9207
// // PageViewController.swift // Gzone_App // // Created by Tracy Sablon on 03/05/2017. // Copyright © 2017 Tracy Sablon. All rights reserved. // import UIKit import XLPagerTabStrip class PageGamesViewController: UITableViewController, IndicatorInfoProvider,UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate { var games : [Game] = [] var topGames : [Game] = [] var followers : [String] = [] let cellIdentifier = "GamesCustomCell" let categories = ["New","Top Games"] var refreshCtrl = UIRefreshControl() var dateFormatter = DateFormatter() var last_index = 0 var update : Bool = true var avatars : [UIImage] = [] var avatarsTopGames : [UIImage] = [] //var searchController : UISearchController! //Mock for populate cells /* struct Game { var title : String? } var games = [[Game(title: "Horizon Zero Dawn"),Game(title: "Resident Evil")], [Game(title: "Tekken 7"),Game(title: "Uncharted 4")], [Game(title: "Grand Theft Auto V"),Game(title: "Injustice 2")]] */ //Initialize the tableView itemInfo var itemInfo = IndicatorInfo(title: "View") init(style: UITableViewStyle, itemInfo: IndicatorInfo) { self.itemInfo = itemInfo super.init(style: style) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.getGames() print("Games View"); refreshCtrl.backgroundColor = UIColor.clear refreshCtrl.tintColor = UIColor.black refreshCtrl.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshCtrl.addTarget(self, action: #selector(PageGamesViewController.PullRefresh), for: UIControlEvents.valueChanged) self.tableView.addSubview(refreshCtrl) //Settings for custom table cell tableView.register(UINib(nibName: "GamesTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: cellIdentifier) /*tableView.allowsSelection = false tableView.estimatedRowHeight = UITableViewAutomaticDimension tableView.rowHeight = 140.0 self.tableView.delegate = self self.tableView.dataSource = self*/ } func updateSearchResults(for searchController: UISearchController) { } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.categories[section] } override func numberOfSections(in tableView: UITableView) -> Int { return self.categories.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if(section == 0){ return self.games.count } else{ return self.topGames.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! GamesTableViewCell if(indexPath.section == 0){ let game = self.games[indexPath.row] _ = indexPath.section cell.gameTitleLbl.text = game.name if(self.avatars.count > indexPath.row){ cell.imageView?.image = self.avatars[indexPath.row] } cell.followButton.isHidden = self.isFollower(game: game) cell.followAction = {(cell) in self.follow(game: game)} }else{ let game = self.topGames[indexPath.row] cell.gameTitleLbl.text = game.name if(self.avatarsTopGames.count > indexPath.row){ cell.imageView?.image = self.avatarsTopGames[indexPath.row] } cell.followButton.isHidden = self.isFollower(game: game) cell.followAction = {(cell) in self.follow(game: game)} } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let storyboard = UIStoryboard(name: "Home", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "Game_ID") as! GameViewController if(indexPath.section == 0){ vc.game = self.games[indexPath.row] vc.isFollow = self.isFollower(game: self.games[indexPath.row]) }else{ vc.game = self.topGames[indexPath.row] vc.isFollow = self.isFollower(game: self.games[indexPath.row]) } self.navigationController?.pushViewController(vc, animated: true) } func follow(game : Game){ game.followerId.append((AuthenticationService.sharedInstance.currentUser?._id)!) self.games[self.games.index(of: game)!] = game self.followGame(game: game) } func isFollower(game : Game)->Bool{ for follower in game.followerId{ if(follower == AuthenticationService.sharedInstance.currentUser?._id){ return true } } return false } func followGame(game : Game){ let gameWB : WBGame = WBGame() // self.offset += 1 gameWB.updateGame(game: game, usersId: game.followerId, accessToken: AuthenticationService.sharedInstance.accessToken!){ (result: Bool) in if(result){ self.refreshTableView() } } } func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return itemInfo } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getGames()->Void{ let gameWB : WBGame = WBGame() gameWB.getAllGames(accessToken: AuthenticationService.sharedInstance.accessToken!,offset: last_index.description){ (result: [Game]) in self.topGamesCreate() if(self.last_index == 0){ self.games = result self.avatars = self.imageFromUrl(games: self.games) }else{ if(result.count == 0){ self.update = false }else{ self.games.append(contentsOf: result) self.avatars = self.imageFromUrl(games: self.games) } self.refreshTableView() let now = Date() let updateString = "Last Updated at " + self.dateFormatter.string(from: now) self.refreshCtrl.attributedTitle = NSAttributedString(string: updateString) if self.refreshCtrl.isRefreshing { self.refreshCtrl.endRefreshing() } } self.refreshTableView() } } func topGamesCreate(){ self.topGames = self.games.sorted{ $0.followerId.count < $1.followerId.count } self.avatarsTopGames = self.imageFromUrl(games: self.topGames) self.refreshTableView() } func refreshTableView(){ DispatchQueue.main.async { self.tableView.reloadData() } } func PullRefresh() { if(update){ last_index += 1 self.getGames() }else{ let updateString = "Il n'y a pas de nouveaux jeux" self.refreshCtrl.attributedTitle = NSAttributedString(string: updateString) if self.refreshCtrl.isRefreshing { self.refreshCtrl.endRefreshing() } } } func imageFromUrl(games : [Game])->[UIImage]{ var avatarsGames : [UIImage] = [] for game in games { if(game.boxart != ""){ let imageUrlString = game.boxart let imageUrl:URL = URL(string: imageUrlString)! let imageData:NSData = NSData(contentsOf: imageUrl)! avatarsGames.append(UIImage(data: imageData as Data)!) }else{ let imageUrlString = "https://vignette3.wikia.nocookie.net/transformers/images/b/b6/Playschool_Go-Bots_G.png/revision/latest?cb=20061127024844" let imageUrl:URL = URL(string: imageUrlString)! let imageData:NSData = NSData(contentsOf: imageUrl)! avatarsGames.append(UIImage(data: imageData as Data)!) } } return avatarsGames } }
bsd-3-clause
e4b625ba51952a7b26e38dddd0422af1
31.301754
159
0.573756
5.049918
false
false
false
false
ntwf/TheTaleClient
TheTale/Stores/PlayerInformation/AccountInformation/Hero/Might/Might.swift
1
989
// // Might.swift // the-tale // // Created by Mikhail Vospennikov on 25/06/2017. // Copyright © 2017 Mikhail Vospennikov. All rights reserved. // import Foundation class Might: NSObject { var value: Double var critChance: Double var pvpEffectivenessBonus: Double var politicsPower: Double required init?(jsonObject: JSON) { guard let value = jsonObject["value"] as? Double, let critChance = jsonObject["crit_chance"] as? Double, let pvpEffectivenessBonus = jsonObject["pvp_effectiveness_bonus"] as? Double, let politicsPower = jsonObject["politics_power"] as? Double else { return nil } self.value = value self.critChance = critChance self.pvpEffectivenessBonus = pvpEffectivenessBonus self.politicsPower = politicsPower } } extension Might { var mightRepresentation: String { return String(format: "%.1f", value) } }
mit
689d6ff7127195a144dc9c57ac8eb87c
25
87
0.635628
4.151261
false
false
false
false
sarahspins/Loop
Loop/Models/ShareService.swift
2
2272
// // ShareService.swift // Loop // // Created by Nate Racklyeft on 7/2/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import ShareClient // Encapsulates the Dexcom Share client service and its authentication struct ShareService: ServiceAuthentication { var credentials: [ServiceCredential] let title: String = NSLocalizedString("Dexcom Share", comment: "The title of the Dexcom Share service") init(username: String?, password: String?) { credentials = [ ServiceCredential( title: NSLocalizedString("Username", comment: "The title of the Dexcom share username credential"), placeholder: nil, isSecret: false, keyboardType: .ASCIICapable, value: username ), ServiceCredential( title: NSLocalizedString("Password", comment: "The title of the Dexcom share password credential"), placeholder: nil, isSecret: true, keyboardType: .ASCIICapable, value: password ) ] if let username = username, password = password { isAuthorized = true client = ShareClient(username: username, password: password) } } // The share client, if credentials are present private(set) var client: ShareClient? var username: String? { return credentials[0].value } var password: String? { return credentials[1].value } private(set) var isAuthorized: Bool = false mutating func verify(completion: (success: Bool, error: ErrorType?) -> Void) { guard let username = username, password = password else { completion(success: false, error: nil) return } let client = ShareClient(username: username, password: password) client.fetchLast(1) { (error, _) in self.isAuthorized = (error == nil) completion(success: self.isAuthorized, error: error) } self.client = client } mutating func reset() { credentials[0].value = nil credentials[1].value = nil isAuthorized = false client = nil } }
apache-2.0
bf6adafb9dc0c855fd7986820fbb84e3
28.493506
115
0.598415
4.947712
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/AssistantV2/Models/MessageContextGlobalSystem.swift
1
9631
/** * (C) Copyright IBM Corp. 2018, 2022. * * 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 /** Built-in system properties that apply to all skills used by the assistant. */ public struct MessageContextGlobalSystem: Codable, Equatable { /** The language code for localization in the user input. The specified locale overrides the default for the assistant, and is used for interpreting entity values in user input such as date values. For example, `04/03/2018` might be interpreted either as April 3 or March 4, depending on the locale. This property is included only if the new system entities are enabled for the skill. */ public enum Locale: String { case enUs = "en-us" case enCa = "en-ca" case enGb = "en-gb" case arAr = "ar-ar" case csCz = "cs-cz" case deDe = "de-de" case esEs = "es-es" case frFr = "fr-fr" case itIt = "it-it" case jaJp = "ja-jp" case koKr = "ko-kr" case nlNl = "nl-nl" case ptBr = "pt-br" case zhCn = "zh-cn" case zhTw = "zh-tw" } /** The user time zone. The assistant uses the time zone to correctly resolve relative time references. */ public var timezone: String? /** A string value that identifies the user who is interacting with the assistant. The client must provide a unique identifier for each individual end user who accesses the application. For user-based plans, this user ID is used to identify unique users for billing purposes. This string cannot contain carriage return, newline, or tab characters. If no value is specified in the input, **user_id** is automatically set to the value of **context.global.session_id**. **Note:** This property is the same as the **user_id** property at the root of the message body. If **user_id** is specified in both locations in a message request, the value specified at the root is used. */ public var userID: String? /** A counter that is automatically incremented with each turn of the conversation. A value of 1 indicates that this is the the first turn of a new conversation, which can affect the behavior of some skills (for example, triggering the start node of a dialog). */ public var turnCount: Int? /** The language code for localization in the user input. The specified locale overrides the default for the assistant, and is used for interpreting entity values in user input such as date values. For example, `04/03/2018` might be interpreted either as April 3 or March 4, depending on the locale. This property is included only if the new system entities are enabled for the skill. */ public var locale: String? /** The base time for interpreting any relative time mentions in the user input. The specified time overrides the current server time, and is used to calculate times mentioned in relative terms such as `now` or `tomorrow`. This can be useful for simulating past or future times for testing purposes, or when analyzing documents such as news articles. This value must be a UTC time value formatted according to ISO 8601 (for example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). This property is included only if the new system entities are enabled for the skill. */ public var referenceTime: String? /** The time at which the session started. With the stateful `message` method, the start time is always present, and is set by the service based on the time the session was created. With the stateless `message` method, the start time is set by the service in the response to the first message, and should be returned as part of the context with each subsequent message in the session. This value is a UTC time value formatted according to ISO 8601 (for example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). */ public var sessionStartTime: String? /** An encoded string that represents the configuration state of the assistant at the beginning of the conversation. If you are using the stateless `message` method, save this value and then send it in the context of the subsequent message request to avoid disruptions if there are configuration changes during the conversation (such as a change to a skill the assistant uses). */ public var state: String? /** For internal use only. */ public var skipUserInput: Bool? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case timezone = "timezone" case userID = "user_id" case turnCount = "turn_count" case locale = "locale" case referenceTime = "reference_time" case sessionStartTime = "session_start_time" case state = "state" case skipUserInput = "skip_user_input" } /** Initialize a `MessageContextGlobalSystem` with member variables. - parameter timezone: The user time zone. The assistant uses the time zone to correctly resolve relative time references. - parameter userID: A string value that identifies the user who is interacting with the assistant. The client must provide a unique identifier for each individual end user who accesses the application. For user-based plans, this user ID is used to identify unique users for billing purposes. This string cannot contain carriage return, newline, or tab characters. If no value is specified in the input, **user_id** is automatically set to the value of **context.global.session_id**. **Note:** This property is the same as the **user_id** property at the root of the message body. If **user_id** is specified in both locations in a message request, the value specified at the root is used. - parameter turnCount: A counter that is automatically incremented with each turn of the conversation. A value of 1 indicates that this is the the first turn of a new conversation, which can affect the behavior of some skills (for example, triggering the start node of a dialog). - parameter locale: The language code for localization in the user input. The specified locale overrides the default for the assistant, and is used for interpreting entity values in user input such as date values. For example, `04/03/2018` might be interpreted either as April 3 or March 4, depending on the locale. This property is included only if the new system entities are enabled for the skill. - parameter referenceTime: The base time for interpreting any relative time mentions in the user input. The specified time overrides the current server time, and is used to calculate times mentioned in relative terms such as `now` or `tomorrow`. This can be useful for simulating past or future times for testing purposes, or when analyzing documents such as news articles. This value must be a UTC time value formatted according to ISO 8601 (for example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). This property is included only if the new system entities are enabled for the skill. - parameter sessionStartTime: The time at which the session started. With the stateful `message` method, the start time is always present, and is set by the service based on the time the session was created. With the stateless `message` method, the start time is set by the service in the response to the first message, and should be returned as part of the context with each subsequent message in the session. This value is a UTC time value formatted according to ISO 8601 (for example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - parameter state: An encoded string that represents the configuration state of the assistant at the beginning of the conversation. If you are using the stateless `message` method, save this value and then send it in the context of the subsequent message request to avoid disruptions if there are configuration changes during the conversation (such as a change to a skill the assistant uses). - parameter skipUserInput: For internal use only. - returns: An initialized `MessageContextGlobalSystem`. */ public init( timezone: String? = nil, userID: String? = nil, turnCount: Int? = nil, locale: String? = nil, referenceTime: String? = nil, sessionStartTime: String? = nil, state: String? = nil, skipUserInput: Bool? = nil ) { self.timezone = timezone self.userID = userID self.turnCount = turnCount self.locale = locale self.referenceTime = referenceTime self.sessionStartTime = sessionStartTime self.state = state self.skipUserInput = skipUserInput } }
apache-2.0
e7b65b183a9ed957d2bc0a4ef3224d71
50.77957
121
0.698474
4.599331
false
false
false
false
plantain-00/demo-set
swift-demo/UIColorWDUtils Demo/UIColorWDUtils Demo/UIColorWDUtils.swift
2
8149
// // UIColorWDUtils.swift // // Created by Walter Da Col on 28/09/14. // Copyright (c) 2014 Walter Da Col. All rights reserved. // import UIKit /** Returns the RGBA value of the provided ARGB color. :param: argb an ARGB Hex value :returns: the RGBA value of given color */ func WDConvertToRGBA(argb: UInt) -> UInt { let sArgb = min(argb ,0xFFFFFFFF) let alpha = (sArgb & 0xFF000000) >> 24 let red = (sArgb & 0x00FF0000) >> 16 let green = (sArgb & 0x0000FF00) >> 8 let blue = (sArgb & 0x000000FF) return (red << 24) + (green << 16) + (blue << 8) + alpha } /** Returns the ARGB value of the provided RGBA color. :param: argb an RGBA Hex value :returns: the ARGB value of given color */ func WDConvertToARGB(rgba: UInt) -> UInt { let sRgba = min(rgba ,0xFFFFFFFF) let red = (sRgba & 0xFF000000) >> 24 let green = (sRgba & 0x00FF0000) >> 16 let blue = (sRgba & 0x0000FF00) >> 8 let alpha = (sRgba & 0x000000FF) return (alpha << 24) + (red << 16) + (green << 8) + blue } /** Returns the color components of the provided color hex value. :param: rgba an RGBA Hex value (0x00000000). :returns: A tuple of intensity values for the color components (including alpha) associated with the specified color. */ func WDDecomposeRGBA(rgba: UInt) -> (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat){ let sRgba = min(rgba,0xFFFFFFFF) let red: CGFloat = CGFloat((sRgba & 0xFF000000) >> 24) / 255.0 let green: CGFloat = CGFloat((sRgba & 0x00FF0000) >> 16) / 255.0 let blue: CGFloat = CGFloat((sRgba & 0x0000FF00) >> 8) / 255.0 let alpha: CGFloat = CGFloat(sRgba & 0x000000FF) / 255.0 return (red,green,blue,alpha) } /** Returns the color components of the provided color hex value. :param: rgb an RGB Hex value (0x000000). :returns: A tuple of intensity values for the color components (including alpha) associated with the specified color. */ func WDDecomposeRGB(rgb: UInt) -> (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat){ return WDDecomposeRGBA(rgb << 8 + 255) } /** Returns the RGBA hex value of the provided 8bit color components (including opacity as float value). :param: red The red component of the color object, specified as a value from 0 to 255. :param: green The green component of the color object, specified as a value from 0 to 255. :param: blue The blue component of the color object, specified as a value from 0 to 255. :param: alpha The opacity value of the color object, specified as a value from 0.0 to 1.0. :returns: A RGBA value for the specified color components. */ func WDCompose8bitRGBA(red:UInt, green:UInt, blue:UInt, alpha: Float) -> UInt { let sRed = min(255, red) let sGreen = min(255, green) let sBlue = min(255, blue) let sAlpha = min(1.0, max(0.0, alpha)) return (sRed << 24) + (sGreen << 16) + (sBlue << 8) + UInt(sAlpha * 255) } /** Returns the RGBA hex value of the provided 8bit color components (opacity defaults to 1.0). :param: red The red component of the color object, specified as a value from 0 to 255. :param: green The green component of the color object, specified as a value from 0 to 255. :param: blue The blue component of the color object, specified as a value from 0 to 255. :returns: A RGBA value for the specified color components. */ func WDCompose8bitRGBA(red:UInt, green:UInt, blue:UInt) -> UInt{ return WDCompose8bitRGBA(red, green, blue, 1.0) } /** * This extension adds some common utilities to UIColor */ extension UIColor { /** Initializes and returns a color object using the specified RGBA hex code. :param: rgba The RGBA hex value. :returns: An initialized color object. */ convenience init(rgba: UInt){ let (red,green,blue,alpha) = WDDecomposeRGBA(rgba) self.init(red: red, green: green, blue:blue, alpha:alpha) } /** Initializes and returns a color object using the specified RGB hex code, opacity defaults to 1.0. :param: rgb The RGB hex value. :returns: An initialized color object. */ convenience init(rgb: UInt){ self.init(rgba: rgb << 8 + 255) } /** Initializes and returns a color object using the specified white amount and RGBA hex value, useful to create color tints. :param: rgba The RGBA hex value. :param: whiteAmount The white amount, specified as a value from 0.0 to 1.0. :returns: An initialized color object. */ convenience init(rgba: UInt, whiteAmount:Float){ let x = CGFloat(min(1.0, max(0.0, whiteAmount))) let (red, green, blue, alpha) = WDDecomposeRGBA(rgba) self.init(red: min(red + x,1.0), green: min(green + x,1.0), blue:min(blue + x,1.0), alpha:alpha) } /** Initializes and returns a color object using the specified white amount and RGB hex value, useful to create color tints. :param: rgb The RGB hex value. :param: whiteAmount The white amount, specified as a value from 0.0 to 1.0. :returns: An initialized color object. */ convenience init(rgb: UInt, whiteAmount:Float){ self.init(rgba:(rgb << 8 + 255), whiteAmount: whiteAmount) } /** Initializes and returns a color object using the specified black amount and RGBA hex value, useful to create color shades. :param: rgba The RGBA hex value. :param: blackAmount The black amount, specified as a value from 0.0 to 1.0. :returns: An initialized color object. */ convenience init(rgba: UInt, blackAmount:Float){ let x = CGFloat(min(1.0, max(0.0, blackAmount))) let (red, green, blue, alpha) = WDDecomposeRGBA(rgba) self.init(red: max(red - x, 0.0), green: max(green - x, 0.0), blue:max(blue - x, 0.0), alpha:alpha) } /** Initializes and returns a color object using the specified black amount and RGB hex value, useful to create color shades. :param: rgb The RGB hex value. :param: blackAmount The black amount, specified as a value from 0.0 to 1.0. :returns: An initialized color object. */ convenience init(rgb: UInt, blackAmount:Float){ self.init(rgba:(rgb << 8 + 255), blackAmount: blackAmount) } /** Initializes and returns a color object using the specified opacity and RGB component 8bit values. :param: red8Bit The red component of the color object, specified as a value from 0 to 255. :param: green8Bit The green component of the color object, specified as a value from 0 to 255. :param: blue8Bit The blue component of the color object, specified as a value from 0 to 255. :param: alpha The opacity value of the color object, specified as a value from 0.0 to 1.0. :returns: An initialized color object. */ convenience init(red8Bit: UInt, green8Bit:UInt, blue8Bit:UInt, alpha:Float){ let sRed = CGFloat(min(255, red8Bit)) / 255.0 let sGreen = CGFloat(min(255, green8Bit)) / 255.0 let sBlue = CGFloat(min(255, blue8Bit)) / 255.0 let sAlpha = CGFloat(min(1.0, max(0.0, alpha))) self.init(red: sRed, green: sGreen, blue: sBlue, alpha: sAlpha) } /** Calculates the RGBA hex value of the receiver. :returns: The RGBA hex value or nil if this color can't be associated with RGBA components. */ func toRGBA() -> UInt? { let colorSpaceModel = CGColorSpaceGetModel(CGColorGetColorSpace(self.CGColor)).value let components = CGColorGetComponents(self.CGColor) switch colorSpaceModel { case kCGColorSpaceModelRGB.value: let (r,g,b,a) = (components[0], components[1], components[2], components[3]) return WDCompose8bitRGBA(UInt(r * 255), UInt(g*255), UInt(b*255), Float(a)) case kCGColorSpaceModelMonochrome.value: let (c,a) = (components[0], components[1]) return WDCompose8bitRGBA(UInt(c * 255), UInt(c*255), UInt(c*255), Float(a)) default: return nil } } }
mit
22897bf98dd85d0f70b9775e348fd742
35.383929
126
0.654436
3.618561
false
false
false
false
crossroadlabs/Regex
Sources/Regex/String+Regex.swift
1
3493
//===--- String+Regex.swift -----------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //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. //===----------------------------------------------------------------------===// /** * Adds Regex extensions to String */ public extension String { /** * Creates a regex using this string as a pattern. Can return nil if pattern is invalid. */ var r : Regex? { get { return try? Regex(pattern: self) } } /** An inverse alias to Regex.split - parameters: - regex: Regex to split the string with - returns: An array. See Regex.split for more details. */ func split(using regex:RegexProtocol?) -> [String] { guard let regex = regex else { return [self] } return regex.split(self) } } infix operator =~ : ComparisonPrecedence infix operator !~ : ComparisonPrecedence /** Syntactic sugar for pattern matching. Used as "ABC" =~ ".*".r - see: Regex.matches for more details. - parameters: - source: String to match - regex: Regex to match the string with - returns: True if matches, false otherwise */ public func =~(source:String, regex:RegexProtocol?) -> Bool { guard let matches = regex?.matches(source) else { return false } return matches } /** Syntactic sugar for pattern matching. Used as "ABC" =~ ".*" Regex is automatically created from the second string. - see: Regex.matches for more details - parameters: - source: String to match - regex: Pattern string to match the string with - returns: True if matches, false otherwise */ public func =~(source:String, pattern:String) -> Bool { return source =~ pattern.r } /** Syntactic sugar for pattern matching. Used as "ABC" !~ ".*".r Basically is negation of =~ operator. - see: Regex.matches for more details - parameters: - source: String to match - regex: Regex to match the string with - returns: False if matches, true otherwise */ public func !~(source:String, regex:RegexProtocol?) -> Bool { return !(source =~ regex) } /** Syntactic sugar for pattern matching. Used as "ABC" =~ ".*" Basically is negation of =~ operator. Regex is automatically created from the second string. - see: Regex.matches for more details - parameters: - source: String to match - regex: Pattern string to match the string with - returns: False if matches, true otherwise */ public func !~(source:String, pattern:String) -> Bool { return !(source =~ pattern.r) } /** Operator is used by `switch` keyword in constructions like following: ```swift switch str { case "\\d+".r: print("has digit") case "[a-z]+".r: print("has letter") default: print("nothing") } ``` Deep integration with Swift. - returns: True if matches, false otherwise */ public func ~=(regex:RegexProtocol?, source:String) -> Bool { return source =~ regex }
apache-2.0
b151af9e4f1b9651bbb32af2b4ea9a6f
26.944
92
0.639851
4.218599
false
false
false
false
josve05a/wikipedia-ios
Wikipedia/Code/NewsCollectionViewCell+WMFFeedContentDisplaying.swift
3
1596
import UIKit extension NewsCollectionViewCell { public func configure(with story: WMFFeedNewsStory, dataStore: MWKDataStore, showArticles: Bool = true, theme: Theme, layoutOnly: Bool) { let previews = story.articlePreviews ?? [] descriptionHTML = story.storyHTML if showArticles { articles = previews.map { (articlePreview) -> CellArticle in return CellArticle(articleURL:articlePreview.articleURL, title: articlePreview.displayTitle, titleHTML: articlePreview.displayTitleHTML, description: articlePreview.descriptionOrSnippet, imageURL: articlePreview.thumbnailURL) } } let articleLanguage = story.articlePreviews?.first?.articleURL.wmf_language descriptionLabel.accessibilityLanguage = articleLanguage semanticContentAttributeOverride = MWLanguageInfo.semanticContentAttribute(forWMFLanguage: articleLanguage) let imageWidthToRequest = traitCollection.wmf_potdImageWidth if let articleURL = story.featuredArticlePreview?.articleURL ?? previews.first?.articleURL, let article = dataStore.fetchArticle(with: articleURL), let imageURL = article.imageURL(forWidth: imageWidthToRequest) { isImageViewHidden = false if !layoutOnly { imageView.wmf_setImage(with: imageURL, detectFaces: true, onGPU: true, failure: {(error) in }, success: { }) } } else { isImageViewHidden = true } apply(theme: theme) resetContentOffset() setNeedsLayout() } }
mit
501dd19c309337d9b1e1fe93e2bea74a
48.875
241
0.686717
5.302326
false
false
false
false
PlusR/UITextSubClass
UITextSubClass/UITextFieldWithDecimalPad/UITextFieldWithDecimalPad.swift
1
1610
import UIKit public class UITextFieldWithDecimalPad: UITextField { public var value: NSDecimalNumber { get { format(number: .init(string: text)) } set { text = format(number: newValue).stringValue } } public var handler: NSDecimalNumberHandler public required init?(coder: NSCoder) { handler = .default super.init(coder: coder) setup() } public init(handler: NSDecimalNumberHandler) { self.handler = handler super.init(frame: .zero) setup() } func setup() { value = .zero keyboardType = .decimalPad addTarget(self, action: #selector(editingChanged), for: .editingChanged) } @objc func editingChanged(_ sender: UITextField) { guard shouldBeReformat(text: text ?? "") else { return } text = format(number: .init(string: text)).stringValue undoManager?.removeAllActions() } func shouldBeReformat(text: String) -> Bool { let phoneNumberRegex = "^([1-9]\\d*|0)?(\\.(\\d+)?)?$" let predicate = NSPredicate(format: "SELF MATCHES %@", phoneNumberRegex) if predicate.evaluate(with: text) { let number = NSDecimalNumber(string: text) let formatNumber = format(number: number) if number == formatNumber { return false } else { return true } } else { return true } } func format(number: NSDecimalNumber) -> NSDecimalNumber { number.adding(.zero, withBehavior: handler) } }
mit
daf538c01c544ed078e8a805a087b5bf
29.377358
80
0.578882
4.791667
false
false
false
false
adrfer/swift
test/Constraints/tuple.swift
1
4699
// RUN: %target-parse-verify-swift // Test various tuple constraints. func f0(x x: Int, y: Float) {} var i : Int var j : Int var f : Float func f1(y y: Float, rest: Int...) {} func f2(_: (x: Int, y: Int) -> Int) {} func f2xy(x x: Int, y: Int) -> Int {} func f2ab(a a: Int, b: Int) -> Int {} func f2yx(y y: Int, x: Int) -> Int {} func f3(x: (x: Int, y: Int) -> ()) {} func f3a(x: Int, y: Int) {} func f3b(_: Int) {} func f4(rest: Int...) {} func f5(x: (Int, Int)) {} func f6(_: (i: Int, j: Int), k: Int = 15) {} //===----------------------------------------------------------------------===// // Conversions and shuffles //===----------------------------------------------------------------------===// // Variadic functions. f4() f4(1) f4(1, 2, 3) f2(f2xy) f2(f2ab) f2(f2yx) // expected-error{{cannot convert value of type '(y: Int, x: Int) -> Int' to expected argument type '(x: Int, y: Int) -> Int'}} f3(f3a) f3(f3b) // expected-error{{cannot convert value of type '(Int) -> ()' to expected argument type '(x: Int, y: Int) -> ()'}} func getIntFloat() -> (int: Int, float: Float) {} var values = getIntFloat() func wantFloat(_: Float) {} wantFloat(values.float) var e : (x: Int..., y: Int) // expected-error{{cannot create a variadic tuple}} typealias Interval = (a:Int, b:Int) func takeInterval(x: Interval) {} takeInterval(Interval(1, 2)) f5((1,1)) // Tuples with existentials var any : Any = () any = (1, 2) any = (label: 4) // Scalars don't have .0/.1/etc i = j.0 // expected-error{{value of type 'Int' has no member '0'}} any.1 // expected-error{{value of type 'Any' (aka 'protocol<>') has no member '1'}} // Fun with tuples protocol PosixErrorReturn { static func errorReturnValue() -> Self } extension Int : PosixErrorReturn { static func errorReturnValue() -> Int { return -1 } } func posixCantFail<A, T : protocol<Comparable, PosixErrorReturn>> (f:(A) -> T) -> (args:A) -> T { return { args in let result = f(args) assert(result != T.errorReturnValue()) return result } } func open(name: String, oflag: Int) -> Int { } var foo: Int = 0 var fd = posixCantFail(open)(args: ("foo", 0)) // Tuples and lvalues class C { init() {} func f(_: C) {} } func testLValue(c: C) { var c = c c.f(c) let x = c c = x } // <rdar://problem/21444509> Crash in TypeChecker::coercePatternToType func invalidPatternCrash(k : Int) { switch k { case (k, cph_: k) as UInt8: // expected-error {{tuple pattern cannot match values of the non-tuple type 'UInt8'}} expected-warning {{cast from 'Int' to unrelated type 'UInt8' always fails}} break } } // <rdar://problem/21875219> Tuple to tuple conversion with IdentityExpr / AnyTryExpr hang class Paws { init() throws {} } func scruff() -> (AnyObject?, ErrorType?) { do { return try (Paws(), nil) } catch { return (nil, error) } } // Test variadics with trailing closures. func variadicWithTrailingClosure(x: Int..., y: Int = 2, fn: (Int, Int) -> Int) { } variadicWithTrailingClosure(1, 2, 3) { $0 + $1 } variadicWithTrailingClosure(1) { $0 + $1 } variadicWithTrailingClosure() { $0 + $1 } variadicWithTrailingClosure { $0 + $1 } variadicWithTrailingClosure(1, 2, 3, y: 0) { $0 + $1 } variadicWithTrailingClosure(1, y: 0) { $0 + $1 } variadicWithTrailingClosure(y: 0) { $0 + $1 } variadicWithTrailingClosure(1, 2, 3, y: 0, fn: +) variadicWithTrailingClosure(1, y: 0, fn: +) variadicWithTrailingClosure(y: 0, fn: +) variadicWithTrailingClosure(1, 2, 3, fn: +) variadicWithTrailingClosure(1, fn: +) variadicWithTrailingClosure(fn: +) // <rdar://problem/23700031> QoI: Terrible diagnostic in tuple assignment func gcd_23700031<T>(a: T, b: T) { var a = a var b = b (a, b) = (b, a % b) // expected-error {{binary operator '%' cannot be applied to two 'T' operands}} // expected-note @-1 {{overloads for '%' exist with these partially matching parameter lists: (UInt8, UInt8), (Int8, Int8), (UInt16, UInt16), (Int16, Int16), (UInt32, UInt32), (Int32, Int32), (UInt64, UInt64), (Int64, Int64), (UInt, UInt), (Int, Int), (Float, Float)}} } // <rdar://problem/24210190> // Don't ignore tuple labels in same-type constraints or stronger. protocol Kingdom { associatedtype King } struct Victory<General> { init<K: Kingdom where K.King == General>(_ king: K) {} } struct MagicKingdom<K> : Kingdom { typealias King = K } func magify<T>(t: T) -> MagicKingdom<T> { return MagicKingdom() } func foo(pair: (Int,Int)) -> Victory<(x:Int, y:Int)> { return Victory(magify(pair)) // expected-error {{cannot invoke initializer for type 'Victory<_>' with an argument list of type '(MagicKingdom<(Int, Int)>)'}} expected-note {{expected an argument list of type '(K)'}} }
apache-2.0
3dae3b0933b2c914bfb07a1daf01286b
26.641176
270
0.618004
3.081311
false
false
false
false
Bajocode/ExploringModerniOSArchitectures
Architectures/Shared/Utility/SharedExtensions.swift
1
2674
// // SharedExtensions.swift // Architectures // // Created by Fabijan Bajo on 29/05/2017. // // import UIKit // MARK: - UIImageView extension UIImageView { public func downloadImage(from url: URL, completion: (() -> Void)? = nil) { // Remove "/" because docs dir sees as folders let cacheKey = url.path.components(separatedBy: "/").dropFirst(3).joined(separator: "") if let image = DataManager.shared.imageStore.image(forKey: cacheKey) { DispatchQueue.main.async { self.image = image completion?() } return } // Nothing in cache / docs? Fetch new URLSession.shared.dataTask(with: url, completionHandler: { [weak self] (data, response, error) in print("Image from network fetch") guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let data = data, error == nil, let image = UIImage(data: data) else { completion?() print("Could not fetch image for url: \(url.path)") return } DataManager.shared.imageStore.setImage(image, forKey: cacheKey) DispatchQueue.main.async { self?.image = image completion?() } }).resume() } } // MARK: - UICollectionViewFlowLayout extension UICollectionViewFlowLayout { // Inits layout with equal spacing for all insets and itemspacings convenience init(abstraction: CollectionViewConfigurable, bounds: CGRect) { self.init() // Define values let spacing = CGFloat(abstraction.interItemSpacing ?? 0) var bottomInset = CGFloat() let widthDivisor = CGFloat(abstraction.widthDivisor) let heightDivisor = CGFloat(abstraction.heightDivisor) // iOS11 no top layout guide if #available(iOS 11.0, *) { bottomInset = 0 } else { bottomInset = CGFloat(abstraction.bottomInset ?? 0) } // Calculate itemSize let fullWspace = (widthDivisor + 1) * spacing let fullHspace = (heightDivisor + 1) * spacing let width = (bounds.width - fullWspace) / widthDivisor let height = (bounds.height - fullHspace) / heightDivisor self.itemSize = CGSize(width: width, height: height) sectionInset = UIEdgeInsets( top: spacing, left: spacing, bottom: bottomInset, right: spacing ) minimumInteritemSpacing = spacing minimumLineSpacing = spacing } }
mit
9f561bc9f7124d85e9b1e89f4ca794b9
33.727273
105
0.585639
4.97026
false
false
false
false
shamanskyh/Precircuiter
Precircuiter/Models/InstrumentDataDocument.swift
1
11460
// // InstrumentDataDocument.swift // Precircuiter // // Created by Harry Shamansky on 9/6/15. // Copyright © 2015 Harry Shamansky. All rights reserved. // import Cocoa class InstrumentDataDocument: NSDocument { /// an array of all lights, moving lights, and practicals /// bound to the array controller in IB and observed in the table view dynamic var allLights: [Instrument] = [] /// an array of all dimmers var allDimmers: [Instrument] = [] /// an array to keep track of non-light and non-dimmer instruments that should /// still be written on export var otherInstruments: [Instrument] = [] /// a way of keeping track of the encoding so that we export as we imported var fileEncoding: String.Encoding? /// an array of the possible fields on each instrument we import var headers: [String] = [] override func makeWindowControllers() { // Returns the Storyboard that contains the Document window let storyboard = NSStoryboard(name: kMainStoryboardIdentifier, bundle: nil) let windowController = storyboard.instantiateController(withIdentifier: kMainDocumentWindowIdentifier) as! NSWindowController self.addWindowController(windowController) } override func data(ofType typeName: String) throws -> Data { // put UID second for easy import into Vectorworks headers = headers.sorted(by: { ($0 == "__UID" && $1 != "__UID") }) headers = headers.sorted(by: { ($0 == "Device Type" && $1 != "Device Type") }) var runningString: String = "" for header in headers { runningString += header runningString.append(("\t" as Character)) } runningString = String(runningString.dropLast()) // remove the trailing tab runningString.append(("\n" as Character)) for inst in allLights + allDimmers + otherInstruments { for header in headers { do { if let item = try getPropertyFromInstrument(inst, propertyString: header) { runningString += item } else { runningString += "-" } runningString.append(("\t" as Character)) } catch { throw TextExportError.propertyNotFound } } runningString = String(runningString.dropLast()) // remove the trailing tab runningString.append(("\n" as Character)) } guard let encoding = fileEncoding else { if let data = runningString.data(using: String.Encoding.macOSRoman) { return data } throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) } if let data = runningString.data(using: encoding) { return data } throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) } override func read(from data: Data, ofType typeName: String) throws { undoManager?.disableUndoRegistration() // TODO: Allow user to specify file encoding fileEncoding = String.Encoding.macOSRoman let rawFile = String(data: data, encoding: fileEncoding!) guard let importString = rawFile else { throw TextImportError.encodingError } var finishedHeaders: Bool = false var currentKeyword: String = "" var currentPosition: Int = 0 var currentInstrument: Instrument = Instrument(UID: nil, location: nil, undoManager: self.undoManager) var tempLights: [Instrument] = [] var tempDimmers: [Instrument] = [] DispatchQueue.global(qos: .background).async { [weak self] in guard let strongSelf = self else { return } for char in importString { if !finishedHeaders { if char == "\t" { strongSelf.headers.append(currentKeyword) currentKeyword = "" } else if char == "\n" || char == "\r" || char == "\r\n" { strongSelf.headers.append(currentKeyword) currentKeyword = "" finishedHeaders = true } else { currentKeyword.append(char) } } else { if char == "\t" { guard currentPosition < strongSelf.headers.count else { DispatchQueue.main.async { [weak strongSelf] in strongSelf?.displayCouldNotImportPlotError() } return } do { try addPropertyToInstrument(&currentInstrument, propertyString: strongSelf.headers[currentPosition], propertyValue: currentKeyword) currentPosition += 1 } catch InstrumentError.ambiguousLocation { DispatchQueue.main.async { [weak strongSelf] in strongSelf?.displayCouldNotImportPlotError() } return } catch InstrumentError.propertyStringUnrecognized { NSLog("Could not import property: \(strongSelf.headers[currentPosition - 1])") continue } catch { DispatchQueue.main.async { [weak strongSelf] in strongSelf?.displayCouldNotImportPlotError() } return } currentKeyword = "" } else if char == "\n" || char == "\r" || char == "\r\n" { guard currentPosition < strongSelf.headers.count else { DispatchQueue.main.async { [weak strongSelf] in strongSelf?.displayCouldNotImportPlotError() } return } // finish the last property do { try addPropertyToInstrument(&currentInstrument, propertyString: strongSelf.headers[currentPosition], propertyValue: currentKeyword) } catch InstrumentError.ambiguousLocation { DispatchQueue.main.async { [weak strongSelf] in strongSelf?.displayCouldNotImportPlotError() } return } catch InstrumentError.propertyStringUnrecognized { NSLog("Could not import property: \(strongSelf.headers[currentPosition])") continue } catch { DispatchQueue.main.async { [weak strongSelf] in strongSelf?.displayCouldNotImportPlotError() } return } currentKeyword = "" currentPosition = 0 currentInstrument.assignedBy = .outsideOfApplication if currentInstrument.deviceType == .power { tempDimmers.append(currentInstrument) } else if currentInstrument.deviceType == .light || currentInstrument.deviceType == .movingLight || currentInstrument.deviceType == .practical { tempLights.append(currentInstrument) } else { strongSelf.otherInstruments.append(currentInstrument) } currentInstrument = Instrument(UID: nil, location: nil, undoManager: strongSelf.undoManager) } else { currentKeyword.append(char) } } } strongSelf.allLights = tempLights strongSelf.allDimmers = tempDimmers // throw an error if no lights or dimmers are found. Probably a garbage plot if strongSelf.allLights.count == 0 && strongSelf.allDimmers.count == 0 { DispatchQueue.main.async { [weak strongSelf] in strongSelf?.displayCouldNotImportPlotError() } return } // if we don't have any locations, also return. the user probably forgot to export all field names. var foundLocation = false for light in strongSelf.allLights { if light.locations.count > 0 { foundLocation = true break } } guard foundLocation == true else { DispatchQueue.main.async { [weak strongSelf] in strongSelf?.displayCouldNotImportPlotError() } return } // For any light that has a dimmer filled in, try to find the corresponding power object, and link that power object to the light as well (two-way link) for light in strongSelf.allLights.filter({ $0.dimmer != nil }) { connect(light: light, dimmers: strongSelf.allDimmers) } // TODO: there's probably a better way to do this, but it's not // going to block a thread since we're in an async block... while (strongSelf.mainWindowController == nil) { continue } DispatchQueue.main.async { [weak strongSelf] in guard let strongStrongSelf = strongSelf else { return } (strongStrongSelf.mainWindowController!.window?.contentViewController as! MainViewController).representedObject = strongStrongSelf strongStrongSelf.undoManager?.enableUndoRegistration() } } } override class var autosavesInPlace: Bool { return false } var mainWindowController: MainWindowController? { return self.windowControllers.filter({ $0 is MainWindowController }).first as? MainWindowController } func displayCouldNotImportPlotError() { let alert = NSAlert() alert.messageText = "Error Importing Plot" alert.informativeText = "Precircuiter could not read the instrument data from this file. Please ensure that you are opening instrument data that you exported from Vectorworks using the File > Export menu.\n\nAlso ensure that all parameters were exported, with the field names exported as the first record.\n\nNote that this is NOT the same as the .xml file that Lightwright uses." mainWindowController?.window?.orderOut(self) alert.runModal() } }
mit
f2d231912db9e786ac4f80948e3571fb
44.29249
388
0.52317
6.012067
false
false
false
false
srn214/Floral
Floral/Pods/WCDB.swift/swift/source/util/Recyclable.swift
1
1194
/* * Tencent is pleased to support the open source community by making * WCDB available. * * Copyright (C) 2017 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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 //TODO: Refactor class Recyclable<Value> { typealias OnRecycled = () -> Void let onRecycled: OnRecycled? final let raw: Value init(_ raw: Value, onRecycled: @escaping OnRecycled) { self.raw = raw self.onRecycled = onRecycled } init(_ raw: Value) { self.raw = raw self.onRecycled = nil } deinit { if onRecycled != nil { onRecycled!() } } }
mit
0c8e1c465aba34a04605ffb16aedc7c1
25.533333
76
0.665829
4.103093
false
false
false
false
srn214/Floral
Floral/Pods/SwiftLocation/Sources/Support/JSONOperation.swift
1
2576
// // SwiftLocation - Efficient Location Tracking for iOS // // Created by Daniele Margutti // - Web: https://www.danielemargutti.com // - Twitter: https://twitter.com/danielemargutti // - Mail: [email protected] // // Copyright © 2019 Daniele Margutti. Licensed under MIT License. import Foundation public class JSONOperation { // MARK: - Public Typealiases - public typealias ResponseData = Result<Any,LocationManager.ErrorReason> public typealias Callback = ((ResponseData) -> Void) // MARK: - Private Properties - /// Task of the operation private var task: URLSessionDataTask? /// Callback to call at the end private var callback: Callback? /// Request to make. private var request: URLRequest // MARK: - Public Methods - /// Create a new request. /// /// - Parameters: /// - url: url to download. /// - timeout: timeout of the request, `10` seconds if not explicitly specified. /// - cachePolicy: cache policy, if not specified `reloadIgnoringLocalAndRemoteCacheData`. public init(_ url: URL, timeout: TimeInterval?, cachePolicy: NSURLRequest.CachePolicy? = nil) { self.request = URLRequest(url: url, cachePolicy: (cachePolicy ?? .reloadIgnoringLocalAndRemoteCacheData), timeoutInterval: timeout ?? 10.0) } /// Start a request. Any pending request from the same class will be discarded. /// /// - Parameter callback: callback to call as response to the request. public func start(_ callback: @escaping Callback) { self.task?.cancel() self.callback = callback self.task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in self?.onReceiveResponse(data, response, error) }) self.task?.resume() } /// Stop task without dispatching the event to callback. public func stop() { self.callback = nil self.task?.cancel() } // MARK: - Private Methods - private func onReceiveResponse(_ data: Data?, _ response: URLResponse?, _ error: Error?) { if let error = error { callback?(.failure(.generic(error.localizedDescription))) return } guard let data = data else { callback?(.failure(.noData(request.url))) return } if let json = try? JSONSerialization.jsonObject(with: data, options: []) { callback?(.success(json)) } } }
mit
8e0642495aefd3aa97b526ac4e6f2fe2
32.012821
147
0.622136
4.804104
false
false
false
false
qualaroo/QualarooSDKiOS
Qualaroo/Survey/Body/Question/List/AnswerListView.swift
1
5501
// // AnswerListView.swift // Qualaroo // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import UIKit class AnswerListView: UIView { class Builder { let question: Question let buttonHandler: SurveyButtonHandler let answerHandler: SurveyAnswerHandler let selecter: AnswerSelectionConfigurator let theme: Theme let onImage: UIImage let offImage: UIImage init(question: Question, buttonHandler: SurveyButtonHandler, answerHandler: SurveyAnswerHandler, selecter: AnswerSelectionConfigurator, theme: Theme, onImage: UIImage, offImage: UIImage) { self.question = question self.buttonHandler = buttonHandler self.answerHandler = answerHandler self.selecter = selecter self.theme = theme self.onImage = onImage self.offImage = offImage } func build() -> AnswerListView { let view = answerListView() let viewModels = selectableViewModels(colors: theme.colors, answers: question.answerList) let imageProvider = ImageProvider(normalColor: theme.colors.uiNormal, normalImage: offImage, selectedColor: theme.colors.uiSelected, selectedImage: onImage) let interactor = answerListInteractor(buttonHandler: buttonHandler, answerHandler: answerHandler, question: question) let presenter = AnswerListPresenter(view: view, interactor: interactor, selecter: selecter) view.setupView(backgroundColor: theme.colors.background, selectableViewModels: viewModels, imageProvider: imageProvider, selectionHandler: presenter) return view } private func answerListView() -> AnswerListView { guard let nib = Bundle.qualaroo()?.loadNibNamed("AnswerListView", owner: nil, options: nil), let view = nib.first as? AnswerListView else { return AnswerListView() } return view } private func selectableViewModels(colors: ColorTheme, answers: [Answer]) -> [SelectableView.ViewModel] { return answers.map { SelectableView.ViewModel(title: $0.title, textColor: colors.text, normalBorderColor: colors.uiNormal, selectedBorderColor: colors.uiSelected, expandabable: $0.isFreeformCommentAllowed) } } private func answerListInteractor(buttonHandler: SurveyButtonHandler, answerHandler: SurveyAnswerHandler, question: Question) -> AnswerListInteractor { let responseBuilder = AnswerListResponseBuilder(question: question) let validator = AnswerListValidator(question: question) return AnswerListInteractor(responseBuilder: responseBuilder, validator: validator, buttonHandler: buttonHandler, answerHandler: answerHandler, question: question) } } private struct Const { static let cellMargin: CGFloat = 20 static let cellSpacing: CGFloat = 8 static let cellEstimatedHeight: CGFloat = 48 } private var presenter: SelectableViewDelegate? @IBOutlet weak var buttonsContainerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var buttonsScrollContainer: UIScrollView! var selectableViews = [SelectableView]() func setupView(backgroundColor: UIColor, selectableViewModels: [SelectableView.ViewModel], imageProvider: SelectionImageProvider, selectionHandler: SelectableViewDelegate) { self.backgroundColor = backgroundColor translatesAutoresizingMaskIntoConstraints = false selectableViews = selectableViewModels.map { SelectableView.Builder(imageProvider: imageProvider, delegate: selectionHandler, viewModel: $0).build() } self.presenter = selectionHandler setupWithViews(selectableViews) } func resize() { Animation(duration: kAnimationTime) { self.buttonsContainerHeightConstraint.constant = self.buttonsScrollContainer.contentSize.height self.superview?.superview?.superview?.layoutIfNeeded() }.run() } private func setupWithViews(_ views: [SelectableView]) { NSLayoutConstraint.fillScrollView(buttonsScrollContainer, with: views, margin: Const.cellMargin, spacing: Const.cellSpacing) let prepareInitialState = Animation(duration: kAnimationTime/3) { let cellsCount = CGFloat(views.count) self.buttonsContainerHeightConstraint.constant = cellsCount * Const.cellEstimatedHeight } let resize = Animation(duration: kAnimationTime * 2/3) { self.resize() } prepareInitialState.then(resize).run() } }
mit
6462249bb710420d794c265363e2dc1e
39.448529
101
0.611525
5.736184
false
false
false
false
kpham13/SkaterBrad
SkaterBrad/SoundNode.swift
1
2066
// // MusicNode.swift // SkaterBrad // // Copyright (c) 2014 Mother Functions. All rights reserved. // import UIKit import SpriteKit import AVFoundation class SoundNode: SKNode { var audioPlayer : AVAudioPlayer! = nil var isSoundOn = true let backgoundMusicFile = "CoolKids" var avAudioSession : AVAudioSession! var musicURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("CoolKids", ofType: "wav")!) init(isSoundOn : Bool) { super.init() self.avAudioSession = AVAudioSession.sharedInstance() self.avAudioSession.setCategory(AVAudioSessionCategoryPlayback, error: nil) self.avAudioSession.setActive(true, error: nil) self.avAudioSession.setCategory(AVAudioSessionCategoryAmbient, error: nil) self.audioPlayer = AVAudioPlayer() //var musicURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(self.backgoundMusicFile, ofType: "mp3")!) self.audioPlayer = AVAudioPlayer(contentsOfURL: musicURL, error: nil) self.audioPlayer.numberOfLoops = 100 // Continuous play of background music [Kevin/Tuan] self.audioPlayer.volume = 0.1 // Adjusts background music volume [Kevin] self.isSoundOn = isSoundOn self.playMusic(isSoundOn) // if self.isSoundOn { // self.audioPlayer.prepareToPlay() // self.audioPlayer.play() // } } func playMusic(isSoundOn : Bool) { var error : NSError? self.audioPlayer = AVAudioPlayer(contentsOfURL: musicURL, error: nil) if error != nil { println(error) } else { if isSoundOn { self.audioPlayer.prepareToPlay() self.audioPlayer.numberOfLoops = -1 self.audioPlayer.volume = 0.25 self.audioPlayer?.play() } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
bsd-2-clause
3ff42d6528020e9231253ace60f8362c
30.318182
127
0.621975
4.632287
false
false
false
false
inacioferrarini/OMDBSpy
OMDBSpyTests/Foundation/ViewControllers/TestBaseViewControllerTests.swift
1
1098
import XCTest @testable import OMDBSpy class TestBaseViewControllerTests: XCTestCase { var viewController: TestBaseViewController! override func setUp() { super.setUp() let appContext = TestUtil().appContext() let navigationController = TestUtil().rootViewController() viewController = TestUtil().testBaseViewController(appContext) navigationController.pushViewController(viewController, animated: true) UIApplication.sharedApplication().keyWindow!.rootViewController = navigationController let _ = navigationController.view let _ = viewController.view } func test_appContext_notNil() { XCTAssertNotNil(viewController.appContext) } func test_viewControllerTitle_nil() { let bundle = NSBundle(forClass: self.dynamicType) let viewControllerTitle = NSLocalizedString("VC_TEST_BASE_VIEW_CONTROLLER", tableName: nil, bundle: bundle, value: "", comment: "") XCTAssertEqual(viewController.viewControllerTitle(), viewControllerTitle) } }
mit
60278be84ef4b400eb3cea27f79f6afc
34.419355
139
0.693989
5.778947
false
true
false
false
swift-api/SampleServer
Sources/SampleServer/main.swift
1
2013
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ // KituraSample shows examples for creating custom routes. import Foundation import KituraSys import KituraNet import Kitura import HeliumLogger import LoggerAPI import SwiftRedis import MongoKitten import SwiftyJSON #if os(Linux) import Glibc #endif // MARK: Setup // Using an implementation for a Logger Log.logger = HeliumLogger() // All Web apps need a router to define routes let router = Kitura.Router() /** * RouterMiddleware can be used for intercepting requests and handling custom behavior * such as authentication and other routing */ class BasicAuthMiddleware: RouterMiddleware { func handle(request: RouterRequest, response: RouterResponse, next: () -> Void) { let authString = request.headers["Authorization"] Log.info("Authorization: \(authString)") // Check authorization string in database to approve the request if fail // response.error = NSError(domain: "AuthFailure", code: 1, userInfo: [:]) next() } } // This route executes the echo middleware router.all(middleware: BasicAuthMiddleware()) //setupRedisAPI(router: router) //setupMongoAPI(router: router) setupHelloAPI() defaultSetup() let slacket = Slacket(using: router) // Listen on port 80 #if os(OSX) let serverPort = 8090 #else let serverPort = 80 #endif let server = HttpServer.listen(port: serverPort, delegate: router) Server.run()
apache-2.0
7d77c64d10259b405c289d57d61a27ef
24.820513
86
0.726776
4.237895
false
false
false
false
FoodMob/FoodMob-iOS
FoodMob/Model/FoodCategory.swift
1
1774
// // FoodCategories.swift // FoodMob // // Created by Jonathan Jemson on 2/10/16. // Copyright © 2016 FoodMob. All rights reserved. // import Foundation /** Preference indicates whether a user likes, dislikes, or cannot have a certain food category. */ public enum Preference: Int { /// No preference. Usuaslly a sign of an error. case None = 0 /// Indicates that a user likes this category. case Like = 1 /// Indicates that a user dislikes this category. case Dislike = 2 /// Indicates that a user cannot have this category. case Restriction = 3 /// A string representation of this enum. public var showingTypeString: String { switch self { case None: return "None" case Like: return "Likes" case Dislike: return "Dislikes" case Restriction: return "Restrictions" } } } /** Represents a food category, which is the tuple of the human-readable name and the Yelp identifier. */ public struct FoodCategory: Hashable { /// Human-readable name of the category private(set) public var displayName: String /// Yelp identifier for the category private(set) public var yelpIdentifier: String /// Conformance to Hashable for FoodCategory public var hashValue: Int { return yelpIdentifier.hashValue } } /** Conformance to Equatable for a FoodCategory. Two food categories are equal iff the Yelp identifiers are equal. - parameter lhs: Left side of the expression. - parameter rhs: Right side of the expression. - returns: Whether two food categories are equal. */ public func ==(lhs: FoodCategory, rhs: FoodCategory) -> Bool { return lhs.yelpIdentifier == rhs.yelpIdentifier }
mit
a117987358398328d348491548ea3bc9
26.292308
99
0.668923
4.410448
false
false
false
false
Zewo/Aeon
Aeon/HTTPServer/HTTPSerializer.swift
1
1752
// HTTPSerializer.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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 HTTP import Stream struct HTTPSerializer: HTTPResponseSerializerType { func serializeResponse(client: StreamType, response: HTTPResponse, completion: (Void throws -> Void) -> Void) { var string = "HTTP/\(response.majorVersion).\(response.minorVersion) \(response.statusCode) \(response.reasonPhrase)\r\n" for (name, value) in response.headers { string += "\(name): \(value)\r\n" } string += "\r\n" var data = string.utf8.map { Int8($0) } data += response.body client.send(data, completion: completion) } }
mit
5478b2140ed381fec1e8b05efdd26be0
39.744186
129
0.715753
4.413098
false
false
false
false
eugeneego/utilities-ios
Sources/UI/UIImage+Render.swift
1
1190
// // UIImage (Render) // Legacy // // Copyright (c) 2015 Eugene Egorov. // License: MIT, https://github.com/eugeneego/legacy/blob/master/LICENSE // #if canImport(UIKit) && !os(watchOS) import UIKit public extension UIImage { typealias Render = (_ rendererContext: UIGraphicsImageRendererContext, _ bounds: CGRect) -> Void static func image(size: CGSize, render: Render) -> UIImage { let renderer = UIGraphicsImageRenderer(size: size) return renderer.image { context in render(context, renderer.format.bounds) } } func prerender() { _ = Self.image(size: CGSize(width: 1, height: 1)) { _, _ in draw(at: .zero) } } func prerenderedImage() -> UIImage { if #available(iOS 15.0, tvOS 15.0, *), let image = preparingForDisplay() { return image } return Self.image(size: size) { _, bounds in draw(in: bounds) } } static func image(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage { image(size: size) { context, bounds in color.setFill() context.fill(bounds) } } } #endif
mit
515c8d494e56cb69cd7c12c1b3976fc7
24.869565
100
0.584874
3.914474
false
false
false
false
qutheory/vapor
Sources/Vapor/Content/Content.swift
1
4355
/// Convertible to / from content in an HTTP message. /// /// Conformance to this protocol consists of: /// /// - `Codable` /// - `RequestDecodable` /// - `ResponseEncodable` /// /// If adding conformance in an extension, you must ensure the type already conforms to `Codable`. /// /// struct Hello: Content { /// let message = "Hello!" /// } /// /// router.get("greeting") { req in /// return Hello() // {"message":"Hello!"} /// } /// public protocol Content: Codable, RequestDecodable, ResponseEncodable { /// The default `MediaType` to use when _encoding_ content. This can always be overridden at the encode call. /// /// Default implementation is `MediaType.json` for all types. /// /// struct Hello: Content { /// static let defaultContentType = .urlEncodedForm /// let message = "Hello!" /// } /// /// router.get("greeting") { req in /// return Hello() // message=Hello! /// } /// /// router.get("greeting2") { req in /// let res = req.response() /// try res.content.encode(Hello(), as: .json) /// return res // {"message":"Hello!"} /// } /// static var defaultContentType: HTTPMediaType { get } /// Called before this `Content` is encoded, generally for a `Response` object. /// /// You should use this method to perform any "sanitizing" which you need on the data. /// For example, you may wish to replace empty strings with a `nil`, `trim()` your /// strings or replace empty arrays with `nil`. You can also use this method to abort /// the encoding if something isn't valid. An empty array may indicate an error, for example. mutating func beforeEncode() throws /// Called after this `Content` is decoded, generally from a `Request` object. /// /// You should use this method to perform any "sanitizing" which you need on the data. /// For example, you may wish to replace empty strings with a `nil`, `trim()` your /// strings or replace empty arrays with `nil`. You can also use this method to abort /// the decoding if something isn't valid. An empty string may indicate an error, for example. mutating func afterDecode() throws } /// MARK: Default Implementations extension Content { public static var defaultContentType: HTTPMediaType { return .json } public static func decodeRequest(_ request: Request) -> EventLoopFuture<Self> { do { let content = try request.content.decode(Self.self) return request.eventLoop.makeSucceededFuture(content) } catch { return request.eventLoop.makeFailedFuture(error) } } public func encodeResponse(for request: Request) -> EventLoopFuture<Response> { let response = Response() do { try response.content.encode(self) } catch { return request.eventLoop.makeFailedFuture(error) } return request.eventLoop.makeSucceededFuture(response) } public mutating func beforeEncode() throws { } public mutating func afterDecode() throws { } } // MARK: Default Conformances extension String: Content { public static var defaultContentType: HTTPMediaType { return .plainText } } extension FixedWidthInteger where Self: Content { public static var defaultContentType: HTTPMediaType { return .plainText } } extension Int: Content { } extension Int8: Content { } extension Int16: Content { } extension Int32: Content { } extension Int64: Content { } extension UInt: Content { } extension UInt8: Content { } extension UInt16: Content { } extension UInt32: Content { } extension UInt64: Content { } extension BinaryFloatingPoint where Self: Content { public static var defaultContentType: HTTPMediaType { return .plainText } } extension Double: Content { } extension Float: Content { } extension Array: Content, ResponseEncodable, RequestDecodable where Element: Content { public static var defaultContentType: HTTPMediaType { return .json } } extension Dictionary: Content, ResponseEncodable, RequestDecodable where Key == String, Value: Content { public static var defaultContentType: HTTPMediaType { return .json } }
mit
c9d85effcab86d2324fd1eceb1c685a1
32.244275
113
0.647302
4.512953
false
false
false
false
narner/AudioKit
AudioKit/Common/MIDI/AKMIDIEvent.swift
1
13026
// // AKMIDIEvent.swift // AudioKit // // Created by Jeff Cooper, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // import CoreMIDI extension MIDIByte { /// This limits the range to be from 0 to 127 func lower7bits() -> MIDIByte { return self & 0x7F } /// This limits the range to be from 0 to 16 func lowbit() -> MIDIByte { return self & 0xF } } extension MIDIPacket { var isSysex: Bool { return data.0 == AKMIDISystemCommand.sysex.rawValue } var status: AKMIDIStatus? { return AKMIDIStatus(rawValue: Int(data.0) >> 4) } var channel: MIDIChannel { return data.0.lowbit() } var command: AKMIDISystemCommand? { return AKMIDISystemCommand(rawValue: data.0) } } /// A container for the values that define a MIDI event public struct AKMIDIEvent { // MARK: - Properties /// Internal data public var internalData = [MIDIByte](zeros: 128) /// The length in bytes for this MIDI message (1 to 3 bytes) var length: MIDIByte? /// Status public var status: AKMIDIStatus? { let status = internalData[0] >> 4 return AKMIDIStatus(rawValue: Int(status)) } /// System Command public var command: AKMIDISystemCommand? { let status = internalData[0] >> 4 if status < 15 { return .none } return AKMIDISystemCommand(rawValue: internalData[0]) } /// MIDI Channel public var channel: MIDIChannel? { let status = internalData[0] >> 4 if status < 16 { return internalData[0].lowbit() } return nil } func statusFrom(rawByte: MIDIByte) -> AKMIDIStatus? { return AKMIDIStatus(rawValue: Int(rawByte >> 4)) } func channelFrom(rawByte: MIDIByte) -> MIDIChannel { let status = rawByte >> 4 if status < 16 { return MIDIChannel(rawByte.lowbit()) } return 0 } /// MIDI Note Number public var noteNumber: MIDINoteNumber? { if status == .noteOn || status == .noteOff { return MIDINoteNumber(internalData[1]) } return nil } /// First data byte public var data1: MIDIByte { return internalData[1] } /// Second data byte public var data2: MIDIByte { return internalData[2] } /// Representation of the MIDI data as a MIDI word 0-16383 public var wordData: MIDIWord { if internalData.count < 2 { return 0 } let x = MIDIWord(internalData[1]) let y = MIDIWord(internalData[2]) << 7 return y + x } var bytes: Data { return Data(bytes: internalData.prefix(3)) } static fileprivate let statusBit: MIDIByte = 0b10000000 // MARK: - Initialization /// Initialize the MIDI Event from a MIDI Packet /// /// - parameter packet: MIDIPacket that is potentially a known event type /// public init(packet: MIDIPacket) { if packet.data.0 < 0xF0 { if let status = packet.status { fillData(status: status, channel: packet.channel, byte1: packet.data.1, byte2: packet.data.2) } } else { if packet.isSysex { internalData = [] //reset internalData var computedLength = MIDIByte(0) //voodoo let mirrorData = Mirror(reflecting: packet.data) for (_, value) in mirrorData.children { if computedLength < 255 { computedLength += 1 } guard let byte = value as? MIDIByte else { AKLog("unable to create sysex midi byte") return } internalData.append(byte) if byte == 247 { break } } setLength(computedLength) } else { if let cmd = packet.command { fillData(command: cmd, byte1: packet.data.1, byte2: packet.data.2) } else { AKLog("AKMIDISystemCommand failure due to bad data - need to investigate") } } } internalData = Array(internalData.prefix(Int(length!))) } /// Generate array of MIDI events from Bluetooth data public static func generateFrom(bluetoothData: [MIDIByte]) -> [AKMIDIEvent] { //1st byte timestamp coarse will always be > 128 //2nd byte fine timestamp will always be > 128 - if 2nd message < 128, is continuing sysex //3nd < 128 running message - timestamp //status byte determines length of message var midiEvents: [AKMIDIEvent] = [] if bluetoothData.count > 1 { var rawEvents: [[MIDIByte]] = [] if bluetoothData[1] < 128 { //continuation of sysex from previous packet - handle separately //(probably needs a whole bluetooth MIDI class so we can see the previous packets) } else { var rawEvent: [MIDIByte] = [] var lastStatus: MIDIByte = 0 var messageJustFinished = false for byte in bluetoothData.dropFirst().dropFirst() { //drops first two bytes as these are timestamp bytes if byte >= 128 { //if we have a new status byte or if rawEvent is a real event if messageJustFinished && byte >= 128 { messageJustFinished = false continue } lastStatus = byte } else { if rawEvent.isEmpty { rawEvent.append(lastStatus) } } rawEvent.append(byte) //set the status byte if (rawEvent.count == 3 && lastStatus != AKMIDISystemCommand.sysex.rawValue) || byte == AKMIDISystemCommand.sysexEnd.rawValue { //end of message messageJustFinished = true if rawEvent.isNotEmpty { rawEvents.append(rawEvent) } rawEvent = [] //init raw Event } } } for event in rawEvents { midiEvents.append(AKMIDIEvent(data: event)) } }//end bluetoothData.count > 0 return midiEvents } /// Initialize the MIDI Event from a raw MIDIByte packet (ie. from Bluetooth) /// /// - Parameters: /// - data: [MIDIByte] bluetooth packet /// public init(data: [MIDIByte]) { if let command = AKMIDISystemCommand(rawValue: data[0]) { internalData = [] // is sys command if command == .sysex { for byte in data { internalData.append(byte) } length = MIDIByte(internalData.count) } else { fillData(command: command, byte1: data[1], byte2: data[2]) } } else if let status = statusFrom(rawByte: data[0]) { // is regular MIDI status let channel = channelFrom(rawByte: data[0]) fillData(status: status, channel: channel, byte1: data[1], byte2: data[2]) } } /// Initialize the MIDI Event from a status message /// /// - Parameters: /// - status: MIDI Status /// - channel: Channel on which the event occurs /// - byte1: First data byte /// - byte2: Second data byte /// init(status: AKMIDIStatus, channel: MIDIChannel, byte1: MIDIByte, byte2: MIDIByte) { fillData(status: status, channel: channel, byte1: byte1, byte2: byte2) } fileprivate mutating func fillData(status: AKMIDIStatus, channel: MIDIChannel, byte1: MIDIByte, byte2: MIDIByte) { internalData[0] = MIDIByte(status.rawValue << 4) | MIDIByte(channel.lowbit()) internalData[1] = byte1.lower7bits() internalData[2] = byte2.lower7bits() setLength(3) } /// Initialize the MIDI Event from a system command message /// /// - Parameters: /// - command: MIDI System Command /// - byte1: First data byte /// - byte2: Second data byte /// init(command: AKMIDISystemCommand, byte1: MIDIByte, byte2: MIDIByte) { fillData(command: command, byte1: byte1, byte2: byte2) } fileprivate mutating func fillData(command: AKMIDISystemCommand, byte1: MIDIByte, byte2: MIDIByte) { if internalData.count <= 0 { return } internalData[0] = command.rawValue switch command { case .sysex: AKLog("sysex") break case .songPosition: internalData[1] = byte1.lower7bits() internalData[2] = byte2.lower7bits() setLength(3) case .songSelect: internalData[1] = byte1.lower7bits() setLength(2) default: setLength(1) } if let existingLength = length { internalData = Array(internalData.prefix(Int(existingLength))) } } // MARK: - Utility constructors for common MIDI events /// Determine whether a given byte is the status byte for a MIDI event /// /// - parameter byte: Byte to test /// static func isStatusByte(_ byte: MIDIByte) -> Bool { return (byte & AKMIDIEvent.statusBit) == AKMIDIEvent.statusBit } /// Determine whether a given byte is a data byte for a MIDI Event /// /// - parameter byte: Byte to test /// static func isDataByte(_ byte: MIDIByte) -> Bool { return (byte & AKMIDIEvent.statusBit) == 0 } /// Convert a byte into a MIDI Status /// /// - parameter byte: Byte to convert /// static func statusFromValue(_ byte: MIDIByte) -> AKMIDIStatus { let status = byte >> 4 return AKMIDIStatus(rawValue: Int(status)) ?? .nothing } /// Create note on event /// /// - Parameters: /// - noteNumber: MIDI Note number /// - velocity: MIDI Note velocity (0-127) /// - channel: Channel on which the note appears /// public init(noteOn noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel) { self.init(status: .noteOn, channel: channel, byte1: noteNumber, byte2: velocity) } /// Create note off event /// /// - Parameters: /// - noteNumber: MIDI Note number /// - velocity: MIDI Note velocity (0-127) /// - channel: Channel on which the note appears /// public init(noteOff noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel) { self.init(status: .noteOff, channel: channel, byte1: noteNumber, byte2: velocity) } /// Create program change event /// /// - Parameters: /// - data: Program change byte /// - channel: Channel on which the program change appears /// public init(programChange data: MIDIByte, channel: MIDIChannel) { self.init(status: .programChange, channel: channel, byte1: data, byte2: 0) } /// Create controller event /// /// - Parameters: /// - controller: Controller number /// - value: Value of the controller /// - channel: Channel on which the controller value has changed /// public init(controllerChange controller: MIDIByte, value: MIDIByte, channel: MIDIChannel) { self.init(status: .controllerChange, channel: channel, byte1: controller, byte2: value) } /// Array of MIDI events from a MIDI packet list poionter static public func midiEventsFrom(packetListPointer: UnsafePointer< MIDIPacketList>) -> [AKMIDIEvent] { return packetListPointer.pointee.map { AKMIDIEvent(packet: $0) } } private mutating func setLength(_ newLength: Int) { setLength(MIDIByte(newLength)) } private mutating func setLength(_ newLength: MIDIByte) { length = newLength internalData = Array(internalData[0..<Int(length!)]) } }
mit
79522ebdc4430ee19ab0b1b499984426
31.081281
120
0.533052
4.755385
false
false
false
false
coderMONSTER/ioscelebrity
YStar/YStar/General/Base/BaseNavigationController.swift
1
2580
// // BaseNavigationController.swift // wp // // Created by 木柳 on 2016/12/17. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit class BaseNavigationController: UINavigationController,UINavigationControllerDelegate ,UIGestureRecognizerDelegate { override func viewDidLoad() { super.viewDidLoad() interactivePopGestureRecognizer?.isEnabled = true interactivePopGestureRecognizer?.delegate = self navigationBar.hideBottomHairline() navigationBar.barTintColor = UIColor.white navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont.systemFont(ofSize: 18), NSForegroundColorAttributeName: UIColor.init(rgbHex: AppConst.ColorKey.main.rawValue) ] navigationBar.tintColor = UIColor.init(rgbHex: AppConst.ColorKey.main.rawValue) navigationBar.backgroundColor = UIColor.white navigationBar.isTranslucent = false } func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } //MARK: 重新写左面的导航 override func pushViewController(_ viewController: UIViewController, animated: Bool) { super.pushViewController(viewController, animated: true) let btn : UIButton = UIButton.init(type: UIButtonType.custom) let backImage = UIImage.imageWith(AppConst.iconFontName.backItem.rawValue, fontSize: CGSize.init(width: 22, height: 22), fontColor: UIColor.init(rgbHex: 0x8c0808)) btn.setTitle("", for: UIControlState.normal) btn.setBackgroundImage(backImage, for: UIControlState.normal ) btn.addTarget(self, action: #selector(popself), for: UIControlEvents.touchUpInside) btn.frame = CGRect.init(x: 0, y: 0, width: 20, height: 20) let barItem : UIBarButtonItem = UIBarButtonItem.init(customView: btn) viewController.navigationItem.leftBarButtonItem = barItem interactivePopGestureRecognizer?.delegate = self } func popself(){ if viewControllers.count > 1 { self.popViewController(animated: true) }else{ dismissController() } } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { if (viewControllers.count <= 1) { return false; } return true; } }
mit
eb0b5621a12600f4147f99a38fa4b15a
38.338462
171
0.686351
5.349372
false
false
false
false
edragoev1/pdfjet
Sources/PDFjet/BMPImage.swift
1
10136
/** * * Copyright 2020 Jonas Krogsböll 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 class BMPImage { var w = 0 // Image width in pixels var h = 0 // Image height in pixels var image: [UInt8]? // The reconstructed image data var deflated: [UInt8]? // The deflated reconstructed image data private var bpp = 0 private var palette: [[UInt8]]? private var r5g6b5: Bool = false // If 16 bit image two encodings can occur private let m10000000: UInt8 = 0x80 private let m01000000: UInt8 = 0x40 private let m00100000: UInt8 = 0x20 private let m00010000: UInt8 = 0x10 private let m00001000: UInt8 = 0x08 private let m00000100: UInt8 = 0x04 private let m00000010: UInt8 = 0x02 private let m00000001: UInt8 = 0x01 private let m11110000: UInt8 = 0xF0 private let m00001111: UInt8 = 0x0F // Tested with images created from GIMP public init(_ stream: InputStream) { let bm = getBytes(stream, 2) // From Wikipedia if (Unicode.Scalar(bm![0]) == "B" && Unicode.Scalar(bm![1]) == "M") || (Unicode.Scalar(bm![0]) == "B" && Unicode.Scalar(bm![1]) == "A") || (Unicode.Scalar(bm![0]) == "C" && Unicode.Scalar(bm![1]) == "I") || (Unicode.Scalar(bm![0]) == "C" && Unicode.Scalar(bm![1]) == "P") || (Unicode.Scalar(bm![0]) == "I" && Unicode.Scalar(bm![1]) == "C") || (Unicode.Scalar(bm![0]) == "P" && Unicode.Scalar(bm![1]) == "T") { skipNBytes(stream, 8) let offset = readSignedInt(stream) readSignedInt(stream) // size of header self.w = readSignedInt(stream) self.h = readSignedInt(stream) skipNBytes(stream, 2) self.bpp = read2BytesLE(stream) let compression = readSignedInt(stream) if bpp > 8 { r5g6b5 = (compression == 3) skipNBytes(stream, 20) if offset > 54 { skipNBytes(stream, offset - 54) } } else { skipNBytes(stream, 12) var numPalColors = readSignedInt(stream) if numPalColors == 0 { numPalColors = Int(pow(2.0, Double(bpp))) } skipNBytes(stream, 4) parsePalette(stream, numPalColors) } parseData(stream) } else { // TODO: Swift.print("BMP data could not be parsed!") } } private func parseData(_ stream: InputStream) { image = [UInt8](repeating: 0, count: (3 * w * h)) let rowsize = 4 * Int(ceil(Double(w * bpp) / 32.0)) // 4 byte alignment var row: [UInt8] var index = 0 for i in 0..<self.h { row = getBytes(stream, rowsize)! if self.bpp == 1 { row = bit1to8(row, w) // opslag i palette } else if self.bpp == 4 { row = bit4to8(row, w) // opslag i palette } else if self.bpp == 8 { // opslag i palette // } else if self.bpp == 16 { if self.r5g6b5 { // 5,6,5 bit row = bit16to24(row, w) } else { row = bit16to24b(row, w) } } else if self.bpp == 24 { // bytes are correct } else if self.bpp == 32 { row = bit32to24(row, w) } else { Swift.print("Can only parse 1 bit, 4bit, 8bit, 16bit, 24bit and 32bit images.") } index = 3*w*((h - i) - 1) if self.palette != nil { // indexed for j in 0..<self.w { image![index] = self.palette![Int((row[j] < 0) ? row[j] : row[j])][2] index += 1 image![index] = self.palette![Int((row[j] < 0) ? row[j] : row[j])][1] index += 1 image![index] = self.palette![Int((row[j] < 0) ? row[j] : row[j])][0] index += 1 } } else { // not indexed var j = 0 while j < 3*self.w { image![index] = row[j + 2] index += 1 image![index] = row[j + 1] index += 1 image![index] = row[j] index += 1 j += 3 } } } deflated = [UInt8]() _ = LZWEncode(&deflated!, &image!) // _ = FlateEncode(&deflated!, &image!, RLE: true) } // 5 + 6 + 5 in B G R format 2 bytes to 3 bytes private func bit16to24(_ row: [UInt8], _ width: Int) -> [UInt8] { var ret = [UInt8](repeating: 0, count: 3*width) var i = 0 var j = 0 while i < 2*width { ret[j] = UInt8((row[i] & 0x1F) << 3) j += 1 ret[j] = UInt8(((row[i + 1] & 0x07) << 5) + (row[i] & 0xE0) >> 3) j += 1 ret[j] = UInt8((row[i + 1] & 0xF8)) j += 1 i += 2 } return ret } // 5 + 5 + 5 in B G R format 2 bytes to 3 bytes private func bit16to24b(_ row: [UInt8], _ width: Int) -> [UInt8] { var ret = [UInt8](repeating: 0, count: 3*width) var i = 0 var j = 0 while i < 2*width { ret[j] = UInt8((row[i] & 0x1F) << 3) j += 1 ret[j] = UInt8(((row[i + 1] & 0x03) << 6) + (row[i] & 0xE0) >> 2) j += 1 ret[j] = UInt8((row[i + 1] & 0x7C) << 1) j += 1 i += 2 } return ret } /* alpha first? */ private func bit32to24(_ row: [UInt8], _ width: Int) -> [UInt8] { var ret = [UInt8](repeating: 0, count: 3*width) var i = 0 var j = 0 while i < 4*width { ret[j] = row[i + 1] j += 1 ret[j] = row[i + 2] j += 1 ret[j] = row[i + 3] j += 1 i += 4 } return ret } private func bit4to8(_ row: [UInt8], _ width: Int) -> [UInt8] { var ret = [UInt8](repeating: 0, count: width) for i in 0..<width { if i % 2 == 0 { ret[i] = UInt8((row[i/2] & m11110000) >> 4) } else { ret[i] = UInt8((row[i/2] & m00001111)) } } return ret } private func bit1to8(_ row: [UInt8], _ width: Int) -> [UInt8] { var ret = [UInt8](repeating: 0, count: width) for i in 0..<width { switch (i % 8) { case 0: ret[i] = UInt8((row[i/8] & m10000000) >> 7); break case 1: ret[i] = UInt8((row[i/8] & m01000000) >> 6); break case 2: ret[i] = UInt8((row[i/8] & m00100000) >> 5); break case 3: ret[i] = UInt8((row[i/8] & m00010000) >> 4); break case 4: ret[i] = UInt8((row[i/8] & m00001000) >> 3); break case 5: ret[i] = UInt8((row[i/8] & m00000100) >> 2); break case 6: ret[i] = UInt8((row[i/8] & m00000010) >> 1); break case 7: ret[i] = UInt8((row[i/8] & m00000001)); break default: break } } return ret } private func parsePalette(_ stream: InputStream, _ size: Int) { self.palette = [[UInt8]]() for _ in 0..<size { self.palette!.append(getBytes(stream, 4)!) } } private func skipNBytes(_ stream: InputStream, _ n: Int) { var buf = [UInt8](repeating: 0, count: n) if stream.read(&buf, maxLength: buf.count) == buf.count { } } private func getBytes(_ stream: InputStream, _ length: Int) -> [UInt8]? { var buf = [UInt8](repeating: 0, count: length) if stream.read(&buf, maxLength: buf.count) == buf.count { return buf } return nil } private func read2BytesLE(_ stream: InputStream) -> Int { let buf = getBytes(stream, 2)! var val: UInt32 = 0 val |= UInt32(buf[1] & 0xff) val <<= 8 val |= UInt32(buf[0] & 0xff) return Int(val) } @discardableResult private func readSignedInt(_ stream: InputStream) -> Int { let buf = getBytes(stream, 4)! var val: Int64 = 0 val |= Int64(buf[3] & 0xff) val <<= 8 val |= Int64(buf[2] & 0xff) val <<= 8 val |= Int64(buf[1] & 0xff) val <<= 8 val |= Int64(buf[0] & 0xff) return Int(val) } public func getWidth() -> Int { return self.w } public func getHeight() -> Int { return self.h } public func getData() -> [UInt8] { return self.deflated! } }
mit
f9abd82b1e212e2e5a69d42a4acadf72
33.355932
95
0.476073
3.670771
false
false
false
false
gaolichuang/actor-platform
actor-apps/app-ios/ActorApp/AppDelegate.swift
1
13248
// // Copyright (C) 2014-2015 Actor LLC. <https://actor.im> // import Foundation import Fabric import Crashlytics @objc class AppDelegate : UIResponder, UIApplicationDelegate { var window : UIWindow? private var binder = Binder() private var syncTask: UIBackgroundTaskIdentifier? private var completionHandler: ((UIBackgroundFetchResult) -> Void)? private let badgeView = UIImageView() private var badgeCount = 0 private var isBadgeVisible = false func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { // Apply crash logging // Even when Fabric/Crashlytics not configured // this method doesn't crash Fabric.with([Crashlytics.self()]) // Creating Actor createActor() // Creating app style initStyles() // Register hockey app if AppConfig.hockeyapp != nil { BITHockeyManager.sharedHockeyManager().configureWithIdentifier(AppConfig.hockeyapp!) BITHockeyManager.sharedHockeyManager().disableCrashManager = true BITHockeyManager.sharedHockeyManager().updateManager.checkForUpdateOnLaunch = true BITHockeyManager.sharedHockeyManager().startManager() BITHockeyManager.sharedHockeyManager().authenticator.authenticateInstallation() } // Register notifications // Register always even when not enabled in build for local notifications if #available(iOS 8.0, *) { let types: UIUserNotificationType = [.Alert, .Badge, .Sound] let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } else { application.registerForRemoteNotificationTypes([.Alert, .Badge, .Sound]) } // Apply styles MainAppTheme.applyAppearance(application) // Bind Messenger LifeCycle binder.bind(Actor.getAppState().isSyncing, closure: { (value: JavaLangBoolean?) -> () in if value!.booleanValue() { if self.syncTask == nil { self.syncTask = application.beginBackgroundTaskWithName("Background Sync", expirationHandler: { () -> Void in }) } } else { if self.syncTask != nil { application.endBackgroundTask(self.syncTask!) self.syncTask = nil } if self.completionHandler != nil { self.completionHandler!(UIBackgroundFetchResult.NewData) self.completionHandler = nil } } }) // Creating main window window = UIWindow(frame: UIScreen.mainScreen().bounds); window?.backgroundColor = UIColor.whiteColor() if (Actor.isLoggedIn()) { onLoggedIn(false) } else { // Create root layout for login let phoneController = AuthPhoneViewController() let loginNavigation = AANavigationController(rootViewController: phoneController) loginNavigation.navigationBar.tintColor = MainAppTheme.navigation.barColor loginNavigation.makeBarTransparent() window?.rootViewController = loginNavigation } window?.makeKeyAndVisible(); badgeView.image = Imaging.roundedImage(UIColor.RGB(0xfe0000), size: CGSizeMake(16, 16), radius: 8) // badgeView.frame = CGRectMake(16, 22, 32, 16) badgeView.alpha = 0 let badgeText = UILabel() badgeText.text = "0" badgeText.textColor = UIColor.whiteColor() // badgeText.frame = CGRectMake(0, 0, 32, 16) badgeText.font = UIFont.systemFontOfSize(12) badgeText.textAlignment = NSTextAlignment.Center badgeView.addSubview(badgeText) window?.addSubview(badgeView) // Bind badge counter binder.bind(Actor.getAppState().globalCounter, closure: { (value: JavaLangInteger?) -> () in self.badgeCount = Int((value!).integerValue) application.applicationIconBadgeNumber = self.badgeCount badgeText.text = "\(self.badgeCount)" if (self.isBadgeVisible && self.badgeCount > 0) { self.badgeView.showView() } else if (self.badgeCount == 0) { self.badgeView.hideView() } badgeText.frame = CGRectMake(0, 0, 128, 16) badgeText.sizeToFit() if badgeText.frame.width < 8 { self.badgeView.frame = CGRectMake(16, 22, 16, 16) } else { self.badgeView.frame = CGRectMake(16, 22, badgeText.frame.width + 8, 16) } badgeText.frame = self.badgeView.bounds }) return true; } func onLoggedIn(isAfterLogin: Bool) { // Create root layout for app Actor.onAppVisible() var rootController : UIViewController? = nil if (isIPad) { let splitController = MainSplitViewController() splitController.viewControllers = [MainTabViewController(isAfterLogin: isAfterLogin), NoSelectionViewController()] rootController = splitController } else { let tabController = MainTabViewController(isAfterLogin: isAfterLogin) binder.bind(Actor.getAppState().isAppLoaded, valueModel2: Actor.getAppState().isAppEmpty) { (loaded: JavaLangBoolean?, empty: JavaLangBoolean?) -> () in if (empty!.booleanValue()) { if (loaded!.booleanValue()) { tabController.showAppIsEmptyPlaceholder() } else { tabController.showAppIsSyncingPlaceholder() } } else { tabController.hidePlaceholders() } } rootController = tabController } window?.rootViewController = rootController! } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { if (url.scheme == "actor") { if (url.host == "invite") { if (Actor.isLoggedIn()) { let token = url.query?.componentsSeparatedByString("=")[1] if token != nil { UIAlertView.showWithTitle(nil, message: localized("GroupJoinMessage"), cancelButtonTitle: localized("AlertNo"), otherButtonTitles: [localized("GroupJoinAction")], tapBlock: { (view, index) -> Void in if (index == view.firstOtherButtonIndex) { Executions.execute(Actor.joinGroupViaLinkCommandWithUrl(token), successBlock: { (val) -> Void in let groupId = val as! JavaLangInteger self.openChat(ACPeer.groupWithInt(groupId.intValue)) }, failureBlock: { (val) -> Void in if let res = val as? ACRpcException { if res.getTag() == "USER_ALREADY_INVITED" { UIAlertView.showWithTitle(nil, message: localized("ErrorAlreadyJoined"), cancelButtonTitle: localized("AlertOk"), otherButtonTitles: nil, tapBlock: nil) return } } UIAlertView.showWithTitle(nil, message: localized("ErrorUnableToJoin"), cancelButtonTitle: localized("AlertOk"), otherButtonTitles: nil, tapBlock: nil) }) } }) } } return true } } return false } func applicationWillEnterForeground(application: UIApplication) { createActor() Actor.onAppVisible(); // Hack for resync phone book Actor.onPhoneBookChanged() } func applicationDidEnterBackground(application: UIApplication) { createActor() Actor.onAppHidden(); if Actor.isLoggedIn() { var completitionTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid completitionTask = application.beginBackgroundTaskWithName("Completition", expirationHandler: { () -> Void in application.endBackgroundTask(completitionTask) completitionTask = UIBackgroundTaskInvalid }) // Wait for 40 secs before app shutdown dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(40.0 * Double(NSEC_PER_SEC))), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in application.endBackgroundTask(completitionTask) completitionTask = UIBackgroundTaskInvalid } } } // MARK: - // MARK: Notifications func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let tokenString = "\(deviceToken)".stringByReplacingOccurrencesOfString(" ", withString: "").stringByReplacingOccurrencesOfString("<", withString: "").stringByReplacingOccurrencesOfString(">", withString: "") if AppConfig.pushId != nil { Actor.registerApplePushWithApnsId(jint(AppConfig.pushId!), withToken: tokenString) } } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { createActor() if !Actor.isLoggedIn() { completionHandler(UIBackgroundFetchResult.NoData) return } self.completionHandler = completionHandler } func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { createActor() if !Actor.isLoggedIn() { completionHandler(UIBackgroundFetchResult.NoData) return } self.completionHandler = completionHandler } // func execute(command: ACCommand) { // execute(command, successBlock: nil, failureBlock: nil) // } // // func execute(command: ACCommand, successBlock: ((val: Any?) -> Void)?, failureBlock: ((val: Any?) -> Void)?) { // let hud = showProgress() // command.startWithCallback(CocoaCallback(result: { (val:Any?) -> () in // dispatchOnUi { // hud.hide(true) // successBlock?(val: val) // } // }, error: { (val) -> () in // dispatchOnUi { // hud.hide(true) // failureBlock?(val: val) // } // })) // } // // func executeRecoverable(command: ACCommand, successBlock: ((val: Any?) -> Void)?, failureBlock: ((val: Any?) -> Void)?) { // // } // // private func showProgress() -> MBProgressHUD { // let window = UIApplication.sharedApplication().windows[1] // let hud = MBProgressHUD(window: window) // hud.mode = MBProgressHUDMode.Indeterminate // hud.removeFromSuperViewOnHide = true // window.addSubview(hud) // window.bringSubviewToFront(hud) // hud.show(true) // return hud // } func openChat(peer: ACPeer) { for i in UIApplication.sharedApplication().windows { if let tab = i.rootViewController as? MainTabViewController { let controller = tab.viewControllers![tab.selectedIndex] as! AANavigationController let destController = ConversationViewController(peer: peer) destController.hidesBottomBarWhenPushed = true controller.pushViewController(destController, animated: true) return } else if let split = i.rootViewController as? MainSplitViewController { split.navigateDetail(ConversationViewController(peer: peer)) return } } } func showBadge() { isBadgeVisible = true if badgeCount > 0 { self.badgeView.showView() } } func hideBadge() { isBadgeVisible = false self.badgeView.hideView() } }
mit
feac4fdba7fa76836b92726447101874
40.145963
223
0.570728
5.893238
false
false
false
false
XiaHaozheJose/swift3_wb
sw3_wb/sw3_wb/Classes/View/Main/WB_NavigationViewController.swift
1
2309
// // WB_NavigationViewController.swift // sw3_wb // // Created by 浩哲 夏 on 2017/9/13. // Copyright © 2017年 浩哲 夏. All rights reserved. // import UIKit class WB_NavigationViewController: UINavigationController,UIGestureRecognizerDelegate { override func loadView() { super.loadView() let naviBar = UINavigationBar.appearance() naviBar.setBackgroundImage(#imageLiteral(resourceName: "navigationbarBackgroundWhite"), for: .default) naviBar.titleTextAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 20)] } override func viewDidLoad() { super.viewDidLoad() let pan = UIPanGestureRecognizer(target: interactivePopGestureRecognizer?.delegate, action: "handleNavigationTransition:") view.addGestureRecognizer(pan) pan.delegate = self self.interactivePopGestureRecognizer?.isEnabled = false self.interactivePopGestureRecognizer?.delegate = self; } // MARK: - 监听 @objc fileprivate func popController(){ popViewController(animated: true) } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return childViewControllers.count > 1 } } // MARK: - 重写 extension WB_NavigationViewController{ override func pushViewController(_ viewController: UIViewController, animated: Bool) { if childViewControllers.count > 0 { viewController.hidesBottomBarWhenPushed = true if childViewControllers.count > 1 { viewController.navigationItem.leftBarButtonItem = JS_UIBarButtonItem(normalImage: #imageLiteral(resourceName: "navigationButtonReturn"), highlightImage: #imageLiteral(resourceName: "navigationButtonReturnClick"), target: self, action: #selector(popController), title: "返回") }else{ viewController.navigationItem.leftBarButtonItem = JS_UIBarButtonItem(normalImage: #imageLiteral(resourceName: "navigationButtonReturn"), highlightImage: #imageLiteral(resourceName: "navigationButtonReturnClick"), target: self, action: #selector(popController), title: title ?? "返回") } } super.pushViewController(viewController, animated: true) } }
mit
e587c5a419ee28bb99cad96ee91239c4
37.610169
298
0.701493
5.436754
false
false
false
false
danielgindi/ChartsRealm
ChartsRealm/Classes/Data/RealmCandleDataSet.swift
1
6997
// // RealmCandleDataSet.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 import Charts import Realm import RealmSwift import Realm.Dynamic open class RealmCandleDataSet: RealmLineScatterCandleRadarDataSet, ICandleChartDataSet { open override func initialize() { } public required init() { super.init() } @objc public init(results: RLMResults<RLMObject>?, xValueField: String, highField: String, lowField: String, openField: String, closeField: String, label: String?) { _highField = highField _lowField = lowField _openField = openField _closeField = closeField super.init(results: results, xValueField: xValueField, yValueField: "", label: label) } public convenience init(results: Results<Object>?, xValueField: String, highField: String, lowField: String, openField: String, closeField: String, label: String?) { var converted: RLMResults<RLMObject>? if results != nil { converted = ObjectiveCSupport.convert(object: results!) as? RLMResults<RLMObject> } self.init(results: converted, xValueField: xValueField, highField: highField, lowField: lowField, openField: openField, closeField: closeField, label: label) } @objc public convenience init(results: RLMResults<RLMObject>?, xValueField: String, highField: String, lowField: String, openField: String, closeField: String) { self.init(results: results, xValueField: xValueField, highField: highField, lowField: lowField, openField: openField, closeField: closeField, label: "DataSet") } public convenience init(results: Results<Object>?, xValueField: String, highField: String, lowField: String, openField: String, closeField: String) { var converted: RLMResults<RLMObject>? if results != nil { converted = ObjectiveCSupport.convert(object: results!) as? RLMResults<RLMObject> } self.init(results: converted, xValueField: xValueField, highField: highField, lowField: lowField, openField: openField, closeField: closeField) } @objc public init(realm: RLMRealm?, modelName: String, resultsWhere: String, xValueField: String, highField: String, lowField: String, openField: String, closeField: String, label: String?) { _highField = highField _lowField = lowField _openField = openField _closeField = closeField super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: xValueField, yValueField: "", label: label) } public convenience init(realm: Realm?, modelName: String, resultsWhere: String, xValueField: String, highField: String, lowField: String, openField: String, closeField: String, label: String?) { var converted: RLMRealm? if realm != nil { converted = ObjectiveCSupport.convert(object: realm!) } self.init(realm: converted, modelName: modelName, resultsWhere: resultsWhere, xValueField: xValueField, highField: highField, lowField: lowField, openField: openField, closeField: closeField, label: label) } // MARK: - Data functions and accessors @objc internal var _highField: String? @objc internal var _lowField: String? @objc internal var _openField: String? @objc internal var _closeField: String? internal override func buildEntryFromResultObject(_ object: RLMObject, x: Double) -> ChartDataEntry { let entry = CandleChartDataEntry( x: _xValueField == nil ? x : object[_xValueField!] as! Double, shadowH: object[_highField!] as! Double, shadowL: object[_lowField!] as! Double, open: object[_openField!] as! Double, close: object[_closeField!] as! Double) return entry } open override func calcMinMax() { if _cache.count == 0 { return } _yMax = -Double.greatestFiniteMagnitude _yMin = Double.greatestFiniteMagnitude _xMax = -Double.greatestFiniteMagnitude _xMin = Double.greatestFiniteMagnitude for e in _cache as! [CandleChartDataEntry] { if e.low < _yMin { _yMin = e.low } if e.high > _yMax { _yMax = e.high } if e.x < _xMin { _xMin = e.x } if e.x > _xMax { _xMax = e.x } } } // MARK: - Styling functions and accessors /// the space between the candle entries /// /// **default**: 0.1 (10%) fileprivate var _barSpace = CGFloat(0.1) /// the space that is left out on the left and right side of each candle, /// **default**: 0.1 (10%), max 0.45, min 0.0 open var barSpace: CGFloat { set { if newValue < 0.0 { _barSpace = 0.0 } else if newValue > 0.45 { _barSpace = 0.45 } else { _barSpace = newValue } } get { return _barSpace } } /// should the candle bars show? /// when false, only "ticks" will show /// /// **default**: true open var showCandleBar: Bool = true /// the width of the candle-shadow-line in pixels. /// /// **default**: 3.0 open var shadowWidth = CGFloat(1.5) /// the color of the shadow line open var shadowColor: NSUIColor? /// use candle color for the shadow open var shadowColorSameAsCandle = false /// Is the shadow color same as the candle color? open var isShadowColorSameAsCandle: Bool { return shadowColorSameAsCandle } /// color for open == close open var neutralColor: NSUIColor? /// color for open > close open var increasingColor: NSUIColor? /// color for open < close open var decreasingColor: NSUIColor? /// Are increasing values drawn as filled? /// increasing candlesticks are traditionally hollow open var increasingFilled = false /// Are increasing values drawn as filled? open var isIncreasingFilled: Bool { return increasingFilled } /// Are decreasing values drawn as filled? /// descreasing candlesticks are traditionally filled open var decreasingFilled = true /// Are decreasing values drawn as filled? open var isDecreasingFilled: Bool { return decreasingFilled } }
apache-2.0
d95f667ec5998c33af72ed566c32c0c6
30.804545
213
0.602687
4.705447
false
false
false
false
dongdonggaui/BiblioArchiver
Carthage/Checkouts/Fuzi/FuziTests/XMLTests.swift
1
3303
// XMLTests.swift // Copyright (c) 2015 Ce Zheng // // 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 Fuzi class XMLTests: XCTestCase { var document: XMLDocument! override func setUp() { super.setUp() let filePath = Bundle(for: XMLTests.self).path(forResource: "xml", ofType: "xml")! do { document = try XMLDocument(data: Data(contentsOfFile: filePath)!) } catch { XCTAssertFalse(true, "Error should not be thrown") } } func testXMLVersion() { XCTAssertEqual(document.version, "1.0", "XML version should be 1.0") } func testXMLEncoding() { XCTAssertEqual(document.encoding, String.Encoding.utf8, "XML encoding should be UTF-8") } func testRoot() { XCTAssertEqual(document.root!.tag, "spec", "root tag should be spec") XCTAssertEqual(document.root!.attributes["w3c-doctype"], "rec", "w3c-doctype should be rec") XCTAssertEqual(document.root!.attributes["lang"], "en", "lang should be en") } func testTitle() { let titleElement = document.root!.firstChild(tag: "header")?.firstChild(tag: "title") XCTAssertNotNil(titleElement, "title element should not be nil") XCTAssertEqual(titleElement?.tag, "title", "tag should be `title`") XCTAssertEqual(titleElement?.stringValue, "Extensible Markup Language (XML)", "title string value should be 'Extensible Markup Language (XML)'") } func testXPath() { let path = "/spec/header/title" let elts = document.xpath(path) var counter = 0 for elt in elts { XCTAssertEqual("title", elt.tag, "tag should be `title`") counter += 1 } XCTAssertEqual(1, counter, "at least one element should have been found at element path '\(path)'") } func testLineNumber() { let headerElement = document.root!.firstChild(tag: "header") XCTAssertNotNil(headerElement, "header element should not be nil") XCTAssertEqual(headerElement?.lineNumber, 123, "header line number should be correct") } func testThrowsError() { do { document = try XMLDocument(cChars: [CChar]()) XCTAssertFalse(true, "error should have been thrown") } catch XMLError.ParserFailure { } catch { XCTAssertFalse(true, "error type should be ParserFailure") } } }
mit
f74b12894dba590c86050d2ff0c9034b
37.858824
148
0.705117
4.284047
false
true
false
false
ashfurrow/RxSwift
RxCocoa/iOS/UIGestureRecognizer+Rx.swift
3
2054
// // UIGestureRecognizer+Rx.swift // Touches // // Created by Carlos García on 10/6/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #if !RX_NO_MODULE import RxSwift #endif // This should be only used from `MainScheduler` class GestureTarget: RxTarget { typealias Callback = (UIGestureRecognizer) -> Void let selector = Selector("eventHandler:") weak var gestureRecognizer: UIGestureRecognizer? var callback: Callback? init(_ gestureRecognizer: UIGestureRecognizer, callback: Callback) { self.gestureRecognizer = gestureRecognizer self.callback = callback super.init() gestureRecognizer.addTarget(self, action: selector) let method = self.methodForSelector(selector) if method == nil { fatalError("Can't find method") } } func eventHandler(sender: UIGestureRecognizer!) { if let callback = self.callback, gestureRecognizer = self.gestureRecognizer { callback(gestureRecognizer) } } override func dispose() { super.dispose() self.gestureRecognizer?.removeTarget(self, action: self.selector) self.callback = nil } } extension UIGestureRecognizer { /** Reactive wrapper for gesture recognizer events. */ public var rx_event: ControlEvent<UIGestureRecognizer> { let source: Observable<UIGestureRecognizer> = create { [weak self] observer in MainScheduler.ensureExecutingOnScheduler() guard let control = self else { observer.on(.Completed) return NopDisposable.instance } let observer = GestureTarget(control) { control in observer.on(.Next(control)) } return observer }.takeUntil(rx_deallocated) return ControlEvent(events: source) } } #endif
mit
09cd73dba4c270b6e1ef925fcdf83015
24.345679
86
0.605943
5.250639
false
false
false
false
nathawes/swift
test/expr/unary/keypath/keypath-availability.swift
6
1064
// RUN: %target-swift-frontend -target x86_64-apple-macosx10.9 -typecheck -verify %s // REQUIRES: OS=macosx struct Butt { var setter_conditionally_available: Int { get { fatalError() } @available(macOS 10.10, *) set { fatalError() } } } func assertExactType<T>(of _: inout T, is _: T.Type) {} @available(macOS 10.9, *) public func unavailableSetterContext() { var kp = \Butt.setter_conditionally_available assertExactType(of: &kp, is: KeyPath<Butt, Int>.self) } @available(macOS 10.10, *) public func availableSetterContext() { var kp = \Butt.setter_conditionally_available assertExactType(of: &kp, is: WritableKeyPath<Butt, Int>.self) } @available(macOS 10.9, *) public func conditionalAvailableSetterContext() { if #available(macOS 10.10, *) { var kp = \Butt.setter_conditionally_available assertExactType(of: &kp, is: WritableKeyPath<Butt, Int>.self) } else { var kp = \Butt.setter_conditionally_available assertExactType(of: &kp, is: KeyPath<Butt, Int>.self) } }
apache-2.0
cacefeb6a6ce6864d4305e2f1a1ba021
29.4
84
0.664474
3.477124
false
false
false
false
eyaldar/TBAnnotationClustering
TBAnnotationClustering-Swift/TBCoordinateQuadTree.swift
1
4261
// // File.swift // TBAnnotationClustering-Swift // // Created by Eyal Darshan on 1/1/16. // Copyright © 2016 eyaldar. All rights reserved. // import Foundation import MapKit class TBCoordinateQuadTree : NSObject { weak var mapView: MKMapView! let hotelTreeBuilder:TBHotelCSVTreeBuilder private var root:TBQuadTreeNode? init(builder:TBHotelCSVTreeBuilder, mapView: MKMapView) { self.hotelTreeBuilder = builder self.mapView = mapView } func buildTree(dataFileName:String, worldBounds:TBBoundingBox) { root = hotelTreeBuilder.buildTree(dataFileName, worldBounds: worldBounds) } func clusteredAnnotationWithinMapRect(rect:MKMapRect, zoomScale:MKZoomScale) -> [TBClusterAnnotation] { let tbCellSize = TBCellSizeForZoomScale(zoomScale) let zoomScaleDouble = Double(zoomScale) let scaleFactor = zoomScaleDouble / tbCellSize let minX = floor(MKMapRectGetMinX(rect) * scaleFactor) let maxX = floor(MKMapRectGetMaxX(rect) * scaleFactor) let minY = floor(MKMapRectGetMinY(rect) * scaleFactor) let maxY = floor(MKMapRectGetMaxY(rect) * scaleFactor) var clusteredAnnotations = [TBClusterAnnotation]() for var x:Double = minX; x <= maxX; x++ { for var y:Double = minY; y <= maxY; y++ { let mapRect = MKMapRectMake(x/scaleFactor, y/scaleFactor, 1.0/scaleFactor, 1.0/scaleFactor) var totalX = 0.0 var totalY = 0.0 var names = [String]() var phoneNumbers = [String]() root?.gatherDataInRange(getBoundingBox(mapRect), action: { (data) -> Void in totalX += data.x totalY += data.y if let hotelInfo = data.data as? TBHotelInfo { names.append(hotelInfo.hotelName) phoneNumbers.append(hotelInfo.hotelPhoneNumber) } }) let count = names.count if count > 1 { let coordinate = CLLocationCoordinate2D(latitude: totalX / Double(count), longitude: totalY / Double(count)) let annotation = TBClusterAnnotation(coordinate: coordinate, count: count) clusteredAnnotations.append(annotation) } if count == 1 { let coordinate = CLLocationCoordinate2D(latitude: totalX, longitude: totalY) let annotation = TBClusterAnnotation(coordinate: coordinate, count: count) annotation.title = names.last! annotation.subtitle = phoneNumbers.last! clusteredAnnotations.append(annotation) } } } return clusteredAnnotations } func getBoundingBox(mapRect:MKMapRect) -> TBBoundingBox { let topLeft = MKCoordinateForMapPoint(mapRect.origin) let bottomRight = MKCoordinateForMapPoint(MKMapPoint(x: MKMapRectGetMaxX(mapRect), y: MKMapRectGetMaxY(mapRect))) let minLat = bottomRight.latitude let maxLat = topLeft.latitude let minLong = topLeft.longitude let maxLong = bottomRight.longitude return TBBoundingBox(x: minLat, y: minLong, xf: maxLat, yf: maxLong) } func TBZoomScaleToZoomLevel(scale:MKZoomScale) -> Int { let totalTilesAtMaxZoom = MKMapSizeWorld.width / 256.0 let zoomLevelAtMaxZoom = Int(log2(totalTilesAtMaxZoom)) let zoomLevel = Int(max(0, Double(zoomLevelAtMaxZoom) + floor(log2(Double(scale)) + 0.5))); return zoomLevel; } func TBCellSizeForZoomScale(zoomScale:MKZoomScale) -> Double { let zoomLevel = TBZoomScaleToZoomLevel(zoomScale); switch (zoomLevel) { case 13, 14, 15: return 64 case 16, 17, 18: return 32 case 19: return 16 default: return 88 } } }
mit
aeb1e4d2a6a64adebd5c663dc7ee5a1d
36.043478
128
0.574178
4.896552
false
false
false
false
PlutusCat/KrVideoPlayerPlus
VideoControl/VideoControl/ViewController.swift
2
1676
// // ViewController.swift // VideoControl // // Created by PlutusCat on 2018/8/8. // Copyright © 2018年 VideoControl. All rights reserved. // import UIKit import IJKMediaFramework class ViewController: UIViewController { var videoView: IJKFFMoviePlayerController! var play: UIButton! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let url = URL(string: ConstantURLs.cctv1.rawValue) let options = IJKFFOptions.byDefault() videoView = IJKFFMoviePlayerController(contentURL: url, with: options) let autoresize = UIViewAutoresizing.flexibleWidth.rawValue | UIViewAutoresizing.flexibleHeight.rawValue videoView.view.autoresizingMask = UIViewAutoresizing(rawValue: autoresize) videoView.view.frame = CGRect(x: 0, y: navigationHeight(), width: view.bounds.width, height: view.bounds.width.proportionHeight()) videoView.scalingMode = .aspectFit videoView.shouldAutoplay = true videoView.prepareToPlay() view.autoresizesSubviews = true view.addSubview(videoView.view) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) videoView.prepareToPlay() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(true) videoView.shutdown() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
dc8d2101dd6b058cd18662896e4e7f0d
25.555556
83
0.641363
5.116208
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/Home/Buildings/Buildings/Cells/BuildingHoursCell.swift
1
4365
// // BuildingHoursCell.swift // PennMobile // // Created by dominic on 6/25/18. // Copyright © 2018 PennLabs. All rights reserved. // import UIKit class BuildingHoursCell: BuildingCell { static let identifier = "BuildingHoursCell" static let cellHeight: CGFloat = 168 static let numDays: Int = 7 var building: BuildingHoursDisplayable! { didSet { setupCell(with: building) } } fileprivate let safeInsetValue: CGFloat = 14 fileprivate var safeArea: UIView! fileprivate var dayLabels: [UILabel]! fileprivate var hourLabels: [UILabel]! // MARK: - Init override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) prepareUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Setup Cell extension BuildingHoursCell { fileprivate func setupCell(with building: BuildingHoursDisplayable) { let weekdayArray = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] let timeStringsForWeek = building.getTimeStrings() for day in 0 ..< BuildingHoursCell.numDays { let dayLabel = dayLabels[day] let hourLabel = hourLabels[day] dayLabel.text = weekdayArray[day] hourLabel.text = timeStringsForWeek[day] if weekdayArray[day] == Date.currentDayOfWeek { dayLabel.font = .primaryInformationFont dayLabel.textColor = .baseGreen hourLabel.font = .primaryInformationFont hourLabel.textColor = .baseGreen } // Shrink label if needed hourLabel.layoutIfNeeded() } } } // MARK: - Initialize and Prepare UI extension BuildingHoursCell { fileprivate func prepareUI() { prepareSafeArea() dayLabels = [UILabel](); hourLabels = [UILabel]() for _ in 0 ..< BuildingHoursCell.numDays { dayLabels.append(getDayLabel()) hourLabels.append(getHourLabel()) } layoutLabels() } // MARK: Safe Area fileprivate func prepareSafeArea() { safeArea = getSafeAreaView() addSubview(safeArea) NSLayoutConstraint.activate([ safeArea.leadingAnchor.constraint(equalTo: leadingAnchor, constant: safeInsetValue * 2), safeArea.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -safeInsetValue * 2), safeArea.topAnchor.constraint(equalTo: topAnchor, constant: safeInsetValue), safeArea.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -safeInsetValue) ]) } // MARK: Layout Labels fileprivate func layoutLabels() { for day in 0 ..< BuildingHoursCell.numDays { let dayLabel = dayLabels[day] let hourLabel = hourLabels[day] addSubview(dayLabel) addSubview(hourLabel) if day == 0 { _ = dayLabel.anchor(safeArea.topAnchor, left: safeArea.leftAnchor, bottom: nil, right: nil) _ = hourLabel.anchor(safeArea.topAnchor, left: dayLabel.rightAnchor, bottom: nil, right: safeArea.rightAnchor) } else { _ = dayLabel.anchor(dayLabels[day - 1].bottomAnchor, left: safeArea.leftAnchor, topConstant: 0) _ = hourLabel.anchor(hourLabels[day - 1].bottomAnchor, left: safeArea.leftAnchor, right: safeArea.rightAnchor, topConstant: 0, leftConstant: 100) } } } fileprivate func getDayLabel() -> UILabel { let label = UILabel() label.font = .secondaryInformationFont label.textColor = UIColor.labelPrimary label.textAlignment = .left label.text = "Day" return label } fileprivate func getHourLabel() -> UILabel { let label = UILabel() label.font = .secondaryInformationFont label.textColor = UIColor.labelPrimary label.textAlignment = .right label.text = "Hour" label.shrinkUntilFits() return label } fileprivate func getSafeAreaView() -> UIView { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view } }
mit
623dc494c29454d8987f26b3dd247d56
31.81203
161
0.628323
4.80088
false
false
false
false
piscoTech/Workout
Workout/View/LoadMoreCell.swift
1
777
// // LoadMoreCell.swift // Workout // // Created by Marco Boschi on 04/08/2018. // Copyright © 2018 Marco Boschi. All rights reserved. // import UIKit class LoadMoreCell: UITableViewCell { @IBOutlet private weak var loadIndicator: UIActivityIndicatorView! @IBOutlet private weak var loadBtn: UIButton! override func awakeFromNib() { super.awakeFromNib() if #available(iOS 13.0, *) { loadIndicator.style = .medium } else { loadIndicator.style = .gray } loadIndicator.color = .systemGray } var isEnabled: Bool { get { return loadBtn.isEnabled } set { loadBtn.isEnabled = newValue loadIndicator.isHidden = newValue if !newValue { loadIndicator.startAnimating() } else { loadIndicator.stopAnimating() } } } }
mit
7c1fc7fc99c3e372338aabebd3457528
17.47619
67
0.686856
3.495495
false
false
false
false
bwearley/NVActivityIndicatorView
NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationDumbbellPulse.swift
1
4198
// // NVActivityIndicatorAnimationDumbbellPulse.swift // NVActivityIndicatorViewDemo // // Created by Brian Earley on 2/20/16. // Copyright © 2016 Nguyen Vinh. All rights reserved. // // Created by Nguyen Vinh on 7/24/15. // Copyright © 2015 Nguyen Vinh. All rights reserved. // import UIKit class NVActivityIndicatorAnimationDumbbellPulse: NVActivityIndicatorAnimationDelegate { func setUpAnimationInLayer(layer: CALayer, size: CGSize, color: UIColor) { let lineSize = size.width / 9 let x = (layer.bounds.size.width - size.width) / 2 let x2 = layer.bounds.size.width - x let y = (layer.bounds.size.height - size.height) / 2 let y2 = layer.bounds.size.height - 4*y let duration: CFTimeInterval = 1 let beginTime = CACurrentMediaTime() let beginTimes = [0.4, 0.2, 0, 0.2, 0.4] let timingFunction = CAMediaTimingFunction(controlPoints: 0.85, 0.25, 0.37, 0.85) // Animation let animation = CAKeyframeAnimation(keyPath: "transform.scale.y") animation.keyTimes = [0, 0.5, 1] animation.timingFunctions = [timingFunction, timingFunction] animation.values = [1, 0.4, 1] animation.duration = duration animation.repeatCount = HUGE animation.removedOnCompletion = false let animation2 = CAKeyframeAnimation(keyPath: "transform.scale.x") animation2.keyTimes = [0, 0.5, 1] animation2.timingFunctions = [timingFunction, timingFunction] animation2.values = [1, 0.4, 1] animation2.duration = duration animation2.repeatCount = HUGE animation2.removedOnCompletion = false // Draw plates let smPlateHeight = 0.5*size.height let lgPlateHeight = size.height let leftSmPlate = NVActivityIndicatorShape.Line.createLayerWith(size: CGSize(width: lineSize, height: smPlateHeight), color: color) animation.beginTime = beginTime + beginTimes[0] leftSmPlate.frame = CGRect( x: x + lineSize * CGFloat(0), y: y2, width: lineSize, height: smPlateHeight) leftSmPlate.addAnimation(animation, forKey: "animation") layer.addSublayer(leftSmPlate) let leftLgPlate = NVActivityIndicatorShape.Line.createLayerWith(size: CGSize(width: lineSize, height: lgPlateHeight), color: color) animation.beginTime = beginTime + beginTimes[1] leftLgPlate.frame = CGRect( x: x + lineSize * CGFloat(1), y: y, width: lineSize, height: lgPlateHeight) leftLgPlate.addAnimation(animation, forKey: "animation") layer.addSublayer(leftLgPlate) let rightSmPlate = NVActivityIndicatorShape.Line.createLayerWith(size: CGSize(width: lineSize, height: smPlateHeight), color: color) animation.beginTime = beginTime + beginTimes[0] rightSmPlate.frame = CGRect( x: x2 - lineSize - lineSize * CGFloat(0), y: y2, width: lineSize, height: smPlateHeight) rightSmPlate.addAnimation(animation, forKey: "animation") layer.addSublayer(rightSmPlate) let rightLgPlate = NVActivityIndicatorShape.Line.createLayerWith(size: CGSize(width: lineSize, height: lgPlateHeight), color: color) animation.beginTime = beginTime + beginTimes[1] rightLgPlate.frame = CGRect( x: x2 - lineSize - lineSize * CGFloat(1), y: y, width: lineSize, height: lgPlateHeight) rightLgPlate.addAnimation(animation, forKey: "animation") layer.addSublayer(rightLgPlate) // Draw bar let bar = NVActivityIndicatorShape.Line.createLayerWith(size: CGSize(width: 0.5*size.width, height: lineSize), color: color) let barFrame = CGRect( x: 0.5*layer.bounds.size.width-0.5*0.5*size.width, y: 0.5*layer.bounds.size.height, width: 0.5*size.width, height: lineSize) animation2.beginTime = beginTime bar.frame = barFrame bar.addAnimation(animation2, forKey: "animation") layer.addSublayer(bar) } }
mit
7a53416dbb9b1bcee147ab9fd4dba3af
39.737864
140
0.643947
4.272912
false
false
false
false
Karetski/NewsReader
NewsReader/NewsTableViewController.swift
1
11731
// // NewsTableViewController.swift // News Reader // // Created by Alexey on 01.10.15. // Copyright © 2015 Alexey. All rights reserved. // import UIKit import CoreData class NewsTableViewController: UITableViewController, RSSParserDelegate { var managedContext: NSManagedObjectContext! var channel: Channel? var imageDownloadsInProgress = [NSIndexPath: ImageDownloader]() lazy var rssLink: String = { var link: String = "http://www.nytimes.com/services/xml/rss/nyt/World.xml" if let channel = self.channel { if let channelLink = channel.link { link = channelLink } } return link }() let newsCellIdentifier = "NewsCell" let imageNewsCellIdentifier = "ImageNewsCell" let newsDetailSegueIdentifier = "NewsDetailSegue" let imageNewsDetailSegueIdentifier = "ImageNewsDetailSegue" let favoritesSegueIdentifier = "FavoritesSegue" // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 160.0 if self.fetchData() { if let channel = self.channel { self.title = channel.title } self.tableView.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Unwind segues @IBAction func favoritesExitSegue(segue:UIStoryboardSegue) { self.beginParsing() } // MARK: - Button actions @IBAction func changeRSSSource(sender: UIBarButtonItem) { let alert = UIAlertController(title: "RSS Source", message: "Change RSS source link", preferredStyle: .Alert) let saveAction = UIAlertAction(title: "Save", style: .Default) { (action: UIAlertAction!) -> Void in let textField = alert.textFields![0] if let newLink = textField.text { self.rssLink = newLink } self.beginParsing() } let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil) alert.addTextFieldWithConfigurationHandler(nil) alert.addAction(saveAction) alert.addAction(cancelAction) presentViewController(alert, animated: true, completion: nil) } @IBAction func refreshButtonAction(sender: UIBarButtonItem) { self.beginParsing() } // MARK: - Helpers func sendMessageWithError(error: NSError, withTitle title: String) { let alert = UIAlertController(title: title, message: error.localizedDescription, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } func beginParsing() { let privateManagedContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) privateManagedContext.parentContext = self.managedContext privateManagedContext.performBlock { dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) { () -> Void in if let url = NSURL(string: self.rssLink) { let parser = RSSParser() parser.delegate = self parser.parseWithURL(url, intoManagedObjectContext: privateManagedContext) } } } } func fetchData() -> Bool { let channelFetch = NSFetchRequest(entityName: "Channel") do { let results = try self.managedContext.executeFetchRequest(channelFetch) as! [Channel] if results.count > 0 { self.channel = results.first return true } else { return false } } catch let error as NSError { print("Error: \(error) " + "description \(error.localizedDescription)") return false } } // MARK: - NRRSSParserDelegate func parsingWasStarted() { if let leftBarButtomItem = self.navigationItem.leftBarButtonItem { leftBarButtomItem.enabled = false } self.title = "Loading..." UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func parsingWasFinished(error: NSError?) { UIApplication.sharedApplication().networkActivityIndicatorVisible = false if let error = error { self.sendMessageWithError(error, withTitle: "Parsing error") if self.fetchData() { if let channel = self.channel { self.title = channel.title } self.tableView.reloadData() } else { self.title = "News Reader" } if let leftBarButtomItem = self.navigationItem.leftBarButtonItem { leftBarButtomItem.enabled = true } return } else { if self.fetchData() { if let channel = self.channel { self.title = channel.title } self.tableView.reloadData() } if let leftBarButtomItem = self.navigationItem.leftBarButtonItem { leftBarButtomItem.enabled = true } } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let channel = self.channel else { return 0 } return channel.items!.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { guard let channel = self.channel else { return UITableViewCell() } let item = channel.items![indexPath.row] as! Item if let thumbnail = item.thumbnail { return self.imageNewsCellAtIndexPath(indexPath, channel: channel, thumbnail: thumbnail) } else { return self.newsCellAtIndexPath(indexPath, channel: channel) } } func newsCellAtIndexPath(indexPath: NSIndexPath, channel: Channel) -> NewsCell { let cell = tableView.dequeueReusableCellWithIdentifier(newsCellIdentifier) as! NewsCell let item = channel.items![indexPath.row] as! Item cell.titleLabel.text = item.title cell.descriptionLabel.text = item.minifiedDescription cell.dateLabel.text = item.date return cell } func imageNewsCellAtIndexPath(indexPath: NSIndexPath, channel: Channel, thumbnail: NSURL) -> ImageNewsCell { let cell = tableView.dequeueReusableCellWithIdentifier(imageNewsCellIdentifier) as! ImageNewsCell let item = channel.items![indexPath.row] as! Item cell.titleLabel.text = item.title cell.descriptionLabel.text = item.minifiedDescription cell.dateLabel.text = item.date cell.tag = indexPath.row if let thumbnailImage = item.thumbnailImage { cell.thumbnailImageView.image = thumbnailImage } else { if self.tableView.dragging == false && self.tableView.decelerating == false { self.startThumbnailDownload(item, indexPath: indexPath, cell: cell) } cell.thumbnailImageView.setImageAnimated(UIImage(named: "ThumbnailPlaceholder.png"), interval: 0.1, animationOption: .TransitionCrossDissolve) } return cell } // MARK: - Image downloading helpers func startThumbnailDownload(item: Item, indexPath: NSIndexPath, cell: ImageNewsCell) { if let _ = self.imageDownloadsInProgress[indexPath] { return } guard let thumbnailURL = item.thumbnail else { return } UIApplication.sharedApplication().networkActivityIndicatorVisible = true let imageDownloader = ImageDownloader() imageDownloader.completionHandler = { [unowned self] (image, error) -> Void in if let error = error { self.sendMessageWithError(error, withTitle: "Image downloading Error") self.imageDownloadsInProgress.removeValueForKey(indexPath) if self.imageDownloadsInProgress.count == 0 { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } return } dispatch_async(dispatch_get_main_queue()) { () -> Void in if indexPath.row == cell.tag { cell.thumbnailImageView.setImageAnimated(image, interval: 0.2, animationOption: .TransitionFlipFromTop) } } item.thumbnailImage = image do { try self.managedContext.save() } catch let error as NSError { print("Error: \(error) " + "description \(error.localizedDescription)") } self.imageDownloadsInProgress.removeValueForKey(indexPath) if self.imageDownloadsInProgress.count == 0 { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } } self.imageDownloadsInProgress[indexPath] = imageDownloader imageDownloader.downloadImageWithURL(thumbnailURL) } func loadImagesForOnscreenRows() { guard let channel = self.channel else { return } guard let visiblePaths = self.tableView.indexPathsForVisibleRows else { return } for indexPath in visiblePaths { let item = channel.items![indexPath.row] as! Item if let _ = item.thumbnailImage { continue } if let _ = item.thumbnail { let cell = tableView.cellForRowAtIndexPath(indexPath) as! ImageNewsCell self.startThumbnailDownload(item, indexPath: indexPath, cell: cell) } } } // MARK: - UIScrollViewDelegate override func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { self.loadImagesForOnscreenRows() } } override func scrollViewDidEndDecelerating(scrollView: UIScrollView) { self.loadImagesForOnscreenRows() } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == newsDetailSegueIdentifier || segue.identifier == self.imageNewsDetailSegueIdentifier { if let destination = segue.destinationViewController as? NewsDetailTableViewController { if let indexPath = self.tableView.indexPathForSelectedRow { if let channel = self.channel { destination.item = channel.items![indexPath.row] as? Item } } } } if segue.identifier == favoritesSegueIdentifier { if let destination = segue.destinationViewController as? FavoritesTableViewController { destination.managedContext = self.managedContext } } } }
mit
ac6a02f69fc49d183f419cd321182c6c
35.092308
154
0.600426
5.596374
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Components/Announcements/AnnouncementsMetadata.swift
1
691
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformKit public struct AnnouncementsMetadata: Decodable { enum CodingKeys: String, CodingKey { case interval case order } public let order: [AnnouncementType] public let interval: TimeInterval public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let order = try container.decode([String].self, forKey: .order) self.order = order.compactMap { AnnouncementType(rawValue: $0) } let days = try container.decode(Int.self, forKey: .interval) interval = TimeInterval(days) * .day } }
lgpl-3.0
800eff252292d1d449d01d13f6ea3ee3
30.363636
72
0.682609
4.539474
false
false
false
false
Ethenyl/JAMFKit
JamfKit/Sources/Models/ComputerCommand/ComputerCommandGeneral.swift
1
1337
// // Copyright © 2017-present JamfKit. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // @objc(JMFKComputerCommandGeneral) public final class ComputerCommandGeneral: NSObject, Requestable { // MARK: - Constants static let CommandKey = "command" static let PasscodeKey = "passcode" // MARK: - Properties @objc public var command = "" @objc public var passcode: UInt = 0 // MARK: - Initialization public init?(json: [String: Any], node: String = "") { guard let command = json[ComputerCommandGeneral.CommandKey] as? String, let passcode = json[ComputerCommandGeneral.PasscodeKey] as? UInt else { return nil } self.command = command self.passcode = passcode } public init?(command: String, passcode: UInt) { guard !command.isEmpty, passcode > 0 else { return nil } self.command = command self.passcode = passcode } // MARK: - Functions public func toJSON() -> [String: Any] { var json = [String: Any]() json[ComputerCommandGeneral.CommandKey] = command json[ComputerCommandGeneral.PasscodeKey] = passcode return json } }
mit
76ac33a295944c7f5dcaaf14efb72e09
23.290909
102
0.613772
4.528814
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/ActionArea/EmptyStateContainerViewController.swift
1
2928
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit extension ActionArea { /// A container for detail empty state view controllers in the Action Area. final class EmptyStateContainerViewController: ContentContainerViewController, EmptyState { private enum Metrics { static let disabledAlpha: CGFloat = 0.2 } private let emptyState: UIViewController // MARK: - Initializers /// Designated initializer. /// /// - Parameters: /// - emptyState: The empty state view controller. Cannot have a material header. init(emptyState: UIViewController) { guard emptyState is EmptyState == false else { preconditionFailure("Empty state view controllers cannot be nested.") } guard !emptyState.hasMaterialHeader else { // The empty state content cannot have its own header because it would be affected by the // disabled appearance. preconditionFailure("Empty state view controllers cannot have a material header.") } self.emptyState = emptyState let content: UIViewController if emptyState.hasMaterialHeader { content = emptyState } else { content = MaterialHeaderContainerViewController(content: emptyState) } super.init(content: content) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - ActionArea.EmptyState var isEnabled: Bool = true { didSet { switch isEnabled { case true: emptyState.view.alpha = 1 case false: emptyState.view.alpha = Metrics.disabledAlpha } } } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() // Copy the `emptyState` background color, so it is still visible when the content's alpha // is reduced. view.backgroundColor = emptyState.view.backgroundColor } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Empty state content in the Action Area should never have a back button. navigationItem.hidesBackButton = true } // MARK: - Implementation override var description: String { return "ActionArea.EmptyStateContainerViewController(content: \(emptyState))" } } }
apache-2.0
aadfe935c369802ca3e00093236a82e9
28.877551
97
0.677254
4.962712
false
false
false
false
pcperini/Thrust
Thrust/Source/JSONDictionary.swift
1
5246
// // JSONDictionary.swift // Thrust // // Created by Patrick Perini on 9/8/14. // Copyright (c) 2014 pcperini. All rights reserved. // import Foundation // MARK: Operators func +=(inout lhs: JSONDictionary, rhs: JSONDictionary) { for key: String in rhs.keys { lhs[key] = rhs[key] } } func -=(inout lhs: JSONDictionary, rhs: JSONDictionary) { for key: String in rhs.keys { lhs.removeValueForKey(key) } } struct JSONDictionary: SequenceType { // MARK: Properties private var dictionary: [String: JSON] = [:] subscript(key: String) -> JSON? { get { return self.dictionary[key] } set { self.dictionary[key] = newValue } } var count: Int { return self.dictionary.count } var isEmpty: Bool { return self.dictionary.isEmpty } var keys: LazyBidirectionalCollection<MapCollectionView<[String : JSON], String>> { return self.dictionary.keys } var values: LazyBidirectionalCollection<MapCollectionView<[String : JSON], JSON>> { return self.dictionary.values } // MARK: Initializers init(_ dictionary: [String: JSON]) { self.dictionary = dictionary } init(_ values: [(String, JSON)]) { self.init(Dictionary(values)) } internal init(rawJSONObject: NSDictionary) { for (key, value) in rawJSONObject { let keyString = key as String let value: AnyObject! = rawJSONObject.objectForKey(key) switch value { case let value as NSNumber: switch String.fromCString(value.objCType)! { case "c", "C": // Bool self.dictionary[keyString] = value as Bool case "q", "l", "i", "s": // Int self.dictionary[keyString] = value as Int default: // Double self.dictionary[keyString] = value as Double } case let value as NSString: self.dictionary[keyString] = value as String case let value as NSArray: self.dictionary[keyString] = JSONArray(rawJSONObject: value as NSArray) case let value as NSDictionary: self.dictionary[keyString] = JSONDictionary(rawJSONObject: value as NSDictionary) default: self.dictionary[keyString] = null } } } // MARK: Accessors func generate() -> DictionaryGenerator<String, JSON> { return self.dictionary.generate() } // MARK: Mutators mutating func updateValue(value: JSON, forKey key: String) -> JSON? { return self.dictionary.updateValue(value, forKey: key) } mutating func removeValueForKey(key: String) -> JSON? { return self.dictionary.removeValueForKey(key) } mutating func removeAll(keepCapacity: Bool = true) { self.dictionary.removeAll(keepCapacity: keepCapacity) } } extension JSONDictionary: JSONContainer { internal var rawJSONObject: NSDictionary { get { var jsonValidDictionary: NSMutableDictionary = NSMutableDictionary.dictionary() for (key, value) in self { let keyString = key as String switch value { case let value as Bool: jsonValidDictionary.setObject(value, forKey: keyString) case let value as Int: jsonValidDictionary.setObject(value, forKey: keyString) case let value as Double: jsonValidDictionary.setObject(value, forKey: keyString) case let value as String: jsonValidDictionary.setObject(value, forKey: keyString) case let value as JSONArray: jsonValidDictionary.setObject(value.rawJSONObject, forKey: keyString) case let value as JSONDictionary: jsonValidDictionary.setObject(value.rawJSONObject, forKey: keyString) default: jsonValidDictionary.setObject(NSNull(), forKey: keyString) } } return jsonValidDictionary } } var jsonString: String? { return NSString(data: NSJSONSerialization.dataWithJSONObject(self.rawJSONObject, options: nil, error: nil)!, encoding: NSUTF8StringEncoding) } } extension JSONDictionary: Printable, DebugPrintable { var description: String { return self.dictionary.description } var debugDescription: String { return self.dictionary.debugDescription } } extension JSONDictionary: Reflectable { func getMirror() -> MirrorType { return self.dictionary.getMirror() } } extension JSONDictionary: DictionaryLiteralConvertible { static func convertFromDictionaryLiteral(elements: (String, JSON)...) -> JSONDictionary { return JSONDictionary(elements) } }
mit
69619ba5f1cec64b53ce37cd3797adbb
29.505814
97
0.574914
5.2251
false
false
false
false
slangley/RxSwift
RxExample/RxExample/Examples/TableView/User.swift
20
605
import Foundation struct User: Equatable, CustomStringConvertible { var firstName: String var lastName: String var imageURL: String init(firstName: String, lastName: String, imageURL: String) { self.firstName = firstName self.lastName = lastName self.imageURL = imageURL } var description: String { get { return firstName + " " + lastName } } } func ==(lhs: User, rhs:User) -> Bool { return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName && lhs.imageURL == rhs.imageURL }
mit
ae902ff00153fc7b30e30c36395a0631
21.444444
65
0.596694
4.653846
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/SwiftyUserDefaults/Sources/SwiftyUserDefaults.swift
12
15609
// // SwiftyUserDefaults // // Copyright (c) 2015-2016 Radosław Pietruszewski // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation public extension UserDefaults { class Proxy { fileprivate let defaults: UserDefaults fileprivate let key: String fileprivate init(_ defaults: UserDefaults, _ key: String) { self.defaults = defaults self.key = key } // MARK: Getters public var object: Any? { return defaults.object(forKey: key) } public var string: String? { return defaults.string(forKey: key) } public var array: [Any]? { return defaults.array(forKey: key) } public var dictionary: [String: Any]? { return defaults.dictionary(forKey: key) } public var data: Data? { return defaults.data(forKey: key) } public var date: Date? { return object as? Date } public var number: NSNumber? { return defaults.numberForKey(key) } public var int: Int? { return number?.intValue } public var double: Double? { return number?.doubleValue } public var bool: Bool? { return number?.boolValue } // MARK: Non-Optional Getters public var stringValue: String { return string ?? "" } public var arrayValue: [Any] { return array ?? [] } public var dictionaryValue: [String: Any] { return dictionary ?? [:] } public var dataValue: Data { return data ?? Data() } public var numberValue: NSNumber { return number ?? 0 } public var intValue: Int { return int ?? 0 } public var doubleValue: Double { return double ?? 0 } public var boolValue: Bool { return bool ?? false } } /// `NSNumber` representation of a user default func numberForKey(_ key: String) -> NSNumber? { return object(forKey: key) as? NSNumber } /// Returns getter proxy for `key` public subscript(key: String) -> Proxy { return Proxy(self, key) } /// Sets value for `key` public subscript(key: String) -> Any? { get { // return untyped Proxy // (make sure we don't fall into infinite loop) let proxy: Proxy = self[key] return proxy } set { guard let newValue = newValue else { removeObject(forKey: key) return } switch newValue { // @warning This should always be on top of Int because a cast // from Double to Int will always succeed. case let v as Double: self.set(v, forKey: key) case let v as Int: self.set(v, forKey: key) case let v as Bool: self.set(v, forKey: key) case let v as URL: self.set(v, forKey: key) default: self.set(newValue, forKey: key) } } } /// Returns `true` if `key` exists public func hasKey(_ key: String) -> Bool { return object(forKey: key) != nil } /// Removes value for `key` public func remove(_ key: String) { removeObject(forKey: key) } /// Removes all keys and values from user defaults /// Use with caution! /// - Note: This method only removes keys on the receiver `UserDefaults` object. /// System-defined keys will still be present afterwards. public func removeAll() { for (key, _) in dictionaryRepresentation() { removeObject(forKey: key) } } } /// Global shortcut for `UserDefaults.standard` /// /// **Pro-Tip:** If you want to use shared user defaults, just /// redefine this global shortcut in your app target, like so: /// ~~~ /// var Defaults = UserDefaults(suiteName: "com.my.app")! /// ~~~ public let Defaults = UserDefaults.standard // MARK: - Static keys /// Extend this class and add your user defaults keys as static constants /// so you can use the shortcut dot notation (e.g. `Defaults[.yourKey]`) public class DefaultsKeys { fileprivate init() {} } /// Base class for static user defaults keys. Specialize with value type /// and pass key name to the initializer to create a key. public class DefaultsKey<ValueType>: DefaultsKeys { // TODO: Can we use protocols to ensure ValueType is a compatible type? public let _key: String public init(_ key: String) { self._key = key super.init() } } extension UserDefaults { /// This function allows you to create your own custom Defaults subscript. Example: [Int: String] public func set<T>(_ key: DefaultsKey<T>, _ value: Any?) { self[key._key] = value } } extension UserDefaults { /// Returns `true` if `key` exists public func hasKey<T>(_ key: DefaultsKey<T>) -> Bool { return object(forKey: key._key) != nil } /// Removes value for `key` public func remove<T>(_ key: DefaultsKey<T>) { removeObject(forKey: key._key) } } // MARK: Subscripts for specific standard types // TODO: Use generic subscripts when they become available extension UserDefaults { public subscript(key: DefaultsKey<String?>) -> String? { get { return string(forKey: key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<String>) -> String { get { return string(forKey: key._key) ?? "" } set { set(key, newValue) } } public subscript(key: DefaultsKey<Int?>) -> Int? { get { return numberForKey(key._key)?.intValue } set { set(key, newValue) } } public subscript(key: DefaultsKey<Int>) -> Int { get { return numberForKey(key._key)?.intValue ?? 0 } set { set(key, newValue) } } public subscript(key: DefaultsKey<Double?>) -> Double? { get { return numberForKey(key._key)?.doubleValue } set { set(key, newValue) } } public subscript(key: DefaultsKey<Double>) -> Double { get { return numberForKey(key._key)?.doubleValue ?? 0.0 } set { set(key, newValue) } } public subscript(key: DefaultsKey<Bool?>) -> Bool? { get { return numberForKey(key._key)?.boolValue } set { set(key, newValue) } } public subscript(key: DefaultsKey<Bool>) -> Bool { get { return numberForKey(key._key)?.boolValue ?? false } set { set(key, newValue) } } public subscript(key: DefaultsKey<Any?>) -> Any? { get { return object(forKey: key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<Data?>) -> Data? { get { return data(forKey: key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<Data>) -> Data { get { return data(forKey: key._key) ?? Data() } set { set(key, newValue) } } public subscript(key: DefaultsKey<Date?>) -> Date? { get { return object(forKey: key._key) as? Date } set { set(key, newValue) } } public subscript(key: DefaultsKey<URL?>) -> URL? { get { return url(forKey: key._key) } set { set(key, newValue) } } // TODO: It would probably make sense to have support for statically typed dictionaries (e.g. [String: String]) public subscript(key: DefaultsKey<[String: Any]?>) -> [String: Any]? { get { return dictionary(forKey: key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[String: Any]>) -> [String: Any] { get { return dictionary(forKey: key._key) ?? [:] } set { set(key, newValue) } } } // MARK: Static subscripts for array types extension UserDefaults { public subscript(key: DefaultsKey<[Any]?>) -> [Any]? { get { return array(forKey: key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Any]>) -> [Any] { get { return array(forKey: key._key) ?? [] } set { set(key, newValue) } } } // We need the <T: AnyObject> and <T: _ObjectiveCBridgeable> variants to // suppress compiler warnings about NSArray not being convertible to [T] // AnyObject is for NSData and NSDate, _ObjectiveCBridgeable is for value // types bridge-able to Foundation types (String, Int, ...) extension UserDefaults { public func getArray<T: _ObjectiveCBridgeable>(_ key: DefaultsKey<[T]>) -> [T] { return array(forKey: key._key) as NSArray? as? [T] ?? [] } public func getArray<T: _ObjectiveCBridgeable>(_ key: DefaultsKey<[T]?>) -> [T]? { return array(forKey: key._key) as NSArray? as? [T] } public func getArray<T: Any>(_ key: DefaultsKey<[T]>) -> [T] { return array(forKey: key._key) as NSArray? as? [T] ?? [] } public func getArray<T: Any>(_ key: DefaultsKey<[T]?>) -> [T]? { return array(forKey: key._key) as NSArray? as? [T] } } extension UserDefaults { public subscript(key: DefaultsKey<[String]?>) -> [String]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[String]>) -> [String] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Int]?>) -> [Int]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Int]>) -> [Int] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Double]?>) -> [Double]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Double]>) -> [Double] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Bool]?>) -> [Bool]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Bool]>) -> [Bool] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Data]?>) -> [Data]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Data]>) -> [Data] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Date]?>) -> [Date]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Date]>) -> [Date] { get { return getArray(key) } set { set(key, newValue) } } } // MARK: - Archiving custom types // MARK: RawRepresentable extension UserDefaults { // TODO: Ensure that T.RawValue is compatible public func archive<T: RawRepresentable>(_ key: DefaultsKey<T>, _ value: T) { set(key, value.rawValue) } public func archive<T: RawRepresentable>(_ key: DefaultsKey<T?>, _ value: T?) { if let value = value { set(key, value.rawValue) } else { remove(key) } } public func unarchive<T: RawRepresentable>(_ key: DefaultsKey<T?>) -> T? { return object(forKey: key._key).flatMap { T(rawValue: $0 as! T.RawValue) } } public func unarchive<T: RawRepresentable>(_ key: DefaultsKey<T>) -> T? { return object(forKey: key._key).flatMap { T(rawValue: $0 as! T.RawValue) } } } // MARK: NSCoding extension UserDefaults { // TODO: Can we simplify this and ensure that T is NSCoding compliant? public func archive<T>(_ key: DefaultsKey<T>, _ value: T) { set(key, NSKeyedArchiver.archivedData(withRootObject: value)) } public func archive<T>(_ key: DefaultsKey<T?>, _ value: T?) { if let value = value { set(key, NSKeyedArchiver.archivedData(withRootObject: value)) } else { remove(key) } } public func unarchive<T>(_ key: DefaultsKey<T>) -> T? { return data(forKey: key._key).flatMap { NSKeyedUnarchiver.unarchiveObject(with: $0) } as? T } public func unarchive<T>(_ key: DefaultsKey<T?>) -> T? { return data(forKey: key._key).flatMap { NSKeyedUnarchiver.unarchiveObject(with: $0) } as? T } } // MARK: - Deprecations infix operator ?= : AssignmentPrecedence /// If key doesn't exist, sets its value to `expr` /// - Deprecation: This will be removed in a future release. /// Please migrate to static keys and use this gist: https://gist.github.com/radex/68de9340b0da61d43e60 /// - Note: This isn't the same as `Defaults.registerDefaults`. This method saves the new value to disk, whereas `registerDefaults` only modifies the defaults in memory. /// - Note: If key already exists, the expression after ?= isn't evaluated @available(*, deprecated:1, message:"Please migrate to static keys and use this gist: https://gist.github.com/radex/68de9340b0da61d43e60") public func ?= (proxy: UserDefaults.Proxy, expr: @autoclosure() -> Any) { if !proxy.defaults.hasKey(proxy.key) { proxy.defaults[proxy.key] = expr() } } /// Adds `b` to the key (and saves it as an integer) /// If key doesn't exist or isn't a number, sets value to `b` @available(*, deprecated:1, message:"Please migrate to static keys to use this.") public func += (proxy: UserDefaults.Proxy, b: Int) { let a = proxy.defaults[proxy.key].intValue proxy.defaults[proxy.key] = a + b } @available(*, deprecated:1, message:"Please migrate to static keys to use this.") public func += (proxy: UserDefaults.Proxy, b: Double) { let a = proxy.defaults[proxy.key].doubleValue proxy.defaults[proxy.key] = a + b } /// Icrements key by one (and saves it as an integer) /// If key doesn't exist or isn't a number, sets value to 1 @available(*, deprecated:1, message:"Please migrate to static keys to use this.") public postfix func ++ (proxy: UserDefaults.Proxy) { proxy += 1 }
mit
0d6d26a898e8bf32d862f610c38efce6
29.968254
169
0.585533
4.23555
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/TXTReader/Speech/Model/TTSConfig.swift
1
3702
// // TTSConfig.swift // iflyDemo // // Created by caony on 2018/9/18. // Copyright © 2018年 QSH. All rights reserved. // import Foundation let filePath = "\(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? "")/speakerres/3589709422/" public class TTSConfig { var speed:String = "50" var volume:String = "50" var pitch:String = "50" var sampleRate:String = "16000" var vcnName:String = "xiaoyan" // the engine type of Text-to-Speech:"auto","local","cloud" var engineType:String = "cloud" var voiceID:String = "51200" var ent:String = "" var ttsPath:String = "" var next_text_len:Int = 0 var next_text:String = "" var speakerPath = "\(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])/speakerres/3589709422/xiaoyan.jet" var commonPath = "\(Bundle.main.resourcePath ?? "")/TTSResource/common.jet" var fileName:String = "tts.pcm" let tts_res_path = "tts_res_path" let unicode = "unicode" private init() {} static var share = TTSConfig() var allSpeakers:[Speaker] = [] func availableSpeakers() ->[Speaker] { let files = (try? FileManager.default.contentsOfDirectory(atPath: filePath)) ?? [] var jets:[String] = [] for file in files { let jet = (file as NSString).lastPathComponent.contains(".jet") if jet { jets.append(file) } } var speakers:[Speaker] = [] for jet in jets { let file = (jet as NSString).lastPathComponent let fileArr = file.components(separatedBy: ".") if fileArr.count > 1 { let name = fileArr[0] for speak in allSpeakers { if speak.name == name { speakers.append(speak) } } } } return speakers } func getSpeakers() { ZSBookManager.calTime { let filePath = Bundle.main.path(forResource: "speakers.plist", ofType: nil) ?? "" if let dict = NSDictionary(contentsOfFile: filePath) { if let speakers = dict["speakers"] as? [Any] { if let models = [Speaker].deserialize(from: speakers) as? [Speaker] { self.allSpeakers = models } } } } print("") } func parseJSONFile(path:String) ->[Speaker] { var models:[Speaker] = [] ZSBookManager.calTime { let url = URL(fileURLWithPath: path) if let data = try? Data(contentsOf: url, options: Data.ReadingOptions.mappedIfSafe) { let str = String(data: data, encoding: .utf8) ?? "" if let obj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) { if let dict = obj as? [String:Any] { // let filePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] // // dict.write(toFile: "\(filePath)/speakers.plist", atomically: true) if let speakers = dict["speakers"] as? [Any] { if let speakersModel = [Speaker].deserialize(from: speakers) as? [Speaker] { models = speakersModel } } } } } } return models } }
mit
dec6076a7dcab189f130a01712f8ba73
33.570093
185
0.534739
4.489078
false
false
false
false
audiokit/AudioKit
Tests/AudioKitTests/Node Tests/Generator Tests/PhaseLockedVocoderTests.swift
2
1337
import AudioKit import AVFoundation import XCTest class PhaseLockedVocoderTests: XCTestCase { // Because SPM doesn't support resources yet, render out a test file. func generateTestFile() -> URL { let osc = Oscillator() let engine = AudioEngine() engine.output = osc osc.start() osc.$frequency.ramp(to: 880, duration: 1.0) let mgr = FileManager.default let url = mgr.temporaryDirectory.appendingPathComponent("test.aiff") try? mgr.removeItem(at: url) let file = try! AVAudioFile(forWriting: url, settings: Settings.audioFormat.settings) try! engine.renderToFile(file, duration: 1) print("rendered test file to \(url)") return url } func testDefault() { let url = generateTestFile() XCTAssertNotNil(url) let file = try! AVAudioFile(forReading: url) let engine = AudioEngine() let vocoder = PhaseLockedVocoder(file: file) engine.output = vocoder let audio = engine.startTest(totalDuration: 2.0) vocoder.$position.ramp(to: 0.5, duration: 0.5) audio.append(engine.render(duration: 1.0)) vocoder.$position.ramp(to: 0, duration: 0.5) audio.append(engine.render(duration: 1.0)) engine.stop() testMD5(audio) } }
mit
39a9651ee903f426c002b6bfde6d52de
26.854167
93
0.630516
4.244444
false
true
false
false
qvacua/vimr
NvimView/Sources/NvimView/NvimView+Api.swift
1
8169
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa import MessagePack import PureLayout import RxPack import RxSwift import RxNeovim import SpriteKit public extension NvimView { func toggleFramerateView() { // Framerate measurement; from https://stackoverflow.com/a/34039775 if self.framerateView == nil { let sk = SKView(forAutoLayout: ()) sk.showsFPS = true self.framerateView = sk self.addSubview(sk) sk.autoPinEdge(toSuperviewEdge: .top, withInset: 10) sk.autoPinEdge(toSuperviewEdge: .right, withInset: 10) sk.autoSetDimensions(to: CGSize(width: 60, height: 15)) return } self.framerateView?.removeAllConstraints() self.framerateView?.removeFromSuperview() self.framerateView = nil } func isBlocked() -> Single<Bool> { self.api.getMode().map { dict in dict["blocking"]?.boolValue ?? false } } func hasDirtyBuffers() -> Single<Bool> { self.api.getDirtyStatus() } func waitTillNvimExits() { self.nvimExitedCondition.wait(for: 5) } func enterResizeMode() { self.currentlyResizing = true self.markForRenderWholeView() } func exitResizeMode() { self.currentlyResizing = false self.markForRenderWholeView() self.resizeNeoVimUi(to: self.bounds.size) } func currentBuffer() -> Single<NvimView.Buffer> { self.api .getCurrentBuf() .flatMap { self.neoVimBuffer(for: $0, currentBuffer: $0) } .subscribe(on: self.scheduler) } func allBuffers() -> Single<[NvimView.Buffer]> { Single .zip(self.api.getCurrentBuf(), self.api.listBufs()) { (curBuf: $0, bufs: $1) } .map { tuple in tuple.bufs.map { buf in self.neoVimBuffer(for: buf, currentBuffer: tuple.curBuf) } } .flatMap(Single.fromSinglesToSingleOfArray) .subscribe(on: self.scheduler) } func isCurrentBufferDirty() -> Single<Bool> { self .currentBuffer() .map(\.isDirty) .subscribe(on: self.scheduler) } func allTabs() -> Single<[NvimView.Tabpage]> { Single.zip( self.api.getCurrentBuf(), self.api.getCurrentTabpage(), self.api.listTabpages() ) { (curBuf: $0, curTab: $1, tabs: $2) } .map { tuple in tuple.tabs.map { tab in self.neoVimTab(for: tab, currentTabpage: tuple.curTab, currentBuffer: tuple.curBuf) } } .flatMap(Single.fromSinglesToSingleOfArray) .subscribe(on: self.scheduler) } func newTab() -> Completable { self.api .command(command: "tabe") .subscribe(on: self.scheduler) } func open(urls: [URL]) -> Completable { self .allTabs() .flatMapCompletable { tabs -> Completable in let buffers = tabs.map(\.windows).flatMap { $0 }.map(\.buffer) let currentBufferIsTransient = buffers.first { $0.isCurrent }?.isTransient ?? false return Completable.concat( urls.map { url -> Completable in let bufExists = buffers.contains { $0.url == url } let wins = tabs.map(\.windows).flatMap { $0 } if let win = bufExists ? wins.first(where: { win in win.buffer.url == url }) : nil { return self.api.setCurrentWin(window: RxNeovimApi.Window(win.handle)) } return currentBufferIsTransient ? self.open(url, cmd: "e") : self.open(url, cmd: "tabe") } ) } .subscribe(on: self.scheduler) } func openInNewTab(urls: [URL]) -> Completable { Completable .concat(urls.map { url in self.open(url, cmd: "tabe") }) .subscribe(on: self.scheduler) } func openInCurrentTab(url: URL) -> Completable { self.open(url, cmd: "e") } func openInHorizontalSplit(urls: [URL]) -> Completable { Completable .concat(urls.map { url in self.open(url, cmd: "sp") }) .subscribe(on: self.scheduler) } func openInVerticalSplit(urls: [URL]) -> Completable { Completable .concat(urls.map { url in self.open(url, cmd: "vsp") }) .subscribe(on: self.scheduler) } func select(buffer: NvimView.Buffer) -> Completable { self .allTabs() .map { tabs in tabs.map(\.windows).flatMap { $0 } } .flatMapCompletable { wins -> Completable in if let win = wins.first(where: { $0.buffer == buffer }) { return self.api.setCurrentWin(window: RxNeovimApi.Window(win.handle)) } return self.api.command(command: "tab sb \(buffer.handle)") } .subscribe(on: self.scheduler) } func goTo(line: Int) -> Completable { self.api.command(command: "\(line)") } /// Closes the current window. func closeCurrentTab() -> Completable { self.api .command(command: "q") .subscribe(on: self.scheduler) } func saveCurrentTab() -> Completable { self.api .command(command: "w") .subscribe(on: self.scheduler) } func saveCurrentTab(url: URL) -> Completable { self.api .command(command: "w \(url.shellEscapedPath)") .subscribe(on: self.scheduler) } func closeCurrentTabWithoutSaving() -> Completable { self.api .command(command: "q!") .subscribe(on: self.scheduler) } func quitNeoVimWithoutSaving() -> Completable { self.api .command(command: "qa!") .subscribe(on: self.scheduler) } func vimOutput(of command: String) -> Single<String> { self.api .exec(src: command, output: true) .subscribe(on: self.scheduler) } func cursorGo(to position: Position) -> Completable { self.api .getCurrentWin() .flatMapCompletable { curWin in self.api.winSetCursor(window: curWin, pos: [position.row, position.column]) } .subscribe(on: self.scheduler) } func didBecomeMain() -> Completable { self.bridge.focusGained(true) } func didResignMain() -> Completable { self.bridge.focusGained(false) } internal func neoVimBuffer( for buf: RxNeovimApi.Buffer, currentBuffer: RxNeovimApi.Buffer? ) -> Single<NvimView.Buffer> { self.api .bufGetInfo(buffer: buf) .map { info -> NvimView.Buffer in let current = buf == currentBuffer guard let path = info["filename"]?.stringValue, let dirty = info["modified"]?.boolValue, let buftype = info["buftype"]?.stringValue, let listed = info["buflisted"]?.boolValue else { throw RxNeovimApi.Error .exception(message: "Could not convert values from the dictionary.") } let url = path == "" || buftype != "" ? nil : URL(fileURLWithPath: path) return NvimView.Buffer( apiBuffer: buf, url: url, type: buftype, isDirty: dirty, isCurrent: current, isListed: listed ) } .subscribe(on: self.scheduler) } private func open(_ url: URL, cmd: String) -> Completable { self.api .command(command: "\(cmd) \(url.shellEscapedPath)") .subscribe(on: self.scheduler) } private func neoVimWindow( for window: RxNeovimApi.Window, currentWindow: RxNeovimApi.Window?, currentBuffer: RxNeovimApi.Buffer? ) -> Single<NvimView.Window> { self.api .winGetBuf(window: window) .flatMap { buf in self.neoVimBuffer(for: buf, currentBuffer: currentBuffer) } .map { buffer in NvimView.Window( apiWindow: window, buffer: buffer, isCurrentInTab: window == currentWindow ) } } private func neoVimTab( for tabpage: RxNeovimApi.Tabpage, currentTabpage: RxNeovimApi.Tabpage?, currentBuffer: RxNeovimApi.Buffer? ) -> Single<NvimView.Tabpage> { Single.zip( self.api.tabpageGetWin(tabpage: tabpage), self.api.tabpageListWins(tabpage: tabpage) ) { (curWin: $0, wins: $1) } .map { tuple in tuple.wins.map { win in self.neoVimWindow(for: win, currentWindow: tuple.curWin, currentBuffer: currentBuffer) } } .flatMap(Single.fromSinglesToSingleOfArray) .map { wins in NvimView.Tabpage(apiTabpage: tabpage, windows: wins, isCurrent: tabpage == currentTabpage) } } }
mit
f2fe0b627f284c285973a9cd545bef0b
27.463415
100
0.623332
3.769728
false
false
false
false
wbaumann/SmartReceiptsiOS
SmartReceipts/Modules/Settings/SettingsFormView.swift
2
31576
// // SettingsFormView.swift // SmartReceipts // // Created by Bogdan Evsenev on 06/07/2017. // Copyright © 2017 Will Baumann. All rights reserved. // import Eureka import RxSwift import StoreKit import Crashlytics import Fabric fileprivate let IMAGE_OPTIONS = [512, 1024, 2048, 0] class SettingsFormView: FormViewController { private var hasValidSubscription = false weak var openModuleSubject: PublishSubject<SettingsRoutes>! weak var alertSubject: PublishSubject<AlertTuple>! weak var settingsView: SettingsView! fileprivate var hadPriceRetrieveError = false fileprivate var purchaseRow: PurchaseButtonRow! fileprivate var footerRow: InputTextRow! fileprivate var removeAdsProduct: SKProduct? fileprivate let bag = DisposeBag() private let dateFormats: [String] var hud: PendingHUDView? var showOption: ShowSettingsOption? init(settingsView: SettingsView, dateFormats: [String]) { self.dateFormats = dateFormats super.init(nibName: nil, bundle: nil) self.settingsView = settingsView } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) purchaseRow.markSpinning() checkSubscription() applySettingsOption() } override func viewDidLoad() { super.viewDidLoad() tableView.separatorColor = UIColor.clear form +++ Section(LocalizedString("pref_pro_header")) <<< PurchaseButtonRow() { [unowned self] row in row.title = LocalizedString("pro_subscription") self.purchaseRow = row }.onCellSelection({ [unowned self] _, row in if !row.isPurchased() { self.hud = PendingHUDView.showFullScreen() self.settingsView.purchaseSubscription() .do(onNext: { [weak self] _ in self?.hud?.hide() }, onError: { [weak self] _ in self?.hud?.hide() }).subscribe(onNext: { [weak self] in guard let safeSelf = self else { return } safeSelf.checkSubscription() }, onError: { error in self.alertSubject.onNext((title: LocalizedString("purchase_failed"), message: error.localizedDescription)) }).disposed(by: self.bag) } }) <<< ButtonRow() { row in row.title = LocalizedString("settings_purchase_restore_label") }.cellUpdate({ cell, row in cell.textLabel?.textColor = AppTheme.primaryColor }).onCellSelection({ [unowned self] _, _ in self.hud = PendingHUDView.showFullScreen() self.settingsView.restoreSubscription() .do(onNext: { [weak self] _ in self?.hud?.hide() }, onError: { [weak self] _ in self?.hud?.hide() }).filter({ $0.valid }) .subscribe(onNext: { [weak self] validation in self?.setupPurchased(expireDate: validation.expireTime) }, onError: { error in self.alertSubject.onNext((title: LocalizedString("purchase_unavailable"), message: error.localizedDescription)) }).disposed(by: self.bag) }) +++ Section(LocalizedString("pref_pro_header")) <<< InputTextRow() { [unowned self] row in row.title = LocalizedString("pref_pro_pdf_footer_title") row.value = WBPreferences.pdfFooterString() self.footerRow = row row.isEnabled = self.hasValidSubscription }.onChange({ row in WBPreferences.setPDFFooterString(row.value ?? "") }).cellUpdate({ cell, row in cell.textField.font = .systemFont(ofSize: 14) }).onCellSelection({ [unowned self] _, row in if !row.isEnabled { self.alertSubject.onNext((title: LocalizedString("pref_pro_header"), message: LocalizedString("settings_pdf_footer_pro_message_body"))) } }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_pro_separate_by_category_title") row.value = WBPreferences.separatePaymantsByCategory() row.onSubtitle = LocalizedString("pref_pro_separate_by_category_summaryOn") row.offSubtitle = LocalizedString("pref_pro_separate_by_category_summaryOff") }.onChange({ row in WBPreferences.setSeparatePaymantsByCategory(row.value!) }).cellUpdate({ [unowned self] cell, _ in cell.isUserInteractionEnabled = self.hasValidSubscription }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_pro_categorical_summation_title") row.value = WBPreferences.includeCategoricalSummation() row.onSubtitle = LocalizedString("pref_pro_categorical_summation_summaryOn") row.offSubtitle = LocalizedString("pref_pro_categorical_summation_summaryOff") }.onChange({ row in WBPreferences.setIncludeCategoricalSummation(row.value!) }).cellUpdate({ [unowned self] cell, _ in cell.isUserInteractionEnabled = self.hasValidSubscription }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_pro_omit_default_table_title") row.value = WBPreferences.omitDefaultPdfTable() }.onChange({ row in WBPreferences.setOmitDefaultPdfTable(row.value!) }).cellUpdate({ [unowned self] cell, _ in cell.isUserInteractionEnabled = self.hasValidSubscription }) +++ Section(LocalizedString("pref_email_header")) <<< textInput(LocalizedString("pref_email_default_email_to_title"), value: WBPreferences.defaultEmailRecipient(), placeholder: LocalizedString("pref_email_default_email_emptyValue")) .onChange({ row in WBPreferences.setDefaultEmailRecipient(row.value ?? "") }) <<< textInput(LocalizedString("pref_email_default_email_cc_title"), value: WBPreferences.defaultEmailCC(), placeholder: LocalizedString("pref_email_default_email_emptyValue")) .onChange({ row in WBPreferences.setDefaultEmailCC(row.value ?? "") }) <<< textInput(LocalizedString("pref_email_default_email_bcc_title"), value: WBPreferences.defaultEmailBCC(), placeholder: LocalizedString("pref_email_default_email_emptyValue")) .onChange({ row in WBPreferences.setDefaultEmailBCC(row.value ?? "") }) <<< textInput(LocalizedString("pref_email_default_email_subject_title"), value: WBPreferences.defaultEmailSubject()) .onChange({ row in WBPreferences.setDefaultEmailSubject(row.value ?? "") }) +++ Section(LocalizedString("pref_general_header")) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_receipt_enable_autocomplete_title") row.onSubtitle = LocalizedString("pref_receipt_enable_autocomplete_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.isAutocompleteEnabled() }.onChange({ row in WBPreferences.setAutocompleteEnabled(row.value!) }) <<< IntRow() { row in row.title = LocalizedString("pref_general_trip_duration_title") row.value = Int(WBPreferences.defaultTripDuration()) }.onChange({ row in let intValue = row.value ?? 0 if intValue > 0 && 1000 > intValue { WBPreferences.setDefaultTripDuration(Int32(intValue)) } }).cellUpdate({ cell, _ in cell.textField.textColor = AppTheme.primaryColor }).cellSetup({ cell, _ in cell.textLabel?.numberOfLines = 3 }) <<< DecimalRow() { row in row.title = LocalizedString("pref_receipt_minimum_receipts_price_title") row.placeholder = LocalizedString("DIALOG_RECEIPTMENU_HINT_PRICE_SHORT") let value = WBPreferences.minimumReceiptPriceToIncludeInReports() row.value = value == WBPreferences.min_FLOAT() || value == Float(Int32.min) ? nil : Double(value) }.onChange({ row in let value = row.value == nil ? WBPreferences.min_FLOAT() : Float(row.value!) WBPreferences.setMinimumReceiptPriceToIncludeInReports(value) }).cellUpdate({ cell, _ in cell.textField.textColor = AppTheme.primaryColor }).cellSetup({ cell, _ in cell.textLabel?.numberOfLines = 3 cell.textField.inputView = NumberKeyboard.create(delegate: cell.textField) }) <<< textInput(LocalizedString("pref_output_username_title"), value: WBPreferences.userID()) .onChange({ row in WBPreferences.setUserID(row.value ?? "") }) <<< PickerInlineRow<String>() { row in row.title = LocalizedString("pref_general_default_currency_title") row.options = Currency.allCurrencyCodesWithCached() row.value = WBPreferences.defaultCurrency() }.onChange({ row in WBPreferences.setDefaultCurrency(row.value!) }).cellSetup({ cell, _ in cell.detailTextLabel?.textColor = AppTheme.primaryColor }) <<< PickerInlineRow<String>() { [unowned self] row in row.title = LocalizedString("pref_general_date_format_title") let dateFormatter = DateFormatter() let date = Date() dateFormatter.dateFormat = WBPreferences.dateFormat() row.value = dateFormatter.string(from: date) row.options = self.dateFormats.map { format in dateFormatter.dateFormat = format return dateFormatter.string(from: date) } }.onChange({ [weak self] row in guard let self = self, let index = row.options.index(of: row.value!) else { return } WBPreferences.setDateFormat(self.dateFormats[index]) }).cellSetup({ cell, _ in cell.detailTextLabel?.textColor = AppTheme.primaryColor }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_general_track_cost_center_title") row.onSubtitle = LocalizedString("pref_general_track_cost_center_summaryOn") row.offSubtitle = LocalizedString("pref_general_track_cost_center_summaryOff") row.value = WBPreferences.trackCostCenter() }.onChange({ row in WBPreferences.setTrackCostCenter(row.value!) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_receipt_predict_categories_title") row.onSubtitle = LocalizedString("pref_receipt_predict_categories_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.predictCategories() }.onChange({ row in WBPreferences.setPredictCategories(row.value!) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_receipt_include_tax_field_title") row.onSubtitle = LocalizedString("pref_receipt_include_tax_field_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.includeTaxField() }.onChange({ row in WBPreferences.setIncludeTaxField(row.value!) }) <<< decimalRow(LocalizedString("pref_receipt_tax_percent_title"), float: WBPreferences.defaultTaxPercentage(), placeholder: "%") .onChange({ row in let value = row.value == nil ? nil : Float(row.value!) WBPreferences.setDefaultTaxPercentage(value ?? 0) }) <<< switchRow(LocalizedString("pref_receipt_pre_tax_title"), value: WBPreferences.enteredPricePreTax()) .onChange({ row in WBPreferences.setEnteredPricePreTax(row.value!) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_receipt_full_page_title") row.onSubtitle = LocalizedString("pref_receipt_full_page_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.assumeFullPage() }.onChange({ row in WBPreferences.setAssumeFullPage(row.value!) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_receipt_match_name_to_category_title") row.onSubtitle = LocalizedString("pref_receipt_match_name_to_category_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.matchNameToCategory() }.onChange({ row in WBPreferences.setMatchNameToCategory(row.value!) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_receipt_match_comment_to_category_title") row.onSubtitle = LocalizedString("pref_receipt_match_comment_to_category_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.matchCommentToCategory() }.onChange({ row in WBPreferences.setMatchCommentToCategory(row.value!) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_receipt_reimbursable_only_title") row.onSubtitle = LocalizedString("pref_receipt_reimbursable_only_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.onlyIncludeReimbursableReceiptsInReports() }.onChange({ row in WBPreferences.setOnlyIncludeReimbursableReceiptsInReports(row.value!) }) <<< switchRow(LocalizedString("pref_receipt_reimbursable_default_title"), value: WBPreferences.expensableDefault()) .onChange({ row in WBPreferences.setExpensableDefault(row.value!) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_receipt_default_to_report_start_date_title") row.onSubtitle = LocalizedString("pref_receipt_default_to_report_start_date_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.defaultToFirstReportDate() }.onChange({ row in WBPreferences.setDefaultToFirstReportDate(row.value!) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_receipt_show_id_title") row.onSubtitle = LocalizedString("pref_receipt_show_id_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.showReceiptID() }.onChange({ row in WBPreferences.setShowReceiptID(row.value!) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_receipt_use_payment_methods_title") row.onSubtitle = LocalizedString("pref_receipt_use_payment_methods_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.usePaymentMethods() }.onChange({ row in WBPreferences.setUsePaymentMethods(row.value!) }) <<< openModuleButton(LocalizedString("pref_receipt_payment_methods_title"), subtitle: LocalizedString("pref_receipt_payment_methods_summary"), route: .paymentMethods) +++ Section(LocalizedString("pref_camera_header")) <<< segmentedRow(LocalizedString("settings_max_camera_resolution_label"), options: imageOptions(), selected: imageOptionFromPreferences()) .onChange({ row in WBPreferences.setCameraMaxHeightWidth(IMAGE_OPTIONS[row.value!]) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_camera_bw_title") row.onSubtitle = LocalizedString("pref_camera_bw_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.cameraSaveImagesBlackAndWhite() }.onChange({ row in WBPreferences.setCameraSaveImagesBlackAndWhite(row.value!) }) +++ Section(LocalizedString("menu_main_categories")) <<< openModuleButton(LocalizedString("manage_categories"), subtitle: LocalizedString("pref_receipt_customize_categories_summary"), route: .categories) +++ Section(LocalizedString("pref_output_custom_csv_title")) <<< openModuleButton(LocalizedString("pref_output_custom_csv_title"), route: .columns(isCSV: true)) +++ Section(LocalizedString("pref_output_custom_pdf_title")) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_output_print_receipt_id_by_photo_title") row.onSubtitle = LocalizedString("pref_output_print_receipt_id_by_photo_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.printReceiptIDByPhoto() }.onChange({ row in WBPreferences.setPrintReceiptIDByPhoto(row.value!) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_output_print_receipt_comment_by_photo_title") row.onSubtitle = LocalizedString("pref_output_print_receipt_comment_by_photo_summaryOn") row.offSubtitle = LocalizedString("pref_output_print_receipt_comment_by_photo_summaryOff") row.value = WBPreferences.printCommentByPhoto() }.onChange({ row in WBPreferences.setPrintCommentByPhoto(row.value!) }) <<< switchRow(LocalizedString("pref_output_receipts_landscape_title"), value: WBPreferences.printReceiptTableLandscape()) .onChange({ row in WBPreferences.setPrintReceiptTableLandscape(row.value!) }) <<< PickerInlineRow<String>() { row in row.title = LocalizedString("pref_output_preferred_language_title") row.options = WBPreferences.languages.map { $0.name } let preferred = WBPreferences.preferredReportLanguage() row.value = WBPreferences.languageBy(identifier: preferred!)?.name }.onChange({ row in guard let lang = WBPreferences.languageBy(name: row.value!) else { return } WBPreferences.setPreferredReportLanguage(lang.identifier) }) <<< segmentedRow(LocalizedString("settings_pdf_page_size"), options: pdfFormats(), selected: pdfFormats().index(of: WBPreferences.prefferedPDFSize().rawValue) ?? 0) .onChange({ row in WBPreferences.setPreferredRawPDFSize(PDFPageSize.pdfPageSizeBy(index: row.value!).rawValue) }) <<< openModuleButton(LocalizedString("pref_output_custom_pdf_title"), route: .columns(isCSV: false)) +++ Section(LocalizedString("pref_distance_header")) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_distance_header") row.onSubtitle = LocalizedString("pref_distance_include_price_in_report_summaryOn") row.offSubtitle = LocalizedString("pref_distance_include_price_in_report_summaryOff") row.value = WBPreferences.isTheDistancePriceBeIncludedInReports() }.onChange({ row in WBPreferences.setTheDistancePriceBeIncludedInReports(row.value!) }) <<< decimalRow(LocalizedString("pref_distance_rate_title"), dobule: WBPreferences.distanceRateDefaultValue(), placeholder: LocalizedString("distance_rate_field")) .onChange({ row in WBPreferences.setDistanceRateDefaultValue(row.value ?? -1) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_distance_print_table_title") row.onSubtitle = LocalizedString("pref_distance_print_table_summaryOn") row.offSubtitle = LocalizedString("pref_distance_print_table_summaryOff") row.value = WBPreferences.printDistanceTable() }.onChange({ row in WBPreferences.setPrintDistanceTable(row.value!) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_distance_print_daily_title") row.onSubtitle = LocalizedString("pref_distance_print_daily_summaryOn") row.offSubtitle = LocalizedString("pref_distance_print_daily_summaryOff") row.value = WBPreferences.printDailyDistanceValues() }.onChange({ row in WBPreferences.setPrintDailyDistanceValues(row.value!) }) +++ Section(LocalizedString("pref_layout_header")) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_layout_display_date_title") row.onSubtitle = LocalizedString("pref_layout_display_date_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.layoutShowReceiptDate() }.onChange({ row in WBPreferences.setLayoutShowReceiptDate(row.value!) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_layout_display_category_title") row.onSubtitle = LocalizedString("pref_layout_display_category_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.layoutShowReceiptCategory() }.onChange({ row in WBPreferences.setLayoutShowReceiptCategory(row.value!) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_layout_display_photo_title") row.onSubtitle = LocalizedString("pref_layout_display_photo_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.layoutShowReceiptAttachmentMarker() }.onChange({ row in WBPreferences.setLayoutShowReceiptAttachmentMarker(row.value!) }) +++ Section(LocalizedString("pref_privacy_header")) <<< openModuleButton(LocalizedString("pref_about_privacy_policy_title"), route: .privacyPolicy) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_privacy_enable_analytics_title") row.onSubtitle = LocalizedString("pref_privacy_enable_analytics_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.analyticsEnabled() }.onChange({ row in WBPreferences.setAnalyticsEnabled(row.value!) AnalyticsManager.sharedManager.setAnalyticsSending(allowed: row.value!) }) <<< DescribedSwitchRow() { row in row.title = LocalizedString("pref_privacy_enable_crash_tracking_title") row.onSubtitle = LocalizedString("pref_privacy_enable_crash_tracking_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.crashTrackingEnabled() }.onChange({ row in WBPreferences.setCrashTrackingEnabled(row.value!) _ = row.value! ? Fabric.with([Crashlytics.self]) : Fabric.with([]) }) <<< DescribedSwitchRow() { row in row.hidden = Condition(booleanLiteral: hasValidSubscription) row.title = LocalizedString("pref_privacy_enable_ad_personalization_title") row.onSubtitle = LocalizedString("pref_privacy_enable_ad_personalization_summary") row.offSubtitle = row.onSubtitle row.value = WBPreferences.adPersonalizationEnabled() }.onChange({ row in WBPreferences.setAdPersonalizationEnabled(row.value!) }) +++ Section(LocalizedString("pref_about_header")) <<< openModuleButton(LocalizedString("pref_about_version_title"), subtitle: UIApplication.shared.version()) <<< openModuleButton(LocalizedString("pref_about_about_title"), route: .about) <<< openModuleButton(LocalizedString("pref_about_terms_title"), route: .termsOfUse) +++ Section(LocalizedString("pref_help_header")) <<< openModuleButton(LocalizedString("pref_help_send_feedback_title"), onTap: { [unowned self] in self.settingsView.sendFeedback(subject: FeedbackEmailSubject) }) <<< openModuleButton(LocalizedString("pref_help_support_email_title"), onTap: { [unowned self] in self.settingsView.sendFeedback(subject: FeedbackBugreportEmailSubject) }) } private func imageOptions() -> [String] { let pixelsString = LocalizedString("settings_camera_pixels_label") let option1 = "512 "+pixelsString let option2 = "1024 "+pixelsString let option3 = "2048 "+pixelsString let option4 = LocalizedString("settings_camera_value_default_label") return [option1, option2, option3, option4] } private func pdfFormats() -> [String] { return ["A4", LocalizedString("pref_output_pdf_page_size_letter_entryValue")] } private func imageOptionFromPreferences() -> Int { return IMAGE_OPTIONS.index(of: WBPreferences.cameraMaxHeightWidth())! } private func checkSubscription() { settingsView.subscriptionValidation().subscribe(onNext: { [weak self] validation in self?.hud?.hide() if validation.valid { self?.setupPurchased(expireDate: validation.expireTime) } else { _ = self?.settingsView.retrivePlusSubscriptionPrice().subscribe(onNext: { [weak self] price in self?.purchaseRow.setPrice(string: price) }, onError: { [weak self] error in _ = self?.purchaseRow.markError().subscribe(onNext: { [weak self] in self?.alertSubject.onNext((title: LocalizedString("purchase_failed"), message: LocalizedString("purchase_unavailable"))) }) }) } }, onError: { [weak self] _ in self?.hud?.hide() }).disposed(by: bag) } private func setupPurchased(expireDate: Date?) { hasValidSubscription = true purchaseRow.markPurchased() purchaseRow.setSubscriptionEnd(date: expireDate) footerRow.isEnabled = true DispatchQueue.main.async { [unowned self] in self.form.allSections[1].reload() } } private func applySettingsOption() { if let option = showOption { DispatchQueue.main.async { [unowned self] in switch option { case .reportCSVOutputSection: self.tableView.scrollToRow(at: IndexPath(row: 0, section: 6), at: .top, animated: false) case .distanceSection: self.tableView.scrollToRow(at: IndexPath(row: 0, section: 8), at: .top, animated: false) case .privacySection: self.tableView.scrollToRow(at: IndexPath(row: 0, section: 10), at: .top, animated: false) } } } } } // MARK: ROW METHODS extension SettingsFormView { fileprivate func textInput(_ title: String, value: String? = nil, placeholder: String? = nil) -> InputTextRow { return InputTextRow() { row in row.title = title row.value = value row.cell.textField.placeholder = placeholder }.cellUpdate({ cell, row in cell.textField.font = .systemFont(ofSize: 14) }) } fileprivate func switchRow(_ title: String, value: Bool = false) -> SwitchRow { return SwitchRow() { row in row.title = title + " " // Fix offset between UILabel and UISwtich row.value = value }.cellSetup({ cell, row in cell.switchControl.onTintColor = AppTheme.primaryColor cell.textLabel?.numberOfLines = 3 }) } fileprivate func openModuleButton(_ title: String, subtitle: String? = nil, route: SettingsRoutes) -> DescribedButtonRow { return DescribedButtonRow() { row in row.title = title row.subtitle = subtitle }.cellUpdate({ cell, row in cell.textLabel?.textAlignment = .left cell.accessoryType = .disclosureIndicator cell.editingAccessoryType = cell.accessoryType cell.textLabel?.textColor = .black }).onCellSelection({ [unowned self] _,_ in self.openModuleSubject.onNext(route) }) } fileprivate func openModuleButton(_ title: String, subtitle: String? = nil, onTap: (()->Void)? = nil) -> DescribedButtonRow { return DescribedButtonRow() { row in row.title = title row.subtitle = subtitle }.cellUpdate({ cell, row in cell.textLabel?.textAlignment = .left cell.accessoryType = .disclosureIndicator cell.editingAccessoryType = cell.accessoryType cell.textLabel?.textColor = .black }).onCellSelection({ _,_ in onTap?() }) } fileprivate func segmentedRow(_ title: String, options: [String], selected: Int? = nil, selectedOption: String? = nil) -> CustomSegmentedRow { var value = 0 if let intVal = selected { value = intVal } else { if let stringValue = selectedOption { value = options.index(of: stringValue) ?? 0 } } return CustomSegmentedRow() { row in row.title = title row.options = options row.value = value }.cellUpdate({ cell, row in cell.titleLabel?.font = .systemFont(ofSize: 12) }) } fileprivate func decimalRow(_ title: String, float: Float, placeholder: String? = nil) -> DecimalRow { return DecimalRow() { row in row.title = title let value = Double(float) row.value = value <= 0 ? nil : value row.placeholder = placeholder }.cellUpdate({ cell, _ in cell.textField.textColor = AppTheme.primaryColor }).cellSetup({ cell, _ in cell.textLabel?.numberOfLines = 3 }) } fileprivate func decimalRow(_ title: String, dobule: Double, placeholder: String? = nil) -> DecimalRow { return DecimalRow() { row in row.title = title let value = dobule row.value = value <= 0 ? nil : value row.placeholder = placeholder }.cellUpdate({ cell, _ in cell.textField.textColor = AppTheme.primaryColor }).cellSetup({ cell, _ in cell.textLabel?.numberOfLines = 3 }) } }
agpl-3.0
5b89bedcf755d0d89afce0d22ff9f948
44.042796
131
0.605004
4.820611
false
false
false
false
JeremyJacquemont/SchoolProjects
IUT/iOS-Projects/Cocktails/Cocktails/Cocktail.swift
1
527
// // Cocktail.swift // Cocktails // // Created by iem on 05/03/2015. // Copyright (c) 2015 JeremyJacquemont. All rights reserved. // import Foundation func == (lhs : Cocktail , rhs : Cocktail) -> Bool { return lhs.name == rhs.name && lhs.ingredients == rhs.ingredients && lhs.directions == rhs.directions } struct Cocktail : Equatable { static let KEY_NAME = "name" static let KEY_INGREDIENTS = "ingredients" static let KEY_DIRECTIONS = "directions" let name, ingredients, directions : String }
apache-2.0
c5b3e56f6b39acfd8abaa5c54f2d6eea
24.142857
105
0.671727
3.356688
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/Cells/HLHotelDetailsImportantPoiCell.swift
1
1518
class HLHotelDetailsImportantPoiCell: HLHotelDetailsTableCell { private static var cellInstance: HLHotelDetailsImportantPoiCell = { return loadViewFromNibNamed(HLHotelDetailsImportantPoiCell.hl_reuseIdentifier()) as! HLHotelDetailsImportantPoiCell }() @IBOutlet fileprivate(set) weak var iconView: UIImageView! @IBOutlet fileprivate(set) weak var titleLabel: UILabel! @IBOutlet fileprivate(set) weak var distanceLabel: UILabel! @IBOutlet fileprivate weak var topConstraint: NSLayoutConstraint! class func estimatedHeight(_ width: CGFloat, first: Bool, last: Bool) -> CGFloat { let cell = cellInstance let font: UIFont = cell.titleLabel.font! let textWidth = width - 60.0 let string: NSString = "Text" var height = string.hl_height(attributes: [NSAttributedString.Key.font : font], width: textWidth) height += first ? 16.0 : 5.0 height += last ? 20.0 : 7.0 return height } override var first: Bool { didSet { self.topConstraint.constant = self.first ? 16.0 : 5.0 self.setNeedsLayout() self.layoutIfNeeded() } } func setup(_ poi: HDKLocationPoint, variant: HLResultVariant) { self.distanceLabel.text = StringUtils.roundedDistance(withMeters: CGFloat(poi.distanceToHotel)) self.iconView.image = HLPoiIconSelector.listPoiIcon(poi, city: variant.hotel.city) self.titleLabel.text = StringUtils.locationPointName(poi) } }
mit
80ed29118ba50d6c19e0ae7de34e1f17
38.947368
123
0.685771
4.491124
false
false
false
false
brentdax/swift
stdlib/public/SDK/Network/NWPath.swift
4
9682
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation import _SwiftNetworkOverlayShims /// An NWInterface object represents an instance of a network interface of a specific /// type, such as a Wi-Fi or Cellular interface. @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) public struct NWInterface : Hashable, CustomDebugStringConvertible { public var debugDescription: String { return self.name } public static func ==(lhs: NWInterface, rhs: NWInterface) -> Bool { return lhs.index == rhs.index && lhs.name == rhs.name } public func hash(into hasher: inout Hasher) { hasher.combine(self.index) hasher.combine(self.name) } /// Interface types represent the underlying media for a network link public enum InterfaceType { /// A virtual or otherwise unknown interface type case other /// A Wi-Fi link case wifi /// A Cellular link case cellular /// A Wired Ethernet link case wiredEthernet /// The Loopback Interface case loopback internal var nw : nw_interface_type_t { switch self { case .wifi: return Network.nw_interface_type_wifi case .cellular: return Network.nw_interface_type_cellular case .wiredEthernet: return Network.nw_interface_type_wired case .loopback: return Network.nw_interface_type_loopback case .other: return Network.nw_interface_type_other } } internal init(_ nw: nw_interface_type_t) { switch nw { case Network.nw_interface_type_wifi: self = .wifi case Network.nw_interface_type_cellular: self = .cellular case Network.nw_interface_type_wired: self = .wiredEthernet case Network.nw_interface_type_loopback: self = .loopback default: self = .other } } } /// The interface type. public let type: InterfaceType /// The name of the interface, such as "en0" public let name: String /// The kernel index of the interface public let index: Int internal let nw: nw_interface_t internal init(_ nw: nw_interface_t) { self.nw = nw self.type = NWInterface.InterfaceType(nw_interface_get_type(nw)) self.name = String(cString: nw_interface_get_name(nw)) self.index = Int(nw_interface_get_index(nw)) } internal init?(_ index: Int) { guard let nw = nw_interface_create_with_index(UInt32(index)) else { return nil } self.init(nw) } internal init?(_ name: String) { guard let nw = nw_interface_create_with_name(name) else { return nil } self.init(nw) } } /// An NWPath object represents a snapshot of network path state. This state /// represents the known information about the local interface and routes that may /// be used to send and receive data. If the network path for a connection changes /// due to interface characteristics, addresses, or other attributes, a new NWPath /// object will be generated. Note that the differences in the path attributes may not /// be visible through public accessors, and these changes should be treated merely /// as an indication that something about the network has changed. @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) public struct NWPath : Equatable, CustomDebugStringConvertible { public var debugDescription: String { return String(describing: self.nw) } /// An NWPath status indicates if there is a usable route available upon which to send and receive data. public enum Status { /// The path has a usable route upon which to send and receive data case satisfied /// The path does not have a usable route. This may be due to a network interface being down, or due to system policy. case unsatisfied /// The path does not currently have a usable route, but a connection attempt will trigger network attachment. case requiresConnection } public let status: NWPath.Status /// A list of all interfaces currently available to this path public let availableInterfaces: [NWInterface] /// Checks if the path uses an NWInterface that is considered to be expensive /// /// Cellular interfaces are considered expensive. WiFi hotspots from an iOS device are considered expensive. Other /// interfaces may appear as expensive in the future. public let isExpensive : Bool public let supportsIPv4 : Bool public let supportsIPv6 : Bool public let supportsDNS : Bool /// Check the local endpoint set on a path. This will be nil for paths /// from an NWPathMonitor. For paths from an NWConnection, this will /// be set to the local address and port in use by the connection. public let localEndpoint: NWEndpoint? /// Check the remote endpoint set on a path. This will be nil for paths /// from an NWPathMonitor. For paths from an NWConnection, this will /// be set to the remote address and port in use by the connection. public let remoteEndpoint: NWEndpoint? /// Checks if the path uses an NWInterface with the specified type public func usesInterfaceType(_ type: NWInterface.InterfaceType) -> Bool { if let path = self.nw { return nw_path_uses_interface_type(path, type.nw) } return false } internal let nw: nw_path_t? internal init(_ path: nw_path_t?) { var interfaces = [NWInterface]() var local: NWEndpoint? = nil var remote: NWEndpoint? = nil if let path = path { let nwstatus = nw_path_get_status(path) switch (nwstatus) { case Network.nw_path_status_satisfied: self.status = .satisfied case Network.nw_path_status_satisfiable: self.status = .requiresConnection default: self.status = .unsatisfied } self.isExpensive = nw_path_is_expensive(path) self.supportsDNS = nw_path_has_dns(path) self.supportsIPv4 = nw_path_has_ipv4(path) self.supportsIPv6 = nw_path_has_ipv6(path) nw_path_enumerate_interfaces(path, { (interface) in interfaces.append(NWInterface(interface)) return true }) if let nwlocal = nw_path_copy_effective_local_endpoint(path) { local = NWEndpoint(nwlocal) } if let nwremote = nw_path_copy_effective_remote_endpoint(path) { remote = NWEndpoint(nwremote) } } else { self.status = .unsatisfied self.isExpensive = false self.supportsDNS = false self.supportsIPv4 = false self.supportsIPv6 = false } self.availableInterfaces = interfaces self.nw = path self.localEndpoint = local self.remoteEndpoint = remote } public static func ==(lhs: NWPath, rhs: NWPath) -> Bool { if let lnw = lhs.nw, let rnw = rhs.nw { return nw_path_is_equal(lnw, rnw) } return lhs.nw == nil && rhs.nw == nil } } /// The NWPathMonitor allows the caller to fetch the current global path (or /// a path restricted to a specific network interface type). The path for the monitor /// is an observable property that will be updated upon each network change. /// Paths generated by a path monitor are not specific to a given endpoint, and /// will not have the localEndpoint or remoteEndpoint properties set. /// The paths will watch the state of multiple interfaces, and allows the /// application to enumerate the available interfaces for use in creating connections /// or listeners bound to specific interfaces. @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) public final class NWPathMonitor { /// Access the current network path tracked by the monitor public var currentPath = NWPath(nil) fileprivate let nw : nw_path_monitor_t /// Set a block to be called when the network path changes private var _pathUpdateHandler: ((_ newPath: NWPath) -> Void)? public var pathUpdateHandler: ((_ newPath: NWPath) -> Void)? { set { self._pathUpdateHandler = newValue } get { return self._pathUpdateHandler } } /// Start the path monitor and set a queue on which path updates /// will be delivered. /// Start should only be called once on a monitor, and multiple calls to start will /// be ignored. public func start(queue: DispatchQueue) { self._queue = queue nw_path_monitor_set_queue(self.nw, queue) nw_path_monitor_start(self.nw) } /// Cancel the path monitor, after which point no more path updates will /// be delivered. public func cancel() { nw_path_monitor_cancel(self.nw) } private var _queue: DispatchQueue? /// Get queue used for delivering the pathUpdateHandler block. /// If the path monitor has not yet been started, the queue will be nil. Once the /// path monitor has been started, the queue will be valid. public var queue: DispatchQueue? { get { return self._queue } } /// Create a network path monitor to monitor overall network state for the /// system. This allows enumeration of all interfaces that are available for /// general use by the application. public init() { self.nw = nw_path_monitor_create() nw_path_monitor_set_update_handler(self.nw) { (newPath) in self.currentPath = NWPath(newPath) if let handler = self._pathUpdateHandler { handler(self.currentPath) } } } /// Create a network path monitor that watches a single interface type. public init(requiredInterfaceType: NWInterface.InterfaceType) { self.nw = nw_path_monitor_create_with_type(requiredInterfaceType.nw) nw_path_monitor_set_update_handler(self.nw) { (newPath) in self.currentPath = NWPath(newPath) if let handler = self._pathUpdateHandler { handler(self.currentPath) } } } }
apache-2.0
dd2165a7933deb3a87587f8dcf28c51f
31.599327
120
0.709048
3.65083
false
false
false
false
yatatsu/Bluebonnet
Tests/TestAPI.swift
1
3465
// // TestAPI.swift // Bluebonnet // // Created by KITAGAWA Tatsuya on 2015/07/03. // Copyright (c) 2015年 CocoaPods. All rights reserved. // import Foundation import Bluebonnet class TestAPI: Bluebonnet { static let baseURL: NSURL = NSURL(string: "https://api.mock.com")! override class var unexpectedError: NSError? { return NSError(domain: "com.mockapi.error", code: 0, userInfo: nil); } override class func requestValidation<T: BluebonnetRequest>(api: T) -> Validation? { switch api { case _ as GetMockValidation: return { (request: NSURLRequest, response: NSHTTPURLResponse) -> Bool in return response.allHeaderFields["validation"] != nil } default: return nil } } struct GetMockValidation: BluebonnetRequest { typealias Response = ValidatedResponse typealias ErrorResponse = MockError let method: HTTPMethod = .GET let parameters: [String:AnyObject] = [:] let path: String = "/validate" var URLRequest: NSURLRequest { return Bluebonnet.build(baseURL, path: path, method: method, parameters: parameters) } } struct GetMock: BluebonnetRequest { typealias Response = MockResponse typealias ErrorResponse = MockError let method: HTTPMethod = .GET let parameters: [String:AnyObject] = [:] let path: String = "/mock" var URLRequest: NSURLRequest { return Bluebonnet.build(baseURL, path: path, method: method, parameters: parameters) } } struct GetParam: BluebonnetRequest { typealias Response = MockResponse typealias ErrorResponse = MockError let method: HTTPMethod = .GET let path: String = "/param" let name: String var parameters: [String:AnyObject] { return ["name":name] } init(name: String) { self.name = name } var URLRequest: NSURLRequest { return Bluebonnet.build(baseURL, path: path, method: method, parameters: parameters) } } } class MockResponse: DataConvertable { let name: String? init?(data: AnyObject) { self.name = data["name"] as? String if self.name == nil { return nil } } static func convert(response: NSHTTPURLResponse, data: AnyObject) -> MockResponse? { return MockResponse(data: data) } } class MockError: DataConvertable { let message: String? let response: NSHTTPURLResponse init(data: AnyObject, response: NSHTTPURLResponse) { self.message = data["message"] as? String self.response = response } static func convert(response: NSHTTPURLResponse, data: AnyObject) -> MockError? { return MockError(data: data, response: response) } } class ValidatedResponse: DataConvertable { let validated: AnyObject? let name: String? init?(response: NSHTTPURLResponse, data: AnyObject) { self.validated = response.allHeaderFields["validation"] self.name = data["name"] as? String if self.name == nil { return nil } } static func convert(response: NSHTTPURLResponse, data: AnyObject) -> ValidatedResponse? { return ValidatedResponse(response: response, data: data) } }
mit
f94966bf13459eceb0897863c31b7269
28.10084
96
0.610742
4.705163
false
false
false
false
petrone/PetroneAPI_swift
PetroneAPI/Packets/PetronePacketModeChange.swift
1
1095
// // PetronePacketModeChange.swift // Petrone // // Created by Byrobot on 2017. 8. 7.. // Copyright © 2017년 Byrobot. All rights reserved. // import Foundation class PetronePacketModeChange : PetronePacketLedCommand { public var mode:PetroneMode = PetroneMode.None override init() { super.init() lightMode = PetroneLigthMode.ArmFlicker interval = 100 repeatCount = 2 command = PetroneCommand.ModePetrone } override func getBluetoothData() -> Data { if mode.rawValue < PetroneMode.Drive.rawValue { lightColor = PetroneColors.Red } else { lightColor = PetroneColors.Blue } self.option = mode.rawValue return super.getBluetoothData() } override func getSerialData() -> Data { if mode.rawValue < PetroneMode.Drive.rawValue { lightColor = PetroneColors.Red } else { lightColor = PetroneColors.Blue } self.option = mode.rawValue return super.getSerialData() } }
mit
9045b9ccd75a7a84a94c5a38de526f6b
23.818182
57
0.604396
4.333333
false
false
false
false
kzaher/RxSwift
Tests/RxSwiftTests/Observable+JustTests.swift
6
2584
// // Observable+JustTests.swift // Tests // // Created by Krunoslav Zaher on 4/29/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import XCTest import RxSwift import RxTest class ObservableJustTest : RxTest { } extension ObservableJustTest { func testJust_Immediate() { let scheduler = TestScheduler(initialClock: 0) let res = scheduler.start { return Observable.just(42) } XCTAssertEqual(res.events, [ .next(200, 42), .completed(200) ]) } func testJust_Basic() { let scheduler = TestScheduler(initialClock: 0) let res = scheduler.start { return Observable.just(42, scheduler: scheduler) } XCTAssertEqual(res.events, [ .next(201, 42), .completed(202) ]) } func testJust_Disposed() { let scheduler = TestScheduler(initialClock: 0) let res = scheduler.start(disposed: 200) { return Observable.just(42, scheduler: scheduler) } XCTAssertEqual(res.events, [ ]) } func testJust_DisposeAfterNext() { let scheduler = TestScheduler(initialClock: 0) let d = SingleAssignmentDisposable() let res = scheduler.createObserver(Int.self) scheduler.scheduleAt(100) { let subscription = Observable.just(42, scheduler: scheduler).subscribe { e in res.on(e) switch e { case .next: d.dispose() default: break } } d.setDisposable(subscription) } scheduler.start() XCTAssertEqual(res.events, [ .next(101, 42) ]) } func testJust_DefaultScheduler() { let res = try! Observable.just(42, scheduler: MainScheduler.instance) .toBlocking() .toArray() XCTAssertEqual(res, [ 42 ]) } func testJust_CompilesInMap() { _ = (1 as Int?).map(Observable.just) } #if TRACE_RESOURCES func testJustReleasesResourcesOnComplete() { _ = Observable<Int>.just(1).subscribe() } #endif #if TRACE_RESOURCES func testJustSchdedulerReleasesResourcesOnComplete() { let testScheduler = TestScheduler(initialClock: 0) _ = Observable<Int>.just(1, scheduler: testScheduler).subscribe() testScheduler.start() } #endif }
mit
8f88fde88be213cd1b9dd2b434a5444c
22.481818
89
0.547038
4.722121
false
true
false
false
Mistin7/Maze-man
Maze-man/SKTAudio.swift
1
3375
/* * Copyright (c) 2013-2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import AVFoundation /** * Audio player that uses AVFoundation to play looping background music and * short sound effects. For when using SKActions just isn't good enough. */ public class SKTAudio { public var backgroundMusicPlayer: AVAudioPlayer? public var soundEffectPlayer: AVAudioPlayer? public class func sharedInstance() -> SKTAudio { return SKTAudioInstance } public func playBackgroundMusic(filename: String) { let url = Bundle.main.url(forResource: filename, withExtension: nil) if (url == nil) { print("Could not find file: \(filename)") return } var error: NSError? = nil do { backgroundMusicPlayer = try AVAudioPlayer(contentsOf: url!) } catch let error1 as NSError { error = error1 backgroundMusicPlayer = nil } if let player = backgroundMusicPlayer { player.numberOfLoops = -1 player.prepareToPlay() player.play() } else { print("Could not create audio player: \(error!)") } } public func pauseBackgroundMusic() { if let player = backgroundMusicPlayer { if player.isPlaying { player.pause() } } } public func resumeBackgroundMusic() { if let player = backgroundMusicPlayer { if !player.isPlaying { player.play() } } } public func playSoundEffect(filename: String) { let url = Bundle.main.url(forResource: filename, withExtension: nil) if (url == nil) { print("Could not find file: \(filename)") return } var error: NSError? = nil do { soundEffectPlayer = try AVAudioPlayer(contentsOf: url!) } catch let error1 as NSError { error = error1 soundEffectPlayer = nil } if let player = soundEffectPlayer { player.numberOfLoops = 0 player.prepareToPlay() player.play() } else { print("Could not create audio player: \(error!)") } } } private let SKTAudioInstance = SKTAudio()
apache-2.0
20170517dbe76fbe617a2d9c09e31e4c
32.75
79
0.62963
5.022321
false
false
false
false
lorentey/swift
test/Sema/diag_ambiguous_overloads.swift
3
4139
// RUN: %target-typecheck-verify-swift enum E : String { case foo = "foo" case bar = "bar" // expected-note {{'bar' declared here}} } func fe(_: E) {} func fe(_: Int) {} func fe(_: Int, _: E) {} func fe(_: Int, _: Int) {} fe(E.baz) // expected-error {{type 'E' has no member 'baz'; did you mean 'bar'?}} fe(.baz) // expected-error {{reference to member 'baz' cannot be resolved without a contextual type}} // FIXME: maybe complain about .nope also? fe(.nope, .nyet) // expected-error {{reference to member 'nyet' cannot be resolved without a contextual type}} func fg<T>(_ f: (T) -> T) -> Void {} // expected-note {{in call to function 'fg'}} fg({x in x}) // expected-error {{generic parameter 'T' could not be inferred}} struct S { func f<T>(_ i: (T) -> T, _ j: Int) -> Void {} // expected-note {{in call to function 'f'}} func f(_ d: (Double) -> Double) -> Void {} func test() -> Void { f({x in x}, 2) // expected-error {{generic parameter 'T' could not be inferred}} } func g<T>(_ a: T, _ b: Int) -> Void {} func g(_ a: String) -> Void {} func test2() -> Void { g(.notAThing, 7) // expected-error {{cannot infer contextual base in reference to member 'notAThing'}} } func h(_ a: Int, _ b: Int) -> Void {} func h(_ a: String) -> Void {} func test3() -> Void { h(.notAThing, 3) // expected-error {{type 'Int' has no member 'notAThing'}} h(.notAThing) // expected-error {{type 'String' has no member 'notAThing'}} } } class DefaultValue { static func foo(_ a: Int) {} static func foo(_ a: Int, _ b: Int = 1) {} static func foo(_ a: Int, _ b: Int = 1, _ c: Int = 2) {} } DefaultValue.foo(1.0, 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} class Variadic { static func foo(_ a: Int) {} static func foo(_ a: Int, _ b: Double...) {} } Variadic.foo(1.0, 2.0, 3.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} //=-------------- SR-7918 --------------=/ class sr7918_Suit { static func foo<T: Any>(_ :inout T) {} static func foo() {} } class sr7918_RandomNumberGenerator {} let myRNG = sr7918_RandomNumberGenerator() // expected-note {{change 'let' to 'var' to make it mutable}} _ = sr7918_Suit.foo(&myRNG) // expected-error {{cannot pass immutable value as inout argument: 'myRNG' is a 'let' constant}} //=-------------- SR-7786 --------------=/ struct sr7786 { func foo() -> UInt { return 0 } func foo<T: UnsignedInteger>(bar: T) -> T { // expected-note {{where 'T' = 'Int'}} return bar } } let s = sr7786() let a = s.foo() let b = s.foo(bar: 123) // expected-error {{instance method 'foo(bar:)' requires that 'Int' conform to 'UnsignedInteger'}} let c: UInt = s.foo(bar: 123) let d = s.foo(bar: 123 as UInt) //=-------------- SR-7440 --------------=/ struct sr7440_ITunesGenre { let genre: Int // expected-note {{'genre' declared here}} let name: String } class sr7440_Genre { static func fetch<B: BinaryInteger>(genreID: B, name: String) {} static func fetch(_ iTunesGenre: sr7440_ITunesGenre) -> sr7440_Genre { return sr7440_Genre.fetch(genreID: iTunesGenre.genreID, name: iTunesGenre.name) // expected-error@-1 {{value of type 'sr7440_ITunesGenre' has no member 'genreID'; did you mean 'genre'?}} // expected-error@-2 {{cannot convert return expression of type '()' to return type 'sr7440_Genre'}} } } //=-------------- SR-5154 --------------=/ protocol sr5154_Scheduler { func inBackground(run task: @escaping () -> Void) } extension sr5154_Scheduler { func inBackground(run task: @escaping () -> [Count], completedBy resultHandler: @escaping ([Count]) -> Void) {} } struct Count { // expected-note {{'init(title:)' declared here}} let title: String } func getCounts(_ scheduler: sr5154_Scheduler, _ handler: @escaping ([Count]) -> Void) { scheduler.inBackground(run: { return [Count()] // expected-error {{missing argument for parameter 'title' in call}} }, completedBy: { // expected-error {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{20-20= _ in}} }) }
apache-2.0
d61acc8fdd6f1b676015eeddbebf4073
33.491667
154
0.62044
3.340597
false
false
false
false
yzyzsun/CurriculaTable
CurriculaTable/CurriculaTable.swift
1
6656
// // CurriculaTable.swift // CurriculaTable // // Created by Sun Yaozhu on 2016-09-10. // Copyright © 2016 Sun Yaozhu. All rights reserved. // import UIKit public class CurriculaTable: UIView { private let controller = CurriculaTableController() private let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout()) public var weekdaySymbolType = CurriculaTableWeekdaySymbolType.short { didSet { collectionView.reloadData() } } public var firstWeekday = CurriculaTableWeekday.monday { didSet { collectionView.reloadData() drawCurricula() } } public var numberOfPeriods = 13 { didSet { collectionView.reloadData() drawCurricula() } } public var curricula = [CurriculaTableItem]() { didSet { drawCurricula() } } public var bgColor = UIColor.clear { didSet { collectionView.backgroundColor = bgColor } } public var symbolsBgColor = UIColor.clear { didSet { collectionView.reloadData() } } public var symbolsFontSize = CGFloat(14) { didSet { collectionView.reloadData() } } public var heightOfWeekdaySymbols = CGFloat(28) { didSet { collectionView.reloadData() drawCurricula() } } public var widthOfPeriodSymbols = CGFloat(32) { didSet { collectionView.reloadData() drawCurricula() } } public var borderWidth = CGFloat(0) { didSet { collectionView.reloadData() } } public var borderColor = UIColor.clear { didSet { collectionView.reloadData() } } public var cornerRadius = CGFloat(0) { didSet { drawCurricula() } } public var rectEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) { didSet { drawCurricula() } } public var textEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) { didSet { drawCurricula() } } public var textFontSize = CGFloat(11) { didSet { drawCurricula() } } public var textAlignment = NSTextAlignment.center { didSet { drawCurricula() } } public var maximumNameLength = 0 { didSet { drawCurricula() } } var weekdaySymbols: [String] { var weekdaySymbols = [String]() switch weekdaySymbolType { case .normal: weekdaySymbols = Calendar.current.standaloneWeekdaySymbols case .short: weekdaySymbols = Calendar.current.shortStandaloneWeekdaySymbols case .veryShort: weekdaySymbols = Calendar.current.veryShortStandaloneWeekdaySymbols } let firstWeekdayIndex = firstWeekday.rawValue - 1 weekdaySymbols.rotate(shiftingToStart: firstWeekdayIndex) return weekdaySymbols } var averageHeight: CGFloat { return (collectionView.frame.height - heightOfWeekdaySymbols) / CGFloat(numberOfPeriods) } var averageWidth: CGFloat { return (collectionView.frame.width - widthOfPeriodSymbols) / 7 - 0.1 } public override init(frame: CGRect) { super.init(frame: frame) initialize() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { controller.curriculaTable = self controller.collectionView = collectionView collectionView.dataSource = controller collectionView.delegate = controller collectionView.backgroundColor = bgColor addSubview(collectionView) } public override func layoutSubviews() { super.layoutSubviews() collectionView.frame = bounds collectionView.reloadData() drawCurricula() } private func drawCurricula() { for subview in subviews { if !(subview is UICollectionView) { subview.removeFromSuperview() } } for (index, curriculum) in curricula.enumerated() { let weekdayIndex = (curriculum.weekday.rawValue - firstWeekday.rawValue + 7) % 7 let x = widthOfPeriodSymbols + averageWidth * CGFloat(weekdayIndex) + rectEdgeInsets.left let y = heightOfWeekdaySymbols + averageHeight * CGFloat(curriculum.startPeriod - 1) + rectEdgeInsets.top let width = averageWidth - rectEdgeInsets.left - rectEdgeInsets.right let height = averageHeight * CGFloat(curriculum.endPeriod - curriculum.startPeriod + 1) - rectEdgeInsets.top - rectEdgeInsets.bottom let view = UIView(frame: CGRect(x: x, y: y, width: width, height: height)) view.backgroundColor = curriculum.bgColor view.layer.cornerRadius = cornerRadius view.layer.masksToBounds = true let label = UILabel(frame: CGRect(x: textEdgeInsets.left, y: textEdgeInsets.top, width: view.frame.width - textEdgeInsets.left - textEdgeInsets.right, height: view.frame.height - textEdgeInsets.top - textEdgeInsets.bottom)) var name = curriculum.name if maximumNameLength > 0 { name.truncate(maximumNameLength) } let attrStr = NSMutableAttributedString(string: name + "\n\n" + curriculum.place, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: textFontSize)]) attrStr.setAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: textFontSize)], range: NSRange(0..<name.count)) label.attributedText = attrStr label.textColor = curriculum.textColor label.textAlignment = textAlignment label.numberOfLines = 0 label.tag = index label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(curriculumTapped))) label.isUserInteractionEnabled = true view.addSubview(label) addSubview(view) } } @objc func curriculumTapped(_ sender: UITapGestureRecognizer) { let curriculum = curricula[(sender.view as! UILabel).tag] curriculum.tapHandler(curriculum) } }
mit
d805f67d9f0bd16cc32569f46b972f83
29.668203
235
0.600451
4.966418
false
false
false
false
zats/Tribute
Tribute.playground/Contents.swift
1
1962
//: Playground - noun: a place where people can play import Tribute import XCPlayground let string = NSMutableAttributedString() .add("Tribute is a ") { $0.font = .systemFontOfSize(15) $0.color = #colorLiteral(red: 0.8504372835, green: 0.2181603462, blue: 0.1592026055, alpha: 1) } .add("micro") { $0.obliqueness = 0.2 $0.underline = .StyleSingle $0.color = #colorLiteral(red: 0.7608990073, green: 0.2564961016, blue: 0, alpha: 1) }.add(" library") { $0.underline = nil $0.color = #colorLiteral(red: 0.8526210189, green: 0.4221832156, blue: 0, alpha: 1) }.add(" for ") { $0.obliqueness = nil $0.color = #colorLiteral(red: 0.9767052531, green: 0.605463922, blue: 0, alpha: 1) } .add(#imageLiteral(resourceName: "[email protected]"), bounds: CGRect(x: 0, y: -8, width: 30, height: 30)) .add("\nIt simplifies"){ $0.reset() $0.color = #colorLiteral(red: 0.5948907137, green: 0.7498663664, blue: 0, alpha: 1) $0.alignment = .Center } .add(" ") .add(" the way you work with") { $0.font = .systemFontOfSize(10) $0.URL = NSURL(string: "http://google.com")! }.add("\nNSAttributedStrings") { $0.URL = nil $0.font = UIFont(name: "Courier", size: 14) $0.color = #colorLiteral(red: 0.1819814891, green: 0.6942673326, blue: 0.5302479267, alpha: 1) $0.textEffect = .Letterpress } string let s = NSMutableAttributedString().add("Hello "){ $0.font = .boldSystemFontOfSize(12) return }.add("World") { $0.bold = false $0.italic = true return } s let page = XCPlaygroundPage.currentPage page.needsIndefiniteExecution = true let label = UILabel() label.attributedText = s label.numberOfLines = 0 label.sizeToFit() label.backgroundColor = #colorLiteral(red: 0.9607843136999999, green: 0.9607843136999999, blue: 0.9607843136999999, alpha: 1) page.liveView = label
mit
77fe75e67adfb93d86319118dfab223e
30.142857
125
0.623344
3.205882
false
false
false
false
AppriaTT/Swift_SelfLearning
Swift/swift05 roll view/swift05 roll view/ViewController.swift
1
2919
// // ViewController.swift // swift05 roll view // // Created by Aaron on 16/7/8. // Copyright © 2016年 Aaron. All rights reserved. // import UIKit class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate { var interests : [Interest]! override func viewDidLoad() { super.viewDidLoad() //创建模糊层 let bgView = UIImageView(image: UIImage(named: "blue")) bgView.frame = self.view.bounds self.view.addSubview(bgView) let effectView = UIVisualEffectView(frame: self.view.bounds) effectView.effect = UIBlurEffect(style: UIBlurEffectStyle.Light) self.view.addSubview(effectView) //创建collectionView let layout = UICollectionViewFlowLayout() layout.itemSize = CGSizeMake(300, 400) layout.scrollDirection = UICollectionViewScrollDirection.Horizontal let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = UIColor.clearColor() self.view.addSubview(collectionView) collectionView.registerClass(ZHCollectionViewCell().classForCoder, forCellWithReuseIdentifier: "cell") // 数据源创建 interests = [ Interest(title: "Hello there, i miss u.", featuredImage: UIImage(named: "hello")!), Interest(title: "🐳🐳🐳🐳🐳",featuredImage: UIImage(named: "dudu")!), Interest(title: "Training like this, #bodyline", featuredImage: UIImage(named: "bodyline")!), Interest(title: "I'm hungry, indeed.", featuredImage: UIImage(named: "wave")!), Interest(title: "Dark Varder, #emoji", featuredImage: UIImage(named: "darkvarder")!), Interest(title: "I have no idea, bitch", featuredImage: UIImage(named: "hhhhh")!),] collectionView .reloadData() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int{ return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return interests.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! ZHCollectionViewCell let interest = interests[indexPath.row] print(interest.title) cell.interest = interest return cell } }
mit
28546e168d2615926c2b7b0f85f00709
39.521127
130
0.672923
5.17446
false
false
false
false
benlangmuir/swift
test/Constraints/associated_types.swift
4
2955
// RUN: %target-typecheck-verify-swift protocol Runcible { associatedtype Runcee } class Mince { init() {} } class Spoon : Runcible { init() {} typealias Runcee = Mince } class Owl<T:Runcible> { init() {} func eat(_ what: T.Runcee, with: T) { } } func owl1() -> Owl<Spoon> { return Owl<Spoon>() } func owl2() -> Owl<Spoon> { return Owl() } func owl3() { Owl<Spoon>().eat(Mince(), with:Spoon()) } // https://github.com/apple/swift/issues/43341 // Can't access associated types through class-constrained generic parameters func spoon<S: Spoon>(_ s: S) { let _: S.Runcee? } // https://github.com/apple/swift/issues/46726 protocol SameTypedDefault { associatedtype X associatedtype Y static var x: X { get } static var y: Y { get } } extension SameTypedDefault where Y == X { static var x: X { return y } } struct UsesSameTypedDefault: SameTypedDefault { static var y: Int { return 0 } } protocol XReqt {} protocol YReqt {} protocol SameTypedDefaultWithReqts { associatedtype X: XReqt // expected-note{{protocol requires nested type 'X'; do you want to add it?}} associatedtype Y: YReqt // expected-note{{protocol requires nested type 'Y'; do you want to add it?}} static var x: X { get } static var y: Y { get } } extension SameTypedDefaultWithReqts where Y == X { static var x: X { return y } } struct XYType: XReqt, YReqt {} struct YType: YReqt {} struct UsesSameTypedDefaultWithReqts: SameTypedDefaultWithReqts { static var y: XYType { return XYType() } } // expected-error@+1{{does not conform}} struct UsesSameTypedDefaultWithoutSatisfyingReqts: SameTypedDefaultWithReqts { static var y: YType { return YType() } } protocol SameTypedDefaultBaseWithReqts { associatedtype X: XReqt // expected-note{{protocol requires nested type 'X'; do you want to add it?}} static var x: X { get } } protocol SameTypedDefaultDerivedWithReqts: SameTypedDefaultBaseWithReqts { associatedtype Y: YReqt static var y: Y { get } } extension SameTypedDefaultDerivedWithReqts where Y == X { static var x: X { return y } } struct UsesSameTypedDefaultDerivedWithReqts: SameTypedDefaultDerivedWithReqts { static var y: XYType { return XYType() } } // expected-error@+1{{does not conform}} struct UsesSameTypedDefaultDerivedWithoutSatisfyingReqts: SameTypedDefaultDerivedWithReqts { static var y: YType { return YType() } } // https://github.com/apple/swift/issues/54624 protocol P1_54624 { associatedtype Assoc // expected-note {{'Assoc' declared here}} } enum E_54624 {} protocol P2_54624: P1_54624 where Assoc == E_54624 { associatedtype Assoc: E_54624 // expected-error {{type 'Self.Assoc' constrained to non-protocol, non-class type 'E_54624'}} // expected-warning@-1 {{redeclaration of associated type 'Assoc' from protocol 'P1_54624' is better expressed as a 'where' clause on the protocol}} }
apache-2.0
b3f9378cf12210cbb38500932a86d74e
23.02439
150
0.693063
3.45614
false
false
false
false
jasonwedepohl/udacity-ios-on-the-map
On The Map/On The Map/Constants.swift
1
700
// // WebMethod.swift // On The Map // // Created by Jason Wedepohl on 2017/09/19. // // import Foundation struct WebMethod { static let get = "GET"; static let post = "POST"; static let delete = "DELETE"; static let put = "PUT" } struct RequestKey { static let accept = "Accept"; static let contentType = "Content-Type"; static let xxsrfToken = "X-XSRF-TOKEN"; } struct RequestValue { static let jsonType = "application/json"; } struct Cookie { static let xsrfToken = "XSRF-TOKEN"; } struct DisplayError { static let unexpected = "An unexpected error occurred." static let network = "Could not connect to the Internet." static let credentials = "Incorrect email or password." }
mit
9e7d4b4ec8094ab6a31c14e2614de283
18.444444
58
0.698571
3.181818
false
false
false
false
ioscreator/ioscreator
IOSCollisionDetectionTutorial/IOSCollisionDetectionTutorial/ViewController.swift
1
3616
// // ViewController.swift // IOSCollisionDetectionTutorial // // Created by Arthur Knopper on 18/02/2019. // Copyright © 2019 Arthur Knopper. All rights reserved. // import UIKit class ViewController: UIViewController { var squareViews:[UIView] = [] var animator:UIDynamicAnimator! var colors:[UIColor] = [] var centerPoint:[CGPoint] = [] var sizeOfSquare:CGSize! var leftBoundaryHeight:CGFloat! var middleBoundaryHeight:CGFloat! var rightBoundaryHeight:CGFloat! var leftBoundaryWidth:CGFloat! var middleBoundaryWidth:CGFloat! var leftSquareCenterPointX:CGFloat! var middleSquareCenterPointX:CGFloat! var rightSquareCenterPointX:CGFloat! var squareCenterPointY:CGFloat! @IBAction func releaseSquare(_ sender: Any) { let newView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: sizeOfSquare.width, height: sizeOfSquare.height)) let randomColorIndex = Int(arc4random()%5) newView.backgroundColor = colors[randomColorIndex] let randomCenterPoint = Int(arc4random()%3) newView.center = centerPoint[randomCenterPoint] squareViews.append(newView) view.addSubview(newView) animator = UIDynamicAnimator(referenceView: view) // create gravity let gravity = UIGravityBehavior(items: squareViews) animator.addBehavior(gravity) // create collision detection let collision = UICollisionBehavior(items: squareViews) // set collision boundaries collision.addBoundary(withIdentifier: "leftBoundary" as NSCopying, from: CGPoint(x: 0.0,y: leftBoundaryHeight), to: CGPoint(x: leftBoundaryWidth, y: leftBoundaryHeight)) collision.addBoundary(withIdentifier: "middleBoundary" as NSCopying, from: CGPoint(x: view.bounds.size.width/3,y: middleBoundaryHeight), to: CGPoint(x: middleBoundaryWidth, y: middleBoundaryHeight)) collision.addBoundary(withIdentifier: "rightBoundary" as NSCopying, from: CGPoint(x: middleBoundaryWidth,y: rightBoundaryHeight), to: CGPoint(x: view.bounds.size.width, y: rightBoundaryHeight)) collision.collisionMode = .everything animator.addBehavior(collision) } override func viewDidLoad() { super.viewDidLoad() setBoundaryValues() // Create the colors array colors = [UIColor.red, UIColor.blue, UIColor.green, UIColor.purple, UIColor.gray] // Create the centerpoint of our squares let leftCenterPoint = CGPoint(x: leftSquareCenterPointX, y: squareCenterPointY) let middleCenterPoint = CGPoint(x: middleSquareCenterPointX, y: squareCenterPointY) let rightCenterPoint = CGPoint(x:rightSquareCenterPointX, y: squareCenterPointY) centerPoint = [leftCenterPoint,middleCenterPoint,rightCenterPoint] // set the size of our squares sizeOfSquare = CGSize(width: 50.0, height: 50.0) } func setBoundaryValues() { leftBoundaryHeight = view.bounds.size.height - 100.0 middleBoundaryHeight = view.bounds.size.height - 150.0 rightBoundaryHeight = view.bounds.size.height - 100.0 leftBoundaryWidth = view.bounds.size.width/3 middleBoundaryWidth = view.bounds.size.width * 0.67 leftSquareCenterPointX = view.bounds.size.width/6 middleSquareCenterPointX = view.bounds.size.width/2 rightSquareCenterPointX = view.bounds.size.width * 0.84 squareCenterPointY = view.bounds.size.height - 400 } }
mit
3918520c9fe2b5c98de97555657a973c
38.293478
206
0.686584
4.490683
false
false
false
false
Frainbow/ShaRead.frb-swift
ShaRead/ShaRead/MailViewController.swift
1
5767
// // MailViewController.swift // ShaRead // // Created by martin on 2016/5/4. // Copyright © 2016年 Frainbow. All rights reserved. // import UIKit import Firebase class MailViewController: UIViewController { @IBOutlet weak var userTableView: UITableView! var users: [ShaUser] = [] var uid: String? var authHandler: FIRAuthStateDidChangeListenerHandle? deinit { if let authHandler = authHandler { FIRAuth.auth()?.removeAuthStateDidChangeListener(authHandler) self.uid = nil } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. initFirebase() } override func viewWillAppear(animated: Bool) { // deselect row on appear if let indexPath = userTableView.indexPathForSelectedRow { userTableView.deselectRowAtIndexPath(indexPath, animated: false) } } override func viewDidAppear(animated: Bool) { setTabBarVisible(true, animated: false) } override func viewWillDisappear(animated: Bool) { setTabBarVisible(false, animated: false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Custom method func initFirebase() { self.authHandler = FIRAuth.auth()?.addAuthStateDidChangeListener({ (auth, user) in if let user = user { self.uid = user.uid self.getRoomList() } else { // redirect to login page self.uid = nil } }) } func getRoomList() { guard let currentUID = self.uid else { return } let rootRef = FIRDatabase.database().reference() rootRef .child("rooms") .queryOrderedByChild("uid") .queryEqualToValue("\(currentUID)") .observeEventType(.ChildAdded, withBlock: { snapshot in let instance = ShaManager.sharedInstance let dic = snapshot.value as! NSDictionary let key = dic["key"] as! String let uid = key.componentsSeparatedByString(" - ")[0] if instance.users[uid] == nil { instance.getUserByUid(uid, success: { self.users.append(instance.users[uid]!) self.userTableView.reloadData() }, failure: { } ) } else { self.users.append(instance.users[uid]!) self.userTableView.reloadData() } }) } // MARK: - TabBar func setTabBarVisible(visible:Bool, animated:Bool) { //* This cannot be called before viewDidLayoutSubviews(), because the frame is not set before this time // bail if the current state matches the desired state if (tabBarIsVisible() == visible) { return } // get a frame calculation ready let frame = self.tabBarController?.tabBar.frame let height = frame?.size.height let offsetY = (visible ? -height! : height) // zero duration means no animation let duration:NSTimeInterval = (animated ? 0.3 : 0.0) // animate the tabBar if frame != nil { UIView.animateWithDuration(duration) { self.tabBarController?.tabBar.frame = CGRectOffset(frame!, 0, offsetY!) return } } } func tabBarIsVisible() ->Bool { return self.tabBarController?.tabBar.frame.origin.y < CGRectGetMaxY(self.view.frame) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension MailViewController: UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return users.count > 0 ? users.count : 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("userCell", forIndexPath: indexPath) as! MailTableViewCell if users.count == 0 { cell.nameLabel.text = "系統管理員:無信件" return cell } cell.avatarImageView.image = nil cell.nameLabel.text = users[indexPath.row].name if let url = NSURL(string: users[indexPath.row].avatar) { cell.avatarImageView.sd_setImageWithURL(url, placeholderImage: ShaDefault.defaultAvatar) } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if users.count == 0 { tableView.deselectRowAtIndexPath(indexPath, animated: true) return } if let controller = self.storyboard?.instantiateViewControllerWithIdentifier("MessageController") as? MessageTableViewController { controller.isAdmin = false controller.targetUser = users[indexPath.row] self.navigationController?.pushViewController(controller, animated: true) } } }
mit
7e41cff33a21951b24845317dbf6c5e0
29.727273
138
0.588757
5.286109
false
false
false
false
xwu/swift
test/Concurrency/Runtime/effectful_properties.swift
1
3132
// RUN: %target-run-simple-swift(-parse-as-library %import-libdispatch) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime enum GeneralError : Error { case UnknownBallKind case Todo } enum BallKind { case MostLostV1 case Chromehard case PT5 case KirksandLignature } @available(SwiftStdlib 5.5, *) class Specs { // obtains the number of dimples subscript(_ bk : BallKind) -> Int { get throws { switch (bk) { case .MostLostV1: return 450 case .Chromehard: return 125 default: throw GeneralError.UnknownBallKind } } } } @available(SwiftStdlib 5.5, *) actor Database { var currentData : Specs { get async { let handle = detach { Specs() } print("obtaining specs...") return await handle.get() } } var hasNewData : Bool { get throws { return true } } } @available(SwiftStdlib 5.5, *) protocol SphericalObject { var name : String { get async throws } var dimples : Int { get async throws } var description : String { get async throws } } @available(SwiftStdlib 5.5, *) class Ball : SphericalObject { var name : String { get async throws { throw GeneralError.Todo } } var dimples : Int { get async throws { throw GeneralError.Todo } } var description : String { get async throws { throw GeneralError.Todo } } } @available(SwiftStdlib 5.5, *) class GolfBall : Ball { private static let db : Database = Database() private var _model : BallKind private var _dimples : Int? init(_ bk : BallKind) { _model = bk } override var name : String { return "golf ball" } override var description : String { get async throws { return "this \(name) has \(await dimples) dimples" } } override var dimples : Int { get async { let newData = (try? await GolfBall.db.hasNewData) ?? false if newData || _dimples == nil { let specs = await GolfBall.db.currentData _dimples = (try? specs[_model]) ?? 0 } return _dimples! } } } // CHECK: obtaining specs... // CHECK: this golf ball has 450 dimples // CHECK: obtaining specs... // CHECK: this golf ball has 125 dimples // CHECK: obtaining specs... // CHECK: this golf ball has 0 dimples // CHECK: obtaining specs... // CHECK: this golf ball has 0 dimples @available(SwiftStdlib 5.5, *) func printAsBall(_ b : Ball) async { print(try! await b.description) } @available(SwiftStdlib 5.5, *) func printAsAsSphericalObject(_ b : SphericalObject) async { print(try! await b.description) } @available(SwiftStdlib 5.5, *) @main struct RunIt { static func main() async { let balls : [(Bool, Ball)] = [ (true, GolfBall(.MostLostV1)), (false, GolfBall(.Chromehard)), (true, GolfBall(.PT5)), (false, GolfBall(.KirksandLignature)) ] for (useProtocol, ball) in balls { if (useProtocol) { await printAsAsSphericalObject(ball) } else { await printAsBall(ball) } } } }
apache-2.0
bbf7a7cff49c59c60efc54f0817c7a78
21.371429
87
0.639847
3.750898
false
false
false
false
bradleybernard/EjectBar
EjectBar/Extensions/NSWindow+.swift
1
2355
// // NSWindow+.swift // EjectBar // // Created by Bradley Bernard on 10/28/20. // Copyright © 2020 Bradley Bernard. All rights reserved. // import Foundation import AppKit extension NSWindow { private static let fadeDuration = 0.35 // Based on the window's: NSWindow.StyleMask // https://developer.apple.com/documentation/appkit/nswindow/stylemask private static let leftRightPadding: CGFloat = 2 private func makeActiveWindow() { makeKeyAndOrderFront(self) NSApp.activate(ignoringOtherApps: true) } func fadeIn(completion: (() -> Void)? = nil) { guard !isMainWindow else { makeActiveWindow() return } guard !isVisible else { makeActiveWindow() completion?() return } alphaValue = 0 makeActiveWindow() NSAnimationContext.runAnimationGroup { [weak self] context in context.duration = Self.fadeDuration self?.animator().alphaValue = 1 } completionHandler: { [weak self] in self?.makeActiveWindow() completion?() } } func fadeOut(completion: (() -> Void)? = nil) { NSAnimationContext.runAnimationGroup { [weak self] context in context.duration = Self.fadeDuration self?.animator().alphaValue = 0 } completionHandler: { [weak self] in guard let self = self else { return } self.contentViewController?.view.window?.orderOut(self) self.alphaValue = 1 completion?() } } func resizeToFitTableView(tableView: NSTableView?) { guard let tableView = tableView else { return } let widthDifference = frame.size.width - tableView.frame.size.width // A window with a tableView has a 1 pixel line on left and 1 pixel line on right, // so we don't want to shrink the window by 2 pixels each time we redraw the tableView. // If the difference in width's is 2, we don't change the frame guard widthDifference != Self.leftRightPadding else { return } var windowFrame = frame windowFrame.size.width = tableView.frame.size.width setFrame(windowFrame, display: true) } }
mit
8e69eb572057d40f67a2fc5897372fce
26.694118
95
0.598131
4.893971
false
false
false
false
damizhou/Leetcode
LeetCode/LeetCode/Easy/NimGame_292.swift
1
2594
// // Day5_NimGame_292.swift // LeetCode // // Created by 潘传洲 on 16/10/25. // Copyright © 2016年 pcz. All rights reserved. // import Foundation class NimGame_292: NSObject { /* ##题目描述: - You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. - Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. - For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. - Hint: - If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner? ##题目大意: - 你正在和朋友玩下面的Nim游戏:桌子上有一堆石头,每一次你们轮流取1至3颗石头。最后一个取走石头的人就是赢家。第一轮由你先取。 - 你们俩都很聪明并且掌握玩游戏的最佳策略。编写函数,给定石头的个数,判断你是否可以赢得游戏。 - 例如,如果堆中有4颗石头,那么你一定不会赢得游戏:无论你第一轮取走1,2,还是3颗石头,下一轮你的朋友都可以取走余下的所有石头。 - 提示: - 如果堆中有5颗石头,你可以找出确保自己能赢的取石子策略吗? ##解题思路: - Nim游戏的解题关键是寻找“必胜态”。 - 根据题设条件: ```` 当n∈[1,3]时,先手必胜。 当n == 4时,无论先手第一轮如何选取,下一轮都会转化为n∈[1,3]的情形,此时先手必负。 当n∈[5,7]时,先手必胜,先手分别通过取走[1,3]颗石头,可将状态转化为n == 4时的情形,此时后手必负。 当n == 8时,无论先手第一轮如何选取,下一轮都会转化为n∈[5,7]的情形,此时先手必负。 ...... ```` - 以此类推,可以得出结论: - 当n % 4 != 0时,先手必胜;否则先手必负。 */ /// 题目和解题思路见292. NimGame.md static func canWinNim(_ n: Int) -> Bool { return n % 4 != 0 } }
apache-2.0
634245ddfd74906a438553884b958045
26.892308
266
0.612245
2.49381
false
false
false
false
justindarc/firefox-ios
Storage/Rust/RustPlaces.swift
2
11611
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared @_exported import MozillaAppServices private let log = Logger.syncLogger public class RustPlaces { let databasePath: String let writerQueue: DispatchQueue let readerQueue: DispatchQueue var api: PlacesAPI? var writer: PlacesWriteConnection? var reader: PlacesReadConnection? public fileprivate(set) var isOpen: Bool = false private var didAttemptToMoveToBackup = false public init(databasePath: String) { self.databasePath = databasePath self.writerQueue = DispatchQueue(label: "RustPlaces writer queue: \(databasePath)", attributes: []) self.readerQueue = DispatchQueue(label: "RustPlaces reader queue: \(databasePath)", attributes: []) } private func open() -> NSError? { do { api = try PlacesAPI(path: databasePath) isOpen = true return nil } catch let err as NSError { if let placesError = err as? PlacesError { switch placesError { case .panic(let message): Sentry.shared.sendWithStacktrace(message: "Panicked when opening Rust Places database", tag: SentryTag.rustPlaces, severity: .error, description: message) default: Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when opening Rust Places database", tag: SentryTag.rustPlaces, severity: .error, description: placesError.localizedDescription) } } else { Sentry.shared.sendWithStacktrace(message: "Unknown error when opening Rust Places database", tag: SentryTag.rustPlaces, severity: .error, description: err.localizedDescription) } return err } } private func close() -> NSError? { api = nil writer = nil reader = nil isOpen = false return nil } private func withWriter<T>(_ callback: @escaping(_ connection: PlacesWriteConnection) throws -> T) -> Deferred<Maybe<T>> { let deferred = Deferred<Maybe<T>>() writerQueue.async { guard self.isOpen else { deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType)) return } if self.writer == nil { self.writer = self.api?.getWriter() } if let writer = self.writer { do { let result = try callback(writer) deferred.fill(Maybe(success: result)) } catch let error { deferred.fill(Maybe(failure: error as MaybeErrorType)) } } else { deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType)) } } return deferred } private func withReader<T>(_ callback: @escaping(_ connection: PlacesReadConnection) throws -> T) -> Deferred<Maybe<T>> { let deferred = Deferred<Maybe<T>>() readerQueue.async { guard self.isOpen else { deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType)) return } if self.reader == nil { do { self.reader = try self.api?.openReader() } catch let error { deferred.fill(Maybe(failure: error as MaybeErrorType)) } } if let reader = self.reader { do { let result = try callback(reader) deferred.fill(Maybe(success: result)) } catch let error { deferred.fill(Maybe(failure: error as MaybeErrorType)) } } else { deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType)) } } return deferred } public func migrateBookmarksIfNeeded(fromBrowserDB browserDB: BrowserDB) { // Since we use the existence of places.db as an indication that we've // already migrated bookmarks, assert that places.db is not open here. assert(!isOpen, "Shouldn't attempt to migrate bookmarks after opening Rust places.db") // We only need to migrate bookmarks here if the old browser.db file // already exists AND the new Rust places.db file does NOT exist yet. // This is to ensure that we only ever run this migration ONCE. In // addition, it is the caller's (Profile.swift) responsibility to NOT // use this migration API for users signed into a Firefox Account. // Those users will automatically get all their bookmarks on next Sync. guard FileManager.default.fileExists(atPath: browserDB.databasePath), !FileManager.default.fileExists(atPath: databasePath) else { return } // Ensure that the old BrowserDB schema is up-to-date before migrating. _ = browserDB.touch().value // Open the Rust places.db now for the first time. _ = reopenIfClosed() do { try api?.migrateBookmarksFromBrowserDb(path: browserDB.databasePath) } catch let err as NSError { Sentry.shared.sendWithStacktrace(message: "Error encountered while migrating bookmarks from BrowserDB", tag: SentryTag.rustPlaces, severity: .error, description: err.localizedDescription) } } public func getBookmarksTree(rootGUID: GUID, recursive: Bool) -> Deferred<Maybe<BookmarkNode?>> { return withReader { connection in return try connection.getBookmarksTree(rootGUID: rootGUID, recursive: recursive) } } public func getBookmark(guid: GUID) -> Deferred<Maybe<BookmarkNode?>> { return withReader { connection in return try connection.getBookmark(guid: guid) } } public func getRecentBookmarks(limit: UInt) -> Deferred<Maybe<[BookmarkItem]>> { return withReader { connection in return try connection.getRecentBookmarks(limit: limit) } } public func getBookmarksWithURL(url: String) -> Deferred<Maybe<[BookmarkItem]>> { return withReader { connection in return try connection.getBookmarksWithURL(url: url) } } public func isBookmarked(url: String) -> Deferred<Maybe<Bool>> { return getBookmarksWithURL(url: url).bind { result in guard let bookmarks = result.successValue else { return deferMaybe(false) } return deferMaybe(!bookmarks.isEmpty) } } public func searchBookmarks(query: String, limit: UInt) -> Deferred<Maybe<[BookmarkItem]>> { return withReader { connection in return try connection.searchBookmarks(query: query, limit: limit) } } public func interruptWriter() { writer?.interrupt() } public func interruptReader() { reader?.interrupt() } public func runMaintenance() { _ = withWriter { connection in try connection.runMaintenance() } } public func deleteBookmarkNode(guid: GUID) -> Success { return withWriter { connection in let result = try connection.deleteBookmarkNode(guid: guid) if !result { log.debug("Bookmark with GUID \(guid) does not exist.") } } } public func deleteBookmarksWithURL(url: String) -> Success { return getBookmarksWithURL(url: url) >>== { bookmarks in let deferreds = bookmarks.map({ self.deleteBookmarkNode(guid: $0.guid) }) return all(deferreds).bind { results in if let error = results.find({ $0.isFailure })?.failureValue { return deferMaybe(error) } return succeed() } } } public func createFolder(parentGUID: GUID, title: String, position: UInt32? = nil) -> Deferred<Maybe<GUID>> { return withWriter { connection in return try connection.createFolder(parentGUID: parentGUID, title: title, position: position) } } public func createSeparator(parentGUID: GUID, position: UInt32? = nil) -> Deferred<Maybe<GUID>> { return withWriter { connection in return try connection.createSeparator(parentGUID: parentGUID, position: position) } } public func createBookmark(parentGUID: GUID, url: String, title: String?, position: UInt32? = nil) -> Deferred<Maybe<GUID>> { return withWriter { connection in return try connection.createBookmark(parentGUID: parentGUID, url: url, title: title, position: position) } } public func updateBookmarkNode(guid: GUID, parentGUID: GUID? = nil, position: UInt32? = nil, title: String? = nil, url: String? = nil) -> Success { return withWriter { connection in return try connection.updateBookmarkNode(guid: guid, parentGUID: parentGUID, position: position, title: title, url: url) } } public func reopenIfClosed() -> NSError? { var error: NSError? = nil writerQueue.sync { guard !isOpen else { return } error = open() } return error } public func forceClose() -> NSError? { var error: NSError? = nil api?.interrupt() writerQueue.sync { guard isOpen else { return } error = close() } return error } public func syncBookmarks(unlockInfo: SyncUnlockInfo) -> Success { let deferred = Success() writerQueue.async { guard self.isOpen else { deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType)) return } do { try self.api?.syncBookmarks(unlockInfo: unlockInfo) deferred.fill(Maybe(success: ())) } catch let err as NSError { if let placesError = err as? PlacesError { switch placesError { case .panic(let message): Sentry.shared.sendWithStacktrace(message: "Panicked when syncing Places database", tag: SentryTag.rustPlaces, severity: .error, description: message) default: Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when syncing Places database", tag: SentryTag.rustPlaces, severity: .error, description: placesError.localizedDescription) } } deferred.fill(Maybe(failure: err)) } } return deferred } public func resetBookmarksMetadata() -> Success { let deferred = Success() writerQueue.async { guard self.isOpen else { deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType)) return } do { try self.api?.resetBookmarksMetadata() deferred.fill(Maybe(success: ())) } catch let error { deferred.fill(Maybe(failure: error as MaybeErrorType)) } } return deferred } }
mpl-2.0
40c2425f1694572504fba4259a6a0b3b
34.616564
217
0.597106
4.955612
false
false
false
false
ktmswzw/FeelClient
FeelingClient/MVC/C/OpenMapViewController.swift
1
7305
// // OpenMapViewController.swift // FeelingClient // // Created by Vincent on 16/3/31. // Copyright © 2016年 xecoder. All rights reserved. // import UIKit import MapKit import CoreLocation import IBAnimatable import MobileCoreServices #if !RX_NO_MODULE import RxSwift import RxCocoa #endif import Haneke class OpenMapViewController: UIViewController, OpenMessageModelDelegate , MKMapViewDelegate, CLLocationManagerDelegate { @IBOutlet weak var distinctText: AnimatableTextField! @IBOutlet weak var mapView: MKMapView! // @IBOutlet weak var openButton: AnimatableButton! var msgscrentId = "" var fromId:String = "" var friendModel: FriendViewModel! var disposeBag = DisposeBag() var latitude = 0.0 var longitude = 0.0 var address = "" var photos: [String] = [] @IBOutlet var segmentButton: UISegmentedControl! @IBOutlet weak var imageCollection: UICollectionView! var isOk = false let locationManager = CLLocationManager() var targetLocation:CLLocation = CLLocation(latitude: 0, longitude: 0) //目标点 var distance = 0.0 //两点距离 let msg: MessageApi = MessageApi.defaultMessages var addressDict: [String : AnyObject]? @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() friendModel = FriendViewModel(delegate: self) locationManager.delegate = self //locationManager.distanceFilter = 1; locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() self.mapView.delegate = self self.mapView.showsUserLocation = true self.imageCollection.delegate = self self.imageCollection.dataSource = self self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "添加好友", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.save)) self.navigationItem.rightBarButtonItem?.enabled = false self.navigationController!.navigationBar.tintColor = UIColor.whiteColor() imageCollection!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "photo") let oneAnnotation = MyAnnotation() oneAnnotation.coordinate = self.targetLocation.coordinate mapView.addAnnotation(oneAnnotation) } @IBAction func gotoNav(sender: AnyObject) { openTransitDirectionsForCoordinates(self.targetLocation.coordinate, addressDictionary: [:]) } func openTransitDirectionsForCoordinates( coord:CLLocationCoordinate2D,addressDictionary: [String : AnyObject]?) { let placemark = MKPlacemark(coordinate: coord, addressDictionary: addressDictionary) // 1 let mapItem = MKMapItem(placemark: placemark) // 2 let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeTransit] // 3 mapItem.openInMapsWithLaunchOptions(launchOptions) // 4 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last latitude = location!.coordinate.latitude longitude = location!.coordinate.longitude if(!isOk){ UIView.animateWithDuration(1.5, animations: { () -> Void in let center = CLLocationCoordinate2D(latitude: self.latitude, longitude: self.longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)) self.mapView.region = region let currentLocation = CLLocation(latitude: self.latitude, longitude: self.longitude) self.distance = getDistinct(currentLocation, targetLocation: self.targetLocation) self.distinctText.text = "距离 \(self.address) 约: \(Int(self.distance)) 米" if(self.distance<100){ self.isOk = true self.arrival() self.navigationItem.rightBarButtonItem?.enabled = true self.distinctText.text = "已开启" } }) } } func arrival() { msg.arrival(self.msgscrentId) { (r:BaseApi.Result) -> Void in switch (r) { case .Success(let r): let m = r as! MessagesSecret if(m.photos.count>0){ self.photos = m.photos } self.imageCollection.reloadData() self.textView.text = m.content break; case .Failure(let msg): self.view.makeToast(msg as! String, duration: 1, position: .Center) break; } } } func save(){ self.navigationController?.view.makeToastActivity(.Center) friendModel.save(self.fromId) { (r:BaseApi.Result) in switch (r) { case .Success(_): self.navigationController?.view.hideToastActivity() self.view.makeToast("添加成功", duration: 1, position: .Center) self.navigationItem.rightBarButtonItem?.enabled = false self.performSegueWithIdentifier("homeMain", sender: self) break case .Failure(let error): self.navigationController?.view.hideToastActivity() self.view.makeToast("添加失败:\(error)", duration: 1, position: .Center) break } } } } extension OpenMapViewController: FriendModelDelegate{ } extension OpenMapViewController: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.photos.count } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { viewBigImages(self.photos[indexPath.row] ) } func viewBigImages(url: String) { self.performSegueWithIdentifier("showImage", sender: url) } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let CellIdentifier = "photo" let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellIdentifier, forIndexPath: indexPath) as! CollectionViewCell let URLString = self.photos[indexPath.row] let URL = NSURL(string:getPathSmall(URLString))! cell.imageView.hnk_setImageFromURL(URL) return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showImage" { let viewController = segue.destinationViewController as! ViewImageViewController viewController.imageUrl = getPath(sender as! String) } } }
mit
6d8e067dd70f661835223c199c72591a
36.554404
158
0.645419
5.384844
false
false
false
false
tbaranes/SwiftyUtils
Sources/Extensions/CoreGraphics/CGPoint/CGPointExtension.swift
1
1936
// // Created by Tom Baranes on 09/04/2017. // Copyright © 2017 Tom Baranes. All rights reserved. // import CoreGraphics // MARK: - Operators extension CGPoint { /// Create a new `CGPoint` by adding up two `CGPoint` together. /// - Parameters: /// - lhs: One of the two `CGPoint` that will be added up. /// - rhs: One of the two `CGPoint` that will be added up. /// - Returns: The `CGPoint` resulting of the two others addition. public static func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint { CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } /// Create a new `CGPoint` by substracting two `CGPoint` together. /// - Parameters: /// - lhs: One of the two `CGPoint` that will be substracted. /// - rhs: One of the two `CGPoint` that will be substracted. /// - Returns: The `CGPoint` resulting of the two others substraction. public static func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint { CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y) } /// Create a new `CGPoint` by multipliing a `CGPoint` with a scalar. /// - Parameters: /// - point: The `CGPoint` that will be multiplied. /// - scalar: The scalar that will be used to multiply the CGPoint. /// - Returns: The result of the multiplication between the CGPoint and the scalar. public static func * (point: CGPoint, scalar: CGFloat) -> CGPoint { CGPoint(x: point.x * scalar, y: point.y * scalar) } } // swiftlint:disable:next static_operator public func += (lhs: inout CGPoint, rhs: CGPoint) { lhs = CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } // swiftlint:disable:next static_operator public func -= (lhs: inout CGPoint, rhs: CGPoint) { lhs = CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y) } // swiftlint:disable:next static_operator public func *= (point: inout CGPoint, scalar: CGFloat) { point = CGPoint(x: point.x * scalar, y: point.y * scalar) }
mit
3868b2354ec4ac417bab82ac96461930
34.833333
87
0.630491
3.499096
false
false
false
false
googlemaps/google-maps-ios-utils
samples/SwiftDemoApp/SwiftDemoApp/AppDelegate.swift
1
1329
/* Copyright (c) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import GoogleMaps import UIKit // Change this key to a valid key registered with the demo app bundle id. let mapsAPIKey = "" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { if mapsAPIKey.isEmpty { fatalError("Please provide an API Key using mapsAPIKey") } GMSServices.provideAPIKey(mapsAPIKey) let masterViewControler = MasterViewController() let navigationController = UINavigationController(rootViewController: masterViewControler) window?.rootViewController = navigationController return true } }
apache-2.0
b66de7f0214b033588eb4489977a0948
33.973684
150
0.76298
4.780576
false
false
false
false
Aishwarya-Ramakrishnan/sparkios
Source/Membership/MembershipClient+Sync.swift
1
3795
// Copyright 2016 Cisco Systems Inc // // 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 MembershipClient { /// Lists all room memberships. By default, lists memberships for rooms to which the authenticated user belongs. /// /// - parameter roomId: Limit results to a specific room by id. /// - parameter personId: Limit results to a specific person by id. /// - parameter personEmail: Limit results to a specific person by email address. /// - parameter max: Limit the maximum number of items in the response. /// - returns: Memberships array public func list(roomId: String? = nil, personId: String? = nil, personEmail: EmailAddress? = nil, max: Int? = nil) throws -> [Membership] { return try SyncUtil.getArray(roomId, personId, personEmail, max, async: list) } /// Add someone to a room by person id; optionally making them a moderator. /// /// - parameter roomId: The rooom id. /// - parameter personId: The person id. /// - parameter isModerator: Set to true to make the person a room moderator. /// - returns: Membership public func create(roomId: String, personId: String, isModerator: Bool = false) throws -> Membership { return try SyncUtil.getObject(roomId, personId, isModerator, async: create) } /// Add someone to a room by email address; optionally making them a moderator. /// /// - parameter roomId: The rooom id. /// - parameter personEmail: The email address. /// - parameter isModerator: Set to true to make the person a room moderator. /// - returns: Membership public func create(roomId: String, personEmail: EmailAddress, isModerator: Bool = false) throws -> Membership { return try SyncUtil.getObject(roomId, personEmail, isModerator, async: create) } /// Get details for a membership by id. /// /// - parameter membershipId: The membership id. /// - returns: Membership public func get(membershipId: String) throws -> Membership { return try SyncUtil.getObject(membershipId, async: get) } /// Updates properties for a membership by id. /// /// - parameter membershipId: The membership id. /// - parameter isModerator: Set to true to make the person a room moderator. /// - returns: Membership public func update(membershipId: String, isModerator: Bool) throws -> Membership { return try SyncUtil.getObject(membershipId, isModerator, async: update) } /// Deletes a membership by id. /// /// - parameter membershipId: The membership id. /// - returns: Void public func delete(membershipId: String) throws { try SyncUtil.deleteObject(membershipId, async: delete) } }
mit
8b59f2b3dd4457c27f135ba0f7932f5e
46.4375
144
0.698814
4.485816
false
false
false
false
JackHowa/Latr
SnapClone/SelectUserViewController.swift
1
5544
// // SelectUserViewController.swift // SnapClone // // Created by Jack Howard on 7/4/17. // Copyright © 2017 JackHowa. All rights reserved. // import Alamofire import UIKit import FirebaseDatabase import FirebaseAuth class SelectUserViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var users : [User] = [] // prep for segue getting those variable values var imageURL = "" // description can mess with swift var descrip = "" // need to keep on knowing the uuid of the photo url so that it will be associated with the message var uuid = "" var displayable = "" // show date // and time var getAt = "" override func viewDidLoad() { super.viewDidLoad() // using delegate to reference the table view outlet self.tableView.dataSource = self self.tableView.delegate = self self.title = "Contacts" // call the database of firebase // listen for db changes at a particular place or index // tell us about any childadded // want to know all of the new users that are added // child users is the header in the storage Database.database().reference().child("users").observe(DataEventType.childAdded, with: {(snapshot) in // returns object of each user // called for each user // print(snapshot) // like calling new let user = User() // setting the values // forcing the value as well as the upcast to a string // need to cast snapshot.value as a NSDictionary. let value = snapshot.value as? NSDictionary user.email = value?["email"] as! String // snapshot dictionary doesn't have a key so can keep this user.uid = snapshot.key // assigns the uid // kind of like shovelling back into users self.users.append(user) self.tableView.reloadData() }) } // add firebase users func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // how many rows return users.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() // calling the cell at the index let user = users[indexPath.row] // assign the label of text cell.textLabel?.text = user.email // make cell a different color // if date is too soon, then make a different color return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // find user that was selected let user = users[indexPath.row] // need to make a dictionary // gets descrip and image url from sender user input in the picture view // sender should always be current user // update the get At time // get at = d/M/yy // via http://nsdateformatter.com/ let message = ["from": Auth.auth().currentUser!.email!, "description": descrip, "image_url": imageURL, "uuid": uuid, "getAt": getAt] // let inputFormatter = DateFormatter() // inputFormatter.dateFormat = "MM/dd/yy" // let showDate = inputFormatter.date(from: getAt) // inputFormatter.dateFormat = "yyyy-MM-dd" // let deliver_at = inputFormatter.string(from: showDate!) // // // let parameters: Parameters = [ // "caption": descrip, // "image_url": imageURL, // "sender_id": "9", // "receiver_id": "9", // "deliver_at": deliver_at, //// "deliver_at": "07-09-2017", //// "deliverable": displayable // ] // // // let headers: HTTPHeaders = ["Accept": "application/json", "Content-Type" :"application/json"] // // Alamofire.request("https://aqueous-waters-34203.herokuapp.com/messages", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in // // // original URL request // print("Request :", response.request!) // // // HTTP URL response --> header and status code // print("Response received is :", response.response as Any) // // // server data : example 267 bytes // print("Response data is :", response.data!) // // // result of response serialization : SUCCESS / FAILURE // print("Response result is :", response.result) // // debugPrint("Debug Print :", response) // } // child by auto id is a firebase function that prevents reuse of id and makes unique // add the message to the set value Database.database().reference().child("users").child(user.uid).child("messages").childByAutoId().setValue(message) // after selecting a row, go back to the root to see any remaining messages // need this pop back after viewing navigationController!.popToRootViewController(animated: true) } }
mit
85b5830d6507c4dc4c49f0f7468c23d6
33.006135
198
0.568645
4.914007
false
false
false
false
spark/photon-tinker-ios
Photon-Tinker/Mesh/Gen3SetupControlPanelFlowCompleteViewController.swift
1
3717
// // Created by Raimundas Sakalauskas on 9/20/18. // Copyright (c) 2018 Particle. All rights reserved. // import UIKit import CoreBluetooth class Gen3SetupControlPanelFlowCompleteViewController: Gen3SetupViewController, Storyboardable { @IBOutlet weak var successView: UIView! @IBOutlet weak var successTitleLabel: ParticleLabel! @IBOutlet weak var successTextLabel: ParticleLabel! internal private(set) weak var context: Gen3SetupContext! internal private(set) var action: Gen3SetupControlPanelCellType! internal private(set) var callback: (() -> ())! override var allowBack: Bool { get { return false } set { super.allowBack = newValue } } func setup(didFinishScreen: @escaping () -> (), deviceType: ParticleDeviceType?, deviceName: String, action: Gen3SetupControlPanelCellType, context: Gen3SetupContext) { self.callback = didFinishScreen self.deviceType = deviceType self.deviceName = deviceName self.action = action self.context = context } override func setStyle() { successTitleLabel.setStyle(font: ParticleStyle.BoldFont, size: ParticleStyle.LargeSize, color: ParticleStyle.PrimaryTextColor) successTextLabel.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.RegularSize, color: ParticleStyle.PrimaryTextColor) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.setSuccess() } override func setContent() { switch action! { case .actionChangeDataLimit: self.successTitleLabel.text = Gen3SetupStrings.ControlPanel.FlowComplete.ChangeDataLimit.Title self.successTextLabel.text = Gen3SetupStrings.ControlPanel.FlowComplete.ChangeDataLimit.Text case .actionNewWifi: self.successTitleLabel.text = Gen3SetupStrings.ControlPanel.FlowComplete.AddNewWifi.Title self.successTextLabel.text = Gen3SetupStrings.ControlPanel.FlowComplete.AddNewWifi.Text case .actionChangePinsStatus: self.successTitleLabel.text = Gen3SetupStrings.ControlPanel.FlowComplete.ToggleEthernet.Title if (context.targetDevice.enableEthernetDetectionFeature!) { self.successTextLabel.text = Gen3SetupStrings.ControlPanel.FlowComplete.ToggleEthernet.ActivateText } else { self.successTextLabel.text = Gen3SetupStrings.ControlPanel.FlowComplete.ToggleEthernet.DeactivateText } case .actionChangeSimStatus: self.successTitleLabel.text = Gen3SetupStrings.ControlPanel.FlowComplete.ToggleSim.Title if (context.targetDevice.setSimActive!) { self.successTextLabel.text = Gen3SetupStrings.ControlPanel.FlowComplete.ToggleSim.ActivateText } else { self.successTextLabel.text = Gen3SetupStrings.ControlPanel.FlowComplete.ToggleSim.DeactivateText } case .actionLeaveMeshNetwork: self.successTitleLabel.text = Gen3SetupStrings.ControlPanel.FlowComplete.LeaveMeshNetwork.Title self.successTextLabel.text = Gen3SetupStrings.ControlPanel.FlowComplete.LeaveMeshNetwork.Text default: break } } func setSuccess() { DispatchQueue.main.async { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(2)) { [weak self] in if let callback = self?.callback { callback() } } } } }
apache-2.0
79ab2c8f00f171254d0bd1a20e15e158
41.724138
172
0.668281
5.191341
false
false
false
false
jpush/jchat-swift
JChat/Src/Utilites/Extension/String+JChat.swift
1
12992
// // JCString+JChat.swift // JChat // // Created by JIGUANG on 2017/2/16. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit public enum JCFileFormat: Int { case document case video case voice case photo case other } extension String { static func getTodayYesterdayString(_ theDate:Date) -> String { let formatter = DateFormatter() let locale:Locale = Locale(identifier: "zh") formatter.locale = locale formatter.dateStyle = .short formatter.timeStyle = .none formatter.doesRelativeDateFormatting = true return formatter.string(from: theDate) } static func getPastDateString(_ theDate:Date) -> String { let formatter = DateFormatter() let locale:Locale = Locale(identifier: "zh") formatter.locale = locale formatter.dateStyle = .long formatter.timeStyle = .none formatter.doesRelativeDateFormatting = true return formatter.string(from: theDate) } static func getFriendlyDateString(_ timeInterval:TimeInterval, forConversation isShort:Bool) -> String { let theDate:Date = Date(timeIntervalSince1970: timeInterval) var output = "" let theDiff = -theDate.timeIntervalSinceNow switch theDiff { case theDiff where theDiff < 60.0: output = "刚刚" break case theDiff where theDiff < 60 * 60: let minute:Int = Int(theDiff/60) output = "\(minute)分钟前" break default: let formatter:DateFormatter = DateFormatter() let locale:Locale = Locale(identifier: "zh") formatter.locale = locale var isTodayYesterday = false var isPastLong = false if theDate.isToday() { formatter.dateFormat = FORMAT_TODAY } else if theDate.isYesterday() { formatter.dateFormat = FORMAT_YESTERDAY isTodayYesterday = true } else if theDate.isThisWeek() { if isShort { formatter.dateFormat = FORMAT_THIS_WEEK_SHORT } else { formatter.dateFormat = FORMAT_THIS_WEEK } } else { if isShort { formatter.dateFormat = FORMAT_PAST_SHORT } else { formatter.dateFormat = FORMAT_PAST_TIME isPastLong = true } } if isTodayYesterday { let todayYesterday = String.getTodayYesterdayString(theDate) if isShort { output = todayYesterday } else { output = formatter.string(from: theDate) output = "\(todayYesterday) \(output)" } } else { output = formatter.string(from: theDate) if isPastLong { let thePastDate = String.getPastDateString(theDate) output = "\(thePastDate) \(output)" } } break } return output } static func conversationIdWithConversation(_ conversation:JMSGConversation) -> String { var conversationId = "" if !conversation.ex.isGroup { let user = conversation.target as! JMSGUser conversationId = "\(user.username)_0" } else { let group = conversation.target as! JMSGGroup conversationId = "\(group.gid)_1" } return conversationId } } extension String { static func errorAlert(_ error: NSError) -> String { var errorAlert: String = "" if error.code > 860000 { let errorcode = JMSGSDKErrorCode(rawValue: Int(error.code)) switch errorcode! as JMSGSDKErrorCode{ case .jmsgErrorSDKNetworkDownloadFailed: errorAlert = "下载失败" break case .jmsgErrorSDKNetworkUploadFailed: errorAlert = "上传资源文件失败" break case .jmsgErrorSDKNetworkUploadTokenVerifyFailed: errorAlert = "上传资源文件Token验证失败" break case .jmsgErrorSDKNetworkUploadTokenGetFailed: errorAlert = "获取服务器Token失败" break case .jmsgErrorSDKDBDeleteFailed: errorAlert = "数据库删除失败" break case .jmsgErrorSDKDBUpdateFailed: errorAlert = "数据库更新失败" break case .jmsgErrorSDKDBSelectFailed: errorAlert = "数据库查询失败" break case .jmsgErrorSDKDBInsertFailed: errorAlert = "数据库插入失败" break case .jmsgErrorSDKParamAppkeyInvalid: errorAlert = "appkey不合法" break case .jmsgErrorSDKParamUsernameInvalid: errorAlert = "用户名不合法" break case .jmsgErrorSDKParamPasswordInvalid: errorAlert = "用户密码不合法" break case .jmsgErrorSDKUserNotLogin: errorAlert = "用户没有登录" break case .jmsgErrorSDKNotMediaMessage: errorAlert = "这不是一条媒体消息" break case .jmsgErrorSDKMediaResourceMissing: errorAlert = "下载媒体资源路径或者数据意外丢失" break case .jmsgErrorSDKMediaCrcCodeIllegal: errorAlert = "媒体CRC码无效" break case .jmsgErrorSDKMediaCrcVerifyFailed: errorAlert = "媒体CRC校验失败" break case .jmsgErrorSDKMediaUploadEmptyFile: errorAlert = "上传媒体文件时, 发现文件不存在" break case .jmsgErrorSDKParamContentInvalid: errorAlert = "无效的消息内容" break case .jmsgErrorSDKParamMessageNil: errorAlert = "空消息" break case .jmsgErrorSDKMessageNotPrepared: errorAlert = "消息不符合发送的基本条件检查" break case .jmsgErrorSDKParamConversationTypeUnknown: errorAlert = "未知的会话类型" break case .jmsgErrorSDKParamConversationUsernameInvalid: errorAlert = "会话 username 无效" break case .jmsgErrorSDKParamConversationGroupIdInvalid: errorAlert = "会话 groupId 无效" break case .jmsgErrorSDKParamGroupGroupIdInvalid: errorAlert = "groupId 无效" break case .jmsgErrorSDKParamGroupGroupInfoInvalid: errorAlert = "group 相关字段无效" break case .jmsgErrorSDKMessageNotInGroup: errorAlert = "你已不在该群,无法发送消息" break // case 810009: // errorAlert = "超出群上限" // break default: break } } if error.code > 800000 && error.code < 820000 { let errorcode = JMSGTcpErrorCode(rawValue: UInt(error.code)) switch errorcode! { case .errorTcpUserNotRegistered: errorAlert = "用户名不存在" break case .errorTcpUserPasswordError: errorAlert = "用户名或密码错误" break default: break } if error.code == 809002 || error.code == 812002 { errorAlert = "你已不在该群" } } if error.code < 600 { let errorcode = JMSGHttpErrorCode(rawValue: UInt(error.code)) switch errorcode! { case .errorHttpServerInternal: errorAlert = "服务器端内部错误" break case .errorHttpUserExist: errorAlert = "用户已经存在" break case .errorHttpUserNotExist: errorAlert = "用户不存在" break case .errorHttpPrameterInvalid: errorAlert = "参数无效" break case .errorHttpPasswordError: errorAlert = "密码错误" break case .errorHttpUidInvalid: errorAlert = "内部UID 无效" break case .errorHttpMissingAuthenInfo: errorAlert = "Http 请求没有验证信息" break case .errorHttpAuthenticationFailed: errorAlert = "Http 请求验证失败" break case .errorHttpAppkeyNotExist: errorAlert = "Appkey 不存在" break case .errorHttpTokenExpired: errorAlert = "Http 请求 token 过期" break case .errorHttpServerResponseTimeout: errorAlert = "服务器端响应超时" break default: break } } if error.code == 869999 { errorAlert = "网络连接错误" } if error.code == 898001 { errorAlert = "用户名已存在" } if error.code == 801006 { errorAlert = "账号已被禁用" } if errorAlert == "" { errorAlert = "未知错误" } return errorAlert } } extension String { var length: Int { return self.count } var isContainsChinese: Bool { let chineseRegex = "^(.*)[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+(.*)$" let chinesePredicate = NSPredicate(format: "SELF MATCHES %@", chineseRegex) if chinesePredicate.evaluate(with: self) { return true } return false } var isExpectations: Bool { let regularExpression = "^([a-zA-Z0-9])[a-zA-Z0-9@_\\-\\.]+$" let predicate = NSPredicate(format: "SELF MATCHES %@", regularExpression) if predicate.evaluate(with: self) { return true } return false } public func trim(trimNewline: Bool = false) ->String { if trimNewline { return self.trimmingCharacters(in: .whitespacesAndNewlines) } return self.trimmingCharacters(in: .whitespaces) } public func py() -> String { let mutableString = NSMutableString(string: self) //把汉字转为拼音 CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false) //去掉拼音的音标 CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false) let py = String(mutableString) return py } public func firstCharacter() -> String { let firstCharacter = String(describing: self.first!) if firstCharacter.isLetterOrNum() { return firstCharacter.uppercased() } let py = String(describing: firstCharacter.py().first!) return py.uppercased() } public func isLetterOrNum() -> Bool { if let value = UnicodeScalar(self)?.value { if value >= 65 && value <= 90 { return true } } return false } static func getRecorderPath() -> String { var recorderPath:String? = nil let now:Date = Date() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yy-MMMM-dd" recorderPath = "\(NSHomeDirectory())/Documents/" dateFormatter.dateFormat = "yyyy-MM-dd-hh-mm-ss" recorderPath?.append("\(dateFormatter.string(from: now))-MySound.ilbc") return recorderPath! } func fileFormat() -> JCFileFormat { let docFormat = ["ppt", "pptx", "doc", "docx", "pdf", "xls", "xlsx", "txt", "wps"] let videoFormat = ["mp4", "mov", "rm", "rmvb", "wmv", "avi", "3gp", "mkv"] let voiceFormat = ["wav", "mp3", "wma", "midi"] let photoFormat = ["jpg", "jpeg", "png", "bmp", "gif"] if docFormat.contains(self) { return .document } if videoFormat.contains(self) { return .video } if voiceFormat.contains(self) { return .voice } if photoFormat.contains(self) { return .photo } return .other } }
mit
781477ec663a845fccf23b9a75d3c418
32.045455
108
0.522534
4.844767
false
false
false
false
arvindhsukumar/ARVBottomMenuController
Pod/Classes/ARVBottomMenuViewController.swift
1
6148
// // ARVBottomMenuViewController.swift // ARVBottomMenuController // // Created by Arvindh Sukumar on 06/03/15. // Copyright (c) 2015 Arvindh Sukumar. All rights reserved. // import UIKit enum ARVBottomMenuState { case Opened case Closed } @objc protocol ARVBottomMenuViewDelegate { optional func heightForBottomController()->CGFloat } class ARVBottomMenuViewController: UIViewController { let defaultMenuHeight: CGFloat = 300 var bottomMenuHeight: CGFloat = 200 var mainController: UIViewController! { didSet { if oldValue != nil{ self.removeController(oldValue) } self.setupMainController() } } var bottomControllers:[UIViewController] = [] var bottomController: UIViewController! { didSet { if oldValue != nil{ self.removeController(oldValue) } self.setupBottomController() } } var delegate: ARVBottomMenuViewDelegate? var parallaxOffset: CGFloat = 140 var menuState: ARVBottomMenuState = ARVBottomMenuState.Closed convenience init(mainController:UIViewController){ self.init(mainController:mainController, bottomControllers:[]) } convenience init(mainController:UIViewController, bottomController:UIViewController?) { var bottomControllers:[UIViewController] = [] if let bc = bottomController { bottomControllers.append(bc) } self.init(mainController:mainController, bottomControllers:bottomControllers) } init(mainController:UIViewController, bottomControllers:[UIViewController]) { super.init() self.mainController = mainController self.bottomControllers = bottomControllers if self.bottomControllers.count > 0{ self.bottomController = self.bottomControllers[0] } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func viewDidLoad() { super.viewDidLoad() self.setupMainController() self.setupBottomController() // Do any additional setup after loading the view. } func removeController(controller:UIViewController){ controller.view.removeFromSuperview() controller.willMoveToParentViewController(nil) controller.beginAppearanceTransition(false, animated: false) controller.removeFromParentViewController() controller.endAppearanceTransition() } func setupMainController(){ var frame = self.view.bounds mainController.view.frame = frame self.addChildViewController(mainController) mainController.didMoveToParentViewController(self) self.view.insertSubview(mainController.view, atIndex: 0) } func setupBottomController(){ var frame = self.bottomController.view.frame self.bottomMenuHeight = self.bottomController.view.frame.size.height frame.origin.y = self.view.bounds.size.height - frame.size.height + self.parallaxOffset bottomController.view.frame = frame self.addChildViewController(bottomController) bottomController.didMoveToParentViewController(self) self.view.insertSubview(bottomController.view, belowSubview: self.mainController.view) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.mainController.beginAppearanceTransition(true , animated: animated) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.mainController.endAppearanceTransition() UIView.animateWithDuration(0.8, animations: { () -> Void in }) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.mainController.beginAppearanceTransition(false , animated: animated) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) self.mainController.endAppearanceTransition() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func toggleBottomMenu(shouldOpen:Bool) { self.view.userInteractionEnabled = false UIView.animateWithDuration(0.7, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.2, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in var frame = self.view.bounds var originAdjustment: CGFloat = shouldOpen ? self.bottomMenuHeight - 20 : 0 frame.origin.y = 0 - originAdjustment self.mainController.view.frame = frame var frame2 = self.bottomController.view.frame var bottomOriginAdjustment: CGFloat = shouldOpen ? 0 : self.parallaxOffset frame2.origin.y = frame.size.height - self.bottomMenuHeight + bottomOriginAdjustment self.bottomController.view.frame = frame2 }) { (finished:Bool) -> Void in if finished { self.menuState = shouldOpen ? .Opened : .Closed self.view.userInteractionEnabled = true } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
497efbd3835e79976246ba8ba637689a
29.74
182
0.642485
5.460036
false
false
false
false
gouyz/GYZBaking
baking/Pods/DKImagePickerController/DKCamera/DKCamera.swift
2
29021
// // DKCamera.swift // DKCameraDemo // // Created by ZhangAo on 15/8/30. // Copyright (c) 2015年 ZhangAo. All rights reserved. // import UIKit import AVFoundation import CoreMotion import ImageIO open class DKCameraPassthroughView: UIView { open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let hitTestingView = super.hitTest(point, with: event) return hitTestingView == self ? nil : hitTestingView } } extension AVMetadataFaceObject { open func realBounds(inCamera camera: DKCamera) -> CGRect { var bounds = CGRect() let previewSize = camera.previewLayer.bounds.size let isFront = camera.currentDevice == camera.captureDeviceFront if isFront { bounds.origin = CGPoint(x: previewSize.width - previewSize.width * (1 - self.bounds.origin.y - self.bounds.size.height / 2), y: previewSize.height * (self.bounds.origin.x + self.bounds.size.width / 2)) } else { bounds.origin = CGPoint(x: previewSize.width * (1 - self.bounds.origin.y - self.bounds.size.height / 2), y: previewSize.height * (self.bounds.origin.x + self.bounds.size.width / 2)) } bounds.size = CGSize(width: self.bounds.width * previewSize.height, height: self.bounds.height * previewSize.width) return bounds } } @objc public enum DKCameraDeviceSourceType : Int { case front, rear } open class DKCamera: UIViewController, AVCaptureMetadataOutputObjectsDelegate { open class func checkCameraPermission(_ handler: @escaping (_ granted: Bool) -> Void) { func hasCameraPermission() -> Bool { return AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) == .authorized } func needsToRequestCameraPermission() -> Bool { return AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) == .notDetermined } hasCameraPermission() ? handler(true) : (needsToRequestCameraPermission() ? AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { granted in DispatchQueue.main.async(execute: { () -> Void in hasCameraPermission() ? handler(true) : handler(false) }) }) : handler(false)) } open var didCancel: (() -> Void)? open var didFinishCapturingImage: ((_ image: UIImage?, _ data: Data?) -> Void)? /// Notify the listener of the detected faces in the preview frame. open var onFaceDetection: ((_ faces: [AVMetadataFaceObject]) -> Void)? /// Be careful this may cause the view to load prematurely. open var cameraOverlayView: UIView? { didSet { if let cameraOverlayView = cameraOverlayView { self.view.addSubview(cameraOverlayView) } } } /// The flashModel will to be remembered to next use. open var flashMode:AVCaptureFlashMode! { didSet { self.updateFlashButton() self.updateFlashMode() self.updateFlashModeToUserDefautls(self.flashMode) } } open class func isAvailable() -> Bool { return UIImagePickerController.isSourceTypeAvailable(.camera) } /// Determines whether or not the rotation is enabled. open var allowsRotate = false /// set to NO to hide all standard camera UI. default is YES. open var showsCameraControls = true { didSet { self.contentView.isHidden = !self.showsCameraControls } } open let captureSession = AVCaptureSession() open var previewLayer: AVCaptureVideoPreviewLayer! fileprivate var beginZoomScale: CGFloat = 1.0 fileprivate var zoomScale: CGFloat = 1.0 open var defaultCaptureDevice = DKCameraDeviceSourceType.rear open var currentDevice: AVCaptureDevice? open var captureDeviceFront: AVCaptureDevice? open var captureDeviceRear: AVCaptureDevice? fileprivate weak var stillImageOutput: AVCaptureStillImageOutput? open var contentView = UIView() open var originalOrientation: UIDeviceOrientation! open var currentOrientation: UIDeviceOrientation! open let motionManager = CMMotionManager() open lazy var flashButton: UIButton = { let flashButton = UIButton() flashButton.addTarget(self, action: #selector(DKCamera.switchFlashMode), for: .touchUpInside) return flashButton }() open var cameraSwitchButton: UIButton! open var captureButton: UIButton! let cameraResource: DKCameraResource init(cameraResource: DKCameraResource = DKDefaultCameraResource()) { self.cameraResource = cameraResource super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { self.cameraResource = DKDefaultCameraResource() super.init(coder: aDecoder) } override open func viewDidLoad() { super.viewDidLoad() self.setupDevices() self.setupUI() self.setupSession() self.setupMotionManager() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !self.captureSession.isRunning { self.captureSession.startRunning() } if !self.motionManager.isAccelerometerActive { self.motionManager.startAccelerometerUpdates(to: OperationQueue.current!, withHandler: { accelerometerData, error in if error == nil { let currentOrientation = accelerometerData!.acceleration.toDeviceOrientation() ?? self.currentOrientation if self.originalOrientation == nil { self.initialOriginalOrientationForOrientation() self.currentOrientation = self.originalOrientation } if let currentOrientation = currentOrientation , self.currentOrientation != currentOrientation { self.currentOrientation = currentOrientation self.updateContentLayoutForCurrentOrientation() } } else { print("error while update accelerometer: \(error!.localizedDescription)", terminator: "") } }) } self.updateSession(isEnable: true) } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if self.originalOrientation == nil { self.contentView.frame = self.view.bounds self.previewLayer.frame = self.view.bounds } } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.updateSession(isEnable: false) self.motionManager.stopAccelerometerUpdates() } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } open override var prefersStatusBarHidden : Bool { return true } // MARK: - Setup let bottomView = UIView() open func setupUI() { self.view.backgroundColor = UIColor.black self.view.addSubview(self.contentView) self.contentView.backgroundColor = UIColor.clear self.contentView.frame = self.view.bounds let bottomViewHeight: CGFloat = 70 bottomView.bounds.size = CGSize(width: contentView.bounds.width, height: bottomViewHeight) bottomView.frame.origin = CGPoint(x: 0, y: contentView.bounds.height - bottomViewHeight) bottomView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin] bottomView.backgroundColor = UIColor(white: 0, alpha: 0.4) contentView.addSubview(bottomView) // switch button let cameraSwitchButton: UIButton = { let cameraSwitchButton = UIButton() cameraSwitchButton.addTarget(self, action: #selector(DKCamera.switchCamera), for: .touchUpInside) cameraSwitchButton.setImage(cameraResource.cameraSwitchImage(), for: .normal) cameraSwitchButton.sizeToFit() return cameraSwitchButton }() cameraSwitchButton.frame.origin = CGPoint(x: bottomView.bounds.width - cameraSwitchButton.bounds.width - 15, y: (bottomView.bounds.height - cameraSwitchButton.bounds.height) / 2) cameraSwitchButton.autoresizingMask = [.flexibleLeftMargin, .flexibleTopMargin, .flexibleBottomMargin] bottomView.addSubview(cameraSwitchButton) self.cameraSwitchButton = cameraSwitchButton // capture button let captureButton: UIButton = { class DKCaptureButton: UIButton { fileprivate override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { self.backgroundColor = UIColor.white return true } fileprivate override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { self.backgroundColor = UIColor.white return true } fileprivate override func endTracking(_ touch: UITouch?, with event: UIEvent?) { self.backgroundColor = nil } fileprivate override func cancelTracking(with event: UIEvent?) { self.backgroundColor = nil } } let captureButton = DKCaptureButton() captureButton.addTarget(self, action: #selector(DKCamera.takePicture), for: .touchUpInside) captureButton.bounds.size = CGSize(width: bottomViewHeight, height: bottomViewHeight).applying(CGAffineTransform(scaleX: 0.9, y: 0.9)) captureButton.layer.cornerRadius = captureButton.bounds.height / 2 captureButton.layer.borderColor = UIColor.white.cgColor captureButton.layer.borderWidth = 2 captureButton.layer.masksToBounds = true return captureButton }() captureButton.center = CGPoint(x: bottomView.bounds.width / 2, y: bottomView.bounds.height / 2) captureButton.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin] bottomView.addSubview(captureButton) self.captureButton = captureButton // cancel button let cancelButton: UIButton = { let cancelButton = UIButton() cancelButton.addTarget(self, action: #selector(dismiss as (Void) -> Void), for: .touchUpInside) cancelButton.setImage(cameraResource.cameraCancelImage(), for: .normal) cancelButton.sizeToFit() return cancelButton }() cancelButton.frame.origin = CGPoint(x: contentView.bounds.width - cancelButton.bounds.width - 15, y: 25) cancelButton.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin] contentView.addSubview(cancelButton) self.flashButton.frame.origin = CGPoint(x: 5, y: 15) contentView.addSubview(self.flashButton) contentView.addGestureRecognizer(UIPinchGestureRecognizer(target: self, action: #selector(DKCamera.handleZoom(_:)))) contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(DKCamera.handleFocus(_:)))) } open func setupSession() { self.captureSession.sessionPreset = AVCaptureSessionPresetPhoto self.setupCurrentDevice() let stillImageOutput = AVCaptureStillImageOutput() if self.captureSession.canAddOutput(stillImageOutput) { self.captureSession.addOutput(stillImageOutput) self.stillImageOutput = stillImageOutput } if self.onFaceDetection != nil { let metadataOutput = AVCaptureMetadataOutput() metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue(label: "MetadataOutputQueue")) if self.captureSession.canAddOutput(metadataOutput) { self.captureSession.addOutput(metadataOutput) metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeFace] } } self.previewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession) self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill self.previewLayer.frame = self.view.bounds let rootLayer = self.view.layer rootLayer.masksToBounds = true rootLayer.insertSublayer(self.previewLayer, at: 0) } open func setupCurrentDevice() { if let currentDevice = self.currentDevice { if currentDevice.isFlashAvailable { self.flashButton.isHidden = false self.flashMode = self.flashModeFromUserDefaults() } else { self.flashButton.isHidden = true } for oldInput in self.captureSession.inputs as! [AVCaptureInput] { self.captureSession.removeInput(oldInput) } let frontInput = try? AVCaptureDeviceInput(device: self.currentDevice) if self.captureSession.canAddInput(frontInput) { self.captureSession.addInput(frontInput) } try! currentDevice.lockForConfiguration() if currentDevice.isFocusModeSupported(.continuousAutoFocus) { currentDevice.focusMode = .continuousAutoFocus } if currentDevice.isExposureModeSupported(.continuousAutoExposure) { currentDevice.exposureMode = .continuousAutoExposure } currentDevice.unlockForConfiguration() } } open func setupDevices() { let devices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) as! [AVCaptureDevice] for device in devices { if device.position == .back { self.captureDeviceRear = device } if device.position == .front { self.captureDeviceFront = device } } switch self.defaultCaptureDevice { case .front: self.currentDevice = self.captureDeviceFront ?? self.captureDeviceRear case .rear: self.currentDevice = self.captureDeviceRear ?? self.captureDeviceFront } } // MARK: - Session fileprivate var isStopped = false open func startSession() { self.isStopped = false if !self.captureSession.isRunning { self.captureSession.startRunning() } } open func stopSession() { self.pauseSession() self.captureSession.stopRunning() } open func pauseSession() { self.isStopped = true self.updateSession(isEnable: false) } open func updateSession(isEnable: Bool) { if ((!self.isStopped) || (self.isStopped && !isEnable)), let connection = self.previewLayer.connection { connection.isEnabled = isEnable } } // MARK: - Callbacks internal func dismiss() { self.didCancel?() } open func takePicture() { let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) if authStatus == .denied { return } if let stillImageOutput = self.stillImageOutput, !stillImageOutput.isCapturingStillImage { self.captureButton.isEnabled = false DispatchQueue.global().async(execute: { if let connection = stillImageOutput.connection(withMediaType: AVMediaTypeVideo) { connection.videoOrientation = self.currentOrientation.toAVCaptureVideoOrientation() connection.videoScaleAndCropFactor = self.zoomScale stillImageOutput.captureStillImageAsynchronously(from: connection, completionHandler: { (imageDataSampleBuffer, error) in if error == nil { let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer) if let didFinishCapturingImage = self.didFinishCapturingImage, let imageData = imageData, let takenImage = UIImage(data: imageData) { let outputRect = self.previewLayer.metadataOutputRectOfInterest(for: self.previewLayer.bounds) let takenCGImage = takenImage.cgImage! let width = CGFloat(takenCGImage.width) let height = CGFloat(takenCGImage.height) let cropRect = CGRect(x: outputRect.origin.x * width, y: outputRect.origin.y * height, width: outputRect.size.width * width, height: outputRect.size.height * height) let cropCGImage = takenCGImage.cropping(to: cropRect) let cropTakenImage = UIImage(cgImage: cropCGImage!, scale: 1, orientation: takenImage.imageOrientation) didFinishCapturingImage(cropTakenImage, imageData) self.captureButton.isEnabled = true } } else { print("error while capturing still image: \(error!.localizedDescription)", terminator: "") } }) } }) } } // MARK: - Handles Zoom open func handleZoom(_ gesture: UIPinchGestureRecognizer) { if gesture.state == .began { self.beginZoomScale = self.zoomScale } else if gesture.state == .changed { self.zoomScale = min(4.0, max(1.0, self.beginZoomScale * gesture.scale)) CATransaction.begin() CATransaction.setAnimationDuration(0.025) self.previewLayer.setAffineTransform(CGAffineTransform(scaleX: self.zoomScale, y: self.zoomScale)) CATransaction.commit() } } // MARK: - Handles Focus open func handleFocus(_ gesture: UITapGestureRecognizer) { if let currentDevice = self.currentDevice , currentDevice.isFocusPointOfInterestSupported { let touchPoint = gesture.location(in: self.view) self.focusAtTouchPoint(touchPoint) } } open func focusAtTouchPoint(_ touchPoint: CGPoint) { func showFocusViewAtPoint(_ touchPoint: CGPoint) { struct FocusView { static let focusView: UIView = { let focusView = UIView() let diameter: CGFloat = 100 focusView.bounds.size = CGSize(width: diameter, height: diameter) focusView.layer.borderWidth = 2 focusView.layer.cornerRadius = diameter / 2 focusView.layer.borderColor = UIColor.white.cgColor return focusView }() } FocusView.focusView.transform = CGAffineTransform.identity FocusView.focusView.center = touchPoint self.view.addSubview(FocusView.focusView) UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.1, options: UIViewAnimationOptions(), animations: { () -> Void in FocusView.focusView.transform = CGAffineTransform.identity.scaledBy(x: 0.6, y: 0.6) }) { (Bool) -> Void in FocusView.focusView.removeFromSuperview() } } if self.currentDevice == nil || self.currentDevice?.isFlashAvailable == false { return } let focusPoint = self.previewLayer.captureDevicePointOfInterest(for: touchPoint) showFocusViewAtPoint(touchPoint) if let currentDevice = self.currentDevice { try! currentDevice.lockForConfiguration() currentDevice.focusPointOfInterest = focusPoint currentDevice.exposurePointOfInterest = focusPoint currentDevice.focusMode = .continuousAutoFocus if currentDevice.isExposureModeSupported(.continuousAutoExposure) { currentDevice.exposureMode = .continuousAutoExposure } currentDevice.unlockForConfiguration() } } // MARK: - Handles Switch Camera internal func switchCamera() { self.currentDevice = self.currentDevice == self.captureDeviceRear ? self.captureDeviceFront : self.captureDeviceRear self.setupCurrentDevice() } // MARK: - Handles Flash internal func switchFlashMode() { switch self.flashMode! { case .auto: self.flashMode = .off case .on: self.flashMode = .auto case .off: self.flashMode = .on } } open func flashModeFromUserDefaults() -> AVCaptureFlashMode { let rawValue = UserDefaults.standard.integer(forKey: "DKCamera.flashMode") return AVCaptureFlashMode(rawValue: rawValue)! } open func updateFlashModeToUserDefautls(_ flashMode: AVCaptureFlashMode) { UserDefaults.standard.set(flashMode.rawValue, forKey: "DKCamera.flashMode") } open func updateFlashButton() { struct FlashImage { let images: [AVCaptureFlashMode: UIImage] init(cameraResource: DKCameraResource) { self.images = [ AVCaptureFlashMode.auto : cameraResource.cameraFlashAutoImage(), AVCaptureFlashMode.on : cameraResource.cameraFlashOnImage(), AVCaptureFlashMode.off : cameraResource.cameraFlashOffImage() ] } } let flashImage: UIImage = FlashImage(cameraResource:cameraResource).images[self.flashMode]! self.flashButton.setImage(flashImage, for: .normal) self.flashButton.sizeToFit() } open func updateFlashMode() { if let currentDevice = self.currentDevice , currentDevice.isFlashAvailable && currentDevice.isFlashModeSupported(self.flashMode) { try! currentDevice.lockForConfiguration() currentDevice.flashMode = self.flashMode currentDevice.unlockForConfiguration() } } // MARK: - AVCaptureMetadataOutputObjectsDelegate public func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) { self.onFaceDetection?(metadataObjects as! [AVMetadataFaceObject]) } // MARK: - Handles Orientation open override var shouldAutorotate : Bool { return false } open func setupMotionManager() { self.motionManager.accelerometerUpdateInterval = 0.5 self.motionManager.gyroUpdateInterval = 0.5 } open func initialOriginalOrientationForOrientation() { self.originalOrientation = UIApplication.shared.statusBarOrientation.toDeviceOrientation() if let connection = self.previewLayer.connection { connection.videoOrientation = self.originalOrientation.toAVCaptureVideoOrientation() } } open func updateContentLayoutForCurrentOrientation() { let newAngle = self.currentOrientation.toAngleRelativeToPortrait() - self.originalOrientation.toAngleRelativeToPortrait() if self.allowsRotate { var contentViewNewSize: CGSize! let width = self.view.bounds.width let height = self.view.bounds.height if UIDeviceOrientationIsLandscape(self.currentOrientation) { contentViewNewSize = CGSize(width: max(width, height), height: min(width, height)) } else { contentViewNewSize = CGSize(width: min(width, height), height: max(width, height)) } UIView.animate(withDuration: 0.2, animations: { self.contentView.bounds.size = contentViewNewSize self.contentView.transform = CGAffineTransform(rotationAngle: newAngle) }) } else { let rotateAffineTransform = CGAffineTransform.identity.rotated(by: newAngle) UIView.animate(withDuration: 0.2, animations: { self.flashButton.transform = rotateAffineTransform self.cameraSwitchButton.transform = rotateAffineTransform }) } } } // MARK: - Utilities public extension UIInterfaceOrientation { func toDeviceOrientation() -> UIDeviceOrientation { switch self { case .portrait: return .portrait case .portraitUpsideDown: return .portraitUpsideDown case .landscapeRight: return .landscapeLeft case .landscapeLeft: return .landscapeRight default: return .portrait } } } public extension UIDeviceOrientation { func toAVCaptureVideoOrientation() -> AVCaptureVideoOrientation { switch self { case .portrait: return .portrait case .portraitUpsideDown: return .portraitUpsideDown case .landscapeRight: return .landscapeLeft case .landscapeLeft: return .landscapeRight default: return .portrait } } func toInterfaceOrientationMask() -> UIInterfaceOrientationMask { switch self { case .portrait: return .portrait case .portraitUpsideDown: return .portraitUpsideDown case .landscapeRight: return .landscapeLeft case .landscapeLeft: return .landscapeRight default: return .portrait } } func toAngleRelativeToPortrait() -> CGFloat { switch self { case .portrait: return 0 case .portraitUpsideDown: return CGFloat.pi case .landscapeRight: return -CGFloat.pi / 2.0 case .landscapeLeft: return CGFloat.pi / 2.0 default: return 0.0 } } } public extension CMAcceleration { func toDeviceOrientation() -> UIDeviceOrientation? { if self.x >= 0.75 { return .landscapeRight } else if self.x <= -0.75 { return .landscapeLeft } else if self.y <= -0.75 { return .portrait } else if self.y >= 0.75 { return .portraitUpsideDown } else { return nil } } } // MARK: - Rersources public extension Bundle { class func cameraBundle() -> Bundle { let assetPath = Bundle(for: DKDefaultCameraResource.self).resourcePath! return Bundle(path: (assetPath as NSString).appendingPathComponent("DKCameraResource.bundle"))! } } open class DKDefaultCameraResource: DKCameraResource { open func imageForResource(_ name: String) -> UIImage { let bundle = Bundle.cameraBundle() let imagePath = bundle.path(forResource: name, ofType: "png", inDirectory: "Images") let image = UIImage(contentsOfFile: imagePath!) return image! } public func cameraCancelImage() -> UIImage { return imageForResource("camera_cancel") } public func cameraFlashOnImage() -> UIImage { return imageForResource("camera_flash_on") } public func cameraFlashAutoImage() -> UIImage { return imageForResource("camera_flash_auto") } public func cameraFlashOffImage() -> UIImage { return imageForResource("camera_flash_off") } public func cameraSwitchImage() -> UIImage { return imageForResource("camera_switch") } }
mit
b0bc2c9bf9be8b6decd7ee378d86d848
36.54075
197
0.602915
5.777225
false
false
false
false
abertelrud/swift-package-manager
Tests/BuildTests/BuildPlanTests.swift
1
200290
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2014-2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Basics @testable import Build import PackageLoading @testable import PackageGraph @testable import PackageModel import SPMBuildCore import SPMTestSupport import SwiftDriver import TSCBasic import Workspace import XCTest import enum TSCUtility.Diagnostics import struct TSCUtility.Triple final class BuildPlanTests: XCTestCase { let inputsDir = AbsolutePath(path: #file).parentDirectory.appending(components: "Inputs") /// The j argument. private var j: String { return "-j3" } func testDuplicateProductNamesWithNonDefaultLibsThrowError() throws { let fs = InMemoryFileSystem(emptyFiles: "/thisPkg/Sources/exe/main.swift", "/fooPkg/Sources/FooLogging/file.swift", "/barPkg/Sources/BarLogging/file.swift" ) let observability = ObservabilitySystem.makeForTesting() XCTAssertThrowsError(try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createFileSystemManifest( name: "fooPkg", path: .init(path: "/fooPkg"), products: [ ProductDescription(name: "Logging", type: .library(.dynamic), targets: ["FooLogging"]), ], targets: [ TargetDescription(name: "FooLogging", dependencies: []), ]), Manifest.createFileSystemManifest( name: "barPkg", path: .init(path: "/barPkg"), products: [ ProductDescription(name: "Logging", type: .library(.static), targets: ["BarLogging"]), ], targets: [ TargetDescription(name: "BarLogging", dependencies: []), ]), Manifest.createRootManifest( name: "thisPkg", path: .init(path: "/thisPkg"), toolsVersion: .vNext, dependencies: [ .localSourceControl(path: .init(path: "/fooPkg"), requirement: .upToNextMajor(from: "1.0.0")), .localSourceControl(path: .init(path: "/barPkg"), requirement: .upToNextMajor(from: "2.0.0")), ], targets: [ TargetDescription(name: "exe", dependencies: [.product(name: "Logging", package: "fooPkg" ), .product(name: "Logging", package: "barPkg" ), ], type: .executable), ]), ], observabilityScope: observability.topScope )) { error in var diagnosed = false if let realError = error as? PackageGraphError, realError.description == "multiple products named 'Logging' in: 'barpkg', 'foopkg'" { diagnosed = true } XCTAssertTrue(diagnosed) } } func testDuplicateProductNamesWithADylib() throws { let fs = InMemoryFileSystem(emptyFiles: "/thisPkg/Sources/exe/main.swift", "/fooPkg/Sources/FooLogging/file.swift", "/barPkg/Sources/BarLogging/file.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createFileSystemManifest( name: "fooPkg", path: .init(path: "/fooPkg"), products: [ ProductDescription(name: "Logging", type: .library(.dynamic), targets: ["FooLogging"]), ], targets: [ TargetDescription(name: "FooLogging", dependencies: []), ]), Manifest.createFileSystemManifest( name: "barPkg", path: .init(path: "/barPkg"), products: [ ProductDescription(name: "Logging", type: .library(.automatic), targets: ["BarLogging"]), ], targets: [ TargetDescription(name: "BarLogging", dependencies: []), ]), Manifest.createRootManifest( name: "thisPkg", path: .init(path: "/thisPkg"), toolsVersion: .vNext, dependencies: [ .localSourceControl(path: .init(path: "/fooPkg"), requirement: .upToNextMajor(from: "1.0.0")), .localSourceControl(path: .init(path: "/barPkg"), requirement: .upToNextMajor(from: "2.0.0")), ], targets: [ TargetDescription(name: "exe", dependencies: [.product(name: "Logging", package: "fooPkg" ), .product(name: "Logging", package: "barPkg" ), ], type: .executable), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: try BuildPlan( buildParameters: mockBuildParameters(shouldLinkStaticSwiftStdlib: true), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(2) result.checkTargetsCount(3) XCTAssertTrue(result.targetMap.values.contains { $0.target.name == "FooLogging" }) XCTAssertTrue(result.targetMap.values.contains { $0.target.name == "BarLogging" }) } func testDuplicateProductNamesUpstream1() throws { let fs = InMemoryFileSystem(emptyFiles: "/thisPkg/Sources/exe/main.swift", "/fooPkg/Sources/FooLogging/file.swift", "/barPkg/Sources/BarLogging/file.swift", "/bazPkg/Sources/BazLogging/file.swift", "/xPkg/Sources/XUtils/file.swift", "/yPkg/Sources/YUtils/file.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createFileSystemManifest( name: "bazPkg", path: .init(path: "/bazPkg"), products: [ ProductDescription(name: "Logging", type: .library(.automatic), targets: ["BazLogging"]), ], targets: [ TargetDescription(name: "BazLogging", dependencies: []), ]), Manifest.createFileSystemManifest( name: "barPkg", path: .init(path: "/barPkg"), products: [ ProductDescription(name: "Logging", type: .library(.automatic), targets: ["BarLogging"]), ], targets: [ TargetDescription(name: "BarLogging", dependencies: []), ]), Manifest.createFileSystemManifest( name: "fooPkg", path: .init(path: "/fooPkg"), toolsVersion: .vNext, dependencies: [ .localSourceControl(path: .init(path: "/barPkg"), requirement: .upToNextMajor(from: "1.0.0")), .localSourceControl(path: .init(path: "/bazPkg"), requirement: .upToNextMajor(from: "1.0.0")), ], products: [ ProductDescription(name: "Logging", type: .library(.automatic), targets: ["FooLogging"]), ], targets: [ TargetDescription(name: "FooLogging", dependencies: [.product(name: "Logging", package: "barPkg" ), .product(name: "Logging", package: "bazPkg" ), ]), ]), Manifest.createFileSystemManifest( name: "xPkg", path: .init(path: "/xPkg"), products: [ ProductDescription(name: "Utils", type: .library(.automatic), targets: ["XUtils"]), ], targets: [ TargetDescription(name: "XUtils", dependencies: []), ]), Manifest.createFileSystemManifest( name: "yPkg", path: .init(path: "/yPkg"), products: [ ProductDescription(name: "Utils", type: .library(.automatic), targets: ["YUtils"]), ], targets: [ TargetDescription(name: "YUtils", dependencies: []), ]), Manifest.createRootManifest( name: "thisPkg", path: .init(path: "/thisPkg"), toolsVersion: .vNext, dependencies: [ .localSourceControl(path: .init(path: "/xPkg"), requirement: .upToNextMajor(from: "1.0.0")), .localSourceControl(path: .init(path: "/yPkg"), requirement: .upToNextMajor(from: "1.0.0")), .localSourceControl(path: .init(path: "/fooPkg"), requirement: .upToNextMajor(from: "1.0.0")), ], targets: [ TargetDescription(name: "exe", dependencies: [.product(name: "Logging", package: "fooPkg" ), .product(name: "Utils", package: "xPkg" ), .product(name: "Utils", package: "yPkg" ), ], type: .executable), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: try BuildPlan( buildParameters: mockBuildParameters(shouldLinkStaticSwiftStdlib: true), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(6) XCTAssertTrue(result.targetMap.values.contains { $0.target.name == "FooLogging" }) XCTAssertTrue(result.targetMap.values.contains { $0.target.name == "BarLogging" }) XCTAssertTrue(result.targetMap.values.contains { $0.target.name == "BazLogging" }) XCTAssertTrue(result.targetMap.values.contains { $0.target.name == "XUtils" }) XCTAssertTrue(result.targetMap.values.contains { $0.target.name == "YUtils" }) } func testDuplicateProductNamesUpstream2() throws { let fs = InMemoryFileSystem(emptyFiles: "/thisPkg/Sources/exe/main.swift", "/fooPkg/Sources/Logging/file.swift", "/barPkg/Sources/BarLogging/file.swift", "/bazPkg/Sources/BazLogging/file.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createFileSystemManifest( name: "bazPkg", path: .init(path: "/bazPkg"), products: [ ProductDescription(name: "Logging", type: .library(.automatic), targets: ["BazLogging"]), ], targets: [ TargetDescription(name: "BazLogging", dependencies: []), ]), Manifest.createFileSystemManifest( name: "barPkg", path: .init(path: "/barPkg"), products: [ ProductDescription(name: "Logging", type: .library(.automatic), targets: ["BarLogging"]), ], targets: [ TargetDescription(name: "BarLogging", dependencies: []), ]), Manifest.createFileSystemManifest( name: "fooPkg", path: .init(path: "/fooPkg"), toolsVersion: .vNext, dependencies: [ .localSourceControl(path: .init(path: "/barPkg"), requirement: .upToNextMajor(from: "1.0.0")), .localSourceControl(path: .init(path: "/bazPkg"), requirement: .upToNextMajor(from: "1.0.0")), ], products: [ ProductDescription(name: "Logging", type: .library(.automatic), targets: ["Logging"]), ], targets: [ TargetDescription(name: "Logging", dependencies: [.product(name: "Logging", package: "barPkg" ), .product(name: "Logging", package: "bazPkg" ), ]), ]), Manifest.createRootManifest( name: "thisPkg", path: .init(path: "/thisPkg"), dependencies: [ .localSourceControl(path: .init(path: "/fooPkg"), requirement: .upToNextMajor(from: "1.0.0")), ], targets: [ TargetDescription(name: "exe", dependencies: [.product(name: "Logging", package: "fooPkg" ), ], type: .executable), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: try BuildPlan( buildParameters: mockBuildParameters(shouldLinkStaticSwiftStdlib: true), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(4) XCTAssertTrue(result.targetMap.values.contains { $0.target.name == "Logging" }) XCTAssertTrue(result.targetMap.values.contains { $0.target.name == "BarLogging" }) XCTAssertTrue(result.targetMap.values.contains { $0.target.name == "BazLogging" }) } func testDuplicateProductNamesChained() throws { let fs = InMemoryFileSystem(emptyFiles: "/thisPkg/Sources/exe/main.swift", "/fooPkg/Sources/FooLogging/file.swift", "/barPkg/Sources/BarLogging/file.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createFileSystemManifest( name: "fooPkg", path: .init(path: "/fooPkg"), toolsVersion: .vNext, dependencies: [ .localSourceControl(path: .init(path: "/barPkg"), requirement: .upToNextMajor(from: "1.0.0")), ], products: [ ProductDescription(name: "Logging", type: .library(.automatic), targets: ["FooLogging"]), ], targets: [ TargetDescription(name: "FooLogging", dependencies: [.product(name: "Logging", package: "barPkg" ), ]), ]), Manifest.createFileSystemManifest( name: "barPkg", path: .init(path: "/barPkg"), products: [ ProductDescription(name: "Logging", type: .library(.automatic), targets: ["BarLogging"]), ], targets: [ TargetDescription(name: "BarLogging", dependencies: []), ]), Manifest.createRootManifest( name: "thisPkg", path: .init(path: "/thisPkg"), dependencies: [ .localSourceControl(path: .init(path: "/fooPkg"), requirement: .upToNextMajor(from: "1.0.0")), ], targets: [ TargetDescription(name: "exe", dependencies: [.product(name: "Logging", package: "fooPkg" ), ], type: .executable), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: try BuildPlan( buildParameters: mockBuildParameters(shouldLinkStaticSwiftStdlib: true), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(3) XCTAssertTrue(result.targetMap.values.contains { $0.target.name == "FooLogging" }) XCTAssertTrue(result.targetMap.values.contains { $0.target.name == "BarLogging" }) } func testDuplicateProductNamesThrowError() throws { let fs = InMemoryFileSystem(emptyFiles: "/thisPkg/Sources/exe/main.swift", "/fooPkg/Sources/FooLogging/file.swift", "/barPkg/Sources/BarLogging/file.swift" ) let observability = ObservabilitySystem.makeForTesting() XCTAssertThrowsError(try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createFileSystemManifest( name: "fooPkg", path: .init(path: "/fooPkg"), toolsVersion: .vNext, products: [ ProductDescription(name: "Logging", type: .library(.automatic), targets: ["FooLogging"]), ], targets: [ TargetDescription(name: "FooLogging", dependencies: []), ]), Manifest.createFileSystemManifest( name: "barPkg", path: .init(path: "/barPkg"), products: [ ProductDescription(name: "Logging", type: .library(.automatic), targets: ["BarLogging"]), ], targets: [ TargetDescription(name: "BarLogging", dependencies: []), ]), Manifest.createRootManifest( name: "thisPkg", path: .init(path: "/thisPkg"), dependencies: [ .localSourceControl(path: .init(path: "/fooPkg"), requirement: .upToNextMajor(from: "1.0.0")), .localSourceControl(path: .init(path: "/barPkg"), requirement: .upToNextMajor(from: "2.0.0")), ], targets: [ TargetDescription(name: "exe", dependencies: [.product(name: "Logging", package: "fooPkg" ), .product(name: "Logging", package: "barPkg" ), ], type: .executable), ]), ], observabilityScope: observability.topScope )) { error in var diagnosed = false if let realError = error as? PackageGraphError, realError.description == "multiple products named 'Logging' in: 'barpkg', 'foopkg'" { diagnosed = true } XCTAssertTrue(diagnosed) } } func testDuplicateProductNamesAllowed() throws { let fs = InMemoryFileSystem(emptyFiles: "/thisPkg/Sources/exe/main.swift", "/fooPkg/Sources/FooLogging/file.swift", "/barPkg/Sources/BarLogging/file.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createFileSystemManifest( name: "fooPkg", path: .init(path: "/fooPkg"), products: [ ProductDescription(name: "Logging", type: .library(.automatic), targets: ["FooLogging"]), ], targets: [ TargetDescription(name: "FooLogging", dependencies: []), ]), Manifest.createFileSystemManifest( name: "barPkg", path: .init(path: "/barPkg"), products: [ ProductDescription(name: "Logging", type: .library(.automatic), targets: ["BarLogging"]), ], targets: [ TargetDescription(name: "BarLogging", dependencies: []), ]), Manifest.createRootManifest( name: "thisPkg", path: .init(path: "/thisPkg"), toolsVersion: .vNext, dependencies: [ .localSourceControl(path: .init(path: "/fooPkg"), requirement: .upToNextMajor(from: "1.0.0")), .localSourceControl(path: .init(path: "/barPkg"), requirement: .upToNextMajor(from: "2.0.0")), ], targets: [ TargetDescription(name: "exe", dependencies: [.product(name: "Logging", package: "fooPkg" ), .product(name: "Logging", package: "barPkg" ), ], type: .executable), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: try BuildPlan( buildParameters: mockBuildParameters(shouldLinkStaticSwiftStdlib: true), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(3) XCTAssertTrue(result.targetMap.values.contains { $0.target.name == "FooLogging" }) XCTAssertTrue(result.targetMap.values.contains { $0.target.name == "BarLogging" }) } func testBasicSwiftPackage() throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift", "/Pkg/Sources/lib/lib.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), targets: [ TargetDescription(name: "exe", dependencies: ["lib"]), TargetDescription(name: "lib", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(shouldLinkStaticSwiftStdlib: true), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(2) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-enable-testing", "-g", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) let lib = try result.target(for: "lib").swiftTarget().compileArguments() XCTAssertMatch(lib, ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-enable-testing", "-g", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) #if os(macOS) let linkArguments = [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "-rpath", "-Xlinker", "@loader_path", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-Xlinker", "-rpath", "-Xlinker", "/fake/path/lib/swift-5.5/macosx", "-target", defaultTargetTriple, "-Xlinker", "-add_ast_path", "-Xlinker", buildPath.appending(components: "exe.build", "exe.swiftmodule").pathString, "-Xlinker", "-add_ast_path", "-Xlinker", buildPath.appending(components: "lib.swiftmodule").pathString, ] #elseif os(Windows) let linkArguments = [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe.exe").pathString, "-module-name", "exe", // "-static-stdlib", "-emit-executable", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ] #else let linkArguments = [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-static-stdlib", "-emit-executable", "-Xlinker", "-rpath=$ORIGIN", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ] #endif XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), linkArguments) #if os(macOS) testDiagnostics(observability.diagnostics) { result in result.check(diagnostic: .contains("can be downloaded"), severity: .warning) } #else XCTAssertNoDiagnostics(observability.diagnostics) #endif } func testExplicitSwiftPackageBuild() throws { // <rdar://82053045> Fix and re-enable SwiftPM test `testExplicitSwiftPackageBuild` try XCTSkipIf(true) try withTemporaryDirectory { path in // Create a test package with three targets: // A -> B -> C let fs = localFileSystem try fs.changeCurrentWorkingDirectory(to: path) let testDirPath = path.appending(component: "ExplicitTest") let buildDirPath = path.appending(component: ".build") let sourcesPath = testDirPath.appending(component: "Sources") let aPath = sourcesPath.appending(component: "A") let bPath = sourcesPath.appending(component: "B") let cPath = sourcesPath.appending(component: "C") try fs.createDirectory(testDirPath) try fs.createDirectory(buildDirPath) try fs.createDirectory(sourcesPath) try fs.createDirectory(aPath) try fs.createDirectory(bPath) try fs.createDirectory(cPath) let main = aPath.appending(component: "main.swift") let aSwift = aPath.appending(component: "A.swift") let bSwift = bPath.appending(component: "B.swift") let cSwift = cPath.appending(component: "C.swift") try localFileSystem.writeFileContents(main) { $0 <<< "baz();" } try localFileSystem.writeFileContents(aSwift) { $0 <<< "import B;" $0 <<< "import C;" $0 <<< "public func baz() { bar() }" } try localFileSystem.writeFileContents(bSwift) { $0 <<< "import C;" $0 <<< "public func bar() { foo() }" } try localFileSystem.writeFileContents(cSwift) { $0 <<< "public func foo() {}" } // Plan package build with explicit module build let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "ExplicitTest", path: testDirPath, targets: [ TargetDescription(name: "A", dependencies: ["B"]), TargetDescription(name: "B", dependencies: ["C"]), TargetDescription(name: "C", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) do { let plan = try BuildPlan( buildParameters: mockBuildParameters( buildPath: buildDirPath, config: .release, toolchain: UserToolchain.default, destinationTriple: UserToolchain.default.triple, useExplicitModuleBuild: true ), graph: graph, fileSystem: fs, observabilityScope: observability.topScope ) let yaml = buildDirPath.appending(component: "release.yaml") let llbuild = LLBuildManifestBuilder(plan, fileSystem: localFileSystem, observabilityScope: observability.topScope) try llbuild.generateManifest(at: yaml) let contents: String = try localFileSystem.readFileContents(yaml) // A few basic checks XCTAssertMatch(contents, .contains("-disable-implicit-swift-modules")) XCTAssertMatch(contents, .contains("-fno-implicit-modules")) XCTAssertMatch(contents, .contains("-explicit-swift-module-map-file")) XCTAssertMatch(contents, .contains("A-dependencies")) XCTAssertMatch(contents, .contains("B-dependencies")) XCTAssertMatch(contents, .contains("C-dependencies")) } catch Driver.Error.unableToDecodeFrontendTargetInfo { // If the toolchain being used is sufficiently old, the integrated driver // will not be able to parse the `-print-target-info` output. In which case, // we cannot yet rely on the integrated swift driver. // This effectively guards the test from running on unsupported, older toolchains. throw XCTSkip() } } } func testSwiftConditionalDependency() throws { let Pkg: AbsolutePath = AbsolutePath(path: "/Pkg") let fs = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "exe", "main.swift").pathString, Pkg.appending(components: "Sources", "PkgLib", "lib.swift").pathString, "/ExtPkg/Sources/ExtLib/lib.swift", "/PlatformPkg/Sources/PlatformLib/lib.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: try .init(validating: Pkg.pathString), dependencies: [ .localSourceControl(path: .init(path: "/ExtPkg"), requirement: .upToNextMajor(from: "1.0.0")), .localSourceControl(path: .init(path: "/PlatformPkg"), requirement: .upToNextMajor(from: "1.0.0")), ], targets: [ TargetDescription(name: "exe", dependencies: [ .target(name: "PkgLib", condition: PackageConditionDescription( platformNames: ["linux", "android"], config: nil )) ]), TargetDescription(name: "PkgLib", dependencies: [ .product(name: "ExtLib", package: "ExtPkg", condition: PackageConditionDescription( platformNames: [], config: "debug" )), .product(name: "PlatformLib", package: "PlatformPkg", condition: PackageConditionDescription( platformNames: ["linux"] )) ]), ] ), Manifest.createLocalSourceControlManifest( name: "ExtPkg", path: .init(path: "/ExtPkg"), products: [ ProductDescription(name: "ExtLib", type: .library(.automatic), targets: ["ExtLib"]), ], targets: [ TargetDescription(name: "ExtLib", dependencies: []), ] ), Manifest.createLocalSourceControlManifest( name: "PlatformPkg", path: .init(path: "/PlatformPkg"), platforms: [PlatformDescription(name: "macos", version: "50.0")], products: [ ProductDescription(name: "PlatformLib", type: .library(.automatic), targets: ["PlatformLib"]), ], targets: [ TargetDescription(name: "PlatformLib", dependencies: []), ] ), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) do { let plan = try BuildPlan( buildParameters: mockBuildParameters(environment: BuildEnvironment( platform: .linux, configuration: .release )), graph: graph, fileSystem: fs, observabilityScope: observability.topScope ) let buildPath: AbsolutePath = plan.buildParameters.dataPath.appending(components: "release") let linkedFileList: String = try fs.readFileContents(AbsolutePath(path: "/path/to/build/release/exe.product/Objects.LinkFileList")) XCTAssertMatch(linkedFileList, .contains("PkgLib")) XCTAssertNoMatch(linkedFileList, .contains("ExtLib")) let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, "release.yaml") try fs.createDirectory(yaml.parentDirectory, recursive: true) let llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope) try llbuild.generateManifest(at: yaml) let contents: String = try fs.readFileContents(yaml) XCTAssertMatch(contents, .contains(""" inputs: ["\(Pkg.appending(components: "Sources", "exe", "main.swift").escapedPathString())","\(buildPath.appending(components: "PkgLib.swiftmodule").escapedPathString())"] """)) } do { let plan = try BuildPlan( buildParameters: mockBuildParameters(environment: BuildEnvironment( platform: .macOS, configuration: .debug )), graph: graph, fileSystem: fs, observabilityScope: observability.topScope ) let linkedFileList: String = try fs.readFileContents(AbsolutePath(path: "/path/to/build/debug/exe.product/Objects.LinkFileList")) XCTAssertNoMatch(linkedFileList, .contains("PkgLib")) XCTAssertNoMatch(linkedFileList, .contains("ExtLib")) let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, "debug.yaml") try fs.createDirectory(yaml.parentDirectory, recursive: true) let llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope) try llbuild.generateManifest(at: yaml) let contents: String = try fs.readFileContents(yaml) XCTAssertMatch(contents, .contains(""" inputs: ["\(Pkg.appending(components: "Sources", "exe", "main.swift").escapedPathString())"] """)) } } func testBasicExtPackages() throws { let fileSystem = InMemoryFileSystem(emptyFiles: "/A/Sources/ATarget/foo.swift", "/A/Tests/ATargetTests/foo.swift", "/B/Sources/BTarget/foo.swift", "/B/Tests/BTargetTests/foo.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fileSystem, manifests: [ Manifest.createRootManifest( name: "A", path: .init(path: "/A"), dependencies: [ .localSourceControl(path: .init(path: "/B"), requirement: .upToNextMajor(from: "1.0.0")), ], targets: [ TargetDescription(name: "ATarget", dependencies: ["BLibrary"]), TargetDescription(name: "ATargetTests", dependencies: ["ATarget"], type: .test), ]), Manifest.createFileSystemManifest( name: "B", path: .init(path: "/B"), products: [ ProductDescription(name: "BLibrary", type: .library(.automatic), targets: ["BTarget"]), ], targets: [ TargetDescription(name: "BTarget", dependencies: []), TargetDescription(name: "BTargetTests", dependencies: ["BTarget"], type: .test), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fileSystem, observabilityScope: observability.topScope )) XCTAssertEqual(Set(result.productMap.keys), ["APackageTests"]) #if os(macOS) XCTAssertEqual(Set(result.targetMap.keys), ["ATarget", "BTarget", "ATargetTests"]) #else XCTAssertEqual(Set(result.targetMap.keys), [ "APackageTests", "APackageDiscoveredTests", "ATarget", "ATargetTests", "BTarget" ]) #endif } func testBasicReleasePackage() throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), targets: [ TargetDescription(name: "exe", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(config: .release), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(1) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "release") let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, ["-swift-version", "4", "-O", "-g", .equal(j), "-DSWIFT_PACKAGE", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) #if os(macOS) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-g", "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "-dead_strip", "-Xlinker", "-rpath", "-Xlinker", "@loader_path", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-Xlinker", "-rpath", "-Xlinker", "/fake/path/lib/swift-5.5/macosx", "-target", defaultTargetTriple, ]) #elseif os(Windows) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-Xlinker", "-debug", "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe.exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "/OPT:REF", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ]) #else XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-g", "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "--gc-sections", "-Xlinker", "-rpath=$ORIGIN", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ]) #endif } func testBasicReleasePackageNoDeadStrip() throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), targets: [ TargetDescription(name: "exe", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(config: .release, linkerDeadStrip: false), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(1) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "release") let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, ["-swift-version", "4", "-O", "-g", .equal(j), "-DSWIFT_PACKAGE", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) #if os(macOS) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-g", "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "-rpath", "-Xlinker", "@loader_path", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-Xlinker", "-rpath", "-Xlinker", "/fake/path/lib/swift-5.5/macosx", "-target", defaultTargetTriple, ]) #elseif os(Windows) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-Xlinker", "-debug", "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe.exe").pathString, "-module-name", "exe", "-emit-executable", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ]) #else XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-g", "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "-rpath=$ORIGIN", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ]) #endif } func testBasicClangPackage() throws { let Pkg: AbsolutePath = AbsolutePath(path: "/Pkg") let ExtPkg: AbsolutePath = AbsolutePath(path: "/ExtPkg") let fs = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "exe", "main.c").pathString, Pkg.appending(components: "Sources", "lib", "lib.c").pathString, Pkg.appending(components: "Sources", "lib", "lib.S").pathString, Pkg.appending(components: "Sources", "lib", "include", "lib.h").pathString, ExtPkg.appending(components: "Sources", "extlib", "extlib.c").pathString, ExtPkg.appending(components: "Sources", "extlib", "include", "ext.h").pathString ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: try .init(validating: Pkg.pathString), dependencies: [ .localSourceControl(path: try .init(validating: ExtPkg.pathString), requirement: .upToNextMajor(from: "1.0.0")), ], targets: [ TargetDescription(name: "exe", dependencies: ["lib"]), TargetDescription(name: "lib", dependencies: ["ExtPkg"]), ]), Manifest.createFileSystemManifest( name: "ExtPkg", path: try .init(validating: ExtPkg.pathString), products: [ ProductDescription(name: "ExtPkg", type: .library(.automatic), targets: ["extlib"]), ], targets: [ TargetDescription(name: "extlib", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(3) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let ext = try result.target(for: "extlib").clangTarget() var args: [String] = [] #if os(macOS) args += ["-fobjc-arc"] #endif args += ["-target", defaultTargetTriple] args += ["-g"] #if os(Windows) args += ["-gcodeview"] #endif args += ["-O0", "-DSWIFT_PACKAGE=1", "-DDEBUG=1"] args += ["-fblocks"] #if !os(Windows) // FIXME(5473) - modules flags on Windows dropped args += ["-fmodules", "-fmodule-name=extlib"] #endif args += ["-I", ExtPkg.appending(components: "Sources", "extlib", "include").pathString] #if !os(Windows) // FIXME(5473) - modules flags on Windows dropped args += ["-fmodules-cache-path=\(buildPath.appending(components: "ModuleCache"))"] #endif XCTAssertEqual(try ext.basicArguments(isCXX: false), args) XCTAssertEqual(try ext.objects, [buildPath.appending(components: "extlib.build", "extlib.c.o")]) XCTAssertEqual(ext.moduleMap, buildPath.appending(components: "extlib.build", "module.modulemap")) let exe = try result.target(for: "exe").clangTarget() args = [] #if os(macOS) args += ["-fobjc-arc", "-target", defaultTargetTriple] #else args += ["-target", defaultTargetTriple] #endif args += ["-g"] #if os(Windows) args += ["-gcodeview"] #endif args += ["-O0", "-DSWIFT_PACKAGE=1", "-DDEBUG=1"] args += ["-fblocks"] #if !os(Windows) // FIXME(5473) - modules flags on Windows dropped args += ["-fmodules", "-fmodule-name=exe"] #endif args += [ "-I", Pkg.appending(components: "Sources", "exe", "include").pathString, "-I", Pkg.appending(components: "Sources", "lib", "include").pathString, "-fmodule-map-file=\(buildPath.appending(components: "lib.build", "module.modulemap"))", "-I", ExtPkg.appending(components: "Sources", "extlib", "include").pathString, "-fmodule-map-file=\(buildPath.appending(components: "extlib.build", "module.modulemap"))", ] #if !os(Windows) // FIXME(5473) - modules flags on Windows dropped args += ["-fmodules-cache-path=\(buildPath.appending(components: "ModuleCache"))"] #endif XCTAssertEqual(try exe.basicArguments(isCXX: false), args) XCTAssertEqual(try exe.objects, [buildPath.appending(components: "exe.build", "main.c.o")]) XCTAssertEqual(exe.moduleMap, nil) #if os(macOS) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "-rpath", "-Xlinker", "@loader_path", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-runtime-compatibility-version", "none", "-target", defaultTargetTriple, ]) #elseif os(Windows) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe.exe").pathString, "-module-name", "exe", "-emit-executable", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-runtime-compatibility-version", "none", "-target", defaultTargetTriple, ]) #else XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "-rpath=$ORIGIN", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-runtime-compatibility-version", "none", "-target", defaultTargetTriple, ]) #endif let linkedFileList: String = try fs.readFileContents(buildPath.appending(components: "exe.product", "Objects.LinkFileList")) XCTAssertEqual(linkedFileList, """ \(buildPath.appending(components: "exe.build", "main.c.o")) \(buildPath.appending(components: "extlib.build", "extlib.c.o")) \(buildPath.appending(components: "lib.build", "lib.c.o")) """) } func testClangConditionalDependency() throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.c", "/Pkg/Sources/PkgLib/lib.c", "/Pkg/Sources/PkgLib/lib.S", "/Pkg/Sources/PkgLib/include/lib.h", "/ExtPkg/Sources/ExtLib/extlib.c", "/ExtPkg/Sources/ExtLib/include/ext.h" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), dependencies: [ .localSourceControl(path: .init(path: "/ExtPkg"), requirement: .upToNextMajor(from: "1.0.0")), ], targets: [ TargetDescription(name: "exe", dependencies: [ .target(name: "PkgLib", condition: PackageConditionDescription( platformNames: ["linux", "android"], config: nil )) ]), TargetDescription(name: "PkgLib", dependencies: [ .product(name: "ExtPkg", package: "ExtPkg", condition: PackageConditionDescription( platformNames: [], config: "debug" )) ]), ]), Manifest.createLocalSourceControlManifest( name: "ExtPkg", path: .init(path: "/ExtPkg"), products: [ ProductDescription(name: "ExtPkg", type: .library(.automatic), targets: ["ExtLib"]), ], targets: [ TargetDescription(name: "ExtLib", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) do { let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(environment: BuildEnvironment( platform: .linux, configuration: .release )), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) let exeArguments = try result.target(for: "exe").clangTarget().basicArguments(isCXX: false) XCTAssert(exeArguments.contains { $0.contains("PkgLib") }) XCTAssert(exeArguments.allSatisfy { !$0.contains("ExtLib") }) let libArguments = try result.target(for: "PkgLib").clangTarget().basicArguments(isCXX: false) XCTAssert(libArguments.allSatisfy { !$0.contains("ExtLib") }) } do { let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(environment: BuildEnvironment( platform: .macOS, configuration: .debug )), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) let arguments = try result.target(for: "exe").clangTarget().basicArguments(isCXX: false) XCTAssert(arguments.allSatisfy { !$0.contains("PkgLib") && !$0.contains("ExtLib") }) let libArguments = try result.target(for: "PkgLib").clangTarget().basicArguments(isCXX: false) XCTAssert(libArguments.contains { $0.contains("ExtLib") }) } } func testCLanguageStandard() throws { let Pkg: AbsolutePath = AbsolutePath(path: "/Pkg") let fs = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "exe", "main.cpp").pathString, Pkg.appending(components: "Sources", "lib", "lib.c").pathString, Pkg.appending(components: "Sources", "lib", "libx.cpp").pathString, Pkg.appending(components: "Sources", "lib", "include", "lib.h").pathString ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: try .init(validating: Pkg.pathString), cLanguageStandard: "gnu99", cxxLanguageStandard: "c++1z", targets: [ TargetDescription(name: "exe", dependencies: ["lib"]), TargetDescription(name: "lib", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let plan = try BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope ) let result = try BuildPlanResult(plan: plan) result.checkProductsCount(1) result.checkTargetsCount(2) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") #if os(macOS) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-lc++", "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "-rpath", "-Xlinker", "@loader_path", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-runtime-compatibility-version", "none", "-target", defaultTargetTriple, ]) #elseif os(Windows) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe.exe").pathString, "-module-name", "exe", "-emit-executable", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-runtime-compatibility-version", "none", "-target", defaultTargetTriple, ]) #else XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-lstdc++", "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "-rpath=$ORIGIN", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-runtime-compatibility-version", "none", "-target", defaultTargetTriple, ]) #endif let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, "debug.yaml") try fs.createDirectory(yaml.parentDirectory, recursive: true) let llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope) try llbuild.generateManifest(at: yaml) let contents: String = try fs.readFileContents(yaml) XCTAssertMatch(contents, .contains(#"-std=gnu99","-c","\#(Pkg.appending(components: "Sources", "lib", "lib.c").escapedPathString())"#)) XCTAssertMatch(contents, .contains(#"-std=c++1z","-c","\#(Pkg.appending(components: "Sources", "lib", "libx.cpp").escapedPathString())"#)) } func testSwiftCMixed() throws { let Pkg: AbsolutePath = AbsolutePath(path: "/Pkg") let fs = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "exe", "main.swift").pathString, Pkg.appending(components: "Sources", "lib", "lib.c").pathString, Pkg.appending(components: "Sources", "lib", "include", "lib.h").pathString ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: try .init(validating: Pkg.pathString), targets: [ TargetDescription(name: "exe", dependencies: ["lib"]), TargetDescription(name: "lib", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(2) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let lib = try result.target(for: "lib").clangTarget() var args: [String] = [] #if os(macOS) args += ["-fobjc-arc", "-target", defaultTargetTriple] #else args += ["-target", defaultTargetTriple] #endif args += ["-g"] #if os(Windows) args += ["-gcodeview"] #endif args += ["-O0", "-DSWIFT_PACKAGE=1", "-DDEBUG=1"] args += ["-fblocks"] #if !os(Windows) // FIXME(5473) - modules flags on Windows dropped args += ["-fmodules", "-fmodule-name=lib"] #endif args += ["-I", Pkg.appending(components: "Sources", "lib", "include").pathString] #if !os(Windows) // FIXME(5473) - modules flags on Windows dropped args += ["-fmodules-cache-path=\(buildPath.appending(components: "ModuleCache"))"] #endif XCTAssertEqual(try lib.basicArguments(isCXX: false), args) XCTAssertEqual(try lib.objects, [buildPath.appending(components: "lib.build", "lib.c.o")]) XCTAssertEqual(lib.moduleMap, buildPath.appending(components: "lib.build", "module.modulemap")) let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, [.anySequence, "-swift-version", "4", "-enable-batch-mode", "-Onone", "-enable-testing", "-g", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG","-Xcc", "-fmodule-map-file=\(buildPath.appending(components: "lib.build", "module.modulemap"))", "-Xcc", "-I", "-Xcc", "\(Pkg.appending(components: "Sources", "lib", "include"))", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) #if os(macOS) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "-rpath", "-Xlinker", "@loader_path", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-Xlinker", "-rpath", "-Xlinker", "/fake/path/lib/swift-5.5/macosx", "-target", defaultTargetTriple, "-Xlinker", "-add_ast_path", "-Xlinker", "/path/to/build/debug/exe.build/exe.swiftmodule", ]) #elseif os(Windows) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe.exe").pathString, "-module-name", "exe", "-emit-executable", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ]) #else XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "-rpath=$ORIGIN", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ]) #endif } func testSwiftCAsmMixed() throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift", "/Pkg/Sources/lib/lib.c", "/Pkg/Sources/lib/lib.S", "/Pkg/Sources/lib/include/lib.h" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), toolsVersion: .v5, targets: [ TargetDescription(name: "exe", dependencies: ["lib"]), TargetDescription(name: "lib", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(2) let lib = try result.target(for: "lib").clangTarget() XCTAssertEqual(try lib.objects, [ AbsolutePath(path: "/path/to/build/debug/lib.build/lib.S.o"), AbsolutePath(path: "/path/to/build/debug/lib.build/lib.c.o") ]) } func testREPLArguments() throws { let Dep: AbsolutePath = AbsolutePath(path: "/Dep") let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift", "/Pkg/Sources/swiftlib/lib.swift", "/Pkg/Sources/lib/lib.c", "/Pkg/Sources/lib/include/lib.h", Dep.appending(components: "Sources", "Dep", "dep.swift").pathString, Dep.appending(components: "Sources", "CDep", "cdep.c").pathString, Dep.appending(components: "Sources", "CDep", "include", "head.h").pathString, Dep.appending(components: "Sources", "CDep", "include", "module.modulemap").pathString ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), dependencies: [ .localSourceControl(path: .init(path: "/Dep"), requirement: .upToNextMajor(from: "1.0.0")), ], targets: [ TargetDescription(name: "exe", dependencies: ["swiftlib"]), TargetDescription(name: "swiftlib", dependencies: ["lib"]), TargetDescription(name: "lib", dependencies: ["Dep"]), ]), Manifest.createFileSystemManifest( name: "Dep", path: .init(path: "/Dep"), products: [ ProductDescription(name: "Dep", type: .library(.automatic), targets: ["Dep"]), ], targets: [ TargetDescription(name: "Dep", dependencies: ["CDep"]), TargetDescription(name: "CDep", dependencies: []), ]), ], createREPLProduct: true, observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let plan = try BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope ) let buildPath: AbsolutePath = plan.buildParameters.dataPath.appending(components: "debug") XCTAssertEqual(try plan.createREPLArguments().sorted(), ["-I\(Dep.appending(components: "Sources", "CDep", "include"))", "-I\(buildPath)", "-I\(buildPath.appending(components: "lib.build"))", "-L\(buildPath)", "-lpkg__REPL", "repl"]) XCTAssertEqual(plan.graph.allProducts.map({ $0.name }).sorted(), [ "Dep", "exe", "pkg__REPL" ]) } func testTestModule() throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/Foo/foo.swift", "/Pkg/Tests/\(SwiftTarget.defaultTestEntryPointName)", "/Pkg/Tests/FooTests/foo.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), targets: [ TargetDescription(name: "Foo", dependencies: []), TargetDescription(name: "FooTests", dependencies: ["Foo"], type: .test), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) #if os(macOS) result.checkTargetsCount(2) #else // On non-Apple platforms, when a custom entry point file is present (e.g. XCTMain.swift), there is one additional target for the synthesized test entry point. result.checkTargetsCount(3) #endif let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let foo = try result.target(for: "Foo").swiftTarget().compileArguments() XCTAssertMatch(foo, [.anySequence, "-swift-version", "4", "-enable-batch-mode", "-Onone", "-enable-testing", "-g", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) let fooTests = try result.target(for: "FooTests").swiftTarget().compileArguments() XCTAssertMatch(fooTests, [.anySequence, "-swift-version", "4", "-enable-batch-mode", "-Onone", "-enable-testing", "-g", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) #if os(macOS) let version = MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .macOS).versionString XCTAssertEqual(try result.buildProduct(for: "PkgPackageTests").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "PkgPackageTests.xctest", "Contents", "MacOS", "PkgPackageTests").pathString, "-module-name", "PkgPackageTests", "-Xlinker", "-bundle", "-Xlinker", "-rpath", "-Xlinker", "@loader_path/../../../", "@\(buildPath.appending(components: "PkgPackageTests.product", "Objects.LinkFileList"))", "-Xlinker", "-rpath", "-Xlinker", "/fake/path/lib/swift-5.5/macosx", "-target", "\(hostTriple.tripleString(forPlatformVersion: version))", "-Xlinker", "-add_ast_path", "-Xlinker", buildPath.appending(components: "Foo.swiftmodule").pathString, "-Xlinker", "-add_ast_path", "-Xlinker", buildPath.appending(components: "FooTests.swiftmodule").pathString, ]) #elseif os(Windows) XCTAssertEqual(try result.buildProduct(for: "PkgPackageTests").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "PkgPackageTests.xctest").pathString, "-module-name", "PkgPackageTests", "-emit-executable", "@\(buildPath.appending(components: "PkgPackageTests.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ]) #else XCTAssertEqual(try result.buildProduct(for: "PkgPackageTests").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "PkgPackageTests.xctest").pathString, "-module-name", "PkgPackageTests", "-emit-executable", "-Xlinker", "-rpath=$ORIGIN", "@\(buildPath.appending(components: "PkgPackageTests.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ]) #endif } func testConcurrencyInOS() throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), platforms: [ PlatformDescription(name: "macos", version: "12.0"), ], targets: [ TargetDescription(name: "exe", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(config: .release), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(1) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "release") let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, [.anySequence, "-swift-version", "4", "-O", "-g", .equal(j), "-DSWIFT_PACKAGE", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) #if os(macOS) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-g", "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "-dead_strip", "-Xlinker", "-rpath", "-Xlinker", "@loader_path", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-target", hostTriple.tripleString(forPlatformVersion: "12.0"), ]) #endif } func testParseAsLibraryFlagForExe() throws { let fs = InMemoryFileSystem(emptyFiles: // executable has a single source file not named `main.swift`, without @main. "/Pkg/Sources/exe1/foo.swift", // executable has a single source file named `main.swift`, without @main. "/Pkg/Sources/exe2/main.swift", // executable has a single source file not named `main.swift`, with @main. "/Pkg/Sources/exe3/foo.swift", // executable has a single source file named `main.swift`, with @main "/Pkg/Sources/exe4/main.swift", // executable has a single source file named `comments.swift`, with @main in comments "/Pkg/Sources/exe5/comments.swift", // executable has a single source file named `comments.swift`, with @main in comments "/Pkg/Sources/exe6/comments.swift", // executable has a single source file named `comments.swift`, with @main in comments "/Pkg/Sources/exe7/comments.swift", // executable has a single source file named `comments.swift`, with @main in comments "/Pkg/Sources/exe8/comments.swift", // executable has a single source file named `comments.swift`, with @main in comments "/Pkg/Sources/exe9/comments.swift", // executable has a single source file named `comments.swift`, with @main in comments and not in comments "/Pkg/Sources/exe10/comments.swift", // executable has a single source file named `comments.swift`, with @main in comments and not in comments "/Pkg/Sources/exe11/comments.swift", // executable has a single source file named `comments.swift`, with @main in comments and not in comments "/Pkg/Sources/exe12/comments.swift", // executable has multiple source files. "/Pkg/Sources/exe13/bar.swift", "/Pkg/Sources/exe13/main.swift", // Snippet with top-level code "/Pkg/Snippets/TopLevelCodeSnippet.swift", // Snippet with @main "/Pkg/Snippets/AtMainSnippet.swift" ) try fs.writeFileContents(AbsolutePath(path: "/Pkg/Sources/exe3/foo.swift")) { """ @main struct Runner { static func main() { print("hello world") } } """ } try fs.writeFileContents(AbsolutePath(path: "/Pkg/Sources/exe4/main.swift")) { """ @main struct Runner { static func main() { print("hello world") } } """ } try fs.writeFileContents(AbsolutePath(path: "/Pkg/Sources/exe5/comments.swift")) { """ // @main in comment print("hello world") """ } try fs.writeFileContents(AbsolutePath(path: "/Pkg/Sources/exe6/comments.swift")) { """ /* @main in comment */ print("hello world") """ } try fs.writeFileContents(AbsolutePath(path: "/Pkg/Sources/exe7/comments.swift")) { """ /* @main in comment */ print("hello world") """ } try fs.writeFileContents(AbsolutePath(path: "/Pkg/Sources/exe8/comments.swift")) { """ /* @main struct Runner { static func main() { print("hello world") } } */ print("hello world") """ } try fs.writeFileContents(AbsolutePath(path: "/Pkg/Sources/exe9/comments.swift")) { """ /*@main struct Runner { static func main() { print("hello world") } }*/ """ } try fs.writeFileContents(AbsolutePath(path: "/Pkg/Sources/exe10/comments.swift")) { """ // @main in comment @main struct Runner { static func main() { print("hello world") } } """ } try fs.writeFileContents(AbsolutePath(path: "/Pkg/Sources/exe11/comments.swift")) { """ /* @main in comment */ @main struct Runner { static func main() { print("hello world") } } """ } try fs.writeFileContents(AbsolutePath(path: "/Pkg/Sources/exe12/comments.swift")) { """ /* @main struct Runner { static func main() { print("hello world") } }*/ @main struct Runner { static func main() { print("hello world") } } """ } try fs.writeFileContents(AbsolutePath(path: "/Pkg/Snippets/TopLevelCodeSnippet.swift")) { """ struct Foo { init() {} func foo() {} } let foo = Foo() foo.foo() """ } try fs.writeFileContents(AbsolutePath(path: "/Pkg/Snippets/AtMainSnippet.swift")) { """ @main struct Runner { static func main() { print("hello world") } } """ } let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), toolsVersion: .v5_5, targets: [ TargetDescription(name: "exe1", type: .executable), TargetDescription(name: "exe2", type: .executable), TargetDescription(name: "exe3", type: .executable), TargetDescription(name: "exe4", type: .executable), TargetDescription(name: "exe5", type: .executable), TargetDescription(name: "exe6", type: .executable), TargetDescription(name: "exe7", type: .executable), TargetDescription(name: "exe8", type: .executable), TargetDescription(name: "exe9", type: .executable), TargetDescription(name: "exe10", type: .executable), TargetDescription(name: "exe11", type: .executable), TargetDescription(name: "exe12", type: .executable), TargetDescription(name: "exe13", type: .executable), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(shouldLinkStaticSwiftStdlib: true), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(15) result.checkTargetsCount(15) XCTAssertNoDiagnostics(observability.diagnostics) // single source file not named main, and without @main should not have -parse-as-library. let exe1 = try result.target(for: "exe1").swiftTarget().emitCommandLine() XCTAssertNoMatch(exe1, ["-parse-as-library"]) // single source file named main, and without @main should not have -parse-as-library. let exe2 = try result.target(for: "exe2").swiftTarget().emitCommandLine() XCTAssertNoMatch(exe2, ["-parse-as-library"]) // single source file not named main, with @main should have -parse-as-library. let exe3 = try result.target(for: "exe3").swiftTarget().emitCommandLine() XCTAssertMatch(exe3, ["-parse-as-library"]) // single source file named main, with @main should have -parse-as-library. let exe4 = try result.target(for: "exe4").swiftTarget().emitCommandLine() XCTAssertMatch(exe4, ["-parse-as-library"]) // multiple source files should not have -parse-as-library. let exe5 = try result.target(for: "exe5").swiftTarget().emitCommandLine() XCTAssertNoMatch(exe5, ["-parse-as-library"]) // @main in comment should not have -parse-as-library. let exe6 = try result.target(for: "exe6").swiftTarget().emitCommandLine() XCTAssertNoMatch(exe6, ["-parse-as-library"]) // @main in comment should not have -parse-as-library. let exe7 = try result.target(for: "exe7").swiftTarget().emitCommandLine() XCTAssertNoMatch(exe7, ["-parse-as-library"]) // @main in comment should not have -parse-as-library. let exe8 = try result.target(for: "exe8").swiftTarget().emitCommandLine() XCTAssertNoMatch(exe8, ["-parse-as-library"]) // @main in comment should not have -parse-as-library. let exe9 = try result.target(for: "exe9").swiftTarget().emitCommandLine() XCTAssertNoMatch(exe9, ["-parse-as-library"]) // @main in comment + non-comment should have -parse-as-library. let exe10 = try result.target(for: "exe10").swiftTarget().emitCommandLine() XCTAssertMatch(exe10, ["-parse-as-library"]) // @main in comment + non-comment should have -parse-as-library. let exe11 = try result.target(for: "exe11").swiftTarget().emitCommandLine() XCTAssertMatch(exe11, ["-parse-as-library"]) // @main in comment + non-comment should have -parse-as-library. let exe12 = try result.target(for: "exe12").swiftTarget().emitCommandLine() XCTAssertMatch(exe12, ["-parse-as-library"]) // multiple source files should not have -parse-as-library. let exe13 = try result.target(for: "exe13").swiftTarget().emitCommandLine() XCTAssertNoMatch(exe13, ["-parse-as-library"]) // A snippet with top-level code should not have -parse-as-library. let topLevelCodeSnippet = try result.target(for: "TopLevelCodeSnippet").swiftTarget().emitCommandLine() XCTAssertNoMatch(topLevelCodeSnippet, ["-parse-as-library"]) // A snippet with @main should have -parse-as-library let atMainSnippet = try result.target(for: "AtMainSnippet").swiftTarget().emitCommandLine() XCTAssertMatch(atMainSnippet, ["-parse-as-library"]) } func testCModule() throws { let Clibgit: AbsolutePath = AbsolutePath(path: "/Clibgit") let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift", Clibgit.appending(components: "module.modulemap").pathString ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), dependencies: [ .localSourceControl(path: try .init(validating: Clibgit.pathString), requirement: .upToNextMajor(from: "1.0.0")) ], targets: [ TargetDescription(name: "exe", dependencies: []), ]), Manifest.createFileSystemManifest( name: "Clibgit", path: .init(path: "/Clibgit") ), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(1) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") XCTAssertMatch(try result.target(for: "exe").swiftTarget().compileArguments(), ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-enable-testing", "-g", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-Xcc", "-fmodule-map-file=\(Clibgit.appending(components: "module.modulemap"))", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) #if os(macOS) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "-rpath", "-Xlinker", "@loader_path", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-Xlinker", "-rpath", "-Xlinker", "/fake/path/lib/swift-5.5/macosx", "-target", defaultTargetTriple, "-Xlinker", "-add_ast_path", "-Xlinker", buildPath.appending(components: "exe.build", "exe.swiftmodule").pathString, ]) #elseif os(Windows) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe.exe").pathString, "-module-name", "exe", "-emit-executable", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ]) #else XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "-rpath=$ORIGIN", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ]) #endif } func testCppModule() throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift", "/Pkg/Sources/lib/lib.cpp", "/Pkg/Sources/lib/include/lib.h" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), targets: [ TargetDescription(name: "lib", dependencies: []), TargetDescription(name: "exe", dependencies: ["lib"]), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(2) let linkArgs = try result.buildProduct(for: "exe").linkArguments() #if os(macOS) XCTAssertMatch(linkArgs, ["-lc++"]) #elseif !os(Windows) XCTAssertMatch(linkArgs, ["-lstdc++"]) #endif } func testDynamicProducts() throws { let fs = InMemoryFileSystem(emptyFiles: "/Foo/Sources/Foo/main.swift", "/Bar/Source/Bar/source.swift" ) let observability = ObservabilitySystem.makeForTesting() let g = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createFileSystemManifest( name: "Bar", path: .init(path: "/Bar"), products: [ ProductDescription(name: "Bar-Baz", type: .library(.dynamic), targets: ["Bar"]), ], targets: [ TargetDescription(name: "Bar", dependencies: []), ]), Manifest.createRootManifest( name: "Foo", path: .init(path: "/Foo"), dependencies: [ .localSourceControl(path: .init(path: "/Bar"), requirement: .upToNextMajor(from: "1.0.0")), ], targets: [ TargetDescription(name: "Foo", dependencies: ["Bar-Baz"]), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(), graph: g, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(2) result.checkTargetsCount(2) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let fooLinkArgs = try result.buildProduct(for: "Foo").linkArguments() let barLinkArgs = try result.buildProduct(for: "Bar-Baz").linkArguments() #if os(macOS) XCTAssertEqual(fooLinkArgs, [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "Foo").pathString, "-module-name", "Foo", "-lBar-Baz", "-emit-executable", "-Xlinker", "-rpath", "-Xlinker", "@loader_path", "@\(buildPath.appending(components: "Foo.product", "Objects.LinkFileList"))", "-Xlinker", "-rpath", "-Xlinker", "/fake/path/lib/swift-5.5/macosx", "-target", defaultTargetTriple, "-Xlinker", "-add_ast_path", "-Xlinker", buildPath.appending(components: "Foo.build", "Foo.swiftmodule").pathString ]) XCTAssertEqual(barLinkArgs, [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "libBar-Baz.dylib").pathString, "-module-name", "Bar_Baz", "-emit-library", "-Xlinker", "-install_name", "-Xlinker", "@rpath/libBar-Baz.dylib", "-Xlinker", "-rpath", "-Xlinker", "@loader_path", "@\(buildPath.appending(components: "Bar-Baz.product", "Objects.LinkFileList"))", "-Xlinker", "-rpath", "-Xlinker", "/fake/path/lib/swift-5.5/macosx", "-target", defaultTargetTriple, "-Xlinker", "-add_ast_path", "-Xlinker", buildPath.appending(components: "Bar.swiftmodule").pathString ]) #elseif os(Windows) XCTAssertEqual(fooLinkArgs, [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "Foo.exe").pathString, "-module-name", "Foo", "-lBar-Baz", "-emit-executable", "@\(buildPath.appending(components: "Foo.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ]) XCTAssertEqual(barLinkArgs, [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "Bar-Baz.dll").pathString, "-module-name", "Bar_Baz", "-emit-library", "@\(buildPath.appending(components: "Bar-Baz.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ]) #else XCTAssertEqual(fooLinkArgs, [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "Foo").pathString, "-module-name", "Foo", "-lBar-Baz", "-emit-executable", "-Xlinker", "-rpath=$ORIGIN", "@\(buildPath.appending(components: "Foo.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ]) XCTAssertEqual(barLinkArgs, [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "libBar-Baz.so").pathString, "-module-name", "Bar_Baz", "-emit-library", "-Xlinker", "-rpath=$ORIGIN", "@\(buildPath.appending(components: "Bar-Baz.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ]) #endif #if os(macOS) XCTAssert( barLinkArgs.contains("-install_name") && barLinkArgs.contains("@rpath/libBar-Baz.dylib") && barLinkArgs.contains("-rpath") && barLinkArgs.contains("@loader_path"), "The dynamic library will not work once moved outside the build directory." ) #endif } func testExecAsDependency() throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift", "/Pkg/Sources/lib/lib.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), products: [ ProductDescription(name: "lib", type: .library(.dynamic), targets: ["lib"]), ], targets: [ TargetDescription(name: "lib", dependencies: []), TargetDescription(name: "exe", dependencies: ["lib"]), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(2) result.checkTargetsCount(2) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-enable-testing", "-g", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) let lib = try result.target(for: "lib").swiftTarget().compileArguments() XCTAssertMatch(lib, ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-enable-testing", "-g", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) #if os(macOS) let linkArguments = [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "liblib.dylib").pathString, "-module-name", "lib", "-emit-library", "-Xlinker", "-install_name", "-Xlinker", "@rpath/liblib.dylib", "-Xlinker", "-rpath", "-Xlinker", "@loader_path", "@\(buildPath.appending(components: "lib.product", "Objects.LinkFileList"))", "-Xlinker", "-rpath", "-Xlinker", "/fake/path/lib/swift-5.5/macosx", "-target", defaultTargetTriple, "-Xlinker", "-add_ast_path", "-Xlinker", buildPath.appending(components: "lib.swiftmodule").pathString, ] #elseif os(Windows) let linkArguments = [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "lib.dll").pathString, "-module-name", "lib", "-emit-library", "@\(buildPath.appending(components: "lib.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ] #else let linkArguments = [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "liblib.so").pathString, "-module-name", "lib", "-emit-library", "-Xlinker", "-rpath=$ORIGIN", "@\(buildPath.appending(components: "lib.product", "Objects.LinkFileList"))", "-target", defaultTargetTriple, ] #endif XCTAssertEqual(try result.buildProduct(for: "lib").linkArguments(), linkArguments) } func testClangTargets() throws { let Pkg: AbsolutePath = AbsolutePath(path: "/Pkg") let fs = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "exe", "main.c").pathString, Pkg.appending(components: "Sources", "lib", "include", "lib.h").pathString, Pkg.appending(components: "Sources", "lib", "lib.cpp").pathString ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: try .init(validating: Pkg.pathString), products: [ ProductDescription(name: "lib", type: .library(.dynamic), targets: ["lib"]), ], targets: [ TargetDescription(name: "lib", dependencies: []), TargetDescription(name: "exe", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(2) result.checkTargetsCount(2) let triple = result.plan.buildParameters.triple let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let exe = try result.target(for: "exe").clangTarget() var expectedExeBasicArgs = triple.isDarwin() ? ["-fobjc-arc"] : [] expectedExeBasicArgs += ["-target", defaultTargetTriple] expectedExeBasicArgs += ["-g"] + (triple.isWindows() ? ["-gcodeview"] : []) expectedExeBasicArgs += ["-O0", "-DSWIFT_PACKAGE=1", "-DDEBUG=1", "-fblocks"] #if !os(Windows) // FIXME(5473) - modules flags on Windows dropped expectedExeBasicArgs += ["-fmodules", "-fmodule-name=exe"] #endif expectedExeBasicArgs += ["-I", Pkg.appending(components: "Sources", "exe", "include").pathString] #if !os(Windows) // FIXME(5473) - modules flags on Windows dropped expectedExeBasicArgs += ["-fmodules-cache-path=\(buildPath.appending(components: "ModuleCache"))"] #endif XCTAssertEqual(try exe.basicArguments(isCXX: false), expectedExeBasicArgs) XCTAssertEqual(try exe.objects, [buildPath.appending(components: "exe.build", "main.c.o")]) XCTAssertEqual(exe.moduleMap, nil) let lib = try result.target(for: "lib").clangTarget() var expectedLibBasicArgs = triple.isDarwin() ? ["-fobjc-arc"] : [] expectedLibBasicArgs += ["-target", defaultTargetTriple] expectedLibBasicArgs += ["-g"] + (triple.isWindows() ? ["-gcodeview"] : []) expectedLibBasicArgs += ["-O0", "-DSWIFT_PACKAGE=1", "-DDEBUG=1", "-fblocks"] let shouldHaveModules = !(triple.isDarwin() || triple.isWindows() || triple.isAndroid()) if shouldHaveModules { expectedLibBasicArgs += ["-fmodules", "-fmodule-name=lib"] } expectedLibBasicArgs += ["-I", Pkg.appending(components: "Sources", "lib", "include").pathString] if shouldHaveModules { expectedLibBasicArgs += ["-fmodules-cache-path=\(buildPath.appending(components: "ModuleCache"))"] } XCTAssertEqual(try lib.basicArguments(isCXX: true), expectedLibBasicArgs) XCTAssertEqual(try lib.objects, [buildPath.appending(components: "lib.build", "lib.cpp.o")]) XCTAssertEqual(lib.moduleMap, buildPath.appending(components: "lib.build", "module.modulemap")) #if os(macOS) XCTAssertEqual(try result.buildProduct(for: "lib").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-lc++", "-L", buildPath.pathString, "-o", buildPath.appending(components: "liblib.dylib").pathString, "-module-name", "lib", "-emit-library", "-Xlinker", "-install_name", "-Xlinker", "@rpath/liblib.dylib", "-Xlinker", "-rpath", "-Xlinker", "@loader_path", "@\(buildPath.appending(components: "lib.product", "Objects.LinkFileList"))", "-runtime-compatibility-version", "none", "-target", defaultTargetTriple ]) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "-rpath", "-Xlinker", "@loader_path", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-runtime-compatibility-version", "none", "-target", defaultTargetTriple ]) #elseif os(Windows) XCTAssertEqual(try result.buildProduct(for: "lib").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "lib.dll").pathString, "-module-name", "lib", "-emit-library", "@\(buildPath.appending(components: "lib.product", "Objects.LinkFileList"))", "-runtime-compatibility-version", "none", "-target", defaultTargetTriple ]) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe.exe").pathString, "-module-name", "exe", "-emit-executable", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-runtime-compatibility-version", "none", "-target", defaultTargetTriple ]) #else XCTAssertEqual(try result.buildProduct(for: "lib").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-lstdc++", "-L", buildPath.pathString, "-o", buildPath.appending(components: "liblib.so").pathString, "-module-name", "lib", "-emit-library", "-Xlinker", "-rpath=$ORIGIN", "@\(buildPath.appending(components: "lib.product", "Objects.LinkFileList"))", "-runtime-compatibility-version", "none", "-target", defaultTargetTriple ]) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe").pathString, "-module-name", "exe", "-emit-executable", "-Xlinker", "-rpath=$ORIGIN", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-runtime-compatibility-version", "none", "-target", defaultTargetTriple ]) #endif } func testNonReachableProductsAndTargets() throws { let fileSystem = InMemoryFileSystem(emptyFiles: "/A/Sources/ATarget/main.swift", "/B/Sources/BTarget1/BTarget1.swift", "/B/Sources/BTarget2/main.swift", "/C/Sources/CTarget/main.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fileSystem, manifests: [ Manifest.createRootManifest( name: "A", path: .init(path: "/A"), dependencies: [ .localSourceControl(path: .init(path: "/B"), requirement: .upToNextMajor(from: "1.0.0")), .localSourceControl(path: .init(path: "/C"), requirement: .upToNextMajor(from: "1.0.0")), ], products: [ ProductDescription(name: "aexec", type: .executable, targets: ["ATarget"]) ], targets: [ TargetDescription(name: "ATarget", dependencies: ["BLibrary"]), ]), Manifest.createFileSystemManifest( name: "B", path: .init(path: "/B"), products: [ ProductDescription(name: "BLibrary", type: .library(.static), targets: ["BTarget1"]), ProductDescription(name: "bexec", type: .executable, targets: ["BTarget2"]), ], targets: [ TargetDescription(name: "BTarget1", dependencies: []), TargetDescription(name: "BTarget2", dependencies: []), ]), Manifest.createFileSystemManifest( name: "C", path: .init(path: "/C"), products: [ ProductDescription(name: "cexec", type: .executable, targets: ["CTarget"]) ], targets: [ TargetDescription(name: "CTarget", dependencies: []), ]), ], observabilityScope: observability.topScope ) #if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION XCTAssertEqual(observability.diagnostics.count, 1) let firstDiagnostic = observability.diagnostics.first.map({ $0.message }) XCTAssert( firstDiagnostic == "dependency 'c' is not used by any target", "Unexpected diagnostic: " + (firstDiagnostic ?? "[none]") ) #endif let graphResult = PackageGraphResult(graph) graphResult.check(reachableProducts: "aexec", "BLibrary") graphResult.check(reachableTargets: "ATarget", "BTarget1") #if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION graphResult.check(products: "aexec", "BLibrary") graphResult.check(targets: "ATarget", "BTarget1") #else graphResult.check(products: "BLibrary", "bexec", "aexec", "cexec") graphResult.check(targets: "ATarget", "BTarget1", "BTarget2", "CTarget") #endif let planResult = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fileSystem, observabilityScope: observability.topScope )) #if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION planResult.checkProductsCount(2) planResult.checkTargetsCount(2) #else planResult.checkProductsCount(4) planResult.checkTargetsCount(4) #endif } func testReachableBuildProductsAndTargets() throws { let fileSystem = InMemoryFileSystem(emptyFiles: "/A/Sources/ATarget/main.swift", "/B/Sources/BTarget1/source.swift", "/B/Sources/BTarget2/source.swift", "/B/Sources/BTarget3/source.swift", "/C/Sources/CTarget/source.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fileSystem, manifests: [ Manifest.createRootManifest( name: "A", path: .init(path: "/A"), dependencies: [ .localSourceControl(path: .init(path: "/B"), requirement: .upToNextMajor(from: "1.0.0")), .localSourceControl(path: .init(path: "/C"), requirement: .upToNextMajor(from: "1.0.0")), ], products: [ ProductDescription(name: "aexec", type: .executable, targets: ["ATarget"]), ], targets: [ TargetDescription(name: "ATarget", dependencies: [ .product(name: "BLibrary1", package: "B", condition: PackageConditionDescription( platformNames: ["linux"], config: nil )), .product(name: "BLibrary2", package: "B", condition: PackageConditionDescription( platformNames: [], config: "debug" )), .product(name: "CLibrary", package: "C", condition: PackageConditionDescription( platformNames: ["android"], config: "release" )), ]) ] ), Manifest.createLocalSourceControlManifest( name: "B", path: .init(path: "/B"), products: [ ProductDescription(name: "BLibrary1", type: .library(.static), targets: ["BTarget1"]), ProductDescription(name: "BLibrary2", type: .library(.static), targets: ["BTarget2"]), ], targets: [ TargetDescription(name: "BTarget1", dependencies: []), TargetDescription(name: "BTarget2", dependencies: [ .target(name: "BTarget3", condition: PackageConditionDescription( platformNames: ["macos"], config: nil )), ]), TargetDescription(name: "BTarget3", dependencies: []), ] ), Manifest.createLocalSourceControlManifest( name: "C", path: .init(path: "/C"), products: [ ProductDescription(name: "CLibrary", type: .library(.static), targets: ["CTarget"]) ], targets: [ TargetDescription(name: "CTarget", dependencies: []), ] ), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let graphResult = PackageGraphResult(graph) do { let linuxDebug = BuildEnvironment(platform: .linux, configuration: .debug) try graphResult.check(reachableBuildProducts: "aexec", "BLibrary1", "BLibrary2", in: linuxDebug) try graphResult.check(reachableBuildTargets: "ATarget", "BTarget1", "BTarget2", in: linuxDebug) let planResult = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(environment: linuxDebug), graph: graph, fileSystem: fileSystem, observabilityScope: observability.topScope )) planResult.checkProductsCount(4) planResult.checkTargetsCount(5) } do { let macosDebug = BuildEnvironment(platform: .macOS, configuration: .debug) try graphResult.check(reachableBuildProducts: "aexec", "BLibrary2", in: macosDebug) try graphResult.check(reachableBuildTargets: "ATarget", "BTarget2", "BTarget3", in: macosDebug) let planResult = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(environment: macosDebug), graph: graph, fileSystem: fileSystem, observabilityScope: observability.topScope )) planResult.checkProductsCount(4) planResult.checkTargetsCount(5) } do { let androidRelease = BuildEnvironment(platform: .android, configuration: .release) try graphResult.check(reachableBuildProducts: "aexec", "CLibrary", in: androidRelease) try graphResult.check(reachableBuildTargets: "ATarget", "CTarget", in: androidRelease) let planResult = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(environment: androidRelease), graph: graph, fileSystem: fileSystem, observabilityScope: observability.topScope )) planResult.checkProductsCount(4) planResult.checkTargetsCount(5) } } func testSystemPackageBuildPlan() throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/module.modulemap" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg") ) ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) XCTAssertThrows(BuildPlan.Error.noBuildableTarget) { _ = try BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope ) } } func testPkgConfigHintDiagnostic() throws { let fileSystem = InMemoryFileSystem(emptyFiles: "/A/Sources/ATarget/foo.swift", "/A/Sources/BTarget/module.modulemap" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fileSystem, manifests: [ Manifest.createRootManifest( name: "A", path: .init(path: "/A"), targets: [ TargetDescription(name: "ATarget", dependencies: ["BTarget"]), TargetDescription( name: "BTarget", type: .system, pkgConfig: "BTarget", providers: [ .brew(["BTarget"]), .apt(["BTarget"]), .yum(["BTarget"]), ] ) ]), ], observabilityScope: observability.topScope ) _ = try BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fileSystem, observabilityScope: observability.topScope ) #if !os(Windows) // FIXME: pkg-config is not generally available on Windows XCTAssertTrue(observability.diagnostics.contains(where: { $0.severity == .warning && $0.message.hasPrefix("you may be able to install BTarget using your system-packager") }), "expected PkgConfigHint diagnostics") #endif } func testPkgConfigGenericDiagnostic() throws { let fileSystem = InMemoryFileSystem(emptyFiles: "/A/Sources/ATarget/foo.swift", "/A/Sources/BTarget/module.modulemap" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fileSystem, manifests: [ Manifest.createRootManifest( name: "A", path: .init(path: "/A"), targets: [ TargetDescription(name: "ATarget", dependencies: ["BTarget"]), TargetDescription( name: "BTarget", type: .system, pkgConfig: "BTarget" ) ]), ], observabilityScope: observability.topScope ) _ = try BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fileSystem, observabilityScope: observability.topScope ) let diagnostic = observability.diagnostics.last! XCTAssertEqual(diagnostic.message, "couldn't find pc file for BTarget") XCTAssertEqual(diagnostic.severity, .warning) XCTAssertEqual(diagnostic.metadata?.targetName, "BTarget") XCTAssertEqual(diagnostic.metadata?.pcFile, "BTarget.pc") } func testWindowsTarget() throws { let Pkg: AbsolutePath = AbsolutePath(path: "/Pkg") let fs = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "exe", "main.swift").pathString, Pkg.appending(components: "Sources", "lib", "lib.c").pathString, Pkg.appending(components: "Sources", "lib", "include", "lib.h").pathString ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: try .init(validating: Pkg.pathString), targets: [ TargetDescription(name: "exe", dependencies: ["lib"]), TargetDescription(name: "lib", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(destinationTriple: .windows), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(2) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let lib = try result.target(for: "lib").clangTarget() let args = [ "-target", "x86_64-unknown-windows-msvc", "-g", "-gcodeview", "-O0", "-DSWIFT_PACKAGE=1", "-DDEBUG=1", "-fblocks", "-I", Pkg.appending(components: "Sources", "lib", "include").pathString ] XCTAssertEqual(try lib.basicArguments(isCXX: false), args) XCTAssertEqual(try lib.objects, [buildPath.appending(components: "lib.build", "lib.c.o")]) XCTAssertEqual(lib.moduleMap, buildPath.appending(components: "lib.build", "module.modulemap")) let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-enable-testing", "-g", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG","-Xcc", "-fmodule-map-file=\(buildPath.appending(components: "lib.build", "module.modulemap"))", "-Xcc", "-I", "-Xcc", "\(Pkg.appending(components: "Sources", "lib", "include"))", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence]) XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "exe.exe").pathString, "-module-name", "exe", "-emit-executable", "@\(buildPath.appending(components: "exe.product", "Objects.LinkFileList"))", "-target", "x86_64-unknown-windows-msvc", ]) let executablePathExtension = try result.buildProduct(for: "exe").binaryPath.extension XCTAssertMatch(executablePathExtension, "exe") } func testWASITarget() throws { let Pkg: AbsolutePath = AbsolutePath(path: "/Pkg") let fs = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "app", "main.swift").pathString, Pkg.appending(components: "Sources", "lib", "lib.c").pathString, Pkg.appending(components: "Sources", "lib", "include", "lib.h").pathString, Pkg.appending(components: "Tests", "test", "TestCase.swift").pathString ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: try .init(validating: Pkg.pathString), targets: [ TargetDescription(name: "app", dependencies: ["lib"]), TargetDescription(name: "lib", dependencies: []), TargetDescription(name: "test", dependencies: ["lib"], type: .test) ] ), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) var parameters = mockBuildParameters(destinationTriple: .wasi) parameters.shouldLinkStaticSwiftStdlib = true let result = try BuildPlanResult(plan: BuildPlan( buildParameters: parameters, graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(2) result.checkTargetsCount(5) // There are two additional targets on non-Apple platforms, for test discovery and test entry point let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let lib = try result.target(for: "lib").clangTarget() let args = [ "-target", "wasm32-unknown-wasi", "-g", "-O0", "-DSWIFT_PACKAGE=1", "-DDEBUG=1", "-fblocks", "-fmodules", "-fmodule-name=lib", "-I", Pkg.appending(components: "Sources", "lib", "include").pathString, "-fmodules-cache-path=\(buildPath.appending(components: "ModuleCache"))" ] XCTAssertEqual(try lib.basicArguments(isCXX: false), args) XCTAssertEqual(try lib.objects, [buildPath.appending(components: "lib.build", "lib.c.o")]) XCTAssertEqual(lib.moduleMap, buildPath.appending(components: "lib.build", "module.modulemap")) let exe = try result.target(for: "app").swiftTarget().compileArguments() XCTAssertMatch( exe, [ "-swift-version", "4", "-enable-batch-mode", "-Onone", "-enable-testing", "-g", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG","-Xcc", "-fmodule-map-file=\(buildPath.appending(components: "lib.build", "module.modulemap"))", "-Xcc", "-I", "-Xcc", "\(Pkg.appending(components: "Sources", "lib", "include"))", "-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence ] ) let appBuildDescription = try result.buildProduct(for: "app") XCTAssertEqual( try appBuildDescription.linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "app.wasm").pathString, "-module-name", "app", "-static-stdlib", "-emit-executable", "@\(buildPath.appending(components: "app.product", "Objects.LinkFileList"))", "-target", "wasm32-unknown-wasi" ] ) let executablePathExtension = appBuildDescription.binaryPath.extension XCTAssertEqual(executablePathExtension, "wasm") let testBuildDescription = try result.buildProduct(for: "PkgPackageTests") XCTAssertEqual( try testBuildDescription.linkArguments(), [ result.plan.buildParameters.toolchain.swiftCompilerPath.pathString, "-L", buildPath.pathString, "-o", buildPath.appending(components: "PkgPackageTests.wasm").pathString, "-module-name", "PkgPackageTests", "-emit-executable", "@\(buildPath.appending(components: "PkgPackageTests.product", "Objects.LinkFileList"))", "-target", "wasm32-unknown-wasi" ] ) let testPathExtension = testBuildDescription.binaryPath.extension XCTAssertEqual(testPathExtension, "wasm") } func testEntrypointRenaming() throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), toolsVersion: .v5_5, targets: [ TargetDescription(name: "exe", type: .executable), ]), ], observabilityScope: observability.topScope ) func createResult(for triple: TSCUtility.Triple) throws -> BuildPlanResult { try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(canRenameEntrypointFunctionName: true, destinationTriple: triple), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) } let supportingTriples: [TSCUtility.Triple] = [.x86_64Linux, .macOS] for triple in supportingTriples { let result = try createResult(for: triple) let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, ["-Xfrontend", "-entry-point-function-name", "-Xfrontend", "exe_main"]) let linkExe = try result.buildProduct(for: "exe").linkArguments() XCTAssertMatch(linkExe, [.contains("exe_main")]) } let unsupportingTriples: [TSCUtility.Triple] = [.wasi, .windows] for triple in unsupportingTriples { let result = try createResult(for: triple) let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertNoMatch(exe, ["-entry-point-function-name"]) } } func testIndexStore() throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift", "/Pkg/Sources/lib/lib.c", "/Pkg/Sources/lib/include/lib.h" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), targets: [ TargetDescription(name: "exe", dependencies: ["lib"]), TargetDescription(name: "lib", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) func check(for mode: BuildParameters.IndexStoreMode, config: BuildConfiguration) throws { let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(config: config, indexStoreMode: mode), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) let lib = try result.target(for: "lib").clangTarget() let path = StringPattern.equal(result.plan.buildParameters.indexStore.pathString) #if os(macOS) XCTAssertMatch(try lib.basicArguments(isCXX: false), [.anySequence, "-index-store-path", path, .anySequence]) #else XCTAssertNoMatch(try lib.basicArguments(isCXX: false), [.anySequence, "-index-store-path", path, .anySequence]) #endif let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, [.anySequence, "-index-store-path", path, .anySequence]) } try check(for: .auto, config: .debug) try check(for: .on, config: .debug) try check(for: .on, config: .release) } func testPlatforms() throws { let fileSystem = InMemoryFileSystem(emptyFiles: "/A/Sources/ATarget/foo.swift", "/B/Sources/BTarget/foo.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fileSystem, manifests: [ Manifest.createRootManifest( name: "A", path: .init(path: "/A"), platforms: [ PlatformDescription(name: "macos", version: "10.13"), ], toolsVersion: .v5, dependencies: [ .localSourceControl(path: .init(path: "/B"), requirement: .upToNextMajor(from: "1.0.0")), ], targets: [ TargetDescription(name: "ATarget", dependencies: ["BLibrary"]), ]), Manifest.createFileSystemManifest( name: "B", path: .init(path: "/B"), platforms: [ PlatformDescription(name: "macos", version: "10.12"), ], toolsVersion: .v5, products: [ ProductDescription(name: "BLibrary", type: .library(.automatic), targets: ["BTarget"]), ], targets: [ TargetDescription(name: "BTarget", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fileSystem, observabilityScope: observability.topScope )) let aTarget = try result.target(for: "ATarget").swiftTarget().compileArguments() #if os(macOS) XCTAssertMatch(aTarget, [.equal("-target"), .equal(hostTriple.tripleString(forPlatformVersion: "10.13")), .anySequence]) #else XCTAssertMatch(aTarget, [.equal("-target"), .equal(defaultTargetTriple), .anySequence] ) #endif let bTarget = try result.target(for: "BTarget").swiftTarget().compileArguments() #if os(macOS) XCTAssertMatch(bTarget, [.equal("-target"), .equal(hostTriple.tripleString(forPlatformVersion: "10.13")), .anySequence]) #else XCTAssertMatch(bTarget, [.equal("-target"), .equal(defaultTargetTriple), .anySequence] ) #endif } func testPlatformsValidation() throws { let fileSystem = InMemoryFileSystem(emptyFiles: "/A/Sources/ATarget/foo.swift", "/B/Sources/BTarget/foo.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fileSystem, manifests: [ Manifest.createRootManifest( name: "A", path: .init(path: "/A"), platforms: [ PlatformDescription(name: "macos", version: "10.13"), PlatformDescription(name: "ios", version: "10"), ], toolsVersion: .v5, dependencies: [ .localSourceControl(path: .init(path: "/B"), requirement: .upToNextMajor(from: "1.0.0")), ], targets: [ TargetDescription(name: "ATarget", dependencies: ["BLibrary"]), ]), Manifest.createFileSystemManifest( name: "B", path: .init(path: "/B"), platforms: [ PlatformDescription(name: "macos", version: "10.14"), PlatformDescription(name: "ios", version: "11"), ], toolsVersion: .v5, products: [ ProductDescription(name: "BLibrary", type: .library(.automatic), targets: ["BTarget"]), ], targets: [ TargetDescription(name: "BTarget", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) XCTAssertThrows(Diagnostics.fatalError) { _ = try BuildPlan( buildParameters: mockBuildParameters(destinationTriple: .macOS), graph: graph, fileSystem: fileSystem, observabilityScope: observability.topScope ) } testDiagnostics(observability.diagnostics) { result in let diagnosticMessage = """ the library 'ATarget' requires macos 10.13, but depends on the product 'BLibrary' which requires macos 10.14; \ consider changing the library 'ATarget' to require macos 10.14 or later, or the product 'BLibrary' to require \ macos 10.13 or earlier. """ result.check(diagnostic: .contains(diagnosticMessage), severity: .error) } } func testBuildSettings() throws { let A: AbsolutePath = AbsolutePath(path: "/A") let fs = InMemoryFileSystem(emptyFiles: "/A/Sources/exe/main.swift", "/A/Sources/bar/bar.swift", "/A/Sources/cbar/barcpp.cpp", "/A/Sources/cbar/bar.c", "/A/Sources/cbar/include/bar.h", "/B/Sources/t1/dep.swift", "/B/Sources/t2/dep.swift", "<end>" ) let aManifest = Manifest.createRootManifest( name: "A", path: .init(path: "/A"), toolsVersion: .v5, dependencies: [ .localSourceControl(path: .init(path: "/B"), requirement: .upToNextMajor(from: "1.0.0")), ], targets: [ try TargetDescription( name: "cbar", settings: [ .init(tool: .c, kind: .headerSearchPath("Sources/headers")), .init(tool: .cxx, kind: .headerSearchPath("Sources/cppheaders")), .init(tool: .c, kind: .define("CCC=2")), .init(tool: .cxx, kind: .define("RCXX"), condition: .init(config: "release")), .init(tool: .linker, kind: .linkedFramework("best")), .init(tool: .c, kind: .unsafeFlags(["-Icfoo", "-L", "cbar"])), .init(tool: .cxx, kind: .unsafeFlags(["-Icxxfoo", "-L", "cxxbar"])), ] ), try TargetDescription( name: "bar", dependencies: ["cbar", "Dep"], settings: [ .init(tool: .swift, kind: .define("LINUX"), condition: .init(platformNames: ["linux"])), .init(tool: .swift, kind: .define("RLINUX"), condition: .init(platformNames: ["linux"], config: "release")), .init(tool: .swift, kind: .define("DMACOS"), condition: .init(platformNames: ["macos"], config: "debug")), .init(tool: .swift, kind: .unsafeFlags(["-Isfoo", "-L", "sbar"])), ] ), try TargetDescription( name: "exe", dependencies: ["bar"], settings: [ .init(tool: .swift, kind: .define("FOO")), .init(tool: .linker, kind: .linkedLibrary("sqlite3")), .init(tool: .linker, kind: .linkedFramework("CoreData"), condition: .init(platformNames: ["macos"])), .init(tool: .linker, kind: .unsafeFlags(["-Ilfoo", "-L", "lbar"])), ] ), ] ) let bManifest = Manifest.createFileSystemManifest( name: "B", path: .init(path: "/B"), toolsVersion: .v5, products: [ try ProductDescription(name: "Dep", type: .library(.automatic), targets: ["t1", "t2"]), ], targets: [ try TargetDescription( name: "t1", settings: [ .init(tool: .swift, kind: .define("DEP")), .init(tool: .linker, kind: .linkedLibrary("libz")), ] ), try TargetDescription( name: "t2", settings: [ .init(tool: .linker, kind: .linkedLibrary("libz")), ] ), ]) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [aManifest, bManifest], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) func createResult(for dest: TSCUtility.Triple) throws -> BuildPlanResult { return try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(destinationTriple: dest), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) } do { let result = try createResult(for: .x86_64Linux) let dep = try result.target(for: "t1").swiftTarget().compileArguments() XCTAssertMatch(dep, [.anySequence, "-DDEP", .end]) let cbar = try result.target(for: "cbar").clangTarget().basicArguments(isCXX: false) XCTAssertMatch(cbar, [.anySequence, "-DCCC=2", "-I\(A.appending(components: "Sources", "cbar", "Sources", "headers"))", "-I\(A.appending(components: "Sources", "cbar", "Sources", "cppheaders"))", "-Icfoo", "-L", "cbar", "-Icxxfoo", "-L", "cxxbar", .end]) let bar = try result.target(for: "bar").swiftTarget().compileArguments() XCTAssertMatch(bar, [.anySequence, "-DLINUX", "-Isfoo", "-L", "sbar", .end]) let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, [.anySequence, "-DFOO", .end]) let linkExe = try result.buildProduct(for: "exe").linkArguments() XCTAssertMatch(linkExe, [.anySequence, "-lsqlite3", "-llibz", "-framework", "best", "-Ilfoo", "-L", "lbar", .end]) } do { let result = try createResult(for: .macOS) let cbar = try result.target(for: "cbar").clangTarget().basicArguments(isCXX: false) XCTAssertMatch(cbar, [.anySequence, "-DCCC=2", "-I\(A.appending(components: "Sources", "cbar", "Sources", "headers"))", "-I\(A.appending(components: "Sources", "cbar", "Sources", "cppheaders"))", "-Icfoo", "-L", "cbar", "-Icxxfoo", "-L", "cxxbar", .end]) let bar = try result.target(for: "bar").swiftTarget().compileArguments() XCTAssertMatch(bar, [.anySequence, "-DDMACOS", "-Isfoo", "-L", "sbar", .end]) let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, [.anySequence, "-DFOO", .end]) let linkExe = try result.buildProduct(for: "exe").linkArguments() XCTAssertMatch(linkExe, [.anySequence, "-lsqlite3", "-llibz", "-framework", "CoreData", "-framework", "best", "-Ilfoo", "-L", "lbar", .anySequence]) } } func testExtraBuildFlags() throws { let libpath: AbsolutePath = AbsolutePath(path: "/fake/path/lib") let fs = InMemoryFileSystem(emptyFiles: "/A/Sources/exe/main.swift", libpath.appending(components: "libSomething.dylib").pathString, "<end>" ) let aManifest = Manifest.createRootManifest( name: "A", path: .init(path: "/A"), toolsVersion: .v5, targets: [ try TargetDescription(name: "exe", dependencies: []), ] ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [aManifest], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) var flags = BuildFlags() flags.linkerFlags = ["-L", "/path/to/foo", "-L/path/to/foo", "-rpath=foo", "-rpath", "foo"] let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(flags: flags), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) let exe = try result.buildProduct(for: "exe").linkArguments() XCTAssertMatch(exe, [.anySequence, "-L", "/path/to/foo", "-L/path/to/foo", "-Xlinker", "-rpath=foo", "-Xlinker", "-rpath", "-Xlinker", "foo", "-L", "\(libpath)"]) } func testUserToolchainCompileFlags() throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift", "/Pkg/Sources/lib/lib.c", "/Pkg/Sources/lib/include/lib.h" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), targets: [ TargetDescription(name: "exe", dependencies: ["lib"]), TargetDescription(name: "lib", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let userDestination = Destination( sdkRootDir: AbsolutePath(path: "/fake/sdk"), toolchainBinDir: try UserToolchain.default.destination.toolchainBinDir, extraFlags: BuildFlags( cCompilerFlags: ["-I/fake/sdk/sysroot", "-clang-flag-from-json"], swiftCompilerFlags: ["-swift-flag-from-json"] ) ) let mockToolchain = try UserToolchain(destination: userDestination) let extraBuildParameters = mockBuildParameters(toolchain: mockToolchain, flags: BuildFlags(cCompilerFlags: ["-clang-command-line-flag"], swiftCompilerFlags: ["-swift-command-line-flag"])) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: extraBuildParameters, graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(2) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let lib = try result.target(for: "lib").clangTarget() var args: [StringPattern] = [.anySequence] #if os(macOS) args += ["-isysroot"] #else args += ["--sysroot"] #endif args += ["\(userDestination.sdkRootDir!)", "-I/fake/sdk/sysroot", "-clang-flag-from-json", .anySequence, "-clang-command-line-flag"] XCTAssertMatch(try lib.basicArguments(isCXX: false), args) let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, ["-module-cache-path", "\(buildPath.appending(components: "ModuleCache"))", .anySequence, "-swift-flag-from-json", "-Xcc", "-clang-command-line-flag", "-swift-command-line-flag"]) } func testExecBuildTimeDependency() throws { let PkgA: AbsolutePath = AbsolutePath(path: "/PkgA") let fs = InMemoryFileSystem(emptyFiles: PkgA.appending(components: "Sources", "exe", "main.swift").pathString, PkgA.appending(components: "Sources", "swiftlib", "lib.swift").pathString, "/PkgB/Sources/PkgB/PkgB.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createFileSystemManifest( name: "PkgA", path: try .init(validating: PkgA.pathString), products: [ ProductDescription(name: "swiftlib", type: .library(.automatic), targets: ["swiftlib"]), ProductDescription(name: "exe", type: .executable, targets: ["exe"]) ], targets: [ TargetDescription(name: "exe", dependencies: []), TargetDescription(name: "swiftlib", dependencies: ["exe"]), ]), Manifest.createRootManifest( name: "PkgB", path: .init(path: "/PkgB"), dependencies: [ .localSourceControl(path: try .init(validating: PkgA.pathString), requirement: .upToNextMajor(from: "1.0.0")), ], targets: [ TargetDescription(name: "PkgB", dependencies: ["swiftlib"]), ]), ], explicitProduct: "exe", observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let plan = try BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope ) let buildPath: AbsolutePath = plan.buildParameters.dataPath.appending(components: "debug") let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, "debug.yaml") try fs.createDirectory(yaml.parentDirectory, recursive: true) let llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope) try llbuild.generateManifest(at: yaml) let contents: String = try fs.readFileContents(yaml) #if os(Windows) XCTAssertMatch(contents, .contains(""" inputs: ["\(PkgA.appending(components: "Sources", "swiftlib", "lib.swift").escapedPathString())","\(buildPath.appending(components: "exe.exe").escapedPathString())"] outputs: ["\(buildPath.appending(components: "swiftlib.build", "lib.swift.o").escapedPathString())","\(buildPath.escapedPathString()) """)) #else // FIXME(5472) - the suffix is dropped XCTAssertMatch(contents, .contains(""" inputs: ["\(PkgA.appending(components: "Sources", "swiftlib", "lib.swift").escapedPathString())","\(buildPath.appending(components: "exe").escapedPathString())"] outputs: ["\(buildPath.appending(components: "swiftlib.build", "lib.swift.o").escapedPathString())","\(buildPath.escapedPathString()) """)) #endif } func testObjCHeader1() throws { let PkgA: AbsolutePath = AbsolutePath(path: "/PkgA") // This has a Swift and ObjC target in the same package. let fs = InMemoryFileSystem(emptyFiles: PkgA.appending(components: "Sources", "Bar", "main.m").pathString, PkgA.appending(components: "Sources", "Foo", "Foo.swift").pathString ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "PkgA", path: try .init(validating: PkgA.pathString), targets: [ TargetDescription(name: "Foo", dependencies: []), TargetDescription(name: "Bar", dependencies: ["Foo"]), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let plan = try BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope ) let result = try BuildPlanResult(plan: plan) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let fooTarget = try result.target(for: "Foo").swiftTarget().compileArguments() #if os(macOS) XCTAssertMatch(fooTarget, [.anySequence, "-emit-objc-header", "-emit-objc-header-path", "/path/to/build/debug/Foo.build/Foo-Swift.h", .anySequence]) #else XCTAssertNoMatch(fooTarget, [.anySequence, "-emit-objc-header", "-emit-objc-header-path", "/path/to/build/debug/Foo.build/Foo-Swift.h", .anySequence]) #endif let barTarget = try result.target(for: "Bar").clangTarget().basicArguments(isCXX: false) #if os(macOS) XCTAssertMatch(barTarget, [.anySequence, "-fmodule-map-file=/path/to/build/debug/Foo.build/module.modulemap", .anySequence]) #else XCTAssertNoMatch(barTarget, [.anySequence, "-fmodule-map-file=/path/to/build/debug/Foo.build/module.modulemap", .anySequence]) #endif let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, "debug.yaml") try fs.createDirectory(yaml.parentDirectory, recursive: true) let llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope) try llbuild.generateManifest(at: yaml) let contents: String = try fs.readFileContents(yaml) XCTAssertMatch(contents, .contains(""" "\(buildPath.appending(components: "Bar.build", "main.m.o").escapedPathString())": tool: clang inputs: ["\(buildPath.appending(components: "Foo.swiftmodule").escapedPathString())","\(PkgA.appending(components: "Sources", "Bar", "main.m").escapedPathString())"] outputs: ["\(buildPath.appending(components: "Bar.build", "main.m.o").escapedPathString())"] description: "Compiling Bar main.m" """)) } func testObjCHeader2() throws { let PkgA: AbsolutePath = AbsolutePath(path: "/PkgA") // This has a Swift and ObjC target in different packages with automatic product type. let fs = InMemoryFileSystem(emptyFiles: PkgA.appending(components: "Sources", "Bar", "main.m").pathString, "/PkgB/Sources/Foo/Foo.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "PkgA", path: try .init(validating: PkgA.pathString), dependencies: [ .localSourceControl(path: .init(path: "/PkgB"), requirement: .upToNextMajor(from: "1.0.0")), ], targets: [ TargetDescription(name: "Bar", dependencies: ["Foo"]), ]), Manifest.createFileSystemManifest( name: "PkgB", path: .init(path: "/PkgB"), products: [ ProductDescription(name: "Foo", type: .library(.automatic), targets: ["Foo"]), ], targets: [ TargetDescription(name: "Foo", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let plan = try BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope ) let result = try BuildPlanResult(plan: plan) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let fooTarget = try result.target(for: "Foo").swiftTarget().compileArguments() #if os(macOS) XCTAssertMatch(fooTarget, [.anySequence, "-emit-objc-header", "-emit-objc-header-path", "/path/to/build/debug/Foo.build/Foo-Swift.h", .anySequence]) #else XCTAssertNoMatch(fooTarget, [.anySequence, "-emit-objc-header", "-emit-objc-header-path", "/path/to/build/debug/Foo.build/Foo-Swift.h", .anySequence]) #endif let barTarget = try result.target(for: "Bar").clangTarget().basicArguments(isCXX: false) #if os(macOS) XCTAssertMatch(barTarget, [.anySequence, "-fmodule-map-file=/path/to/build/debug/Foo.build/module.modulemap", .anySequence]) #else XCTAssertNoMatch(barTarget, [.anySequence, "-fmodule-map-file=/path/to/build/debug/Foo.build/module.modulemap", .anySequence]) #endif let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, "debug.yaml") try fs.createDirectory(yaml.parentDirectory, recursive: true) let llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope) try llbuild.generateManifest(at: yaml) let contents: String = try fs.readFileContents(yaml) XCTAssertMatch(contents, .contains(""" "\(buildPath.appending(components: "Bar.build", "main.m.o").escapedPathString())": tool: clang inputs: ["\(buildPath.appending(components: "Foo.swiftmodule").escapedPathString())","\(PkgA.appending(components: "Sources", "Bar", "main.m").escapedPathString())"] outputs: ["\(buildPath.appending(components: "Bar.build", "main.m.o").escapedPathString())"] description: "Compiling Bar main.m" """)) } func testObjCHeader3() throws { let PkgA: AbsolutePath = AbsolutePath(path: "/PkgA") // This has a Swift and ObjC target in different packages with dynamic product type. let fs = InMemoryFileSystem(emptyFiles: PkgA.appending(components: "Sources", "Bar", "main.m").pathString, "/PkgB/Sources/Foo/Foo.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "PkgA", path: try .init(validating: PkgA.pathString), dependencies: [ .localSourceControl(path: .init(path: "/PkgB"), requirement: .upToNextMajor(from: "1.0.0")), ], targets: [ TargetDescription(name: "Bar", dependencies: ["Foo"]), ]), Manifest.createFileSystemManifest( name: "PkgB", path: .init(path: "/PkgB"), products: [ ProductDescription(name: "Foo", type: .library(.dynamic), targets: ["Foo"]), ], targets: [ TargetDescription(name: "Foo", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let plan = try BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope ) let dynamicLibraryExtension = plan.buildParameters.triple.dynamicLibraryExtension #if os(Windows) let dynamicLibraryPrefix = "" #else let dynamicLibraryPrefix = "lib" #endif let result = try BuildPlanResult(plan: plan) let fooTarget = try result.target(for: "Foo").swiftTarget().compileArguments() #if os(macOS) XCTAssertMatch(fooTarget, [.anySequence, "-emit-objc-header", "-emit-objc-header-path", "/path/to/build/debug/Foo.build/Foo-Swift.h", .anySequence]) #else XCTAssertNoMatch(fooTarget, [.anySequence, "-emit-objc-header", "-emit-objc-header-path", "/path/to/build/debug/Foo.build/Foo-Swift.h", .anySequence]) #endif let barTarget = try result.target(for: "Bar").clangTarget().basicArguments(isCXX: false) #if os(macOS) XCTAssertMatch(barTarget, [.anySequence, "-fmodule-map-file=/path/to/build/debug/Foo.build/module.modulemap", .anySequence]) #else XCTAssertNoMatch(barTarget, [.anySequence, "-fmodule-map-file=/path/to/build/debug/Foo.build/module.modulemap", .anySequence]) #endif let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, "debug.yaml") try fs.createDirectory(yaml.parentDirectory, recursive: true) let llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope) try llbuild.generateManifest(at: yaml) let contents: String = try fs.readFileContents(yaml) XCTAssertMatch(contents, .contains(""" "\(buildPath.appending(components: "Bar.build", "main.m.o").escapedPathString())": tool: clang inputs: ["\(buildPath.appending(components: "\(dynamicLibraryPrefix)Foo\(dynamicLibraryExtension)").escapedPathString())","\(PkgA.appending(components: "Sources", "Bar", "main.m").escapedPathString())"] outputs: ["\(buildPath.appending(components: "Bar.build", "main.m.o").escapedPathString())"] description: "Compiling Bar main.m" """)) } func testModulewrap() throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift", "/Pkg/Sources/lib/lib.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), targets: [ TargetDescription(name: "exe", dependencies: ["lib"]), TargetDescription(name: "lib", dependencies: []), ] ), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(destinationTriple: .x86_64Linux), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let objects = try result.buildProduct(for: "exe").objects XCTAssertTrue(objects.contains(buildPath.appending(components: "exe.build", "exe.swiftmodule.o")), objects.description) XCTAssertTrue(objects.contains(buildPath.appending(components: "lib.build", "lib.swiftmodule.o")), objects.description) let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, "debug.yaml") try fs.createDirectory(yaml.parentDirectory, recursive: true) let llbuild = LLBuildManifestBuilder(result.plan, fileSystem: fs, observabilityScope: observability.topScope) try llbuild.generateManifest(at: yaml) let contents: String = try fs.readFileContents(yaml) XCTAssertMatch(contents, .contains(""" "\(buildPath.appending(components: "exe.build", "exe.swiftmodule.o").escapedPathString())": tool: shell inputs: ["\(buildPath.appending(components: "exe.build", "exe.swiftmodule").escapedPathString())"] outputs: ["\(buildPath.appending(components: "exe.build", "exe.swiftmodule.o").escapedPathString())"] description: "Wrapping AST for exe for debugging" args: ["\(result.plan.buildParameters.toolchain.swiftCompilerPath.escapedPathString())","-modulewrap","\(buildPath.appending(components: "exe.build", "exe.swiftmodule").escapedPathString())","-o","\(buildPath.appending(components: "exe.build", "exe.swiftmodule.o").escapedPathString())","-target","x86_64-unknown-linux-gnu"] """)) XCTAssertMatch(contents, .contains(""" "\(buildPath.appending(components: "lib.build", "lib.swiftmodule.o").escapedPathString())": tool: shell inputs: ["\(buildPath.appending(components: "lib.swiftmodule").escapedPathString())"] outputs: ["\(buildPath.appending(components: "lib.build", "lib.swiftmodule.o").escapedPathString())"] description: "Wrapping AST for lib for debugging" args: ["\(result.plan.buildParameters.toolchain.swiftCompilerPath.escapedPathString())","-modulewrap","\(buildPath.appending(components: "lib.swiftmodule").escapedPathString())","-o","\(buildPath.appending(components: "lib.build", "lib.swiftmodule.o").escapedPathString())","-target","x86_64-unknown-linux-gnu"] """)) } func testArchiving() throws { let fs = InMemoryFileSystem(emptyFiles: "/Package/Sources/rary/rary.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Package", path: .init(path: "/Package"), products: [ ProductDescription(name: "rary", type: .library(.static), targets: ["rary"]), ], targets: [ TargetDescription(name: "rary", dependencies: []), ] ), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, "debug.yaml") try fs.createDirectory(yaml.parentDirectory, recursive: true) let llbuild = LLBuildManifestBuilder(result.plan, fileSystem: fs, observabilityScope: observability.topScope) try llbuild.generateManifest(at: yaml) let contents: String = try fs.readFileContents(yaml) if result.plan.buildParameters.triple.isWindows() { XCTAssertMatch(contents, .contains(""" "C.rary-debug.a": tool: shell inputs: ["\(buildPath.appending(components: "rary.build", "rary.swift.o").escapedPathString())","\(buildPath.appending(components: "rary.build", "rary.swiftmodule.o").escapedPathString())"] outputs: ["\(buildPath.appending(components: "library.a").escapedPathString())"] description: "Archiving \(buildPath.appending(components: "library.a").escapedPathString())" args: ["\(result.plan.buildParameters.toolchain.librarianPath.escapedPathString())","/LIB","/OUT:\(buildPath.appending(components: "library.a").escapedPathString())","@\(buildPath.appending(components: "rary.product", "Objects.LinkFileList").escapedPathString())"] """)) } else if result.plan.buildParameters.triple.isDarwin() { XCTAssertMatch(contents, .contains(""" "C.rary-debug.a": tool: shell inputs: ["\(buildPath.appending(components: "rary.build", "rary.swift.o").escapedPathString())"] outputs: ["\(buildPath.appending(components: "library.a").escapedPathString())"] description: "Archiving \(buildPath.appending(components: "library.a").escapedPathString())" args: ["\(result.plan.buildParameters.toolchain.librarianPath.escapedPathString())","-o","\(buildPath.appending(components: "library.a").escapedPathString())","@\(buildPath.appending(components: "rary.product", "Objects.LinkFileList").escapedPathString())"] """)) } else { // assume Unix `ar` is the librarian XCTAssertMatch(contents, .contains(""" "C.rary-debug.a": tool: shell inputs: ["\(buildPath.appending(components: "rary.build", "rary.swift.o").escapedPathString())","\(buildPath.appending(components: "rary.build", "rary.swiftmodule.o").escapedPathString())"] outputs: ["\(buildPath.appending(components: "library.a").escapedPathString())"] description: "Archiving \(buildPath.appending(components: "library.a").escapedPathString())" args: ["\(result.plan.buildParameters.toolchain.librarianPath.escapedPathString())","crs","\(buildPath.appending(components: "library.a").escapedPathString())","@\(buildPath.appending(components: "rary.product", "Objects.LinkFileList").escapedPathString())"] """)) } } func testSwiftBundleAccessor() throws { // This has a Swift and ObjC target in the same package. let fs = InMemoryFileSystem(emptyFiles: "/PkgA/Sources/Foo/Foo.swift", "/PkgA/Sources/Foo/foo.txt", "/PkgA/Sources/Foo/bar.txt", "/PkgA/Sources/Bar/Bar.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "PkgA", path: .init(path: "/PkgA"), toolsVersion: .v5_2, targets: [ TargetDescription( name: "Foo", resources: [ .init(rule: .copy, path: "foo.txt"), .init(rule: .process(localization: .none), path: "bar.txt"), ] ), TargetDescription( name: "Bar" ), ] ) ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let plan = try BuildPlan( buildParameters: mockBuildParameters(), graph: graph, fileSystem: fs, observabilityScope: observability.topScope ) let result = try BuildPlanResult(plan: plan) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let fooTarget = try result.target(for: "Foo").swiftTarget() XCTAssertEqual(try fooTarget.objects.map{ $0.pathString }, [ buildPath.appending(components: "Foo.build", "Foo.swift.o").pathString, buildPath.appending(components: "Foo.build", "resource_bundle_accessor.swift.o").pathString, ]) let resourceAccessor = fooTarget.sources.first{ $0.basename == "resource_bundle_accessor.swift" }! let contents: String = try fs.readFileContents(resourceAccessor) XCTAssertMatch(contents, .contains("extension Foundation.Bundle")) // Assert that `Bundle.main` is executed in the compiled binary (and not during compilation) // See https://bugs.swift.org/browse/SR-14555 and https://github.com/apple/swift-package-manager/pull/2972/files#r623861646 XCTAssertMatch(contents, .contains("let mainPath = Bundle.main.")) let barTarget = try result.target(for: "Bar").swiftTarget() XCTAssertEqual(try barTarget.objects.map{ $0.pathString }, [ buildPath.appending(components: "Bar.build", "Bar.swift.o").pathString, ]) } func testSwiftWASIBundleAccessor() throws { // This has a Swift and ObjC target in the same package. let fs = InMemoryFileSystem(emptyFiles: "/PkgA/Sources/Foo/Foo.swift", "/PkgA/Sources/Foo/foo.txt", "/PkgA/Sources/Foo/bar.txt", "/PkgA/Sources/Bar/Bar.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "PkgA", path: .init(path: "/PkgA"), toolsVersion: .v5_2, targets: [ TargetDescription( name: "Foo", resources: [ .init(rule: .copy, path: "foo.txt"), .init(rule: .process(localization: .none), path: "bar.txt"), ] ), TargetDescription( name: "Bar" ), ] ) ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let plan = try BuildPlan( buildParameters: mockBuildParameters(destinationTriple: .wasi), graph: graph, fileSystem: fs, observabilityScope: observability.topScope ) let result = try BuildPlanResult(plan: plan) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let fooTarget = try result.target(for: "Foo").swiftTarget() XCTAssertEqual(try fooTarget.objects.map{ $0.pathString }, [ buildPath.appending(components: "Foo.build", "Foo.swift.o").pathString, buildPath.appending(components: "Foo.build", "resource_bundle_accessor.swift.o").pathString ]) let resourceAccessor = fooTarget.sources.first{ $0.basename == "resource_bundle_accessor.swift" }! let contents: String = try fs.readFileContents(resourceAccessor) XCTAssertMatch(contents, .contains("extension Foundation.Bundle")) // Assert that `Bundle.main` is executed in the compiled binary (and not during compilation) // See https://bugs.swift.org/browse/SR-14555 and https://github.com/apple/swift-package-manager/pull/2972/files#r623861646 XCTAssertMatch(contents, .contains("let mainPath = \"")) let barTarget = try result.target(for: "Bar").swiftTarget() XCTAssertEqual(try barTarget.objects.map{ $0.pathString }, [ buildPath.appending(components: "Bar.build", "Bar.swift.o").pathString, ]) } func testShouldLinkStaticSwiftStdlib() throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift", "/Pkg/Sources/lib/lib.swift" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), targets: [ TargetDescription(name: "exe", dependencies: ["lib"]), TargetDescription(name: "lib", dependencies: []), ]), ], observabilityScope: observability.topScope ) let supportingTriples: [TSCUtility.Triple] = [.x86_64Linux, .arm64Linux, .wasi] for triple in supportingTriples { let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(shouldLinkStaticSwiftStdlib: true, destinationTriple: triple), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, ["-static-stdlib"]) let lib = try result.target(for: "lib").swiftTarget().compileArguments() XCTAssertMatch(lib, ["-static-stdlib"]) let link = try result.buildProduct(for: "exe").linkArguments() XCTAssertMatch(link, ["-static-stdlib"]) } } func testXCFrameworkBinaryTargets(platform: String, arch: String, destinationTriple: TSCUtility.Triple) throws { let Pkg: AbsolutePath = AbsolutePath(path: "/Pkg") let fs = InMemoryFileSystem(emptyFiles: Pkg.appending(components: "Sources", "exe", "main.swift").pathString, Pkg.appending(components: "Sources", "Library", "Library.swift").pathString, Pkg.appending(components: "Sources", "CLibrary", "library.c").pathString, Pkg.appending(components: "Sources", "CLibrary", "include", "library.h").pathString ) try! fs.createDirectory(AbsolutePath(path: "/Pkg/Framework.xcframework"), recursive: true) try! fs.writeFileContents( AbsolutePath(path: "/Pkg/Framework.xcframework/Info.plist"), bytes: ByteString(encodingAsUTF8: """ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>AvailableLibraries</key> <array> <dict> <key>LibraryIdentifier</key> <string>\(platform)-\(arch)</string> <key>LibraryPath</key> <string>Framework.framework</string> <key>SupportedArchitectures</key> <array> <string>\(arch)</string> </array> <key>SupportedPlatform</key> <string>\(platform)</string> </dict> </array> <key>CFBundlePackageType</key> <string>XFWK</string> <key>XCFrameworkFormatVersion</key> <string>1.0</string> </dict> </plist> """)) try! fs.createDirectory(AbsolutePath(path: "/Pkg/StaticLibrary.xcframework"), recursive: true) try! fs.writeFileContents( AbsolutePath(path: "/Pkg/StaticLibrary.xcframework/Info.plist"), bytes: ByteString(encodingAsUTF8: """ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>AvailableLibraries</key> <array> <dict> <key>LibraryIdentifier</key> <string>\(platform)-\(arch)</string> <key>HeadersPath</key> <string>Headers</string> <key>LibraryPath</key> <string>libStaticLibrary.a</string> <key>SupportedArchitectures</key> <array> <string>\(arch)</string> </array> <key>SupportedPlatform</key> <string>\(platform)</string> </dict> </array> <key>CFBundlePackageType</key> <string>XFWK</string> <key>XCFrameworkFormatVersion</key> <string>1.0</string> </dict> </plist> """)) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: try .init(validating: Pkg.pathString), products: [ ProductDescription(name: "exe", type: .executable, targets: ["exe"]), ProductDescription(name: "Library", type: .library(.dynamic), targets: ["Library"]), ProductDescription(name: "CLibrary", type: .library(.dynamic), targets: ["CLibrary"]), ], targets: [ TargetDescription(name: "exe", dependencies: ["Library"]), TargetDescription(name: "Library", dependencies: ["Framework"]), TargetDescription(name: "CLibrary", dependencies: ["StaticLibrary"]), TargetDescription(name: "Framework", path: "Framework.xcframework", type: .binary), TargetDescription(name: "StaticLibrary", path: "StaticLibrary.xcframework", type: .binary), ] ), ], binaryArtifacts: [ .plain("pkg"): [ "Framework": .init(kind: .xcframework, originURL: nil, path: AbsolutePath(path: "/Pkg/Framework.xcframework")), "StaticLibrary": .init(kind: .xcframework, originURL: nil, path: AbsolutePath(path: "/Pkg/StaticLibrary.xcframework")) ] ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(destinationTriple: destinationTriple), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) XCTAssertNoDiagnostics(observability.diagnostics) result.checkProductsCount(3) result.checkTargetsCount(3) let buildPath: AbsolutePath = result.plan.buildParameters.dataPath.appending(components: "debug") let libraryBasicArguments = try result.target(for: "Library").swiftTarget().compileArguments() XCTAssertMatch(libraryBasicArguments, [.anySequence, "-F", "\(buildPath)", .anySequence]) let libraryLinkArguments = try result.buildProduct(for: "Library").linkArguments() XCTAssertMatch(libraryLinkArguments, [.anySequence, "-F", "\(buildPath)", .anySequence]) XCTAssertMatch(libraryLinkArguments, [.anySequence, "-L", "\(buildPath)", .anySequence]) XCTAssertMatch(libraryLinkArguments, [.anySequence, "-framework", "Framework", .anySequence]) let exeCompileArguments = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exeCompileArguments, [.anySequence, "-F", "\(buildPath)", .anySequence]) XCTAssertMatch(exeCompileArguments, [.anySequence, "-I", "\(Pkg.appending(components: "Framework.xcframework", "\(platform)-\(arch)"))", .anySequence]) let exeLinkArguments = try result.buildProduct(for: "exe").linkArguments() XCTAssertMatch(exeLinkArguments, [.anySequence, "-F", "\(buildPath)", .anySequence]) XCTAssertMatch(exeLinkArguments, [.anySequence, "-L", "\(buildPath)", .anySequence]) XCTAssertMatch(exeLinkArguments, [.anySequence, "-framework", "Framework", .anySequence]) let clibraryBasicArguments = try result.target(for: "CLibrary").clangTarget().basicArguments(isCXX: false) XCTAssertMatch(clibraryBasicArguments, [.anySequence, "-F", "\(buildPath)", .anySequence]) XCTAssertMatch(clibraryBasicArguments, [.anySequence, "-I", "\(Pkg.appending(components: "StaticLibrary.xcframework", "\(platform)-\(arch)", "Headers"))", .anySequence]) let clibraryLinkArguments = try result.buildProduct(for: "CLibrary").linkArguments() XCTAssertMatch(clibraryLinkArguments, [.anySequence, "-F", "\(buildPath)", .anySequence]) XCTAssertMatch(clibraryLinkArguments, [.anySequence, "-L", "\(buildPath)", .anySequence]) XCTAssertMatch(clibraryLinkArguments, ["-lStaticLibrary"]) let executablePathExtension = try result.buildProduct(for: "exe").binaryPath.extension ?? "" XCTAssertMatch(executablePathExtension, "") let dynamicLibraryPathExtension = try result.buildProduct(for: "Library").binaryPath.extension XCTAssertMatch(dynamicLibraryPathExtension, "dylib") } func testXCFrameworkBinaryTargets() throws { try testXCFrameworkBinaryTargets(platform: "macos", arch: "x86_64", destinationTriple: .macOS) let arm64Triple = try TSCUtility.Triple("arm64-apple-macosx") try testXCFrameworkBinaryTargets(platform: "macos", arch: "arm64", destinationTriple: arm64Triple) let arm64eTriple = try TSCUtility.Triple("arm64e-apple-macosx") try testXCFrameworkBinaryTargets(platform: "macos", arch: "arm64e", destinationTriple: arm64eTriple) } func testArtifactsArchiveBinaryTargets(artifactTriples:[TSCUtility.Triple], destinationTriple: TSCUtility.Triple) throws -> Bool { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift") let artifactName = "my-tool" let toolPath = AbsolutePath(path: "/Pkg/MyTool.artifactbundle") try fs.createDirectory(toolPath, recursive: true) try fs.writeFileContents( toolPath.appending(component: "info.json"), bytes: ByteString(encodingAsUTF8: """ { "schemaVersion": "1.0", "artifacts": { "\(artifactName)": { "type": "executable", "version": "1.1.0", "variants": [ { "path": "all-platforms/mytool", "supportedTriples": ["\(artifactTriples.map{ $0.tripleString }.joined(separator: "\", \""))"] } ] } } } """)) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), products: [ ProductDescription(name: "exe", type: .executable, targets: ["exe"]), ], targets: [ TargetDescription(name: "exe", dependencies: ["MyTool"]), TargetDescription(name: "MyTool", path: "MyTool.artifactbundle", type: .binary), ] ), ], binaryArtifacts: [ .plain("pkg"): [ "MyTool": .init(kind: .artifactsArchive, originURL: nil, path: toolPath), ] ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: mockBuildParameters(destinationTriple: destinationTriple), graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) XCTAssertNoDiagnostics(observability.diagnostics) result.checkProductsCount(1) result.checkTargetsCount(1) let availableTools = try result.buildProduct(for: "exe").availableTools return availableTools.contains(where: { $0.key == artifactName }) } func testArtifactsArchiveBinaryTargets() throws { XCTAssertTrue(try testArtifactsArchiveBinaryTargets(artifactTriples: [.macOS], destinationTriple: .macOS)) do { let triples = try ["arm64-apple-macosx", "x86_64-apple-macosx", "x86_64-unknown-linux-gnu"].map(TSCUtility.Triple.init) XCTAssertTrue(try testArtifactsArchiveBinaryTargets(artifactTriples: triples, destinationTriple: triples.first!)) } do { let triples = try ["x86_64-unknown-linux-gnu"].map(TSCUtility.Triple.init) XCTAssertFalse(try testArtifactsArchiveBinaryTargets(artifactTriples: triples, destinationTriple: .macOS)) } } func testAddressSanitizer() throws { try sanitizerTest(.address, expectedName: "address") } func testThreadSanitizer() throws { try sanitizerTest(.thread, expectedName: "thread") } func testUndefinedSanitizer() throws { try sanitizerTest(.undefined, expectedName: "undefined") } func testScudoSanitizer() throws { try sanitizerTest(.scudo, expectedName: "scudo") } private func sanitizerTest(_ sanitizer: PackageModel.Sanitizer, expectedName: String) throws { let fs = InMemoryFileSystem(emptyFiles: "/Pkg/Sources/exe/main.swift", "/Pkg/Sources/lib/lib.swift", "/Pkg/Sources/clib/clib.c", "/Pkg/Sources/clib/include/clib.h" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fileSystem: fs, manifests: [ Manifest.createRootManifest( name: "Pkg", path: .init(path: "/Pkg"), targets: [ TargetDescription(name: "exe", dependencies: ["lib", "clib"]), TargetDescription(name: "lib", dependencies: []), TargetDescription(name: "clib", dependencies: []), ]), ], observabilityScope: observability.topScope ) XCTAssertNoDiagnostics(observability.diagnostics) // Unrealistic: we can't enable all of these at once on all platforms. // This test codifies current behavior, not ideal behavior, and // may need to be amended if we change it. var parameters = mockBuildParameters(shouldLinkStaticSwiftStdlib: true) parameters.sanitizers = EnabledSanitizers([sanitizer]) let result = try BuildPlanResult(plan: BuildPlan( buildParameters: parameters, graph: graph, fileSystem: fs, observabilityScope: observability.topScope )) result.checkProductsCount(1) result.checkTargetsCount(3) let exe = try result.target(for: "exe").swiftTarget().compileArguments() XCTAssertMatch(exe, ["-sanitize=\(expectedName)"]) let lib = try result.target(for: "lib").swiftTarget().compileArguments() XCTAssertMatch(lib, ["-sanitize=\(expectedName)"]) let clib = try result.target(for: "clib").clangTarget().basicArguments(isCXX: false) XCTAssertMatch(clib, ["-fsanitize=\(expectedName)"]) XCTAssertMatch(try result.buildProduct(for: "exe").linkArguments(), ["-sanitize=\(expectedName)"]) } }
apache-2.0
6162e3437613f389d258e769da09c2ee
45.514166
432
0.542618
4.979366
false
false
false
false
ImperialCollegeDocWebappGroup/webappProject
webapp/FriendProfile.swift
1
1728
// // FriendProfile.swift // webapp // // Created by ZhangZhuofan on 12/06/2015. // Copyright (c) 2015 Shan, Jinyi. All rights reserved. // import UIKit class FriendProfile: UIViewController { @IBOutlet weak var FriendName: UILabel! var name : String = "" @IBOutlet weak var icon: UIImageView! let link1 : String = "http://www.doc.ic.ac.uk/~jl6613/babyicon.jpeg" var iconUrl: String = "" override func viewDidLoad() { super.viewDidLoad() FriendName.text = name // Do any additional setup after loading the view. let url = NSURL(string: iconUrl) if let data1 = NSData(contentsOfURL: url!) { println("!!!!!2") icon.image = UIImage(data:data1) } self.navigationItem.title = "Friend Profile" self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] self.navigationController?.navigationBar.setBackgroundImage(UIImage(named:"navigation"), forBarMetrics: .Default) self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-3.0
7ac062b3bcab4b5f7f338860c2dc7faa
28.288136
125
0.652199
4.81337
false
false
false
false
GraphQLSwift/Graphiti
Sources/Graphiti/Schema/Schema.swift
1
2739
import GraphQL import NIO public final class Schema<Resolver, Context> { public let schema: GraphQLSchema private init( coders: Coders, components: [Component<Resolver, Context>] ) throws { let typeProvider = SchemaTypeProvider() for component in components { try component.update(typeProvider: typeProvider, coders: coders) } guard let query = typeProvider.query else { fatalError("Query type is required.") } schema = try GraphQLSchema( query: query, mutation: typeProvider.mutation, subscription: typeProvider.subscription, types: typeProvider.types, directives: typeProvider.directives ) } } public extension Schema { convenience init( coders: Coders = Coders(), @ComponentBuilder<Resolver, Context> _ components: () -> Component<Resolver, Context> ) throws { try self.init( coders: coders, components: [components()] ) } convenience init( coders: Coders = Coders(), @ComponentBuilder<Resolver, Context> _ components: () -> [Component<Resolver, Context>] ) throws { try self.init( coders: coders, components: components() ) } func execute( request: String, resolver: Resolver, context: Context, eventLoopGroup: EventLoopGroup, variables: [String: Map] = [:], operationName: String? = nil ) -> EventLoopFuture<GraphQLResult> { do { return try graphql( schema: schema, request: request, rootValue: resolver, context: context, eventLoopGroup: eventLoopGroup, variableValues: variables, operationName: operationName ) } catch { return eventLoopGroup.next().makeFailedFuture(error) } } func subscribe( request: String, resolver: Resolver, context: Context, eventLoopGroup: EventLoopGroup, variables: [String: Map] = [:], operationName: String? = nil ) -> EventLoopFuture<SubscriptionResult> { do { return try graphqlSubscribe( schema: schema, request: request, rootValue: resolver, context: context, eventLoopGroup: eventLoopGroup, variableValues: variables, operationName: operationName ) } catch { return eventLoopGroup.next().makeFailedFuture(error) } } }
mit
d4c60e5a7fcff33d46cbf053f8ce72e8
27.237113
95
0.550931
5.370588
false
false
false
false
smartystreets/smartystreets-ios-sdk
samples/Sources/swiftExamples/USStreetSingleAddressExample.swift
1
2620
import Foundation import SmartyStreets class USStreetSingleAddressExample { func run() -> String { let id = "ID" let hostname = "HOSTNAME" // The appropriate license values to be used for your subscriptions // can be found on the Subscriptions page of the account dashboard. // https://www.smartystreets.com/docs/cloud/licensing let client = ClientBuilder(id: id, hostname: hostname).withLicenses(licenses:["us-core-cloud"]).buildUsStreetApiClient() // Documentation for input fields can be found at: // https://smartystreets.com/docs/us-street-api#input-fields var lookup = USStreetLookup() lookup.inputId = "24601" lookup.addressee = "John Doe" lookup.street = "1600 Amphitheatre Pkwy" lookup.street2 = "closet under the stairs" lookup.secondary = "APT 2" lookup.urbanization = "" // Only applies to Puerto Rico addresses lookup.city = "Mountain View" lookup.state = "CA" lookup.zipCode = "94043" lookup.maxCandidates = 3 lookup.matchStrategy = "invalid" // "invalid" is the most permissive match, // this will always return at least one result even if the address is invalid. // Refer to the documentation for additional Match Strategy options. var error: NSError! = nil _ = client.sendLookup(lookup: &lookup, error: &error) if let error = error { let output = """ Domain: \(error.domain) Error Code: \(error.code) Description: \(error.userInfo[NSLocalizedDescriptionKey] as! NSString) """ return output } let results:[USStreetCandidate] = lookup.result var output = "Results:\n" if results.count == 0 { return "Error. Address is not valid" } let candidate = results[0] output.append(""" There is at least one candidate.\n If the match parameter is set to STRICT, the address is valid.\n Otherwise, check the Analysis output fields to see if the address is valid.\n \nZIP Code: \(candidate.components?.zipCode ?? "") \nCounty: \(candidate.metadata?.countyName ?? "") \nLatitude: \(candidate.metadata?.latitude ?? 0.0) \nLongitude: \(candidate.metadata?.longitude ?? 0.0) """ ) return output } }
apache-2.0
e4914f48cfafb9cee2fe5ca1c7e37631
41.258065
189
0.569466
4.71223
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Stats/Insights/Insights Management/AddInsightTableViewController.swift
1
4537
import UIKit import Gridicons class AddInsightTableViewController: UITableViewController { // MARK: - Properties private weak var insightsDelegate: SiteStatsInsightsDelegate? private var insightsShown = [StatSection]() private var selectedStat: StatSection? private lazy var tableHandler: ImmuTableViewHandler = { return ImmuTableViewHandler(takeOver: self) }() // MARK: - Init override init(style: UITableView.Style) { super.init(style: style) navigationItem.title = NSLocalizedString("Add New Stats Card", comment: "Add New Stats Card view title") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } convenience init(insightsDelegate: SiteStatsInsightsDelegate, insightsShown: [StatSection]) { self.init(style: .grouped) self.insightsDelegate = insightsDelegate self.insightsShown = insightsShown } // MARK: - View override func viewDidLoad() { super.viewDidLoad() ImmuTable.registerRows([AddInsightStatRow.self], tableView: tableView) reloadViewModel() WPStyleGuide.configureColors(view: view, tableView: tableView) WPStyleGuide.configureAutomaticHeightRows(for: tableView) tableView.accessibilityIdentifier = "Add Insight Table" navigationItem.leftBarButtonItem = UIBarButtonItem(image: .gridicon(.cross), style: .plain, target: self, action: #selector(doneTapped)) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if selectedStat == nil { insightsDelegate?.addInsightDismissed?() } } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 38 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0 } @objc private func doneTapped() { dismiss(animated: true, completion: nil) } } private extension AddInsightTableViewController { // MARK: - Table Model func reloadViewModel() { tableHandler.viewModel = tableViewModel() } func tableViewModel() -> ImmuTable { return ImmuTable(sections: [ sectionForCategory(.general), sectionForCategory(.postsAndPages), sectionForCategory(.activity) ] ) } // MARK: - Table Sections func sectionForCategory(_ category: InsightsCategories) -> ImmuTableSection { return ImmuTableSection(headerText: category.title, rows: category.insights.map { let enabled = !insightsShown.contains($0) return AddInsightStatRow(title: $0.insightManagementTitle, enabled: enabled, action: enabled ? rowActionFor($0) : nil) } ) } func rowActionFor(_ statSection: StatSection) -> ImmuTableAction { return { [unowned self] row in self.selectedStat = statSection self.insightsDelegate?.addInsightSelected?(statSection) self.dismiss(animated: true, completion: nil) } } // MARK: - Insights Categories enum InsightsCategories { case general case postsAndPages case activity var title: String { switch self { case .general: return NSLocalizedString("General", comment: "Add New Stats Card category title") case .postsAndPages: return NSLocalizedString("Posts and Pages", comment: "Add New Stats Card category title") case .activity: return NSLocalizedString("Activity", comment: "Add New Stats Card category title") } } var insights: [StatSection] { switch self { case .general: return [.insightsAllTime, .insightsMostPopularTime, .insightsAnnualSiteStats, .insightsTodaysStats] case .postsAndPages: return [.insightsLatestPostSummary, .insightsPostingActivity, .insightsTagsAndCategories] case .activity: return [.insightsCommentsPosts, .insightsFollowersEmail, .insightsFollowerTotals, .insightsPublicize] } } } }
gpl-2.0
90d428ed52a6d68cf3c76d2d87f01d39
32.858209
144
0.61803
5.337647
false
false
false
false
amnuaym/TiAppBuilder
Day0/HelloWorld/HelloWorld/AppDelegate.swift
1
4588
// // AppDelegate.swift // HelloWorld // // Created by Amnuay M on 8/3/17. // Copyright © 2017 Amnuay M. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "HelloWorld") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
gpl-3.0
e0d53397a4357c775cd4d971eb7e71aa
48.322581
285
0.685415
5.865729
false
false
false
false
allbto/WayThere
ios/WayThere/Pods/Alamofire/Source/Upload.swift
93
6812
// Alamofire.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation extension Manager { private enum Uploadable { case Data(NSURLRequest, NSData) case File(NSURLRequest, NSURL) case Stream(NSURLRequest, NSInputStream) } private func upload(uploadable: Uploadable) -> Request { var uploadTask: NSURLSessionUploadTask! var HTTPBodyStream: NSInputStream? switch uploadable { case .Data(let request, let data): dispatch_sync(queue) { uploadTask = self.session.uploadTaskWithRequest(request, fromData: data) } case .File(let request, let fileURL): dispatch_sync(queue) { uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL) } case .Stream(let request, var stream): dispatch_sync(queue) { uploadTask = self.session.uploadTaskWithStreamedRequest(request) } HTTPBodyStream = stream } let request = Request(session: session, task: uploadTask) if HTTPBodyStream != nil { request.delegate.taskNeedNewBodyStream = { _, _ in return HTTPBodyStream } } delegate[request.delegate.task] = request.delegate if startRequestsImmediately { request.resume() } return request } // MARK: File /** Creates a request for uploading a file to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. :param: URLRequest The URL request :param: file The file to upload :returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { return upload(.File(URLRequest.URLRequest, file)) } /** Creates a request for uploading a file to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. :param: method The HTTP method. :param: URLString The URL string. :param: file The file to upload :returns: The created upload request. */ public func upload(method: Method, _ URLString: URLStringConvertible, file: NSURL) -> Request { return upload(URLRequest(method, URLString), file: file) } // MARK: Data /** Creates a request for uploading data to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. :param: URLRequest The URL request :param: data The data to upload :returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { return upload(.Data(URLRequest.URLRequest, data)) } /** Creates a request for uploading data to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. :param: method The HTTP method. :param: URLString The URL string. :param: data The data to upload :returns: The created upload request. */ public func upload(method: Method, _ URLString: URLStringConvertible, data: NSData) -> Request { return upload(URLRequest(method, URLString), data: data) } // MARK: Stream /** Creates a request for uploading a stream to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. :param: URLRequest The URL request :param: stream The stream to upload :returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { return upload(.Stream(URLRequest.URLRequest, stream)) } /** Creates a request for uploading a stream to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. :param: method The HTTP method. :param: URLString The URL string. :param: stream The stream to upload. :returns: The created upload request. */ public func upload(method: Method, _ URLString: URLStringConvertible, stream: NSInputStream) -> Request { return upload(URLRequest(method, URLString), stream: stream) } } // MARK: - extension Request { // MARK: - UploadTaskDelegate class UploadTaskDelegate: DataTaskDelegate { var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask } var uploadProgress: ((Int64, Int64, Int64) -> Void)! // MARK: - NSURLSessionTaskDelegate // MARK: Override Closures var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? // MARK: Delegate Methods func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if taskDidSendBodyData != nil { taskDidSendBodyData!(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else { progress.totalUnitCount = totalBytesExpectedToSend progress.completedUnitCount = totalBytesSent uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend) } } } }
mit
61c96ed9c62c330b377ff4cc03479a47
34.842105
162
0.665051
5.174772
false
false
false
false
calkinssean/woodshopBMX
WoodshopBMX/WoodshopBMX/AddItemViewController.swift
1
10061
// // AddItemViewController.swift // M3rch // // Created by Sean Calkins on 4/4/16. // Copyright © 2016 Sean Calkins. All rights reserved. // import UIKit class AddItemViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { //MARK: - Properties var currentEvent: Event? var currentItem: Item? var arrayOfSubItems = [SubItem]() let pickerController = UIImagePickerController() var imageName: String? var currentStock: Int = 0 var newItem = true var sizeStrings = [String]() //MARK: - Outlets @IBOutlet weak var backgroundImageView: UIImageView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var itemNameTextField: UITextField! @IBOutlet weak var itemPriceTextField: UITextField! @IBOutlet weak var purchasedPriceTextField: UITextField! @IBOutlet weak var currentStockLabel: UILabel! //MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(self.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil ) NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(self.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil ) self.imageView.frame.size = CGSizeMake(self.view.frame.width / 2, self.view.frame.width / 2) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let event = self.currentEvent { if event.name == "WoodShop" { self.backgroundImageView.image = UIImage(named: "wood copy") } } self.setUpCurrentStockLabel() } //MARK: - Save tapped @IBAction func colorsAndSizesTapped(sender: UIButton) { if let itemName = itemNameTextField.text { if let price = Double(itemPriceTextField.text!) { if let purchasedPrice = Double(purchasedPriceTextField.text!) { if let imageName = self.imageName { if self.newItem == true { if DataController.sharedInstance.seedItem(itemName, price: price, purchasedPrice: purchasedPrice, imageName: imageName, event: self.currentEvent!) { let fetchedItems = DataController.sharedInstance.fetchItems() for item in fetchedItems { if item.imageName == imageName { self.currentItem = item } } self.newItem = false self.performSegueWithIdentifier("showColorsSegue", sender: self) } else { presentAlert("Please Enter All Fields Correctly") } } else { self.performSegueWithIdentifier("showColorsSegue", sender: self) } } else { presentAlert("Please Take a Picture") } } else { presentAlert("Please Enter a Purchased Price") } } else { presentAlert("Please Enter a Selling Price") } } else { presentAlert("Please Enter a Name") } } //MARK: - Take Picture Tapped @IBAction func takePictureTapped(sender: UIButton) { pickerController.delegate = self //checks if camera is available, if not look in photo library if UIImagePickerController.isSourceTypeAvailable(.Camera) { pickerController.sourceType = .Camera pickerController.allowsEditing = true } else { pickerController.allowsEditing = true pickerController.sourceType = .PhotoLibrary } self.presentViewController(pickerController, animated: true) { } } //MARK: - Photo picker delegate func imagePickerControllerDidCancel(picker: UIImagePickerController) { pickerController.dismissViewControllerAnimated(true) { } } //MARK: - Image picker controller func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage { //creates a unique filename from timestamp let fileName: NSTimeInterval = NSDate().timeIntervalSince1970 self.imageName = "\(fileName).png" if let imageName = self.imageName { //sets the image view to the chosen image self.imageView.image = editedImage //creates a new filepath from docs directory and fileName let filepath = getDocumentsDirectory().URLByAppendingPathComponent(imageName) //converts image into data let pngData = UIImagePNGRepresentation(editedImage) do { //saves image to filepath in data form try pngData?.writeToURL(filepath, options: []) } catch { print("There was an error saving the image: \(error)") } } } pickerController.dismissViewControllerAnimated(true) { } } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { self.imageView.image = image pickerController.dismissViewControllerAnimated(true) { } } //MARK: - Prepare for segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showColorsSegue" { let controller = segue.destinationViewController as! ColorsAndSizesViewController controller.currentItem = self.currentItem controller.currentEvent = self.currentEvent } } //MARK: - Present Alert func presentAlert(message: String) { let alert = UIAlertController(title: "\(message)", message: nil, preferredStyle: .Alert) let action = UIAlertAction(title: "Ok", style: .Default) { (action: UIAlertAction) -> Void in } alert.addAction(action) presentViewController(alert, animated: true, completion: nil) } //MARK: - Set Up Current Stock Label func setUpCurrentStockLabel() { let fetchedSubItems = DataController.sharedInstance.fetchSubItems() self.arrayOfSubItems.removeAll() for subItem in fetchedSubItems { if subItem.item == self.currentItem { self.arrayOfSubItems.append(subItem) } } self.currentStock = 0 for item in arrayOfSubItems { self.currentStock = Int(self.currentStock + Int(item.quantity!)) } self.currentStockLabel.text = "\(self.currentStock)" } //MARK: - Textfield Delegate func textFieldShouldReturn(textField: UITextField) -> Bool { if textField == self.itemNameTextField { self.itemNameTextField.resignFirstResponder() self.itemPriceTextField.becomeFirstResponder() } if textField == self.itemPriceTextField { self.itemPriceTextField.resignFirstResponder() self.purchasedPriceTextField.becomeFirstResponder() } if textField == self.purchasedPriceTextField { self.purchasedPriceTextField.resignFirstResponder() } return true } func textFieldDidBeginEditing(textField: UITextField) { } //MARK: - Scroll view keyboard methods func adjustInsetForKeyboardShow(show: Bool, notification: NSNotification) { guard let value = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue else { return } scrollView.contentInset.bottom = 0 scrollView.scrollIndicatorInsets.bottom = 0 let keyboardFrame = value.CGRectValue() let adjustmentHeight = (CGRectGetHeight(keyboardFrame) + 20) * (show ? 1 : -1) scrollView.contentInset.bottom += adjustmentHeight scrollView.scrollIndicatorInsets.bottom += adjustmentHeight } func keyboardWillShow(notification: NSNotification) { adjustInsetForKeyboardShow(true, notification: notification) } func keyboardWillHide(notification: NSNotification) { adjustInsetForKeyboardShow(false, notification: notification) } //MARK: - Unwind Segue @IBAction func unwindSegue(segue: UIStoryboardSegue){ self.newItem = false } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } }
apache-2.0
5ac8699b15184febde87ee28a1c7b89f
33.452055
176
0.555964
6.371121
false
false
false
false
urbanthings/urbanthings-sdk-apple
UrbanThingsAPI/Public/Request/TransitAgencyRequest.swift
1
1515
// // TransitAgencyRequest.swift // UrbanThingsAPI // // Created by Mark Woollard on 08/05/2016. // Copyright © 2016 UrbanThings. All rights reserved. // import Foundation /// Defines a request for a transit agency. public protocol TransitAgencyRequest: GetRequest { associatedtype Result = TransitAgency /// The agency ID for the transit agency to fetch data for. var agencyID: String { get } } /// Default implementation of `TransitAgencyRequest` protocol provided by the API as standard means /// of passing parameters to API request methods. You may provide your own implementation if needed to pass to the API /// request methods. public struct UTTransitAgencyRequest: TransitAgencyRequest { public typealias Result = TransitAgency public typealias Parser = (_ json: Any?, _ logger: Logger) throws -> Result public let endpoint = "static/agencies" /// The agency ID for the transit agency to fetch data for. public let agencyID: String /// Parser to use when processing response to the request public let parser: Parser /// Initialize an instance of `UTTransitAgencyRequest` /// - parameters: /// - agencyID: The agency ID for the transit agency to fetch data for. /// - parser: Optional custom parser to process the response from the server. If omitted standard parser will be used. public init(agencyID: String, parser: @escaping Parser = urbanThingsParser) { self.parser = parser self.agencyID = agencyID } }
apache-2.0
17d3cd79f8b5e5d0677d997efbc3a2a8
34.209302
124
0.719287
4.560241
false
false
false
false
jquave/LumaJSON
LumaJSON.swift
1
2630
// // LumaJSON.swift // LumaJSON // // Created by Jameson Quave on 2/28/15. // Copyright (c) 2015 Lumarow, LLC. All rights reserved. // import Foundation class LumaJSONObject: Printable { var value: AnyObject? subscript(index: Int) -> LumaJSONObject? { return (value as? [AnyObject]).map { LumaJSONObject($0[index]) } } subscript(key: String) -> LumaJSONObject? { return (value as? NSDictionary).map { LumaJSONObject($0[key]) } } subscript(key: String) -> AnyObject? { get { return self[key]?.value } } subscript(key: Int) -> AnyObject? { get { return self[key]?.value } } init(_ value: AnyObject?) { self.value = value } var description: String { get { return "LumaJSONObject: \(self.value)" } } } struct LumaJSON { static var logErrors = true static func jsonFromObject(object: [String: AnyObject]) -> String? { var err: NSError? if let jsonData = NSJSONSerialization.dataWithJSONObject( (object as NSDictionary) , options: nil, error: &err) { if let jsonStr = NSString(data: jsonData, encoding: NSUTF8StringEncoding) { return jsonStr as String } } else if(err != nil) { if LumaJSON.logErrors { println( err?.localizedDescription ) } } return nil } static func parse(json: String) -> LumaJSONObject? { if let jsonData = json.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false){ var err: NSError? let parsed: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableLeaves, error: &err) if let parsedArray = parsed as? NSArray { return LumaJSONObject(parsedArray) } if let parsedDictionary = parsed as? NSDictionary { return LumaJSONObject(parsedDictionary) } if LumaJSON.logErrors && (err != nil) { println(err?.localizedDescription) } return LumaJSONObject(parsed) } return nil } } extension String { func toJSON() -> LumaJSONObject? { return LumaJSON.parse(self) } init? (jsonDictionary: [String: AnyObject]) { if let t = LumaJSON.jsonFromObject(jsonDictionary) { self = t } else { return nil } } }
mit
ce5d63e70e464a4eec001aaec475262f
25.039604
123
0.542586
4.573913
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/AppDelegate.swift
1
17705
import AppboyKit import AppCenter import AppCenterDistribute import FBSDKCoreKit import Firebase import Foundation #if DEBUG @testable import KsApi #else import KsApi #endif import AppboySegment import Kickstarter_Framework import Library import Optimizely import Prelude import ReactiveExtensions import ReactiveSwift import SafariServices import Segment import UIKit import UserNotifications @UIApplicationMain internal final class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? fileprivate let viewModel: AppDelegateViewModelType = AppDelegateViewModel() internal var rootTabBarController: RootTabBarViewController? { return self.window?.rootViewController as? RootTabBarViewController } func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { // FBSDK initialization ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions) Settings.shouldLimitEventAndDataUsage = true // Braze initialization SEGAppboyIntegrationFactory.instance()?.saveLaunchOptions(launchOptions) SEGAppboyIntegrationFactory.instance()?.appboyOptions = [ABKInAppMessageControllerDelegateKey: self] UIView.doBadSwizzleStuff() UIViewController.doBadSwizzleStuff() UIImageView.appearance(whenContainedInInstancesOf: [UITabBar.self]) .accessibilityIgnoresInvertColors = true AppEnvironment.replaceCurrentEnvironment( AppEnvironment.fromStorage( ubiquitousStore: NSUbiquitousKeyValueStore.default, userDefaults: UserDefaults.standard ) ) #if DEBUG if KsApi.Secrets.isOSS { AppEnvironment.replaceCurrentEnvironment(apiService: MockService()) } #endif self.viewModel.outputs.updateCurrentUserInEnvironment .observeForUI() .observeValues { [weak self] user in AppEnvironment.updateCurrentUser(user) AppEnvironment.current.ksrAnalytics.identify(newUser: user) self?.viewModel.inputs.currentUserUpdatedInEnvironment() } self.viewModel.outputs.forceLogout .observeForUI() .observeValues { AppEnvironment.logout() NotificationCenter.default.post(.init(name: .ksr_sessionEnded, object: nil)) } self.viewModel.outputs.updateConfigInEnvironment .observeForUI() .observeValues { [weak self] config in AppEnvironment.updateConfig(config) self?.viewModel.inputs.didUpdateConfig(config) } self.viewModel.outputs.postNotification .observeForUI() .observeValues(NotificationCenter.default.post) self.viewModel.outputs.presentViewController .observeForUI() .observeValues { [weak self] in self?.rootTabBarController?.dismiss(animated: true, completion: nil) self?.rootTabBarController?.present($0, animated: true, completion: nil) } self.viewModel.outputs.goToDiscovery .observeForUI() .observeValues { [weak self] in self?.rootTabBarController?.switchToDiscovery(params: $0) } self.viewModel.outputs.goToActivity .observeForUI() .observeValues { [weak self] in self?.rootTabBarController?.switchToActivities() } self.viewModel.outputs.goToDashboard .observeForUI() .observeValues { [weak self] in self?.rootTabBarController?.switchToDashboard(project: $0) } self.viewModel.outputs.goToCreatorMessageThread .observeForUI() .observeValues { [weak self] in self?.goToCreatorMessageThread($0, $1) } self.viewModel.outputs.goToLoginWithIntent .observeForControllerAction() .observeValues { [weak self] intent in let vc = LoginToutViewController.configuredWith(loginIntent: intent) let nav = UINavigationController(rootViewController: vc) nav.modalPresentationStyle = .formSheet self?.rootTabBarController?.present(nav, animated: true, completion: nil) } self.viewModel.outputs.goToMessageThread .observeForUI() .observeValues { [weak self] in self?.goToMessageThread($0) } self.viewModel.outputs.goToProjectActivities .observeForUI() .observeValues { [weak self] in self?.goToProjectActivities($0) } self.viewModel.outputs.goToSearch .observeForUI() .observeValues { [weak self] in self?.rootTabBarController?.switchToSearch() } self.viewModel.outputs.goToMobileSafari .observeForUI() .observeValues { UIApplication.shared.open($0) } self.viewModel.outputs.goToLandingPage .observeForUI() .observeValues { [weak self] in let isIpad = AppEnvironment.current.device.userInterfaceIdiom == .pad let landingPage = LandingPageViewController() |> \.modalPresentationStyle .~ (isIpad ? .formSheet : .fullScreen) self?.rootTabBarController?.present(landingPage, animated: true) } self.viewModel.outputs.applicationIconBadgeNumber .observeForUI() .observeValues { UIApplication.shared.applicationIconBadgeNumber = $0 } self.viewModel.outputs.pushTokenRegistrationStarted .observeForUI() .observeValues { print("📲 [Push Registration] Push token registration started 🚀") } self.viewModel.outputs.pushTokenSuccessfullyRegistered .observeForUI() .observeValues { token in print("📲 [Push Registration] Push token successfully registered (\(token)) ✨") } self.viewModel.outputs.registerPushTokenInSegment .observeForUI() .observeValues { token in Analytics.shared().registeredForRemoteNotifications(withDeviceToken: token) } self.viewModel.outputs.showAlert .observeForUI() .observeValues { [weak self] in self?.presentContextualPermissionAlert($0) } self.viewModel.outputs.unregisterForRemoteNotifications .observeForUI() .observeValues(UIApplication.shared.unregisterForRemoteNotifications) self.viewModel.outputs.configureOptimizely .observeForUI() .observeValues { [weak self] key, logLevel, dispatchInterval in self?.configureOptimizely(with: key, logLevel: logLevel, dispatchInterval: dispatchInterval) } self.viewModel.outputs.configureAppCenterWithData .observeForUI() .observeValues { data in AppCenter.userId = data.userId AppCenter.start( withAppSecret: data.appSecret, services: [ Distribute.self ] ) } #if RELEASE || APPCENTER self.viewModel.outputs.configureFirebase .observeForUI() .observeValues { FirebaseApp.configure() AppEnvironment.current.ksrAnalytics.logEventCallback = { event, _ in Crashlytics.crashlytics().log(format: "%@", arguments: getVaList([event])) } } #endif self.viewModel.outputs.synchronizeUbiquitousStore .observeForUI() .observeValues { _ = AppEnvironment.current.ubiquitousStore.synchronize() } self.viewModel.outputs.setApplicationShortcutItems .observeForUI() .observeValues { shortcutItems in UIApplication.shared.shortcutItems = shortcutItems.map { $0.applicationShortcutItem } } self.viewModel.outputs.findRedirectUrl .observeForUI() .observeValues { [weak self] in self?.findRedirectUrl($0) } self.viewModel.outputs.goToCategoryPersonalizationOnboarding .observeForControllerAction() .observeValues { [weak self] in let categorySelectionViewController = LandingViewController.instantiate() let navController = NavigationController(rootViewController: categorySelectionViewController) let isIpad = AppEnvironment.current.device.userInterfaceIdiom == .pad navController.modalPresentationStyle = isIpad ? .formSheet : .fullScreen self?.rootTabBarController?.present(navController, animated: true) } self.viewModel.outputs.emailVerificationCompleted .observeForUI() .observeValues { [weak self] message, success in self?.rootTabBarController?.dismiss(animated: false, completion: nil) self?.rootTabBarController? .messageBannerViewController?.showBanner(with: success ? .success : .error, message: message) } NotificationCenter.default .addObserver(forName: Notification.Name.ksr_sessionStarted, object: nil, queue: nil) { [weak self] _ in self?.viewModel.inputs.userSessionStarted() } NotificationCenter.default .addObserver( forName: Notification.Name.ksr_showNotificationsDialog, object: nil, queue: nil ) { [weak self] in self?.viewModel.inputs.showNotificationDialog(notification: $0) } NotificationCenter.default .addObserver(forName: Notification.Name.ksr_sessionEnded, object: nil, queue: nil) { [weak self] _ in self?.viewModel.inputs.userSessionEnded() } self.viewModel.outputs.configureSegment .observeValues { writeKey in let configuration = Analytics.configuredClient(withWriteKey: writeKey) Analytics.setup(with: configuration) AppEnvironment.current.ksrAnalytics.configureSegmentClient(Analytics.shared()) } self.viewModel.outputs.segmentIsEnabled .observeValues { enabled in enabled ? Analytics.shared().enable() : Analytics.shared().disable() } NotificationCenter.default .addObserver( forName: Notification.Name.ksr_configUpdated, object: nil, queue: nil ) { [weak self] _ in self?.viewModel.inputs.configUpdatedNotificationObserved() } NotificationCenter.default .addObserver( forName: Notification.Name.ksr_perimeterXCaptcha, object: nil, queue: nil ) { [weak self] note in self?.viewModel.inputs.perimeterXCaptchaTriggeredWithUserInfo(note.userInfo) } self.window?.tintColor = .ksr_create_700 self.viewModel.inputs.applicationDidFinishLaunching( application: application, launchOptions: launchOptions ) self.viewModel.outputs.goToPerimeterXCaptcha .observeForControllerAction() .observeValues { response in self.goToPerimeterXCaptcha(response) } UNUserNotificationCenter.current().delegate = self return self.viewModel.outputs.applicationDidFinishLaunchingReturnValue } func applicationWillEnterForeground(_: UIApplication) { self.viewModel.inputs.applicationWillEnterForeground() } func applicationDidEnterBackground(_: UIApplication) { self.viewModel.inputs.applicationDidEnterBackground() } func application( _: UIApplication, continue userActivity: NSUserActivity, restorationHandler _: @escaping ([UIUserActivityRestoring]?) -> Void ) -> Bool { return self.viewModel.inputs.applicationContinueUserActivity(userActivity) } func application( _ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:] ) -> Bool { // If this is not a Facebook login call, handle the potential deep-link guard !ApplicationDelegate.shared.application(app, open: url, options: options) else { return true } return self.viewModel.inputs.applicationOpenUrl( application: app, url: url, options: options ) } // MARK: - Remote notifications internal func application( _: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) { self.viewModel.inputs.didRegisterForRemoteNotifications(withDeviceTokenData: deviceToken) } internal func application( _: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error ) { print("🔴 Failed to register for remote notifications: \(error.localizedDescription)") } func application( _: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler _: @escaping (UIBackgroundFetchResult) -> Void ) { SEGAppboyIntegrationFactory.instance()?.saveRemoteNotification(userInfo) } internal func applicationDidReceiveMemoryWarning(_: UIApplication) { self.viewModel.inputs.applicationDidReceiveMemoryWarning() } internal func application( _: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void ) { self.viewModel.inputs.applicationPerformActionForShortcutItem(shortcutItem) completionHandler(true) } // MARK: - Functions private func configureOptimizely( with key: String, logLevel: OptimizelyLogLevelType, dispatchInterval: TimeInterval ) { let eventDispatcher = DefaultEventDispatcher(timerInterval: dispatchInterval) let optimizelyClient = OptimizelyClient( sdkKey: key, eventDispatcher: eventDispatcher, defaultLogLevel: logLevel.logLevel ) optimizelyClient.start(resourceTimeout: 3) { [weak self] result in guard let self = self else { return } let optimizelyConfigurationError = self.viewModel.inputs.optimizelyConfigured(with: result) guard let optimizelyError = optimizelyConfigurationError else { print("🔮 Optimizely SDK Successfully Configured") AppEnvironment.updateOptimizelyClient(optimizelyClient) self.viewModel.inputs.didUpdateOptimizelyClient(optimizelyClient) return } print("🔴 Optimizely SDK Configuration Failed with Error: \(optimizelyError.localizedDescription)") Crashlytics.crashlytics().record(error: optimizelyError) self.viewModel.inputs.optimizelyClientConfigurationFailed() } } fileprivate func presentContextualPermissionAlert(_ notification: Notification) { guard let context = notification.userInfo?.values.first as? PushNotificationDialog.Context else { return } let alert = UIAlertController(title: context.title, message: context.message, preferredStyle: .alert) alert.addAction( UIAlertAction(title: Strings.project_star_ok(), style: .default) { [weak self] _ in self?.viewModel.inputs.didAcceptReceivingRemoteNotifications() } ) alert.addAction( UIAlertAction(title: PushNotificationDialog.titleForDismissal, style: .cancel, handler: { _ in PushNotificationDialog.didDenyAccess(for: context) }) ) DispatchQueue.main.async { if let viewController = notification.userInfo?[UserInfoKeys.viewController] as? UIViewController { viewController.present(alert, animated: true, completion: nil) } else { self.rootTabBarController?.present(alert, animated: true, completion: nil) } } } private func goToMessageThread(_ messageThread: MessageThread) { self.rootTabBarController?.switchToMessageThread(messageThread) } private func goToPerimeterXCaptcha(_ response: PerimeterXBlockResponseType) { response.displayCaptcha(on: self.window?.rootViewController) } private func goToCreatorMessageThread(_ projectId: Param, _ messageThread: MessageThread) { self.rootTabBarController? .switchToCreatorMessageThread(projectId: projectId, messageThread: messageThread) } private func goToProjectActivities(_ projectId: Param) { self.rootTabBarController?.switchToProjectActivities(projectId: projectId) } private func findRedirectUrl(_ url: URL) { let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil) let task = session.dataTask(with: url) task.resume() } } // MARK: - URLSessionTaskDelegate extension AppDelegate: URLSessionTaskDelegate { public func urlSession( _: URLSession, task _: URLSessionTask, willPerformHTTPRedirection _: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void ) { request.url.doIfSome(self.viewModel.inputs.foundRedirectUrl) completionHandler(nil) } } // MARK: - UNUserNotificationCenterDelegate extension AppDelegate: UNUserNotificationCenterDelegate { public func userNotificationCenter( _: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void ) { self.rootTabBarController?.didReceiveBadgeValue(notification.request.content.badge as? Int) completionHandler([.banner, .list]) } func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completion: @escaping () -> Void ) { guard let rootTabBarController = self.rootTabBarController else { completion() return } // Braze let factory = SEGAppboyIntegrationFactory.instance() userNotificationCenterDidReceiveResponse(appBoy: Appboy.sharedInstance()) { factory?.appboyHelper.userNotificationCenter(center, receivedNotificationResponse: response) } isNil: { factory?.appboyHelper.save(center, notificationResponse: response) } self.viewModel.inputs.didReceive(remoteNotification: response.notification.request.content.userInfo) rootTabBarController.didReceiveBadgeValue(response.notification.request.content.badge as? Int) completion() } } // MARK: - ABKInAppMessageControllerDelegate extension AppDelegate: ABKInAppMessageControllerDelegate { func before(inAppMessageDisplayed inAppMessage: ABKInAppMessage) -> ABKInAppMessageDisplayChoice { return self.viewModel.inputs.brazeWillDisplayInAppMessage(inAppMessage) } }
apache-2.0
3e862443345c511a36f5c952b7aac10a
32.242481
109
0.724512
5.209131
false
true
false
false
tjw/swift
stdlib/public/core/Hasher.swift
1
10478
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Defines the Hasher struct, representing Swift's standard hash function. // //===----------------------------------------------------------------------===// import SwiftShims internal protocol _HasherCore { init(seed: (UInt64, UInt64)) mutating func compress(_ value: UInt64) mutating func finalize(tailAndByteCount: UInt64) -> UInt64 } @inline(__always) internal func _loadPartialUnalignedUInt64LE( _ p: UnsafeRawPointer, byteCount: Int ) -> UInt64 { var result: UInt64 = 0 switch byteCount { case 7: result |= UInt64(p.load(fromByteOffset: 6, as: UInt8.self)) &<< 48 fallthrough case 6: result |= UInt64(p.load(fromByteOffset: 5, as: UInt8.self)) &<< 40 fallthrough case 5: result |= UInt64(p.load(fromByteOffset: 4, as: UInt8.self)) &<< 32 fallthrough case 4: result |= UInt64(p.load(fromByteOffset: 3, as: UInt8.self)) &<< 24 fallthrough case 3: result |= UInt64(p.load(fromByteOffset: 2, as: UInt8.self)) &<< 16 fallthrough case 2: result |= UInt64(p.load(fromByteOffset: 1, as: UInt8.self)) &<< 8 fallthrough case 1: result |= UInt64(p.load(fromByteOffset: 0, as: UInt8.self)) fallthrough case 0: return result default: _sanityCheckFailure() } } /// This is a buffer for segmenting arbitrary data into 8-byte chunks. Buffer /// storage is represented by a single 64-bit value in the format used by the /// finalization step of SipHash. (The least significant 56 bits hold the /// trailing bytes, while the most significant 8 bits hold the count of bytes /// appended so far, modulo 256. The count of bytes currently stored in the /// buffer is in the lower three bits of the byte count.) internal struct _HasherTailBuffer { // msb lsb // +---------+-------+-------+-------+-------+-------+-------+-------+ // |byteCount| tail (<= 56 bits) | // +---------+-------+-------+-------+-------+-------+-------+-------+ internal var value: UInt64 @inline(__always) internal init() { self.value = 0 } @inline(__always) internal init(tail: UInt64, byteCount: UInt64) { // byteCount can be any value, but we only keep the lower 8 bits. (The // lower three bits specify the count of bytes stored in this buffer.) _sanityCheck(tail & ~(1 << ((byteCount & 7) << 3) - 1) == 0) self.value = (byteCount &<< 56 | tail) } internal var tail: UInt64 { @inline(__always) get { return value & ~(0xFF &<< 56) } } internal var byteCount: UInt64 { @inline(__always) get { return value &>> 56 } } internal var isFinalized: Bool { @inline(__always) get { return value == 1 } } @inline(__always) internal mutating func finalize() { // A byteCount of 0 with a nonzero tail never occurs during normal use. value = 1 } @inline(__always) internal mutating func append(_ bytes: UInt64) -> UInt64 { let c = byteCount & 7 if c == 0 { value = value &+ (8 &<< 56) return bytes } let shift = c &<< 3 let chunk = tail | (bytes &<< shift) value = (((value &>> 56) &+ 8) &<< 56) | (bytes &>> (64 - shift)) return chunk } @inline(__always) internal mutating func append(_ bytes: UInt64, count: UInt64) -> UInt64? { _sanityCheck(count >= 0 && count < 8) _sanityCheck(bytes & ~((1 &<< (count &<< 3)) &- 1) == 0) let c = byteCount & 7 let shift = c &<< 3 if c + count < 8 { value = (value | (bytes &<< shift)) &+ (count &<< 56) return nil } let chunk = tail | (bytes &<< shift) value = ((value &>> 56) &+ count) &<< 56 if c + count > 8 { value |= bytes &>> (64 - shift) } return chunk } } internal struct _BufferingHasher<Core: _HasherCore> { private var _buffer: _HasherTailBuffer private var _core: Core @inline(__always) internal init(seed: (UInt64, UInt64)) { self._buffer = _HasherTailBuffer() self._core = Core(seed: seed) } @inline(__always) internal mutating func combine(_ value: UInt) { #if arch(i386) || arch(arm) combine(UInt32(truncatingIfNeeded: value)) #else combine(UInt64(truncatingIfNeeded: value)) #endif } @inline(__always) internal mutating func combine(_ value: UInt64) { precondition(!_buffer.isFinalized) _core.compress(_buffer.append(value)) } @inline(__always) internal mutating func combine(_ value: UInt32) { precondition(!_buffer.isFinalized) let value = UInt64(truncatingIfNeeded: value) if let chunk = _buffer.append(value, count: 4) { _core.compress(chunk) } } @inline(__always) internal mutating func combine(_ value: UInt16) { precondition(!_buffer.isFinalized) let value = UInt64(truncatingIfNeeded: value) if let chunk = _buffer.append(value, count: 2) { _core.compress(chunk) } } @inline(__always) internal mutating func combine(_ value: UInt8) { precondition(!_buffer.isFinalized) let value = UInt64(truncatingIfNeeded: value) if let chunk = _buffer.append(value, count: 1) { _core.compress(chunk) } } @inline(__always) internal mutating func combine(bytes: UInt64, count: Int) { precondition(!_buffer.isFinalized) _sanityCheck(count <= 8) let count = UInt64(truncatingIfNeeded: count) if let chunk = _buffer.append(bytes, count: count) { _core.compress(chunk) } } @inline(__always) internal mutating func combine(bytes: UnsafeRawBufferPointer) { precondition(!_buffer.isFinalized) var remaining = bytes.count guard remaining > 0 else { return } var data = bytes.baseAddress! // Load first unaligned partial word of data do { let start = UInt(bitPattern: data) let end = _roundUp(start, toAlignment: MemoryLayout<UInt64>.alignment) let c = min(remaining, Int(end - start)) if c > 0 { let chunk = _loadPartialUnalignedUInt64LE(data, byteCount: c) combine(bytes: chunk, count: c) data += c remaining -= c } } _sanityCheck( remaining == 0 || Int(bitPattern: data) & (MemoryLayout<UInt64>.alignment - 1) == 0) // Load as many aligned words as there are in the input buffer while remaining >= MemoryLayout<UInt64>.size { combine(UInt64(littleEndian: data.load(as: UInt64.self))) data += MemoryLayout<UInt64>.size remaining -= MemoryLayout<UInt64>.size } // Load last partial word of data _sanityCheck(remaining >= 0 && remaining < 8) if remaining > 0 { let chunk = _loadPartialUnalignedUInt64LE(data, byteCount: remaining) combine(bytes: chunk, count: remaining) } } @inline(__always) internal mutating func finalize() -> UInt64 { precondition(!_buffer.isFinalized) let hash = _core.finalize(tailAndByteCount: _buffer.value) _buffer.finalize() return hash } } @_fixed_layout // FIXME: Should be resilient (rdar://problem/38549901) public struct _Hasher { internal typealias Core = _BufferingHasher<_SipHash13Core> internal var _core: Core @effects(releasenone) public init() { self._core = Core(seed: _Hasher._seed) } @usableFromInline @effects(releasenone) internal init(_seed seed: (UInt64, UInt64)) { self._core = Core(seed: seed) } /// Indicates whether we're running in an environment where hashing needs to /// be deterministic. If this is true, the hash seed is not random, and hash /// tables do not apply per-instance perturbation that is not repeatable. /// This is not recommended for production use, but it is useful in certain /// test environments where randomization may lead to unwanted nondeterminism /// of test results. public // SPI static var _isDeterministic: Bool { @inlinable @inline(__always) get { return _swift_stdlib_Hashing_parameters.deterministic; } } /// The 128-bit hash seed used to initialize the hasher state. Initialized /// once during process startup. public // SPI static var _seed: (UInt64, UInt64) { @inlinable @inline(__always) get { // The seed itself is defined in C++ code so that it is initialized during // static construction. Almost every Swift program uses hash tables, so // initializing the seed during the startup seems to be the right // trade-off. return ( _swift_stdlib_Hashing_parameters.seed0, _swift_stdlib_Hashing_parameters.seed1) } } @inlinable @inline(__always) public mutating func combine<H: Hashable>(_ value: H) { value._hash(into: &self) } //FIXME: Convert to @usableFromInline internal once integers hash correctly. @effects(releasenone) public mutating func _combine(_ value: UInt) { _core.combine(value) } //FIXME: Convert to @usableFromInline internal once integers hash correctly. @effects(releasenone) public mutating func _combine(_ value: UInt64) { _core.combine(value) } //FIXME: Convert to @usableFromInline internal once integers hash correctly. @effects(releasenone) public mutating func _combine(_ value: UInt32) { _core.combine(value) } //FIXME: Convert to @usableFromInline internal once integers hash correctly. @effects(releasenone) public mutating func _combine(_ value: UInt16) { _core.combine(value) } //FIXME: Convert to @usableFromInline internal once integers hash correctly. @effects(releasenone) public mutating func _combine(_ value: UInt8) { _core.combine(value) } @effects(releasenone) public mutating func _combine(bytes value: UInt64, count: Int) { _core.combine(bytes: value, count: count) } @effects(releasenone) public mutating func combine(bytes: UnsafeRawBufferPointer) { _core.combine(bytes: bytes) } @effects(releasenone) public mutating func finalize() -> Int { return Int(truncatingIfNeeded: _core.finalize()) } }
apache-2.0
04ac5721da6de30f10924b55cfebe59b
29.109195
80
0.627219
4.033102
false
false
false
false
mehmetf/plugins
packages/shared_preferences/shared_preferences_macos/macos/Classes/SharedPreferencesPlugin.swift
1
1961
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import FlutterMacOS import Foundation public class SharedPreferencesPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel( name: "plugins.flutter.io/shared_preferences", binaryMessenger: registrar.messenger) let instance = SharedPreferencesPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { case "getAll": result(getAllPrefs()) case "setBool", "setInt", "setDouble", "setString", "setStringList": let arguments = call.arguments as! [String: Any] let key = arguments["key"] as! String UserDefaults.standard.set(arguments["value"], forKey: key) result(true) case "commit": // UserDefaults does not need to be synchronized. result(true) case "remove": let arguments = call.arguments as! [String: Any] let key = arguments["key"] as! String UserDefaults.standard.removeObject(forKey: key) result(true) case "clear": let defaults = UserDefaults.standard for (key, _) in getAllPrefs() { defaults.removeObject(forKey: key) } result(true) default: result(FlutterMethodNotImplemented) } } } /// Returns all preferences stored by this plugin. private func getAllPrefs() -> [String: Any] { var filteredPrefs: [String: Any] = [:] if let appDomain = Bundle.main.bundleIdentifier, let prefs = UserDefaults.standard.persistentDomain(forName: appDomain) { for (key, value) in prefs where key.hasPrefix("flutter.") { filteredPrefs[key] = value } } return filteredPrefs }
bsd-3-clause
0f46c49e9c0f29145dc5133226f09574
31.147541
82
0.677715
4.406742
false
false
false
false
Takanu/Pelican
Sources/Pelican/Pelican/Client/Portal.swift
1
3999
// // Result.swift // Pelican // // Taken from Vapor's HTTP Module (https://github.com/vapor/engine) // import Foundation import Dispatch /** A simple background function that uses dispatch to send a code block to a global queue */ public func background(function: @escaping () -> Void) { DispatchQueue.global().async(execute: function) } /** There was an error thrown by the portal itself vs a user thrown variable */ public enum PortalError: String, Error { /** Portal was destroyed w/o being closed */ case notClosed /** Portal timedOut before it was closed. */ case timedOut } /** A port of Vapor's Portal class (V2.x), defined in their HTTP module to handle the asynchronous nature of URLSession data tasks in a synchronous environment (https://github.com/vapor/engine) */ public final class Portal<T> { fileprivate var result: Result<T>? = .none private let semaphore: DispatchSemaphore private let lock = NSLock() init(_ semaphore: DispatchSemaphore) { self.semaphore = semaphore } /** Close the portal with a successful result */ public func close(with value: T) { lock.locked { guard result == nil else { return } result = .success(value) semaphore.signal() } } /** Close the portal with an appropriate error */ public func close(with error: Error) { lock.locked { guard result == nil else { return } result = .failure(error) semaphore.signal() } } /** Dismiss the portal throwing a notClosed error. */ public func destroy() { semaphore.signal() } } extension Portal { /** This function is used to enter an asynchronous supported context with a portal object that can be used to complete a given operation. ``` let value = try Portal<Int>.open { portal in // .. do whatever necessary passing around `portal` object // eventually call portal.close(with: 42) // or portal.close(with: errorSignifyingFailure) } ``` - parameter timeout: The time that the portal will automatically close if it isn't closed by the handler, in seconds. - warning: Calling close on a `portal` multiple times will have no effect. */ public static func open( timeout: Double = (60 * 60), _ handler: @escaping (Portal) throws -> Void ) throws -> T { // Create the semaphore and portal. let semaphore = DispatchSemaphore(value: 0) let portal = Portal<T>(semaphore) // Dispatch the handler work on a global thread. background { do { try handler(portal) } catch { portal.close(with: error) } } // Wait for the portal to signal the semaphore. let waitResult = semaphore.wait(timeout: .now() + timeout) // Use the result to decide if we should return or throw an error. switch waitResult { case .success: guard let result = portal.result else { throw PortalError.notClosed } return try result.extract() case .timedOut: throw PortalError.timedOut } } } extension Portal { /** Execute timeout operations */ static func timeout(_ timeout: Double, operation: @escaping () throws -> T) throws -> T { return try Portal<T>.open(timeout: timeout) { portal in let value = try operation() portal.close(with: value) } } } extension PortalError { public var identifier: String { return rawValue } public var reason: String { switch self { case .notClosed: return "the portal finished, but was somehow not properly closed" case .timedOut: return "the portal timed out before it could finish its operation" } } public var possibleCauses: [String] { return [ "user forgot to call `portal.close(with: )`" ] } public var suggestedFixes: [String] { return [ "ensure the timeout length is adequate for required operation time", "make sure that `portal.close(with: )` is being called with an error or valid value" ] } } extension NSLock { public func locked(closure: () throws -> Void) rethrows { lock() defer { unlock() } // MUST be deferred to ensure lock releases if throws try closure() } }
mit
a03c88edd5d2289394b17b234eb17611
21.982759
189
0.689672
3.55151
false
false
false
false
codecaffeine/SubsonicSwift
Classes/DictionaryExtensions.swift
1
633
// // DictionaryExtensions.swift // SubsonicSwift // // Created by Matt Thomas on 6/18/14. // Copyright (c) 2014 Matt Thomas. All rights reserved. // import Foundation extension Dictionary { var percentEncodedQueryString: String { var htmlParams = String[]() for (key, value) in self { if let keyString = key as? String { if let valueString = value as? String { htmlParams += "\(keyString.percentEncodedAll)=\(valueString.percentEncodedAll)" } } } return NSArray(array:htmlParams).componentsJoinedByString("&") } }
mit
4d6d42468da55427bbbffc7ff9f787ee
26.521739
99
0.600316
4.586957
false
false
false
false
Novkirishki/JustNinja
Just Ninja/Just Ninja/GameViewController.swift
1
1830
// // GameViewController.swift // Just Ninja // // Created by Nikolai Novkirishki on 1/31/16. // Copyright (c) 2016 Nikolai Novkirishki. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { var scene: GameScene! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBarHidden = true // Configure the view let skView = view as! SKView skView.multipleTouchEnabled = false // Create and confugure the scene scene = GameScene(size: skView.bounds.size) scene.scaleMode = .AspectFill scene.viewController = self // Present the scene skView.presentScene(scene) } override func loadView() { self.view = SKView(frame: CGRect(x: 0, y: 0, width: 667, height: 375 )) } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return .Landscape } else { return .All } } override func prefersStatusBarHidden() -> Bool { return true } func openHighscores(score: String!) { let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let navigationController = storyBoard.instantiateViewControllerWithIdentifier("addHighscoreNavigation") as! UINavigationController let highscoreController = navigationController.viewControllers.first as! ComposeHighscoreViewController highscoreController.score = score self.presentViewController(navigationController, animated:true, completion:nil) } }
mit
3a14836bda96f5bca15eacbfc25fe264
28.063492
138
0.64918
5.382353
false
false
false
false
AlexLittlejohn/Particles
Particles/ParticlesScene.swift
1
3627
// // ParticleScene.swift // Particles // // Created by Alex Littlejohn on 2015/11/19. // Copyright (c) 2015 Alex Littlejohn. All rights reserved. // import SpriteKit class ParticlesScene: SKScene { var particles: [Particle] = [] var values: ParticleValues { didSet { setup() } } required init(size: CGSize, values: ParticleValues) { self.values = values super.init(size: size) setup() } required init?(coder aDecoder: NSCoder) { fatalError() } func setup() { removeAllChildren() (0..<values.particleCount).forEach { _ in let x = CGFloat.random(in: 0...size.width) let y = CGFloat.random(in: 0...size.height) let mass = CGFloat.random(in: 0.5...8) let color = values.colors[Int.random(in: 0..<values.colors.count)] let particle = Particle(x: x, y: y, mass: mass, color: color) particles.append(particle) addChild(particle) } scaleMode = .aspectFill } override func update(_ currentTime: CFTimeInterval) { particles.forEach { particle in if CGFloat.random(in: 0...1) < 0.08 { particle.charge = -particle.charge } for b in particles { let dx = b.x - particle.x let dy = b.y - particle.y let dSq = (dx * dx + dy * dy) + 0.1 let dst = sqrt(dSq) let rad = particle.radius + b.radius if dst >= rad { let len = 1/dst let fx = dx * len let fy = dy * len let f = min(values.maximumForce, (values.gravity * particle.mass * b.mass) / dSq) particle.fx += f * fx * b.charge particle.fy += f * fy * b.charge b.fx += -f * fx * particle.charge b.fy += -f * fx * particle.charge } } particle.vx += particle.fx particle.vy += particle.fy particle.vx *= values.friction particle.vy *= values.friction particle.tail.insert(CGPoint(x: particle.x, y: particle.y), at: 0) if particle.tail.count > values.tailLength { _ = particle.tail.popLast() } particle.x += particle.vx particle.y += particle.vy particle.fx = 0 particle.fy = 0 if particle.x > size.width + particle.radius { particle.x = -particle.radius particle.tail = [] } else if particle.x < -particle.radius { particle.x = size.width + particle.radius particle.tail = [] } if particle.y > size.height + particle.radius { particle.y = -particle.radius particle.tail = [] } else if particle.y < -particle.radius { particle.y = size.height + particle.radius particle.tail = [] } particle.lineWidth = particle.radius * 2.0 let path = CGMutablePath() path.move(to: CGPoint(x: particle.x, y: particle.y)) for point in particle.tail { path.addLine(to: point) } particle.path = path } } }
mit
d7c0397c4b64d4af5a044d6dd4631cb3
30.267241
101
0.465674
4.556533
false
false
false
false
ulrikdamm/Sqlable
Sources/Sqlable/ReadRow.swift
1
4817
// // ReadRow.swift // Simplyture // // Created by Ulrik Damm on 27/10/2015. // Copyright © 2015 Robocat. All rights reserved. // import Foundation import SQLite3 /// A row returned from the SQL database, from which you can read column values public struct ReadRow { private let handle : OpaquePointer private let tablename : String let columnIndex : [String: Int] /// Create a read row from a SQLite handle public init(handle : OpaquePointer, tablename : String) { self.handle = handle self.tablename = tablename var columnIndex : [String: Int] = [:] for i in (0..<sqlite3_column_count(handle)) { let name = String(validatingUTF8: sqlite3_column_name(handle, i))! columnIndex[name] = Int(i) } self.columnIndex = columnIndex } /// Read an integer value for a column /// /// - Parameters: /// - column: A column from a Sqlable type /// - Returns: The integer value for that column in the current row public func get(_ column : Column) throws -> Int { let index = try columnIndex(column) return Int(sqlite3_column_int64(handle, index)) } /// Read a double value for a column /// /// - Parameters: /// - column: A column from a Sqlable type /// - Returns: The double value for that column in the current row public func get(_ column : Column) throws -> Double { let index = try columnIndex(column) return Double(sqlite3_column_double(handle, index)) } /// Read a string value for a column /// /// - Parameters: /// - column: A column from a Sqlable type /// - Returns: The string value for that column in the current row public func get(_ column : Column) throws -> String { let index = try columnIndex(column) return String(cString: sqlite3_column_text(handle, index)) } /// Read a date value for a column /// /// - Parameters: /// - column: A column from a Sqlable type /// - Returns: The date value for that column in the current row public func get(_ column : Column) throws -> Date { let timestamp : Int = try get(column) return Date(timeIntervalSince1970: TimeInterval(timestamp)) } /// Read a boolean value for a column /// /// - Parameters: /// - column: A column from a Sqlable type /// - Returns: The boolean value for that column in the current row public func get(_ column : Column) throws -> Bool { let index = try columnIndex(column) return sqlite3_column_int(handle, index) == 0 ? false : true } /// Read an optional integer value for a column /// /// - Parameters: /// - column: A column from a Sqlable type /// - Returns: The integer value for that column in the current row or nil if null public func get(_ column : Column) throws -> Int? { let index = try columnIndex(column) if sqlite3_column_type(handle, index) == SQLITE_NULL { return nil } else { let i : Int = try get(column) return i } } /// Read an optional double value for a column /// /// - Parameters: /// - column: A column from a Sqlable type /// - Returns: The double value for that column in the current row or nil if null public func get(_ column : Column) throws -> Double? { let index = try columnIndex(column) if sqlite3_column_type(handle, index) == SQLITE_NULL { return nil } else { let i : Double = try get(column) return i } } /// Read an optional string value for a column /// /// - Parameters: /// - column: A column from a Sqlable type /// - Returns: The string value for that column in the current row or nil if null public func get(_ column : Column) throws -> String? { let index = try columnIndex(column) if sqlite3_column_type(handle, index) == SQLITE_NULL { return nil } else { let i : String = try get(column) return i } } /// Read an optional date value for a column /// /// - Parameters: /// - column: A column from a Sqlable type /// - Returns: The date value for that column in the current row or nil if null public func get(_ column : Column) throws -> Date? { let index = try columnIndex(column) if sqlite3_column_type(handle, index) == SQLITE_NULL { return nil } else { let i : Date = try get(column) return i } } /// Read an optional boolean value for a column /// /// - Parameters: /// - column: A column from a Sqlable type /// - Returns: The boolean value for that column in the current row or nil if null public func get(_ column : Column) throws -> Bool? { let index = try columnIndex(column) if sqlite3_column_type(handle, index) == SQLITE_NULL { return nil } else { let i : Bool = try get(column) return i } } private func columnIndex(_ column : Column) throws -> Int32 { guard let index = columnIndex[column.name] else { throw SqlError.readError("Column \"\(column.name)\" not found on \(tablename)") } return Int32(index) } }
mit
1c6b9bf53070da2789c4be2cb7224f94
28.012048
83
0.662998
3.370189
false
false
false
false
xedin/swift
validation-test/stdlib/Glibc.swift
7
758
// RUN: %target-run-simple-swift // REQUIRES: executable_test // // UNSUPPORTED: OS=macosx // UNSUPPORTED: OS=ios // UNSUPPORTED: OS=tvos // UNSUPPORTED: OS=watchos // REQUIRES-ANY: OS=linux-gnu, OS=linux-androideabi, OS=linux-android import Swift import StdlibUnittest import Glibc var GlibcTestSuite = TestSuite("Glibc") GlibcTestSuite.test("errno") { errno = 0 expectEqual(0, errno) close(-1) expectEqual(EBADF, errno) } GlibcTestSuite.test("sendfile") { // Check that `sendfile` is available. Don't actually call it, because doing that is non-trivial. _ = sendfile } var GlibcIoctlConstants = TestSuite("GlibcIoctlConstants") GlibcIoctlConstants.test("tty ioctl constants availability") { let aConstant = TIOCSTI } runAllTests()
apache-2.0
e68f60fe711cbcb0abfddd54866cdcc6
19.486486
100
0.733509
3.477064
false
true
false
false
hanwanjie853710069/Easy-living
易持家/Class/Class_project/ELLook/View/ECLookCell.swift
1
2740
// // ECLookCell.swift // 易持家 // // Created by 王木木 on 16/5/21. // Copyright © 2016年 王木木. All rights reserved. // import UIKit class ECLookCell: UITableViewCell { var timeLabel: UILabel = { let label = UILabel() label.textColor = DarkGrayTextColor label.font = UIFont.systemFontOfSize(16) label.textAlignment = .Center return label }() var moneyLabel: UILabel = { let label = UILabel() label.textColor = DarkGrayTextColor label.font = UIFont.systemFontOfSize(16) label.textAlignment = .Center return label }() var lookLabel: UILabel = { let label = UILabel() label.textColor = DarkGrayTextColor label.font = UIFont.systemFontOfSize(16) label.textAlignment = .Center return label }() static let cellId = "lookCell" class func cellFor(tableView: UITableView) ->ECLookCell{ var cell = tableView.dequeueReusableCellWithIdentifier(self.cellId) as?ECLookCell if cell == nil { cell = ECLookCell.init(style: .Default, reuseIdentifier: self.cellId) } return cell! } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) creatUI() } func creatUI(){ for temp in 0...2 { let label = UILabel.init(frame: CGRectMake(CGFloat(temp)*(ScreenWidth/3), 0, ScreenWidth/3, 44)) label.textAlignment = .Center self.addSubview(label) switch temp { case 0: self.timeLabel = label case 1: self.moneyLabel = label default: self.lookLabel = label } } self.timeLabel.autoPinEdgeToSuperviewEdge(.Bottom) self.timeLabel.autoPinEdgeToSuperviewEdge(.Top) self.timeLabel.autoPinEdgeToSuperviewEdge(.Left) self.timeLabel.autoSetDimension(.Width, toSize: ScreenWidth/3) self.lookLabel.autoPinEdgeToSuperviewEdge(.Bottom) self.lookLabel.autoPinEdgeToSuperviewEdge(.Top) self.lookLabel.autoPinEdgeToSuperviewEdge(.Right) self.lookLabel.autoSetDimension(.Width, toSize: ScreenWidth/3) self.moneyLabel.autoPinEdgeToSuperviewEdge(.Bottom) self.moneyLabel.autoPinEdgeToSuperviewEdge(.Top) self.moneyLabel.autoAlignAxisToSuperviewAxis(.Vertical) self.moneyLabel.autoSetDimension(.Width, toSize: ScreenWidth/3) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
7ab56465139cbde481f9f2a7e4de2c5b
30.252874
108
0.620816
4.829485
false
false
false
false
DrGo/LearningSwift
PLAYGROUNDS/LSB_B016_Evaluation.playground/section-2.swift
2
6956
// Since @autoclosure was discontinued in Swift 1.2, lazy won't work. // Attempting to use Box here will result in an infinite loop. // Requires fix in ExpressionParser / Parser.swift //import UIKit //import ExpressionParser // ///* //// Evaluation //// //// Based on: //// http://www.objc.io/books/ (Chapter 13, Case Study: Build a Spreadsheet Application) //// (Functional Programming in Swift, by Chris Eidhof, Florian Kugler, and Wouter Swierstra) ///===================================*/ // // //// This is just a test of the import from the "ExpressionParser" module. //let myParser: Parser<Character, Character> = Parser { _ in // return none() //} // //// Here goes nothing... // // ///*=====================================================================/ //// Evaluation ///=====================================================================*/ // // ///*---------------------------------------------------------------------/ //// Result ///---------------------------------------------------------------------*/ //enum Result { // case IntResult(Int) // case ListResult([Result]) // case EvaluationError(String) //} // // ///*---------------------------------------------------------------------/ //// lift - Allows use of func on Ints to be used on Result enums ///---------------------------------------------------------------------*/ //func lift(f: (Int, Int) -> Int) -> ((Result, Result) -> Result) { // return { l, r in // switch (l, r) { // case (.IntResult(let x), .IntResult(let y)): // return .IntResult(f(x, y)) // default: // return .EvaluationError("Type error, couldn't evaluate \(l) + \(r)") // } // } //} // // ///*---------------------------------------------------------------------/ //// integerOperators - List of operators //// ("o" currently required to appease compiler) ///---------------------------------------------------------------------*/ //func o(f: (Int, Int) -> Int) -> (Int, Int) -> Int { // return f //} // //let integerOperators: Dictionary<String, (Int, Int) -> Int> = //[ "+": o(+), "/": o(/), "*": o(*), "-": o(-) ] // // // ///*---------------------------------------------------------------------/ //// evaluateIntegerOperator - Evaluates the Result of an binary Int //// operation ///---------------------------------------------------------------------*/ //func evaluateIntegerOperator(op: String, // l: Expression, // r: Expression, // evaluate: Expression? -> Result) // -> Result? { // // return integerOperators[op].map { // lift($0)(evaluate(l), evaluate(r)) // } //} // // ///*---------------------------------------------------------------------/ //// evaluateListOperator - Evaluates the Result of list expression //// //// NOTE: We only handle single column spreadsheets right now. ///---------------------------------------------------------------------*/ //func evaluateListOperator(op: String, // l: Expression, // r: Expression, // evaluate: Expression? -> Result) // -> Result? { // // switch (op, l, r) { // case (":", .Reference("A", let row1), // .Reference("A", let row2)) where row1 <= row2: // return Result.ListResult(Array(row1...row2).map { // evaluate(Expression.Reference("A", $0)) // }) // default: // return nil // } //} // ///*---------------------------------------------------------------------/ //// evaluateBinary - Evaluates the Result of any binary expression ///---------------------------------------------------------------------*/ //func evaluateBinary(op: String, // l: Expression, // r: Expression, // evaluate: Expression? -> Result) -> Result { // // return evaluateIntegerOperator(op, l, r, evaluate) // ?? evaluateListOperator(op, l, r, evaluate) // ?? .EvaluationError("Couldn't find operator \(op)") //} // // ///*---------------------------------------------------------------------/ //// evaluateFunction - Evaluates the Result of some functions //// //// NOTE: We only support limited set of functions, of one parameter. ///---------------------------------------------------------------------*/ //func evaluateFunction(functionName: String, parameter: Result) -> Result { // switch (functionName, parameter) { // case ("SUM", .ListResult(let list)): // return list.reduce(Result.IntResult(0), combine: lift(+)) // case ("MIN", .ListResult(let list)): // return list.reduce(Result.IntResult(Int.max), combine: lift { min($0, $1) }) // default: // return .EvaluationError("Couldn't evaluate function") // } //} // // ///*---------------------------------------------------------------------/ //// evaluateExpression - Evaluates a single express //// //// Takes a context to lookup saved cell value expressions ///---------------------------------------------------------------------*/ //func evaluateExpression(context: [Expression?]) -> Expression? -> Result { // // return { (e: Expression?) in // e.map { expression in // let recurse = evaluateExpression(context) // switch (expression) { // case .Number(let x): // return Result.IntResult(x) // case .Reference("A", let idx): // return recurse(context[idx]) // case .BinaryExpression(let s, let l, let r): // return evaluateBinary(s, l.toExpression(), // r.toExpression(), recurse) // case .FunctionCall(let f, let p): // return evaluateFunction(f, // recurse(p.toExpression())) // default: // return .EvaluationError("Couldn't evaluate " + // "expression") // } // } ?? .EvaluationError("Couldn't parse expression") // } //} // // ///*---------------------------------------------------------------------/ //// evaluateExpressions - Convenience function for evaluating many //// optional expressions ///---------------------------------------------------------------------*/ //func evaluateExpressions(expressions: [Expression?]) -> [Result] { // return expressions.map(evaluateExpression(expressions)) //} // // //let result6 = evaluateExpressions([parseExpression("3 * 2")]) //result6[0] // //func readResult(r: Result) -> String { // switch r { // case let .IntResult(i): // return "Int: \(i)" // case let .ListResult(list): // return list.reduce("") { $0 + readResult($1) } // case let .EvaluationError(er): // return er // } //} // //readResult(result6[0]) // // //// This is a spreadsheet! //let a0 = parseExpression("3 * 2") //let a1 = parseExpression("9") //let a2 = parseExpression("A0 + A1") //var r = evaluateExpressions([a0, a1, a2]) //readResult(r[0]) //readResult(r[1]) //readResult(r[2])
gpl-3.0
cfff15cfbbb09d27c7d38ac78c1b4075
32.931707
96
0.448821
4.328563
false
false
false
false
airspeedswift/swift
test/IRGen/objc_methods.swift
2
6588
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-os %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import Foundation // Protocol methods require extended method type encodings to capture block // signatures and parameter object types. @objc protocol Fooable { func block(_: (Int) -> Int) func block2(_: (Int,Int) -> Int) func takesString(_: String) -> String func takesArray(_: [AnyObject]) -> [AnyObject] func takesDict(_: [NSObject: AnyObject]) -> [NSObject: AnyObject] func takesSet(_: Set<NSObject>) -> Set<NSObject> } class Foo: Fooable { func bar() {} @objc func baz() {} @IBAction func garply(_: AnyObject?) {} @IBSegueAction func harply(_: AnyObject?, _: AnyObject) -> AnyObject? {fatalError()} @objc func block(_: (Int) -> Int) {} @objc func block2(_: (Int,Int) -> Int) {} @objc func takesString(_ x: String) -> String { return x } @objc func takesArray(_ x: [AnyObject]) -> [AnyObject] { return x } @objc func takesDict(_ x: [NSObject: AnyObject]) -> [NSObject: AnyObject] { return x } @objc func takesSet(_ x: Set<NSObject>) -> Set<NSObject> { return x } @objc func fail() throws {} } class ObjcDestructible: NSObject { var object: NSObject init(object: NSObject) { self.object = object } } // CHECK: [[NO_ARGS_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00" // CHECK: [[GARPLY_SIGNATURE:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00" // CHECK: [[HARPLY_SIGNATURE:@.*]] = private unnamed_addr constant [14 x i8] c"@32@0:8@16@24\00" // CHECK: [[BLOCK_SIGNATURE_TRAD:@.*]] = private unnamed_addr constant [12 x i8] c"v24@0:8@?16\00" // CHECK-macosx: [[FAIL_SIGNATURE:@.*]] = private unnamed_addr constant [12 x i8] c"c24@0:8^@16\00" // CHECK-ios: [[FAIL_SIGNATURE:@.*]] = private unnamed_addr constant [12 x i8] c"B24@0:8^@16\00" // CHECK-tvos: [[FAIL_SIGNATURE:@.*]] = private unnamed_addr constant [12 x i8] c"B24@0:8^@16\00" // CHECK: @_INSTANCE_METHODS__TtC12objc_methods3Foo = internal constant { {{.*}}] } { // CHECK: i32 24, // CHECK: i32 10, // CHECK: [10 x { i8*, i8*, i8* }] [{ // CHECK: i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(baz)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[NO_ARGS_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void (i8*, i8*)* @"$s12objc_methods3FooC3bazyyFTo" to i8*) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(garply:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[GARPLY_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void (i8*, i8*, i8*)* @"$s12objc_methods3FooC6garplyyyyXlSgFTo" to i8*) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([9 x i8], [9 x i8]* @"\01L_selector_data(harply::)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* [[HARPLY_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (i8* (i8*, i8*, i8*, i8*)* @"$s12objc_methods3FooC6harplyyyXlSgAE_yXltFTo" to i8*) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(block:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* [[BLOCK_SIGNATURE_TRAD]], i64 0, i64 0), // CHECK: i8* bitcast (void (i8*, i8*, i64 (i64)*)* @"$s12objc_methods3FooC5blockyyS2iXEFTo" to i8*) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(block2:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* [[BLOCK_SIGNATURE_TRAD]], i64 0, i64 0), // CHECK: i8* bitcast (void (i8*, i8*, i64 (i64, i64)*)* @"$s12objc_methods3FooC6block2yyS2i_SitXEFTo" to i8*) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(failAndReturnError:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* [[FAIL_SIGNATURE]], i64 0, i64 0), // CHECK-macosx: i8* bitcast (i8 (i8*, i8*, %4**)* @"$s12objc_methods3FooC4failyyKFTo" to i8*) // CHECK-ios: i8* bitcast (i1 (i8*, i8*, %4**)* @"$s12objc_methods3FooC4failyyKFTo" to i8*) // CHECK: }] // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK: @_INSTANCE_METHODS__TtC12objc_methods16ObjcDestructible = internal constant { {{.*}}] } { // CHECK: i32 24, // CHECK: i32 2, // CHECK: [2 x { i8*, i8*, i8* }] [{ // CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[NO_ARGS_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void (%6*, i8*)* @"$s12objc_methods16ObjcDestructibleCfETo" to i8*) }] // CHECK: }] // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK: [[BLOCK_SIGNATURE_EXT_1:@.*]] = private unnamed_addr constant [18 x i8] c"v24@0:8@?<q@?q>16\00" // CHECK: [[BLOCK_SIGNATURE_EXT_2:@.*]] = private unnamed_addr constant [19 x i8] c"v24@0:8@?<q@?qq>16\00" // CHECK: [[STRING_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [31 x i8] c"@\22NSString\2224@0:8@\22NSString\2216\00" // CHECK: [[ARRAY_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [29 x i8] c"@\22NSArray\2224@0:8@\22NSArray\2216\00" // CHECK: [[DICT_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [39 x i8] c"@\22NSDictionary\2224@0:8@\22NSDictionary\2216\00" // CHECK: [[SET_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [25 x i8] c"@\22NSSet\2224@0:8@\22NSSet\2216\00" // CHECK: @_PROTOCOL_METHOD_TYPES__TtP12objc_methods7Fooable_ = internal constant [6 x i8*] [ // CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* [[BLOCK_SIGNATURE_EXT_1]], i64 0, i64 0) // CHECK: i8* getelementptr inbounds ([19 x i8], [19 x i8]* [[BLOCK_SIGNATURE_EXT_2]], i64 0, i64 0) // CHECK: i8* getelementptr inbounds ([31 x i8], [31 x i8]* [[STRING_SIGNATURE_EXT]], i64 0, i64 0) // CHECK: i8* getelementptr inbounds ([29 x i8], [29 x i8]* [[ARRAY_SIGNATURE_EXT]], i64 0, i64 0) // CHECK: i8* getelementptr inbounds ([39 x i8], [39 x i8]* [[DICT_SIGNATURE_EXT]], i64 0, i64 0) // CHECK: i8* getelementptr inbounds ([25 x i8], [25 x i8]* [[SET_SIGNATURE_EXT]], i64 0, i64 0) // CHECK: ] // rdar://16006333 - observing properties don't work in @objc classes @objc class ObservingAccessorTest : NSObject { var bounds: Int = 0 { willSet {} didSet {} } }
apache-2.0
5c17b5ba156a3de68a19421f87ca23a0
56.286957
157
0.624469
2.853183
false
false
false
false
damonthecricket/my-utils
UnitTests/UI/Extensions/CGRectExtensionsTests.swift
1
4962
// // CGRectExtensionsTests.swift // MYUtils // // Created by Damon Cricket on 02.06.17. // Copyright © 2017 Trenlab. All rights reserved. // import XCTest @testable import MYUtils fileprivate enum CGOperator { case plus case minus case multiplying case division func closure() -> (CGFloat, CGFloat) -> CGFloat { switch self { case .plus: return (+) case .minus: return (-) case .multiplying: return (*) case .division: return (/) } } static let operators: [CGOperator] = [.plus, .minus, .multiplying, .division] } class CGRectExtensionsTests: XCTestCase { // MARK: - CGRect func testCGRectOperators() { for mock in getRectOperatorsData() { let result: CGRect switch mock.oprt { case .plus: result = mock.lhs + mock.rhs case .minus: result = mock.lhs - mock.rhs case .multiplying: result = mock.lhs * mock.rhs case .division: result = mock.lhs / mock.rhs } XCTAssertEqual(result, mock.result) } for mock in getPointOperatorsData() { let result: CGPoint switch mock.oprt { case .plus: result = mock.lhs + mock.rhs case .minus: result = mock.lhs - mock.rhs case .multiplying: result = mock.lhs * mock.rhs case .division: result = mock.lhs / mock.rhs } XCTAssertEqual(result, mock.result) } for mock in getSizeOperatorsData() { let result: CGSize switch mock.oprt { case .plus: result = mock.lhs + mock.rhs case .minus: result = mock.lhs - mock.rhs case .multiplying: result = mock.lhs * mock.rhs case .division: result = mock.lhs / mock.rhs } XCTAssertEqual(result, mock.result) } } // MARK: - Operators Data fileprivate func getRectOperatorsData() -> [(lhs: CGRect, rhs: CGRect, oprt: CGOperator, result: CGRect)] { var data: [(lhs: CGRect, rhs: CGRect, oprt: CGOperator, result: CGRect)] = [] for oprt in CGOperator.operators { let lhsRect = CGRect(x: randomSignedCFloat(), y: randomSignedCFloat(), width: randomCFloat(), height: randomCFloat()) let rhsRect = CGRect(x: randomSignedCFloat(), y: randomSignedCFloat(), width: randomCFloat(), height: randomCFloat()) let clsr: (CGFloat, CGFloat) -> CGFloat = oprt.closure() let resultRect = CGRect(x: clsr(lhsRect.minX, rhsRect.minX), y: clsr(lhsRect.minY, rhsRect.minY), width: clsr(lhsRect.width, rhsRect.width), height: clsr(lhsRect.height, rhsRect.height)) data.append((lhs: lhsRect, rhs: rhsRect, oprt: oprt, result: resultRect)) } return data } fileprivate func getPointOperatorsData() -> [(lhs: CGPoint, rhs: CGPoint, oprt: CGOperator, result: CGPoint)] { var data: [(lhs: CGPoint, rhs: CGPoint, oprt: CGOperator, result: CGPoint)] = [] for oprt in CGOperator.operators { let lhsPoint = CGPoint(x: randomSignedCFloat(), y: randomSignedCFloat()) let rhsPoint = CGPoint(x: randomSignedCFloat(), y: randomSignedCFloat()) let clsr: (CGFloat, CGFloat) -> CGFloat = oprt.closure() let resultPoint = CGPoint(x: clsr(lhsPoint.x, rhsPoint.x), y: clsr(lhsPoint.y, rhsPoint.y)) data.append((lhs: lhsPoint, rhs: rhsPoint, oprt: oprt, result: resultPoint)) } return data } fileprivate func getSizeOperatorsData() -> [(lhs: CGSize, rhs: CGSize, oprt: CGOperator, result: CGSize)] { var data: [(lhs: CGSize, rhs: CGSize, oprt: CGOperator, result: CGSize)] = [] for oprt in CGOperator.operators { let lhsSize = CGSize(width: randomCFloat(), height: randomCFloat()) let rhsSize = CGSize(width: randomCFloat(), height: randomCFloat()) let clsr: (CGFloat, CGFloat) -> CGFloat = oprt.closure() let resultSize = CGSize(width: clsr(lhsSize.width, rhsSize.width), height: clsr(lhsSize.height, rhsSize.height)) data.append((lhs: lhsSize, rhs: rhsSize, oprt: oprt, result: resultSize)) } return data } fileprivate func randomSignedCFloat() -> CGFloat { return randomCFloat() * CGFloat.randomSign } fileprivate func randomCFloat() -> CGFloat { return CGFloat.random(min: 10, max: 1000) } }
mit
7a25390f05ebec5897e85c66c52e8471
32.073333
198
0.546866
4.37478
false
false
false
false
rolson/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/AppDelegate.swift
1
6414
// Copyright 2016 Esri. // // 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 ArcGIS @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? private var indexArray:[String]! private var wordsDictionary:[String: [String]]! private var readmeDirectoriesURLs:[NSURL]! func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { if url.absoluteString!.rangeOfString("auth", options: [], range: nil, locale: nil) != nil { AGSApplicationDelegate.sharedApplicationDelegate().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } return true } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController splitViewController.presentsWithGesture = false splitViewController.preferredDisplayMode = UISplitViewControllerDisplayMode.PrimaryHidden let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() navigationController.topViewController!.navigationItem.leftItemsSupplementBackButton = true splitViewController.delegate = self self.modifyAppearance() //enable/disable touches based on settings self.setTouchPref() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. self.setTouchPref() } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } //MARK: - Touch settings func setTouchPref() { //enable/disable touches based on settings let bool = NSUserDefaults.standardUserDefaults().boolForKey("showTouch") if bool { DemoTouchManager.showTouches() DemoTouchManager.touchBorderColor = UIColor.lightGrayColor() DemoTouchManager.touchFillColor = UIColor(white: 231/255.0, alpha: 1) } else { DemoTouchManager.hideTouches() } } // MARK: - Appearance modification func modifyAppearance() { UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()] UINavigationBar.appearance().barTintColor = UIColor.primaryBlue() UINavigationBar.appearance().tintColor = UIColor.whiteColor() UIToolbar.appearance().barTintColor = UIColor.backgroundGray() UIToolbar.appearance().tintColor = UIColor.primaryBlue() } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController { if let topAsDetailController = secondaryAsNavController.topViewController { // if topAsDetailController.detailItem == nil { // // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. // return true // } } } return true } } extension UIColor { class func primaryBlue() -> UIColor { return UIColor(red: 0, green: 0.475, blue: 0.757, alpha: 1) } class func secondaryBlue() -> UIColor { return UIColor(red: 0, green: 0.368, blue: 0.584, alpha: 1) } class func backgroundGray() -> UIColor { return UIColor(red: 0.973, green: 0.973, blue: 0.973, alpha: 1) } class func primaryTextColor() -> UIColor { return UIColor(red: 0.196, green: 0.196, blue: 0.196, alpha: 1) } class func secondaryTextColor() -> UIColor { return UIColor(red: 0.349, green: 0.349, blue: 0.349, alpha: 1) } }
apache-2.0
4041377787ada277768cb97302e3fb22
45.478261
285
0.711257
5.524548
false
false
false
false
bm842/TradingLibrary
Tests/PlaybackTests.swift
2
14745
/* The MIT License (MIT) Copyright (c) 2016 Bertrand Marlier 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 Brokers import Logger class PlaybackBrokerTests: BrokerTests { var playbackInstrument: PlaybackInstrument! func inject(price: Price? = nil, time: Timestamp? = nil) { let spread = 0.0001 let setPrice = price ?? 1.1000 let tick = Tick(time: time ?? Timestamp.now, bid: setPrice - spread/2, ask: setPrice + spread/2) playbackInstrument.inject(tick: tick) } override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. Logger.defaultLogChain.requiredLevel = .all if let _ = getenv("TRAVIS") { } else { // escape color code in logs locally only //Logger.defaultLogChain.logEventFormatter = DefaultLogEventFormatter(WithColorFormatter: XcodeColorsFormatter()) } let playbackBroker = PlaybackBroker(description: "Test") let account = playbackBroker.addAccount("Account", balance: 10000, currency: .USD) playbackInstrument = PlaybackInstrument(instrument: "EUR_USD", displayName: "EUR/USD", pip: 0.0001, minTradeUnits: 1, maxTradeUnits: 10000000, precision: 0.00001, marginRate: 0.01, base: .EUR, quote: .USD) account.addInstrument(playbackInstrument) playbackInstrument.emulatesNotificationDelay = false //playbackInstrument.injectTick(tick: Tick(time: Timestamp.now, bid: 1.1000, ask: 1.1001)) inject(price: 1.1000) broker = playbackBroker } func refreshInstruments(_ accountIndex: Int) { let sync = Sync<RequestStatus>() let account = broker.accounts[accountIndex] account.refreshInstruments { sync.post($0) } guard let status = sync.take(delay:4 * Seconds) , status.isSuccess else { XCTFail("no instrument fetched") return } } func executeMarketOrder(_ side: Side, units: UInt, instrument: Instrument) { log.debug("%f: \(side) \(units) units") let syncExecution = Sync<(RequestStatus,OrderExecution)>() let orderCreation = OrderCreation(type: .market, side: side, units: units) instrument.submitOrder(orderCreation) { status, execution in syncExecution.post((status,execution)) } if let (status,execution) = syncExecution.take(delay: 4 * Seconds) { log.debug("execution status = \(status) \(execution)") //log.debug("order execution = \(execution)") if status.tradingHaltedForInstrument || status.isSuccess { // success //return } } } func test_account_1() { _test_account_1() } func test_account_2() { _test_account_2() } func test_trade_1() { let accountIndex = 0 refreshAccounts() refreshInstruments(accountIndex) broker.activate() Thread.sleep(delay: 1*Seconds) // wait for the stream to be operational guard let eur_usd = broker.accounts[accountIndex].findInstrument({ $0.displayName == "EUR/USD" }) else { XCTFail("currency not found") return } var step = 0 let expected: [(ordersCount:Int,tradesCount:Int)] = [ (0, 1), (0, 2), (0, 3), (0, 1), (0, 1), (0, 0) ] let account = broker.accounts[accountIndex] eur_usd.startTradeEventsStreaming(DispatchQueue.global(qos: .background)) { (event) in log.debug("event: \(event) (\(account.openOrders.count),\(account.openTrades.count))") if expected[step].ordersCount == account.openOrders.count && expected[step].tradesCount == account.openTrades.count { step += 1 } } executeMarketOrder(.buy, units: 2, instrument: eur_usd) Thread.sleep(delay: 2*Seconds) executeMarketOrder(.buy, units: 2, instrument: eur_usd) Thread.sleep(delay: 2*Seconds) executeMarketOrder(.buy, units: 2, instrument: eur_usd) Thread.sleep(delay: 2*Seconds) executeMarketOrder(.sell, units: 5, instrument: eur_usd) Thread.sleep(delay: 2*Seconds) executeMarketOrder(.sell, units: 2, instrument: eur_usd) Thread.sleep(delay: 2*Seconds) executeMarketOrder(.buy, units: 1, instrument: eur_usd) Thread.sleep(delay: 2*Seconds) //Thread.sleep(delay: 1000*Seconds) XCTAssert(step == 6) } func test_trade_params_1() { let accountIndex = 0 refreshAccounts() refreshInstruments(accountIndex) broker.activate() Thread.sleep(delay: 1*Seconds) // wait for the stream to be operational guard let eur_usd = broker.accounts[accountIndex].findInstrument({ $0.displayName == "EUR/USD" }) else { XCTFail("currency not found") return } var step = 0 let expected: [(ordersCount:Int,tradesCount:Int)] = [ (0, 1), (0, 1), (0, 0) ] let account = broker.accounts[accountIndex] eur_usd.startTradeEventsStreaming(DispatchQueue.global(qos: .background)) { (event) in log.debug("event: \(event)") if expected[step].ordersCount == account.openOrders.count && expected[step].tradesCount == account.openTrades.count { step += 1 } } let newOrder = OrderCreation(type: .market, side: .sell, units: 2, entry: 2.5, stopLoss: 3, expiry: Timestamp(seconds: Timestamp.now.seconds+300)) eur_usd.submitOrder(newOrder) { status,execution in } Thread.sleep(delay: 2*Seconds) guard account.openTrades.count > 0 else { XCTFail("no trades!") return } let trade = account.openTrades[0] XCTAssert(trade.takeProfit == nil) XCTAssert(trade.stopLoss == 3) trade.modify(change: [.takeProfit(price: 0.5), .stopLoss(price: nil)]) { status in } Thread.sleep(delay: 2*Seconds) XCTAssert(trade.takeProfit == 0.5) XCTAssert(trade.stopLoss == nil) trade.close { status in } Thread.sleep(delay: 2*Seconds) eur_usd.stopTradeEventsStreaming() XCTAssert(step == 3) } func test_trade_stopLossFilled_1() { let accountIndex = 0 refreshAccounts() refreshInstruments(accountIndex) broker.activate() Thread.sleep(delay: 1*Seconds) // wait for the stream to be operational guard let eur_usd = broker.accounts[accountIndex].findInstrument({ $0.displayName == "EUR/USD" }) else { XCTFail("currency not found") return } var step = 0 let expected: [(ordersCount:Int,tradesCount:Int)] = [ (0, 1), (0, 0) ] let account = broker.accounts[accountIndex] eur_usd.startTradeEventsStreaming(DispatchQueue.global(qos: .background)) { (event) in log.debug("event: \(event)") if expected[step].ordersCount == account.openOrders.count && expected[step].tradesCount == account.openTrades.count { step += 1 } } let newOrder = OrderCreation(type: .market, side: .sell, units: 2, //entry: 2.5, stopLoss: 1.1050) //expiry: Timestamp(seconds: Timestamp.now.seconds+300 eur_usd.submitOrder(newOrder) { status,execution in } Thread.sleep(delay: 1*Seconds) inject(price: 1.1020) Thread.sleep(delay: 1*Seconds) guard account.openTrades.count > 0 else { XCTFail("no trades!") return } inject(price: 1.1055) // stop Thread.sleep(delay: 1*Seconds) eur_usd.stopTradeEventsStreaming() XCTAssert(step == 2) } func test_order_expiry_1() { let accountIndex = 0 refreshAccounts() refreshInstruments(accountIndex) broker.activate() Thread.sleep(delay: 1*Seconds) // wait for the stream to be operational guard let eur_usd = broker.accounts[accountIndex].findInstrument({ $0.displayName == "EUR/USD" }) else { XCTFail("currency not found") return } var step = 0 let expected: [(ordersCount:Int,tradesCount:Int)] = [ (1, 0), (0, 0) ] let account = broker.accounts[accountIndex] eur_usd.startTradeEventsStreaming(DispatchQueue.global(qos: .background)) { (event) in log.debug("event: \(event)") if expected[step].ordersCount == account.openOrders.count && expected[step].tradesCount == account.openTrades.count { if step == expected.count { XCTFail("too many events") } else { step += 1 } } } let syncExecution = Sync<(RequestStatus,OrderExecution)>() let newOrder = OrderCreation(type: .marketIfTouched, side: .buy, units: 1, entry: 0.5, expiry: Timestamp(seconds: Timestamp.now.seconds+2)) eur_usd.submitOrder(newOrder) { status,execution in syncExecution.post((status,execution)) } if let (status,execution) = syncExecution.take(delay: 1 * Seconds) { log.debug("execution status = \(status) \(execution)") //log.debug("order execution = \(execution)") if status.tradingHaltedForInstrument || status.isSuccess { // success //return } } Thread.sleep(delay: 1*Seconds) self.inject(time: Timestamp(seconds: Timestamp.now.seconds+3)) Thread.sleep(delay: 1*Seconds) eur_usd.stopTradeEventsStreaming() XCTAssert(step == 2) } func test_order_params_1() { let accountIndex = 0 refreshAccounts() refreshInstruments(accountIndex) broker.activate() Thread.sleep(delay: 1*Seconds) // wait for the stream to be operational guard let eur_usd = broker.accounts[accountIndex].findInstrument({ $0.displayName == "EUR/USD" }) else { XCTFail("currency not found") return } var step = 0 let expected: [(ordersCount:Int,tradesCount:Int)] = [ (1, 0), (1, 0), (0, 0) ] let account = broker.accounts[accountIndex] eur_usd.startTradeEventsStreaming(DispatchQueue.global(qos: .background)) { (event) in log.debug("event: \(event)") if expected[step].ordersCount == account.openOrders.count && expected[step].tradesCount == account.openTrades.count { step += 1 } } let newOrder = OrderCreation(type: .marketIfTouched, side: .buy, units: 1, entry: 0.5, stopLoss: 0.1, expiry: Timestamp(seconds: Timestamp.now.seconds+300)) eur_usd.submitOrder(newOrder) { status,execution in } Thread.sleep(delay: 2*Seconds) let order = account.openOrders[0] XCTAssert(order.takeProfit == nil) XCTAssert(order.stopLoss == 0.1) order.modify(change: [.takeProfit(price: 2), .stopLoss(price: nil)]) { status in } Thread.sleep(delay: 2*Seconds) XCTAssert(order.takeProfit == 2) XCTAssert(order.stopLoss == nil) order.cancel { status in } Thread.sleep(delay: 2*Seconds) eur_usd.stopTradeEventsStreaming() XCTAssert(step == 3) } }
mit
9a34caba8b8967909a241f70f1ef82de
31.054348
213
0.523432
4.774935
false
false
false
false