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
saturnboy/learning_spritekit_swift
LearningSpriteKit/LearningSpriteKit/GameScene4.swift
1
1901
// // GameScene4.swift // LearningSpriteKit // // Created by Justin on 12/1/14. // Copyright (c) 2014 SaturnBoy. All rights reserved. // import SpriteKit class GameScene4: SKScene { var anim:SKAction = SKAction.fadeAlphaTo(1.0, duration: 1.0) override func didMoveToView(view: SKView) { println("GameScene4: \(view.frame.size)") self.backgroundColor = UIColor(red: 0.3, green: 0.1, blue: 0.3, alpha: 1.0) let atlas = SKTextureAtlas(named: "alien") let t1 = atlas.textureNamed("alien1") let t2 = atlas.textureNamed("alien2") let t3 = atlas.textureNamed("alien3") let t4 = atlas.textureNamed("alien4") let t5 = atlas.textureNamed("alien5") let t6 = atlas.textureNamed("alien6") let t7 = atlas.textureNamed("alien7") let t8 = atlas.textureNamed("alien8") let t9 = atlas.textureNamed("alien9") let t10 = atlas.textureNamed("alien10") //create animation self.anim = SKAction.animateWithTextures([t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t9,t8,t7,t6,t5,t4,t3,t2,t1], timePerFrame: 0.05) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { if let touch: AnyObject = touches.anyObject() { let loc = touch.locationInNode(self) println("touch: \(loc)") // move alien to touch pos let alien = SKSpriteNode(imageNamed: "alien1"); alien.position = loc alien.alpha = 0.0 self.addChild(alien); let fadeIn = SKAction.fadeInWithDuration(0.5); let fadeOut = SKAction.fadeOutWithDuration(0.5); alien.runAction(SKAction.sequence([fadeIn, self.anim, fadeOut])) } } override func update(currentTime: CFTimeInterval) { //pass } }
mit
0edbbdf16f64711f1531a019a313c92a
32.350877
129
0.58969
3.863821
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/DynamicButton/Sources/DynamicButtonStyles/DynamicButtonStyleCheckMark.swift
3
2051
/* * DynamicButton * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit /// Check mark style: ✓ final public class DynamicButtonStyleCheckMark: DynamicButtonStyle { convenience required public init(center: CGPoint, size: CGFloat, offset: CGPoint, lineWidth: CGFloat) { let headPoint = CGPoint(x: center.x, y: center.y) let leftPoint = CGPoint(x: offset.x + size / 4, y: offset.y + size / 4) let rightPoint = CGPoint(x: offset.x + size, y: offset.y) let offsetPoint = CGPoint(x: -size / 8, y: size / 4) let p1 = PathHelper.line(from: headPoint, to: leftPoint, offset: offsetPoint) let p2 = PathHelper.line(from: headPoint, to: rightPoint, offset: offsetPoint) self.init(pathVector: (p1, p1, p2, p2)) } // MARK: - Conforming the CustomStringConvertible Protocol /// A textual representation of "Check Mark" style. public override var description: String { return "Check Mark" } }
mit
8ee45aadcfe0d9777a372a7f18964790
40.816327
105
0.729624
4.114458
false
false
false
false
markohlebar/Fontana
Spreadit/View/SettingsViewController.swift
1
5031
// // SettingsViewController.swift // Spreadit // // Created by Marko Hlebar on 31/01/2016. // Copyright © 2016 Marko Hlebar. All rights reserved. // import UIKit import BIND class SettingsViewController: BNDViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView: UITableView? lazy var viewModels: [TableRowViewModel] = { return [ DonateCellModel(model: "Donate", navigationController:self.navigationController!), NavigationCellModel(model: "How do I use this app?"), NavigationCellModel(model: "Future development board"), ] }() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.tabBarItem = UITabBarItem(tabBarSystemItem:.More, tag: 1) self.navigationItem.title = "More" self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: "presentShareViewController") subscribeToNotifications() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func subscribeToNotifications() { let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "updateDonationCell", name: DonationStoreDidUpdateProductsNotification, object: nil) } func updateDonationCell() { guard let tableView = self.tableView where tableView.numberOfRowsInSection(0) > 0 else { return } let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView?.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } override func viewDidLoad() { super.viewDidLoad() self.tableView?.tableFooterView = UIView() self.viewModel = SettingsViewModel() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) FNTAppTracker.trackEvent(FNTAppTrackerScreenViewEvent, withTags: [FNTAppTrackerScreenNameTag : "More"]) } func settingsViewModel() -> SettingsViewModel { return self.viewModel as! SettingsViewModel } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let viewModel = viewModels[indexPath.row] as TableRowViewModel var cell = tableView.dequeueReusableCellWithIdentifier(viewModel.identifier()) as? BNDTableViewCell if (cell == nil) { cell = UIView.loadFromNib(viewModel.identifier()) as? BNDTableViewCell } cell!.viewModel = viewModel return cell! } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModels.count } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.row == 1 { if let viewController = UIViewController.loadFromStoryboard("VideoViewController") { self.navigationController?.pushViewController(viewController, animated: true) } FNTAppTracker.trackEvent(FNTAppTrackerActionEvent, withTags: [FNTAppTrackerEventActionTag: "More - onViewTutorial"]) } else if indexPath.row == 2 { if let viewController = UIViewController.loadFromStoryboard("WebViewController") as? BNDViewController { viewController.viewModel = WebViewModel.viewModelWithModel("https://trello.com/b/ebULNqww/fontana-future") viewController.navigationItem.title = "Future Development" self.navigationController?.pushViewController(viewController, animated: true) } FNTAppTracker.trackEvent(FNTAppTrackerActionEvent, withTags: [FNTAppTrackerEventActionTag: "More - onViewFutureBoard"]) } } func presentShareViewController() { let activityViewController = UIActivityViewController(activityItems: [self.settingsViewModel()], applicationActivities: nil) activityViewController.excludedActivityTypes = [ UIActivityTypePrint, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll, UIActivityTypeAddToReadingList, ] navigationController?.presentViewController(activityViewController, animated: true, completion: nil) FNTAppTracker.trackEvent(FNTAppTrackerActionEvent, withTags: [FNTAppTrackerEventActionTag: "More - onShare"]) } func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let viewModel = viewModels[indexPath.row] return viewModel.cellHeight() } }
agpl-3.0
df6b7c07a1bea881475f28a3a1db207f
37.396947
139
0.664215
5.715909
false
false
false
false
luckymarmot/ThemeKit
Sources/UserTheme.swift
1
8688
// // UserTheme.swift // ThemeKit // // Created by Nuno Grilo on 06/09/16. // Copyright © 2016 Paw & Nuno Grilo. All rights reserved. // import Foundation /** A `Theme` class wrapping a user provided theme file (`.theme`). To enable user themes, set theme folder on `ThemeManager.userThemesFolderURL`. Notes about `.theme` files: - lines starting with `#` or `//` will be treated as comments, thus, ignored; - non-comment lines consists on simple variable/value assignments (eg, `variable = value`); - `variable` name can contain characters `[a-zA-Z0-9_-.]+`; - custom variables can be specified (eg, `myBackgroundColor = ...`); - theming properties match the class methods of `ThemeColor`, `ThemeGradient` and `ThemeImage` (eg, `labelColor`); - variables can be referenced by prefixing them with `$` (eg, `mainBorderColor = $commonBorderColor`); - colors are defined using `rgb(255, 255, 255)` or `rgba(255, 255, 255, 1.0)` (case insensitive); - gradients are defined using `linear-gradient(color1, color2)` (where colors are defined as above; case insensitive); - pattern images are defined using `pattern(named:xxxx)` (named images) or `pattern(file:../dddd/xxxx.yyy)` (filesystem images); - images are defined using `image(named:xxxx)` (named images) or `image(file:../dddd/xxxx.yyy)` (filesystem images); - `ThemeManager.themes` property is automatically updated when there are changes on the user themes folder; - file changes are applied on-the-fly, if it corresponds to the currently applied theme. Example `.theme` file: ```ruby // ************************* Theme Info ************************* // displayName = My Theme 1 identifier = com.luckymarmot.ThemeKit.MyTheme1 darkTheme = true // ********************* Colors & Gradients ********************* // # define color for `ThemeColor.brandColor` brandColor = $blue # define a new color for `NSColor.labelColor` (overriding) labelColor = rgb(11, 220, 111) # define gradient for `ThemeGradient.brandGradient` brandGradient = linear-gradient($orange.sky, rgba(200, 140, 60, 1.0)) // ********************* Images & Patterns ********************** // # define pattern image from named image "paper" for color `ThemeColor.contentBackgroundColor` contentBackgroundColor = pattern(named:paper) # define pattern image from filesystem (relative to user themes folder) for color `ThemeColor.bottomBackgroundColor` bottomBackgroundColor = pattern(file:../some/path/some-file.png) # use named image "apple" namedImage = image(named:apple) # use image from filesystem (relative to user themes folder) fileImage = image(file:../some/path/some-file.jpg) // *********************** Common Colors ************************ // blue = rgb(0, 170, 255) orange.sky = rgb(160, 90, 45, .5) // ********************** Fallback Assets *********************** // fallbackForegroundColor = rgb(255, 10, 90, 1.0) fallbackBackgroundColor = rgb(255, 200, 190) fallbackGradient = linear-gradient($blue, rgba(200, 140, 60, 1.0)) ``` With the exception of system overrided named colors (e.g., `labelColor`), which defaults to the original system provided named color, unimplemented properties on theme file will default to `-fallbackForegroundColor`, `-fallbackBackgroundColor`, `-fallbackGradient` and `-fallbackImage`, for foreground color, background color, gradients and images, respectively. */ @objc(TKUserTheme) public class UserTheme: NSObject, Theme { /// Unique theme identifier. public var identifier: String = "{Theme-Not-Loaded}" /// Theme display name. public var displayName: String = "Theme Not Loaded" /// Theme short display name. public var shortDisplayName: String = "Not Loaded" /// Is this a dark theme? public var isDarkTheme: Bool = false /// File URL. @objc public var fileURL: URL? /// Dictionary with key/values pairs read from the .theme file private var _keyValues: NSMutableDictionary = NSMutableDictionary() /// Dictionary with evaluated key/values pairs read from the .theme file private var _evaluatedKeyValues: NSMutableDictionary = NSMutableDictionary() // MARK: - // MARK: Initialization /// `init()` is disabled. private override init() { super.init() } /// Calling `init(_:)` is not allowed outside this library. /// Use `ThemeManager.shared.theme(:_)` instead. /// /// - parameter themeFileURL: A theme file (`.theme`) URL. /// /// - returns: An instance of `UserTheme`. @objc internal init(_ themeFileURL: URL) { super.init() // Load file fileURL = themeFileURL loadThemeFile(from: themeFileURL) } /// Reloads user theme from file. @objc public func reload() { if let url = fileURL { _keyValues.removeAllObjects() _evaluatedKeyValues.removeAllObjects() loadThemeFile(from: url) } } // MARK: - // MARK: Theme Assets /// Theme asset for the specified key. Supported assets are `NSColor`, `NSGradient`, `NSImage` and `NSString`. /// /// - parameter key: A color name, gradient name, image name or a theme string /// /// - returns: The theme value for the specified key. @objc public func themeAsset(_ key: String) -> Any? { var value = _evaluatedKeyValues[key] if value == nil, let evaluatedValue = _keyValues.evaluatedObject(key: key) { value = evaluatedValue _evaluatedKeyValues.setObject(evaluatedValue, forKey: key as NSString) } return value } /// Checks if a theme asset is provided for the given key. /// /// Do not check for theme asset availability with `themeAsset(_:)`, use /// this method instead, which is much faster. /// /// - parameter key: A color name, gradient name, image name or a theme string /// /// - returns: `true` if theme provides an asset for the given key; `false` otherwise. @objc public func hasThemeAsset(_ key: String) -> Bool { return _keyValues[key] != nil } // MARK: - // MARK: File /// Load theme file /// /// - parameter from: A theme file (`.theme`) URL. private func loadThemeFile(from: URL) { // Load contents from theme file if let themeContents = try? String(contentsOf: from, encoding: String.Encoding.utf8) { // Split content into lines var lineCharset = CharacterSet(charactersIn: ";") lineCharset.formUnion(CharacterSet.newlines) let lines: [String] = themeContents.components(separatedBy: lineCharset) // Parse lines for line in lines { // Trim let trimmedLine = line.trimmingCharacters(in: CharacterSet.whitespaces) // Skip comments if trimmedLine.hasPrefix("#") || trimmedLine.hasPrefix("//") { continue } // Assign theme key-values (lazy evaluation) let assignment = trimmedLine.components(separatedBy: "=") if assignment.count == 2 { let key = assignment[0].trimmingCharacters(in: CharacterSet.whitespaces) let value = assignment[1].trimmingCharacters(in: CharacterSet.whitespaces) _keyValues.setObject(value, forKey: key as NSString) } } // Initialize properties with evaluated values from file // Identifier if let identifierString = themeAsset("identifier") as? String { identifier = identifierString } else { identifier = "{identifier: is mising}" } // Display Name if let displayNameString = themeAsset("displayName") as? String { displayName = displayNameString } else { displayName = "{displayName: is mising}" } // Short Display Name if let shortDisplayNameString = themeAsset("shortDisplayName") as? String { shortDisplayName = shortDisplayNameString } else { shortDisplayName = "{shortDisplayName: is mising}" } // Dark? if let isDarkThemeString = themeAsset("darkTheme") as? String { isDarkTheme = NSString(string: isDarkThemeString).boolValue } else { isDarkTheme = false } } } override public var description: String { return "<\(UserTheme.self): \(themeDescription(self))>" } }
mit
488b81b412a6d6f21439adc3f2a6edff
37.100877
129
0.619431
4.606045
false
false
false
false
akane/Gaikan
GaikanTests/UIKit/Extension/UINavigationBarSpec.swift
1
2057
// // This file is part of Gaikan // // Created by Simone Civetta on 26/02/16. // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code // import Foundation import Quick import Nimble import Gaikan class UINavigationBarSpec: QuickSpec { override func spec() { var navigationBar: UINavigationBar! beforeEach { navigationBar = UINavigationBar() } describe("styleInline") { var style: StyleRule! context("when giving style") { it("should inherit view styles") { style = [ .tintColor: UIColor.blue ] navigationBar.styleInline = style expect(navigationBar.tintColor) == UIColor.blue } it("should apply a title font") { style = [ .font: UIFont.systemFont(ofSize: 42.0) ] navigationBar.titleStyle.styleInline = style expect(navigationBar.titleTextAttributes![NSFontAttributeName] as? UIFont) == UIFont.systemFont(ofSize: 42.0) } it("should apply a foreground color to the title") { style = [ .color: UIColor.blue ] navigationBar.titleStyle.styleInline = style expect(navigationBar.titleTextAttributes![NSForegroundColorAttributeName] as? UIColor) == UIColor.blue } it("should apply a shadow to the title") { let shadow = NSShadow() shadow.shadowOffset = CGSize(width: 2, height: 3) style = [ .textShadow: shadow ] navigationBar.titleStyle.styleInline = style expect(navigationBar.titleTextAttributes![NSShadowAttributeName] as? NSShadow) == shadow } } } } }
mit
8cd7ca83dcf6528219b33df558a59b04
31.650794
129
0.529412
5.810734
false
false
false
false
themasterapp/master-app-ios
MasterApp/Modules/Components/Other/UrlBuilder.swift
1
1806
// // UrlBuilder.swift // MasterApp // // Created by MasterApp on 11/15/16. // Copyright © 2016 YSimplicity. All rights reserved. // import Foundation /*! This struct builds the URL for the app. It adds the localization and authToken to the URL */ struct UrlBuilder { private var URL : NSURL init(URL: NSURL) { self.URL = URL } func build() -> NSURL { let finalUrl = urlWithAuthToken(urlForLocalization(URL)) return finalUrl } private func urlForLocalization(URL: NSURL) -> NSURL { let nextLanguage = NSLocale.currentLocale().localeIdentifier let newLocaleUrl = nextLanguage.hasPrefix("pt") ? K.Localization.Portuguese : K.Localization.English let localeQuery = NSURLQueryItem(name: "locale", value: newLocaleUrl) let components = NSURLComponents(URL: URL, resolvingAgainstBaseURL: false) if (components?.queryItems == nil) { components?.queryItems = [localeQuery] } else { components?.queryItems?.append(localeQuery) } let finalUrl = components?.URL ?? URL return finalUrl } private func urlWithAuthToken(URL: NSURL) -> NSURL { let components = NSURLComponents(URL: URL, resolvingAgainstBaseURL: false) let token = UserSessionManager.sharedInstance.authToken() guard !token.isEmpty else { return URL } let authTokenQuery = NSURLQueryItem(name: "auth_token", value: UserSessionManager.sharedInstance.authToken()) if (components?.queryItems == nil) { components?.queryItems = [authTokenQuery] } else { components?.queryItems?.append(authTokenQuery) } let finalUrl = components?.URL ?? URL return finalUrl } }
mit
cb224f41e0e129de66d0f9c9e155df88
29.083333
117
0.640443
4.737533
false
false
false
false
pyconjp/pyconjp-ios
PyConJP/ViewController/Conference/ConferenceTimetableViewController.swift
1
5316
// // ConferenceTimetableViewController.swift // PyConJP // // Created by Yutaro Muta on 2017/06/17. // Copyright © 2017 PyCon JP. All rights reserved. // import UIKit import SpreadsheetView final class ConferenceTimetableViewController: UIViewController, StoryboardIdentifiable { @IBOutlet weak var timetableView: SpreadsheetView! { didSet { timetableView.dataSource = self timetableView.delegate = self timetableView.register(TimetableCell.nib, forCellWithReuseIdentifier: TimetableCell.nibName) timetableView.register(TimetableRoomCell.nib, forCellWithReuseIdentifier: TimetableRoomCell.nibName) timetableView.register(TimetableTimeAxisCell.nib, forCellWithReuseIdentifier: TimetableTimeAxisCell.nibName) timetableView.gridStyle = .none } } fileprivate(set) var dataStore: ConferenceTimetableDataStore? static func build(_ pyconJPDate: PyConJPDate) -> ConferenceTimetableViewController { let viewController: ConferenceTimetableViewController = UIStoryboard(storyboard: .conference).instantiateViewController() viewController.dataStore = ConferenceTimetableDataStore(pyconJPDate: pyconJPDate) return viewController } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refresh() } @objc func refreshNotification(_ notification: Notification) { refresh() } private func refresh() { dataStore?.reloadTimetable() timetableView.reloadData() } } extension ConferenceTimetableViewController: SpreadsheetViewDataSource { func numberOfColumns(in spreadsheetView: SpreadsheetView) -> Int { return dataStore?.numberOfColumns() ?? 0 } func numberOfRows(in spreadsheetView: SpreadsheetView) -> Int { return dataStore?.numberOfRows() ?? 0 } func spreadsheetView(_ spreadsheetView: SpreadsheetView, widthForColumn column: Int) -> CGFloat { return dataStore?.widthForColumn(column) ?? 0.0 } func spreadsheetView(_ spreadsheetView: SpreadsheetView, heightForRow row: Int) -> CGFloat { return dataStore?.heightForRow(row) ?? 0.0 } func spreadsheetView(_ spreadsheetView: SpreadsheetView, cellForItemAt indexPath: IndexPath) -> Cell? { let section = ConferenceTimetableDataStore.Section(indexPath: indexPath) guard let cellIdentifier = dataStore?.cellIdentifier(indexPath) else { return nil } let cell = spreadsheetView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) switch (section, cell) { case (.rowHeader, let roomCell as TimetableRoomCell): guard let room = dataStore?.room(indexPath) else { return nil } roomCell.fill(room) return cell case (.columnHeader, let timeCell as TimetableTimeAxisCell): guard let hourClock = dataStore?.hourClock(indexPath) else { return nil } timeCell.fill(hourClock) return timeCell case (.timetable, let timetableCell as TimetableCell): guard let talkObject = dataStore?.talk(indexPath) else { return nil } timetableCell.fill(talkObject) return timetableCell default: return nil } } func mergedCells(in spreadsheetView: SpreadsheetView) -> [CellRange] { var mergedCells = [CellRange]() // TimeAxis guard let hourDuration = dataStore?.timetable.hourDuration else { return mergedCells } for hour in hourDuration.enumerated() { mergedCells.append(CellRange(from: (row: 60 * hour.offset + 1, column: 0), to: (row: 60 * (hour.offset + 1), column: 0))) } // Talks guard let start = dataStore?.start else { return mergedCells } dataStore?.timetable.tracks.enumerated().forEach({ column, track in track.talks.forEach({ talk in let startTime = Int(talk.startDate.timeIntervalSince(start) / 60) mergedCells.append(CellRange(from: (row: startTime + 1, column: column + 1), to: (row: startTime + talk.minutesDuration, column: column + 1))) }) }) return mergedCells } func frozenColumns(in spreadsheetView: SpreadsheetView) -> Int { return dataStore?.frozenColumns ?? 0 } func frozenRows(in spreadsheetView: SpreadsheetView) -> Int { return dataStore?.frozenRows ?? 0 } } extension ConferenceTimetableViewController: SpreadsheetViewDelegate { func spreadsheetView(_ spreadsheetView: SpreadsheetView, didSelectItemAt indexPath: IndexPath) { let section = ConferenceTimetableDataStore.Section(indexPath: indexPath) switch section { case .corner, .rowHeader, .columnHeader: break case .timetable: guard let talkObject = dataStore?.talk(indexPath) else { return } let talkDetailViewController = TalkDetailViewController.build(id: talkObject.id) navigationController?.pushViewController(talkDetailViewController, animated: true) } } }
mit
1ef26fe8b0e5a38c41129ed99f755107
38.962406
129
0.662277
5.076409
false
false
false
false
AsyncNinja/AsyncNinja
Sources/AsyncNinja/EventSource_Merge2Unrelated.swift
1
4781
// // Copyright (c) 2016-2017 Anton Mironov // // 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 Dispatch /// Merges channels with completely unrelated types into one public func merge<LeftSource: EventSource, RightSource: EventSource>( _ leftSource: LeftSource, _ rightSource: RightSource, cancellationToken: CancellationToken? = nil, bufferSize: DerivedChannelBufferSize = .default ) -> Channel<Either<LeftSource.Update, RightSource.Update>, (LeftSource.Success, RightSource.Success)> { // Test: EventSource_Merge2Tests.testMergeIntsAndStrings typealias DestinationUpdate = Either<LeftSource.Update, RightSource.Update> typealias ResultungSuccess = (LeftSource.Success, RightSource.Success) typealias Destination = Producer<DestinationUpdate, ResultungSuccess> let producer = Destination(bufferSize: bufferSize.bufferSize(leftSource, rightSource)) cancellationToken?.add(cancellable: producer) let helper = Merge2UnrelatesEventSourcesHelper<LeftSource, RightSource, Destination>(destination: producer) producer._asyncNinja_retainHandlerUntilFinalization(helper.makeHandler(leftSource: leftSource)) producer._asyncNinja_retainHandlerUntilFinalization(helper.makeHandler(rightSource: rightSource)) return producer } /// **internal use only** /// Encapsulates merging behavior private class Merge2UnrelatesEventSourcesHelper< LeftSource: EventSource, RightSource: EventSource, Destination: EventDestination> where Destination.Update == Either<LeftSource.Update, RightSource.Update>, Destination.Success == (LeftSource.Success, RightSource.Success) { var locking = makeLocking() var leftSuccess: LeftSource.Success? var rightSuccess: RightSource.Success? weak var destination: Destination? init(destination: Destination) { self.destination = destination } func makeHandlerBlock<Update, Success>( updateHandler: @escaping (_ update: Update, _ originalExecutor: Executor) -> Void, successHandler: @escaping (_ success: Success) -> (LeftSource.Success, RightSource.Success)? ) -> (_ event: ChannelEvent<Update, Success>, _ originalExecutor: Executor) -> Void { // `self` is being captured but it is okay // because it does not retain valuable resources return { (event, originalExecutor) in switch event { case let .update(update): updateHandler(update, originalExecutor) case let .completion(.failure(error)): self.destination?.fail(error, from: originalExecutor) case let .completion(.success(localSuccess)): self.locking.lock() defer { self.locking.unlock() } if let success = successHandler(localSuccess) { self.destination?.succeed(success, from: originalExecutor) } } } } func makeHandler(leftSource: LeftSource) -> AnyObject? { func handleUpdate(update: LeftSource.Update, originalExecutor: Executor) { self.destination?.update(.left(update), from: originalExecutor) } let handlerBlock = makeHandlerBlock(updateHandler: handleUpdate) { (success: LeftSource.Success) in self.leftSuccess = success return self.rightSuccess.map { (success, $0) } } return leftSource.makeHandler(executor: .immediate, handlerBlock) } func makeHandler(rightSource: RightSource) -> AnyObject? { func handleUpdate(update: RightSource.Update, originalExecutor: Executor) { self.destination?.update(.right(update), from: originalExecutor) } let handlerBlock = makeHandlerBlock(updateHandler: handleUpdate) { (success: RightSource.Success) in self.rightSuccess = success return self.leftSuccess.map { ($0, success) } } return rightSource.makeHandler(executor: .immediate, handlerBlock) } }
mit
4ca72b25818acc59a515ecdbba800428
42.072072
109
0.745869
4.435065
false
false
false
false
burhanuddin353/TFTColor
Example/TFTColor/ViewController.swift
1
5312
// // ViewController.swift // Swift Example // // Created by Burhanuddin Sunelwala on 12/9/15. // Copyright © 2015 Burhanuddin Sunelwala. All rights reserved. // import UIKit import TFTColor class ViewController: UIViewController { @IBOutlet weak var rgbHexTextField: UITextField! @IBOutlet weak var cmykHexTextField: UITextField! @IBOutlet weak var redTextField: UITextField! @IBOutlet weak var greenTextField: UITextField! @IBOutlet weak var blueTextField: UITextField! @IBOutlet weak var cyanTextField: UITextField! @IBOutlet weak var magentaTextField: UITextField! @IBOutlet weak var yellowTextField: UITextField! @IBOutlet weak var blackTextField: UITextField! @IBOutlet weak var colorView: UIView! override func viewDidLoad() { super.viewDidLoad() rgbHexTextField.text = "#00ff00" colorView.backgroundColor = UIColor(rgbHexString: rgbHexTextField.text!, alpha: 1.0) let viewColor = colorView.backgroundColor! cmykHexTextField.text = viewColor.cmykHexString redTextField.text = "\(viewColor.redValue)" greenTextField.text = "\(viewColor.greenValue)" blueTextField.text = "\(viewColor.blueValue)" cyanTextField.text = "\(viewColor.cyanValue)" magentaTextField.text = "\(viewColor.magentaValue)" yellowTextField.text = "\(viewColor.yellowValue)" blackTextField.text = "\(viewColor.blackValue)" let aview = UIView(frame: CGRect(x: 15, y: 100, width: 100, height: 100)) aview.backgroundColor = viewColor.complementary view.addSubview(aview) } @IBAction func didChange(_ textField: UITextField) { if let text = textField.text { switch textField { case rgbHexTextField: colorView.backgroundColor = UIColor(rgbHexString: text, alpha: 1.0) let viewColor = colorView.backgroundColor! cmykHexTextField.text = viewColor.cmykHexString redTextField.text = "\(viewColor.redValue)" greenTextField.text = "\(viewColor.greenValue)" blueTextField.text = "\(viewColor.blueValue)" cyanTextField.text = "\(viewColor.cyanValue)" magentaTextField.text = "\(viewColor.magentaValue)" yellowTextField.text = "\(viewColor.yellowValue)" blackTextField.text = "\(viewColor.blackValue)" case cmykHexTextField: colorView.backgroundColor = UIColor(cmykHexString: text, alpha: 1.0) let viewColor = colorView.backgroundColor! rgbHexTextField.text = viewColor.rgbHexString redTextField.text = "\(viewColor.redValue)" greenTextField.text = "\(viewColor.greenValue)" blueTextField.text = "\(viewColor.blueValue)" cyanTextField.text = "\(viewColor.cyanValue)" magentaTextField.text = "\(viewColor.magentaValue)" yellowTextField.text = "\(viewColor.yellowValue)" blackTextField.text = "\(viewColor.blackValue)" case redTextField, greenTextField, blueTextField: colorView.backgroundColor = UIColor(red: CGFloat(Float(redTextField.text!) ?? 0)/255.0, green: CGFloat(Float(greenTextField.text!) ?? 0)/255.0, blue: CGFloat(Float(blueTextField.text!) ?? 0)/255.0, alpha: 1.0) let viewColor = colorView.backgroundColor! cmykHexTextField.text = viewColor.cmykHexString rgbHexTextField.text = viewColor.rgbHexString cyanTextField.text = "\(viewColor.cyanValue)" magentaTextField.text = "\(viewColor.magentaValue)" yellowTextField.text = "\(viewColor.yellowValue)" blackTextField.text = "\(viewColor.blackValue)" case cyanTextField, magentaTextField, yellowTextField, blackTextField: colorView.backgroundColor = UIColor(cyan: Float(cyanTextField.text!) ?? 0/255.0, magenta: Float(magentaTextField.text!) ?? 0/255.0, yellow: Float(yellowTextField.text!) ?? 0/255.0, black: Float(blackTextField.text!) ?? 0/255.0, alpha: 1.0) let viewColor = colorView.backgroundColor! cmykHexTextField.text = viewColor.cmykHexString rgbHexTextField.text = viewColor.rgbHexString redTextField.text = "\(viewColor.redValue)" greenTextField.text = "\(viewColor.greenValue)" blueTextField.text = "\(viewColor.blueValue)" default: colorView.backgroundColor = UIColor.white } } } }
mit
b98eb4a380d839bd1d281fcdc7789728
43.258333
107
0.566372
5.227362
false
false
false
false
TeamProxima/predictive-fault-tracker
mobile/SieHack/Pods/Charts/Source/Charts/Jobs/AnimatedViewPortJob.swift
53
3381
// // AnimatedViewPortJob.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class AnimatedViewPortJob: ViewPortJob { internal var phase: CGFloat = 1.0 internal var xOrigin: CGFloat = 0.0 internal var yOrigin: CGFloat = 0.0 fileprivate var _startTime: TimeInterval = 0.0 fileprivate var _displayLink: NSUIDisplayLink! fileprivate var _duration: TimeInterval = 0.0 fileprivate var _endTime: TimeInterval = 0.0 fileprivate var _easing: ChartEasingFunctionBlock? public init( viewPortHandler: ViewPortHandler, xValue: Double, yValue: Double, transformer: Transformer, view: ChartViewBase, xOrigin: CGFloat, yOrigin: CGFloat, duration: TimeInterval, easing: ChartEasingFunctionBlock?) { super.init(viewPortHandler: viewPortHandler, xValue: xValue, yValue: yValue, transformer: transformer, view: view) self.xOrigin = xOrigin self.yOrigin = yOrigin self._duration = duration self._easing = easing } deinit { stop(finish: false) } open override func doJob() { start() } open func start() { _startTime = CACurrentMediaTime() _endTime = _startTime + _duration _endTime = _endTime > _endTime ? _endTime : _endTime updateAnimationPhase(_startTime) _displayLink = NSUIDisplayLink(target: self, selector: #selector(animationLoop)) _displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes) } open func stop(finish: Bool) { if _displayLink != nil { _displayLink.remove(from: RunLoop.main, forMode: RunLoopMode.commonModes) _displayLink = nil if finish { if phase != 1.0 { phase = 1.0 phase = 1.0 animationUpdate() } animationEnd() } } } fileprivate func updateAnimationPhase(_ currentTime: TimeInterval) { let elapsedTime: TimeInterval = currentTime - _startTime let duration: TimeInterval = _duration var elapsed: TimeInterval = elapsedTime if elapsed > duration { elapsed = duration } if _easing != nil { phase = CGFloat(_easing!(elapsed, duration)) } else { phase = CGFloat(elapsed / duration) } } @objc fileprivate func animationLoop() { let currentTime: TimeInterval = CACurrentMediaTime() updateAnimationPhase(currentTime) animationUpdate() if currentTime >= _endTime { stop(finish: true) } } internal func animationUpdate() { // Override this } internal func animationEnd() { // Override this } }
mit
041da1b5ff051c3ae60db0055863909b
22.809859
88
0.545401
5.282813
false
false
false
false
einsteinx2/iSub
Carthage/Checkouts/KSHLSPlayer/KSHLSPlayer/KSHLSView/Streaming/Receiver/KSStreamReceiver.swift
1
6946
// // KSStreamReceiver.swift // KSHLSPlayer // // Created by Ken Sun on 2016/1/12. // Copyright © 2016年 KS. All rights reserved. // import Foundation import QuartzCore public class KSStreamReciever { struct Config { /** Max number of concurrent TS segments download tasks. */ static let concurrentDownloadMax = 3 /** Number of segments that we keep in hand to maintain downloading list. */ static let segmentWindowSize = 10 /** The timeout for response of request in seconds. */ static let requestTimeout = 3.0 /** The timeout for receiving data of request in seconds. */ static let resourceTimeout = 10.0 } let playlistUrl: String /** Authentication info. */ var username: String? var password: String? /** URL query string. */ var m3u8Query: String? var tsQuery: String? /** HLS components. */ internal var playlist: HLSPlaylist! internal var segments: [TSSegment] = [] /** Be sure to lock `segments` when operatiing on it. */ internal let segmentFence: AnyObject = NSObject() internal var session: NSURLSession? internal var playlistTask: NSURLSessionTask? /** ts url path -> task */ internal var segmentTasks: [String : NSURLSessionTask] = [:] internal var tsDownloads: Set<String> = Set() internal var pollingPlaylist = false /** Cached data for lastest playlist. */ private var playlistData: NSData! required public init(url: String) { playlistUrl = url } func startPollingPlaylist() { if pollingPlaylist { return } pollingPlaylist = true let conf = NSURLSessionConfiguration.defaultSessionConfiguration() conf.timeoutIntervalForRequest = Config.requestTimeout conf.timeoutIntervalForResource = Config.resourceTimeout session = NSURLSession.init() getPlaylist() } func stopPollingPlaylist() { playlistTask?.cancel() playlistTask = nil pollingPlaylist = false } func getPlaylist() { let url = m3u8Query != nil ? "\(playlistUrl)?\(m3u8Query)" : playlistUrl var time: NSTimeInterval? playlistTask = session?.dataTaskWithURL(NSURL.init(string: url)!, completionHandler: { [weak self] data, response, error in self?.handlePlaylistResponse(data, response: response, error: error, startTime: time!) }) if let task = playlistTask { time = CACurrentMediaTime() task.resume() } } private func handlePlaylistResponse(data: NSData?, response: NSURLResponse?, error: NSError?, startTime: NSTimeInterval) { // success if (response as? NSHTTPURLResponse)?.statusCode == 200 && data?.length > 0 { var interval: NSTimeInterval! // playlist is unchanged if playlistData != nil && playlistData.isEqualToData(data!) { playlistDidNotChange() interval = (playlist?.targetDuration ?? 1.0) / 2 } else { playlistData = data playlist = HLSPlaylist(data: playlistData) playlistDidUpdate() getSegments() interval = playlist.targetDuration ?? 1.0 } // polling playlist if pollingPlaylist && prepareForPlaylist() { // interval should minus past time for connection let delay = interval - (CACurrentMediaTime() - startTime) if delay <= 0 { getPlaylist() } else { let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))) dispatch_after(popTime, dispatch_get_main_queue(), { [weak self] in self?.getPlaylist() }) } } } // failure else { playlistDidFail(response as? NSHTTPURLResponse, error: error) } } // override func playlistDidFail(response: NSHTTPURLResponse?, error: NSError?) { } // override func playlistDidNotChange() { } // override func playlistDidUpdate() { } // override func prepareForPlaylist() -> Bool { return true } // override func getSegments() { } func isSegmentConnectionFull() -> Bool { return segmentTasks.count >= Config.concurrentDownloadMax } func downloadSegment(ts: TSSegment) { if isSegmentConnectionFull() { return } willDownloadSegment(ts) tsDownloads.insert(ts.url) let url = tsQuery != nil ? "\(ts.url)?\(tsQuery)" : ts.url let task = session?.dataTaskWithURL(NSURL.init(string: url)!, completionHandler: { [weak self] data, response, error in self?.handleSegmentResponse(ts, data: data, response: response, error: error) }) if task != nil { segmentTasks[ts.url] = task task!.resume() } } private func handleSegmentResponse(ts: TSSegment, data: NSData?, response: NSURLResponse?, error: NSError?) { // success if (response as? NSHTTPURLResponse)?.statusCode == 200 && data?.length > 0 { didDownloadSegment(ts, data: data!) } // failure else { segmentDidFail(ts, response: response as? NSHTTPURLResponse, error: error) } } func finishSegment(ts: TSSegment) { segmentTasks[ts.url] = nil if !isSegmentConnectionFull() { getSegments() } } // override func segmentDidFail(ts: TSSegment, response: NSHTTPURLResponse?, error: NSError?) { // this must be called to finish task finishSegment(ts) } // override func willDownloadSegment(ts: TSSegment) { } // override func didDownloadSegment(ts: TSSegment, data: NSData) { // this must be called to finish task finishSegment(ts) } } protocol KSStreamReceiverDelegate: class { func receiver(receiver: KSStreamReciever, didReceivePlaylist playlist: HLSPlaylist) func receiver(receiver: KSStreamReciever, playlistDidNotChange playlist: HLSPlaylist) func receiver(receiver: KSStreamReciever, playlistDidFailWithError error: NSError?, urlStatusCode code: Int) func receiver(receiver: KSStreamReciever, didReceiveSegment segment: TSSegment, data: NSData) func receiver(receiver: KSEventReceiver, segmentDidFail segment: TSSegment, withError error: NSError?) }
gpl-3.0
3dd6f78f970d1f521b5881a2d69d7823
28.931034
131
0.582169
5.005768
false
false
false
false
xu6148152/binea_project_for_ios
SlidingMenuLikeQQ/SlidingMenuLikeQQ/ViewController.swift
1
6925
// // ViewController.swift // SlidingMenuLikeQQ // // Created by Binea Xu on 9/14/15. // Copyright © 2015 Binea Xu. All rights reserved. // import UIKit class ViewController: UIViewController{ let FULL_DISTANCE: CGFloat = 0.78 let PROPORTION: CGFloat = 0.77 var proportionOfLeftView: CGFloat = 1 var distanceOfLeftView: CGFloat = 50 var centerOfLeftViewAtBeginning: CGPoint! var distance: CGFloat = 0 //shadow var blackCover: UIView! //mainview var mainView: UIView! var mainTabBarController: MainTabBarController! var tapGesture: UITapGestureRecognizer! var homeNavigationController: UINavigationController! var homeViewController: HomeViewController! var leftViewController: LeftViewController! override func viewDidLoad() { super.viewDidLoad() let imageView = UIImageView(image: UIImage(named: "back")) imageView.frame = UIScreen.mainScreen().bounds self.view.addSubview(imageView) leftViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("LeftViewController") as! LeftViewController if Common.screenWidth > 320 { proportionOfLeftView = Common.screenWidth / 320 distanceOfLeftView = (Common.screenWidth - 320) * FULL_DISTANCE / 2 } leftViewController.view.center = CGPointMake(leftViewController.view.center.x - 50, leftViewController.view.center.y) leftViewController.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.8, 0.8) centerOfLeftViewAtBeginning = leftViewController.view.center self.view.addSubview(leftViewController.view) blackCover = UIView(frame: CGRectOffset(self.view.frame, 0, 0)) blackCover.backgroundColor = UIColor.blackColor() self.view.addSubview(blackCover) mainView = UIView(frame: self.view.frame) let nibContents = NSBundle.mainBundle().loadNibNamed("MainTabBarController", owner: nil, options: nil) mainTabBarController = nibContents.first as! MainTabBarController let tabBarView = mainTabBarController.view mainView.addSubview(tabBarView) homeNavigationController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("HomeNavigationController") as! UINavigationController homeViewController = homeNavigationController.viewControllers.first as! HomeViewController tabBarView.addSubview(homeViewController.navigationController!.view) tabBarView.addSubview(homeViewController.view) tabBarView.bringSubviewToFront(mainTabBarController.tabBar) self.view.addSubview(mainView) homeViewController.navigationItem.leftBarButtonItem?.action = Selector("showLeft") homeViewController.navigationItem.rightBarButtonItem?.action = Selector("showRight") let panGesture = homeViewController.panGesture panGesture.addTarget(self, action: Selector("pan:")) mainView.addGestureRecognizer(panGesture) tapGesture = UITapGestureRecognizer(target: self, action: "showHome") } func pan(recoginizer: UIPanGestureRecognizer) { let x = recoginizer.translationInView(self.view).x let trueDistance = distance + x let trueProportion = trueDistance / (Common.screenWidth * FULL_DISTANCE) if recoginizer.state == UIGestureRecognizerState.Ended { if trueDistance > Common.screenWidth * (PROPORTION / 3) { showLeft() }else if trueDistance < Common.screenWidth * (-PROPORTION / 3) { showHome() } else { showRight() } return } var proportion: CGFloat = recoginizer.view!.frame.origin.x >= 0 ? -1 : 1 proportion *= trueDistance / Common.screenWidth proportion *= 1 - PROPORTION proportion /= FULL_DISTANCE + PROPORTION / 2 - 0.5 proportion += 1 if proportion <= PROPORTION { return } blackCover.alpha = (proportion - PROPORTION) / (1 - PROPORTION) recoginizer.view!.center = CGPointMake(self.view.center.x + trueDistance, self.view.center.y) recoginizer.view!.transform = CGAffineTransformScale(CGAffineTransformIdentity, proportion, proportion) let pro = 0.8 + (proportionOfLeftView - 0.8) * trueProportion leftViewController.view.center = CGPointMake(centerOfLeftViewAtBeginning.x + distanceOfLeftView * trueProportion, centerOfLeftViewAtBeginning.y - (proportionOfLeftView - 1) * leftViewController.view.frame.height * trueProportion / 2) leftViewController.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, pro, pro) } func showLeft() { mainView.addGestureRecognizer(tapGesture) distance = self.view.center.x * (FULL_DISTANCE * 2 + PROPORTION - 1) doTheAnimation(self.PROPORTION, oriention: ORIENTION.LEFT) homeNavigationController.popToRootViewControllerAnimated(true) } func showRight() { mainView.removeGestureRecognizer(tapGesture) distance = 0 doTheAnimation(1, oriention: ORIENTION.HOME) } func showHome() { mainView.addGestureRecognizer(tapGesture) distance = self.view.center.x * (FULL_DISTANCE * 2 + PROPORTION - 1) doTheAnimation(self.PROPORTION, oriention: ORIENTION.RIGHT) } func doTheAnimation(proprotion: CGFloat, oriention: ORIENTION) { UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.mainView.center = CGPointMake(self.view.center.x + self.distance, self.view.center.y) self.mainView.transform = CGAffineTransformScale(CGAffineTransformIdentity, proprotion, proprotion) if oriention == ORIENTION.LEFT { self.leftViewController.view.center = CGPointMake(self.centerOfLeftViewAtBeginning.x + self.distanceOfLeftView, self.leftViewController.view.center.y) self.leftViewController.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, self.proportionOfLeftView, self.proportionOfLeftView) } self.blackCover.alpha = oriention == ORIENTION.HOME ? 1 : 0 self.leftViewController.view.alpha = oriention == ORIENTION.RIGHT ? 0 : 1 }, completion: nil) } enum ORIENTION { case LEFT case HOME case RIGHT } }
mit
953b15749f418e23d3bda0d3049d6a16
37.687151
241
0.655979
5.140312
false
false
false
false
muukii/DataSources
Sources/DataSources/Throttle.swift
1
1257
// // Throttle.swift // DataSources // // Created by muukii on 8/9/17. // Copyright © 2017 muukii. All rights reserved. // import Foundation final class Throttle { private var timerReference: DispatchSourceTimer? let interval: TimeInterval let queue: DispatchQueue private var lastSendTime: Date? init(interval: TimeInterval, queue: DispatchQueue = .main) { self.interval = interval self.queue = queue } func on(handler: @escaping () -> Void) { let now = Date() if let _lastSendTime = lastSendTime { if (now.timeIntervalSinceReferenceDate - _lastSendTime.timeIntervalSinceReferenceDate) >= interval { handler() lastSendTime = now } } else { lastSendTime = now } let deadline = DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(interval * 1000.0)) timerReference?.cancel() let timer = DispatchSource.makeTimerSource(queue: queue) timer.schedule(deadline: deadline) timer.setEventHandler(handler: { [weak timer, weak self] in self?.lastSendTime = nil handler() timer?.cancel() self?.timerReference = nil }) timer.resume() timerReference = timer } func cancel() { timerReference = nil } }
mit
4ae13ed8b8d2406be3b790375c2aafd1
20.288136
106
0.660032
4.243243
false
false
false
false
dpettigrew/Artisan
src/Artisan.swift
1
18945
/* Artisan.swift Created by David Pettigrew on 4/7/15. Copyright (c) 2015-2017 LifeCentrics. All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import CoreGraphics import Foundation import Foundation @IBDesignable public class Artisan { public class func color(fromHexRGB hex: String) -> UIColor { var cString: String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if cString.hasPrefix("#") { cString = cString.substring(from: cString.index(cString.startIndex, offsetBy: 1)) } if cString.characters.count == 3 { var paddedString: String = "" let range = cString.characters.startIndex..<cString.characters.endIndex cString.enumerateSubstrings(in: range, options: .byComposedCharacterSequences, { (substring, _, _, _) in paddedString = paddedString + substring! + substring! }) cString = paddedString } if cString.characters.count == 6 { var rgbValue: UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } if cString.characters.count == 8 { var rgbValue: UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF000000) >> 24) / 255.0, green: CGFloat((rgbValue & 0x00FF0000) >> 16) / 255.0, blue: CGFloat((rgbValue & 0x0000FF00) >> 8) / 255.0, alpha: CGFloat(rgbValue & 0x000000FF) / 255.0 ) } return .gray } public class func randomColorString() -> String { return String(format: "%02X", arc4random()%255) + String(format: "%02X", arc4random()%255) + String(format: "%02X", arc4random()%255) } public class func hexColorString(red: UInt8, green: UInt8, blue: UInt8) -> String { return String(format: "%02X", red) + String(format: "%02X", green) + String(format: "%02X", blue) } public class func radians(_ degrees: Double) -> Double { return degrees * Double.pi/180 } } public class Drawer { public var element: Element public var drawFunc: (Element) -> Void public init(element: Element, drawFunc: @escaping (Element) -> Void) { self.element = element self.drawFunc = drawFunc } } public class Paper: UIView { public override init(frame: CGRect) { super.init(frame: frame) } public convenience init() { self.init(frame: CGRect.zero) } // swiftlint:disable variable_name public convenience init (x: Double, y: Double, width: Double, height: Double) { let rect: CGRect = CGRect(x: CGFloat(x), y: CGFloat(y), width: CGFloat(width), height: CGFloat(height)) self.init(frame: rect) } // swiftlint:enable variable_name public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } @IBInspectable public var fill: String = "666666" { didSet { backgroundColor = Artisan.color(fromHexRGB: fill) setNeedsDisplay() } } var drawers = [Drawer]() public override func draw(_ rect: CGRect) { for drawer in drawers { drawer.drawFunc(drawer.element) } } public func ellipse(xCenter: Double, yCenter: Double, width: Double, height: Double) -> Ellipse { var ellipseOrigX = xCenter - width/2 var ellipseOrigY = Double(bounds.origin.y) - height/2 + yCenter var ellipse: Ellipse = Ellipse(xCenter: ellipseOrigX, yCenter: ellipseOrigY, width: width, height: height) ellipse.paper = self layer.addSublayer(ellipse) // Ellipse Drawing func draw(_ element: Element) { let ellipse_: Ellipse = element as! Ellipse let rect = CGRect(x: CGFloat(ellipse_.xCenter), y: CGFloat(ellipse_.yCenter), width: CGFloat(ellipse_.width), height: CGFloat(ellipse_.height)) ellipse_.path = UIBezierPath(ovalIn: rect).cgPath ellipse_.fillColor = Artisan.color(fromHexRGB: ellipse_.fill).cgColor ellipse_.strokeColor = Artisan.color(fromHexRGB: ellipse_.stroke).cgColor } let drawer: Drawer = Drawer(element: ellipse, drawFunc: draw) drawers.append(drawer) setNeedsDisplay() return ellipse } public func circle(xCenter: Double, yCenter: Double, radius: Double) -> Ellipse { return ellipse(xCenter: xCenter, yCenter: yCenter, width: radius * 2, height: radius * 2) } public func arc(xCenter: Double, yCenter: Double, radius: Double, startAngle: Double, endAngle: Double, clockwise: Bool) -> Path { var clockwiseStr: String = clockwise == true ? "1" : "0" var path: Path = Path(instructionString: "A \(xCenter) \(yCenter) \(radius) \(startAngle) \(endAngle) \(clockwiseStr)") path.paper = self layer.addSublayer(path) func draw(_ element: Element) { let path = element as! Path if path.fill == "" { path.fillColor = nil } else { path.fillColor = Artisan.color(fromHexRGB: path.fill).cgColor } path.strokeColor = Artisan.color(fromHexRGB: path.stroke).cgColor } let drawer: Drawer = Drawer(element: path as Element, drawFunc: draw) drawers.append(drawer) setNeedsDisplay() return path } public func rect(xOrigin: Double, yOrigin: Double, width: Double, height: Double, cornerRadius: Double = 0) -> Rectangle { var rect: Rectangle = Rectangle(xOrigin: xOrigin, yOrigin: yOrigin, width: width, height: height) rect.cornerRadius = CGFloat(cornerRadius) rect.paper = self layer.addSublayer(rect) func draw(_ element: Element) { let rectangle: Rectangle = element as! Rectangle let rect = CGRect(x: CGFloat(rectangle.xOrigin), y: CGFloat(rectangle.yOrigin), width: CGFloat(rectangle.width), height: CGFloat(rectangle.height)) // Rectangle Drawing rectangle.path = UIBezierPath(roundedRect: rect, cornerRadius: rectangle.cornerRadius).cgPath rectangle.fillColor = Artisan.color(fromHexRGB: rectangle.fill).cgColor rectangle.strokeColor = Artisan.color(fromHexRGB: rectangle.stroke).cgColor } let drawer: Drawer = Drawer(element: rect, drawFunc: draw) drawers.append(drawer) setNeedsDisplay() return rect } public func clear() { drawers = Array<Drawer>() setNeedsDisplay() } public func image(src: UIImage, xOrigin: Double, yOrigin: Double, width: Double, height: Double) -> Image { var image: Image = Image(src: src, xOrigin: xOrigin, yOrigin: yOrigin, width: width, height: height) image.paper = self func draw(_ element: Element) { let image = element as! Image let rect = CGRect(x: CGFloat(image.xOrigin), y: CGFloat(image.yOrigin), width: CGFloat(image.width), height: CGFloat(image.height)) image.uiImage?.draw(in: rect) } let drawer: Drawer = Drawer(element: image as Element, drawFunc: draw) drawers.append(drawer) setNeedsDisplay() return image } public func path(_ commands: String) -> Path { var path: Path = Path(instructionString: commands) path.paper = self layer.addSublayer(path) func draw(_ element: Element) { let path = element as! Path path.strokeColor = Artisan.color(fromHexRGB: path.stroke).cgColor if path.fill == "" { path.fillColor = nil } else { path.fillColor = Artisan.color(fromHexRGB: path.fill).cgColor } } let drawer: Drawer = Drawer(element: path as Element, drawFunc: draw) drawers.append(drawer) setNeedsDisplay() return path } } public class Element: CAShapeLayer { var paper: Paper? public var stroke: String = "222222" { didSet { paper?.setNeedsDisplay() } } public var fill: String = "" { didSet { paper?.setNeedsDisplay() } } public override var lineWidth: CGFloat { didSet { paper?.setNeedsDisplay() } } public override func action(forKey event: String) -> CAAction? { if event == "path" { let animation = CABasicAnimation(keyPath: event) animation.duration = CATransaction.animationDuration() animation.timingFunction = CATransaction.animationTimingFunction() return animation } return super.action(forKey: event) } } public class Ellipse: Element { public var xCenter: Double = 0.0 public var yCenter: Double = 0.0 public var width: Double = 0.0 public var height: Double = 0.0 var shapeLayer: CAShapeLayer? public init (xCenter: Double, yCenter: Double, width: Double, height: Double) { self.xCenter = xCenter self.yCenter = yCenter self.width = width self.height = height super.init() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public required override init(layer: Any) { super.init(layer: layer) } } public class Rectangle: Element { public var xOrigin: Double = 0.0 public var yOrigin: Double = 0.0 public var width: Double = 0.0 public var height: Double = 0.0 public override var cornerRadius: CGFloat { didSet { paper?.setNeedsDisplay() } } public init (xOrigin: Double, yOrigin: Double, width: Double, height: Double) { self.xOrigin = xOrigin self.yOrigin = yOrigin self.width = width self.height = height super.init() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public required override init(layer: Any) { super.init(layer: layer) } } public class Image: Element { public var xOrigin: Double = 0.0 public var yOrigin: Double = 0.0 public var width: Double = 0.0 public var height: Double = 0.0 public var uiImage: UIImage? public init (src: UIImage, xOrigin: Double, yOrigin: Double, width: Double, height: Double) { self.xOrigin = xOrigin self.yOrigin = yOrigin self.width = width self.height = height uiImage = src super.init() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public required override init(layer: Any) { super.init(layer: layer) } } public class Path: Element { public var instructionString: String { didSet { path = Path.pathRef(for: instructionString) } } public class func pathRef(for instructionString: String) -> CGMutablePath { var cursorLoc: CGPoint = CGPoint(x: 0, y: 0) let pathRef = CGMutablePath() var instructionStartIndex: Int = 0 var instructions: [String] = instructionString.components(separatedBy: " ") for i in 0..<instructions.count { if i < instructionStartIndex { continue } let instruction = instructions[i] switch instruction { case "M": // moveto (absolute) e.g. M 250 550 if instructions.count <= instructionStartIndex+2 { print("Encountered incomplete M path instruction") break } let xStr = instructions[instructionStartIndex+1] let yStr = instructions[instructionStartIndex+2] if let xNum = NumberFormatter().number(from: xStr), let yNum = NumberFormatter().number(from: yStr) { let x: CGFloat = CGFloat(xNum) let y: CGFloat = CGFloat(yNum) pathRef.move(to: CGPoint(x: x, y: y)) instructionStartIndex = instructionStartIndex + 3 cursorLoc = CGPoint(x: x, y: y) } case "m": // moveto (relative) e.g. m 250 550 if instructions.count <= instructionStartIndex+2 { print("Encountered incomplete m path instruction") break } let xStr = instructions[instructionStartIndex+1] let yStr = instructions[instructionStartIndex+2] if let xNum = NumberFormatter().number(from: xStr), let yNum = NumberFormatter().number(from: yStr) { let x: CGFloat = CGFloat(xNum) let y: CGFloat = CGFloat(yNum) cursorLoc = CGPoint(x: cursorLoc.x + x, y: cursorLoc.y + y) pathRef.move(to: CGPoint(x: cursorLoc.x, y: cursorLoc.y)) instructionStartIndex = instructionStartIndex + 3 } case "L": // lineto (absolute) e.g. L 190 78 if instructions.count <= instructionStartIndex+2 { print("Encountered incomplete L path instruction") break } let xStr = instructions[instructionStartIndex+1] let yStr = instructions[instructionStartIndex+2] if let xNum = NumberFormatter().number(from: xStr), let yNum = NumberFormatter().number(from: yStr) { let x: CGFloat = CGFloat(xNum) let y: CGFloat = CGFloat(yNum) pathRef.addLine(to: CGPoint(x: x, y: y)) instructionStartIndex = instructionStartIndex + 3 cursorLoc = CGPoint(x: x, y: y) } case "l": // lineto (relative) e.g. l 10 100 if instructions.count <= instructionStartIndex+2 { print("Encountered incomplete l path instruction") break } let xStr = instructions[instructionStartIndex+1] let yStr = instructions[instructionStartIndex+2] if let xNum = NumberFormatter().number(from: xStr), let yNum = NumberFormatter().number(from: yStr) { let x: CGFloat = CGFloat(xNum) let y: CGFloat = CGFloat(yNum) cursorLoc = CGPoint(x: cursorLoc.x + x, y: cursorLoc.y + y) pathRef.addLine(to: CGPoint(x: cursorLoc.x, y: cursorLoc.y)) instructionStartIndex = instructionStartIndex + 3 } case "a", "A": // arc e.g. a 100 100 25 180 270 1 if instructions.count <= instructionStartIndex+6 { print("Encountered incomplete a or A path instruction") break } let xCenterStr = instructions[instructionStartIndex+1] let yCenterStr = instructions[instructionStartIndex+2] let radiusStr = instructions[instructionStartIndex+3] let startAngleStr = instructions[instructionStartIndex+4] let endAngleStr = instructions[instructionStartIndex+5] let clockwiseStr = instructions[instructionStartIndex+6] if let xCenterNum = NumberFormatter().number(from: xCenterStr), let yCenterNum = NumberFormatter().number(from: yCenterStr), let radiusNum = NumberFormatter().number(from: radiusStr), let startAngleNum = NumberFormatter().number(from: startAngleStr), let endAngleNum = NumberFormatter().number(from: endAngleStr), let clockwiseNum = NumberFormatter().number(from: clockwiseStr) { let x: CGFloat = CGFloat(xCenterNum) let y: CGFloat = CGFloat(yCenterNum) let radius: CGFloat = CGFloat(radiusNum) let startAngle: CGFloat = CGFloat(Artisan.radians(Double(startAngleNum))) let endAngle: CGFloat = CGFloat(Artisan.radians(Double(endAngleNum))) let clockwise: Bool = Bool(clockwiseNum) // inverted clockwise used, since for iOS "clockwise arc results in a counterclockwise arc after the transformation is applied" https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/CGContext/index.html#//apple_ref/c/func/CGContextAddArc pathRef.addArc(center: CGPoint(x: x, y: y), radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: !clockwise) instructionStartIndex = instructionStartIndex + 7 } case "z", "Z": // closepath pathRef.closeSubpath() instructionStartIndex = instructionStartIndex + 2 default: print("Failed to process path instruction") } } return pathRef } public init(instructionString: String) { self.instructionString = instructionString super.init() path = Path.pathRef(for: instructionString) } public required init?(coder aDecoder: NSCoder) { instructionString = "" super.init(coder: aDecoder) } public required override init(layer: Any) { instructionString = "" super.init(layer: layer) } }
mit
1f741779bc31ca7d5d4a9da61c6ec9e2
38.386694
283
0.598153
4.58162
false
false
false
false
kumabook/MusicFav
MusicFav/FeedbackWebViewController.swift
1
1171
// // FeedbackWebViewController.swift // MusicFav // // Created by Hiroki Kumamoto on 5/3/15. // Copyright (c) 2015 Hiroki Kumamoto. All rights reserved. // import UIKit class FeedbackWebViewController: UIViewController { var webView: UIWebView! init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Send Feedback".localize() navigationItem.backBarButtonItem?.title = "" webView = UIWebView(frame: view.frame) view.addSubview(webView) let mainBundle = Bundle.main if let file = mainBundle.path(forResource: "feedback_en".localize(), ofType:"html"), let data = NSData(contentsOfFile: file) { webView.load(data as Data, mimeType: "text/html", textEncodingName: "UTF-8", baseURL: URL(fileURLWithPath: file)) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func back() { let _ = navigationController?.popViewController(animated: true) } }
mit
081946e34d37b1b8503be1e9105db691
27.560976
134
0.652434
4.48659
false
false
false
false
gregomni/swift
test/type/opaque_return_structural.swift
3
4886
// RUN: %target-typecheck-verify-swift -disable-availability-checking // Tests for experimental extensions to opaque return type support. protocol P { func paul() } protocol Q {} extension Int: P, Q { func paul() {} } extension String: P, Q { func paul() {} } class C {} class D: P, Q { func paul() {}; func d() {} } func asUnwrappedOptionalBase() -> (some P)! { return 1 } // expected-warning{{using '!' is not allowed here; treating this as '?' instead}} // // FIXME: We should be able to support this func asHOFRetRet() -> () -> some P { return { 1 } } // expected-error{{cannot convert value of type 'Int' to closure result type 'some P'}} // func asHOFRetArg() -> (some P) -> () { return { (x: Int) -> () in } } // expected-error{{'some' cannot appear in parameter position in result type '(some P) -> ()'}} // // ERROR: 'some' types are only implemented for the declared type of properties and subscripts and the return type of functions // let x = { () -> some P in return 1 } func twoOpaqueTypes() -> (some P, some P) { return (1, 2) } func asTupleElemBad() -> (P, some Q) { return (1, C()) } // expected-note{{opaque return type declared here}} expected-error{{requires that 'C' conform to 'Q'}} func asTupleElem() -> (P, some Q) { return (1, 2) } func asArrayElem() -> [some P] { return [1] } func asOptionalBase() -> (some P)? { return 1 } let asTupleElemLet: (P, some Q) = (1, 2) let asArrayElemLet: [some P] = [1] let asOptionalBaseLet: (some P)? = 1 struct S1<T> { var x: T } struct S2<T, U> { var x: T var y: U } struct R1<T: P> { var x: T } struct R2<T: P, U: Q> { var x: T var y: U } func asUnconstrainedGeneric1() -> S1<some P> { return S1(x: 1) } func asUnconstrainedGeneric2() -> S2<P, some Q> { return S2(x: 1, y: 2) } func asConstrainedGeneric1() -> R1<some P> { return R1(x: 1) } func asConstrainedGeneric2() -> R2<Int, some Q> { return R2(x: 1, y: 2) } func asNestedGenericDirect() -> S1<S1<some P>> { return S1(x: S1(x: 1)) } func asNestedGenericIndirect() -> S1<S1<(Int, some P)>> { return S1(x: S1(x: (1, 2))) } let asUnconstrainedGeneric2Let: S2<P, some Q> = S2(x: 1, y: 2) let asNestedGenericIndirectLet: S1<S1<(Int, some P)>> = S1(x: S1(x: (1, 2))) // Tests an interesting SILGen case. For the underlying opaque type, we have to // use the generic calling convention for closures. func funcToAnyOpaqueCoercion() -> S1<some Any> { let f: () -> () = {} return S1(x: f) } // TODO: We should give better error messages here. The opaque types have // underlying types 'Int' and 'String', but the return statments have underlying // types '(Int, Int)' and '(String, Int)'. func structuralMismatchedReturnTypes(_ x: Bool, _ y: Int, _ z: String) -> (some P, Int) { // expected-error{{do not have matching underlying types}} if x { return (y, 1) // expected-note{{return statement has underlying type 'Int'}} } else { return (z, 1) // expected-note{{return statement has underlying type 'String'}} } } func structuralMemberLookupBad() { var tup: (some P, Int) = (D(), 1) tup.0.paul(); tup.0.d(); // expected-error{{value of type 'some P' has no member 'd'}} } // expected-error@+1 {{'some' cannot appear in parameter position in result type '(some P) -> Void'}} func opaqueParameter() -> (some P) -> Void {} // expected-error@+1 {{'some' cannot appear in parameter position in result type '((some P) -> Void) -> Void'}} func opaqueParameter() -> ((some P) -> Void) -> Void {} typealias Takes<T> = (T) -> Void // expected-error@+1 {{'some' cannot appear in parameter position in result type 'Takes<some P>' (aka '(some P) -> ()')}} func indirectOpaqueParameter() -> Takes<some P> {} struct X<T, U> { } struct StructuralMethods { func f1() -> X<(some P)?, [some Q]> { return X<Int?, [String]>() } func f2(cond: Bool) -> X<(some P)?, [some Q]> { if cond { return X<Int?, [String]>() } else { return X<Int?, [String]>() } } // TODO: Diagnostics here should be more clear about which "some" is the // problem. func f3(cond: Bool) -> X<(some P)?, [some Q]> { // expected-error{{function declares an opaque return type 'some P', but the return statements in its body do not have matching underlying types}} if cond { return X<String?, [String]>() // expected-note{{return statement has underlying type 'String'}} } else { return X<Int?, [String]>() // expected-note{{return statement has underlying type 'Int'}} } } func f4(cond: Bool) -> X<(some P)?, [some Q]> { // expected-error{{function declares an opaque return type 'some Q', but the return statements in its body do not have matching underlying types}} if cond { return X<Int?, [String]>() // expected-note{{return statement has underlying type 'String'}} } else { return X<Int?, [Int]>() // expected-note{{return statement has underlying type 'Int'}} } } }
apache-2.0
4cf3704dd2ed4bac6714bd0794f19ce7
37.171875
196
0.635284
3.266043
false
false
false
false
PjGeeroms/IOSRecipeDB
YummlyProject/Controllers/RecipesViewController.swift
1
10436
// // RecipeCollectionViewController.swift // YummlyProject // // Created by Pieter-Jan Geeroms on 20/12/2016. // Copyright © 2016 Pieter-Jan Geeroms. All rights reserved. // import UIKit import Alamofire import AlamofireImage import SearchTextField class RecipesViewController: UIViewController { @IBOutlet weak var searchBar: SearchTextField! @IBOutlet weak var collectionView: UICollectionView! // Unwind point @IBAction func unwindToRecipes(segue: UIStoryboardSegue){ navigationController?.isNavigationBarHidden = false } @IBAction func unwindFromAdd(segue: UIStoryboardSegue) { navigationController?.isNavigationBarHidden = false refreshTableView() } fileprivate var recipes: [Recipe] = [] private var currentTask: DataRequest? private var selectedIndex: Int? private let headers: HTTPHeaders = [ "Accept": "application/json", "Content-Type" : "application/json", "Authorization" : "Token \(Service.shared.user.token)" ] override func viewDidLoad() { // Show the navigationBar navigationController?.isNavigationBarHidden = false // Searchbar settings searchBar.theme = .darkTheme() // Change current theme //searchBar.theme.font = UIFont.systemFontOfSize(12) searchBar.theme.font = UIFont(name: "Avenir", size: 14)! searchBar.theme.bgColor = UIColor(red:0.13, green:0.13, blue:0.13, alpha:1.0) searchBar.theme.borderColor = UIColor(red:0.13, green:0.13, blue:0.13, alpha:1.0) searchBar.theme.separatorColor = UIColor(red:1.00, green:1.00, blue:1.00, alpha:1.0) searchBar.theme.cellHeight = 50 searchBar.maxNumberOfResults = 5 searchBar.highlightAttributes = [NSBackgroundColorAttributeName: UIColor(red:0.13, green:0.13, blue:0.13, alpha:1.0), NSFontAttributeName:UIFont.boldSystemFont(ofSize: 14)] searchBar.itemSelectionHandler = {item in self.searchBar.text = item.title self.selectedIndex = self.recipes.index(where: { $0.name == item.title }) self.searchBar.resignFirstResponder() self.performSegue(withIdentifier: "detailRecipeFromSelector", sender: self) } searchBar.userStoppedTypingHandler = { if let criteria = self.searchBar.text { if (criteria.characters.count == 0) { self.searchBar.resignFirstResponder() self.refreshTableView() } if criteria.characters.count > 1 { // Show the loading indicator self.searchBar.showLoadingIndicator() self.currentTask?.cancel() self.currentTask = Alamofire.request("\(Service.shared.baseApi)/recipes/filter/\(criteria)", headers: self.headers).responseCollection { (response: DataResponse<[Recipe]>) in switch response.result { case .success(let recipes): self.recipes = recipes for (index,recipe) in self.recipes.enumerated() { // Load images // Filter images without imageString Service.shared.sessionManager.request(recipe.imageString).responseImage(completionHandler: { imageResponse in switch imageResponse.result { case .success(let image): recipe.image = image self.collectionView.reloadData() case .failure(_): if index % 2 == 0 { recipe.image = #imageLiteral(resourceName: "darkTile") } else { recipe.image = #imageLiteral(resourceName: "lightTile") } } }) } var items: [SearchTextFieldItem] = [] recipes.forEach({ items.append(SearchTextFieldItem(title: $0.name)) }) self.searchBar.filterItems(items) self.collectionView.reloadData() self.searchBar.stopLoadingIndicator() case .failure(_): self.searchBar.stopLoadingIndicator() } } } } } // Load recipes currentTask?.cancel() currentTask = Alamofire.request("\(Service.shared.baseApi)/recipes", headers: headers).responseCollection { (response: DataResponse<[Recipe]>) in switch response.result { case .success(let recipes): self.recipes = recipes for (index,recipe) in self.recipes.enumerated() { // Load images // Filter images without imageString Service.shared.sessionManager.request(recipe.imageString).responseImage(completionHandler: { imageResponse in switch imageResponse.result { case .success(let image): recipe.image = image self.collectionView.reloadData() case .failure(let error): if index % 2 == 0 { recipe.image = #imageLiteral(resourceName: "darkTile") } else { recipe.image = #imageLiteral(resourceName: "lightTile") } print(error) } }) } case .failure(let error): print(error) } } let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refreshTableView), for: .valueChanged) collectionView.refreshControl = refreshControl } func refreshTableView() { currentTask?.cancel() currentTask = Alamofire.request("\(Service.shared.baseApi)/recipes", headers: headers).responseCollection { (response: DataResponse<[Recipe]>) in switch response.result { case .success(let recipes): self.recipes = recipes for (index,recipe) in self.recipes.enumerated() { // Load images // Filter images without imageString Service.shared.sessionManager.request(recipe.imageString).responseImage(completionHandler: { imageResponse in switch imageResponse.result { case .success(let image): recipe.image = image self.collectionView.reloadData() self.collectionView.refreshControl?.endRefreshing() case .failure(let error): if index % 2 == 0 { recipe.image = #imageLiteral(resourceName: "darkTile") } else { recipe.image = #imageLiteral(resourceName: "lightTile") } print(error) } }) } case .failure(let error): print(error) } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier! { case "addRecipe": let _ = segue.destination as! AddRecipeViewController case "detailRecipe": let recipeOverviewController = segue.destination as! RecipeOverviewController selectedIndex = collectionView.indexPathsForSelectedItems![0].row; recipeOverviewController.recipe = recipes[selectedIndex!] case "detailRecipeFromSelector": let recipeOverviewController = segue.destination as! RecipeOverviewController recipeOverviewController.recipe = recipes[selectedIndex!] default: break } } } extension RecipesViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return recipes.count } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "recipeCell", for: indexPath) as! RecipeCell let recipe = recipes[indexPath.row] cell.recipeName.text = recipe.name cell.recipeSource.text = recipe.author.username cell.recipeImage.image = recipe.image //cell.recipeImage.af_setImage(withURL: URL(string: recipe.image)!) return cell } } extension RecipesViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let height = collectionView.frame.height / 2 return CGSize(width: collectionView.frame.width, height: height) } }
mit
9f95aaaf17c007494e61ae7f6a8d1cc2
41.418699
194
0.515956
6.248503
false
false
false
false
at-internet/atinternet-ios-swift-sdk
Tracker/Tracker/Dispatcher.swift
1
7646
/* This SDK is licensed under the MIT license (MIT) Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France) 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. */ // // Dispatcher.swift // Tracker // import UIKit //#if AT_EXTENSION //import TrackerExtension //#else //import Tracker //#endif class Dispatcher { /// Tracker instance var tracker: Tracker init(tracker: Tracker) { self.tracker = tracker } /** Send the built hit */ internal func dispatch(_ businessObjects: [BusinessObject]?) { if(businessObjects != nil) { for(_, businessObject) in (businessObjects!).enumerated() { switch(businessObject) { case let screen as AbstractScreen: screen.setEvent() var hasOrder: Bool = false for(_, value) in self.tracker.businessObjects { if ((value is ScreenInfo || value is InternalSearch || (value is OnAppAd && (value as! OnAppAd).action == OnAppAd.Action.View) || value is Order) && value.timeStamp <= screen.timeStamp) { if(value is Order) { hasOrder = true } value.setEvent() self.tracker.businessObjects.removeValue(forKey: value.id) } } if(tracker.cart.cartId != "" && ((screen.isBasketScreen) || hasOrder)) { tracker.cart.setEvent() } self.tracker.businessObjects.removeValue(forKey: businessObject.id) case let gesture as Gesture: businessObject.setEvent() if(gesture.action == Gesture.Action.Search) { for(_, value) in self.tracker.businessObjects { if (value is InternalSearch && value.timeStamp <= businessObject.timeStamp) { value.setEvent() self.tracker.businessObjects.removeValue(forKey: value.id) } } } self.tracker.businessObjects.removeValue(forKey: businessObject.id) default: businessObject.setEvent() self.tracker.businessObjects.removeValue(forKey: businessObject.id) break } // If there is some customObjects on the pipeline for(_, value) in self.tracker.businessObjects { if(value is CustomObject || value is NuggAd) { if(value.timeStamp <= businessObject.timeStamp) { value.setEvent() self.tracker.businessObjects.removeValue(forKey: value.id) } } } } } // Saves screen name and level 2 in context if hit type is Screen if(Hit.getHitType(self.tracker.buffer.volatileParameters, self.tracker.buffer.persistentParameters) == Hit.HitType.screen) { TechnicalContext.screenName = Tool.appendParameterValues(HitParam.Screen.rawValue, volatileParameters: self.tracker.buffer.volatileParameters, persistentParameters: self.tracker.buffer.persistentParameters) let level2 = Int(Tool.appendParameterValues(HitParam.Level2.rawValue, volatileParameters: self.tracker.buffer.volatileParameters, persistentParameters: self.tracker.buffer.persistentParameters)) if let optLevel2 = level2 { TechnicalContext.level2 = optLevel2 } else { TechnicalContext.level2 = 0 } Crash.lastScreen(TechnicalContext.screenName) } // Add life cycle metrics in stc variable let appendOptionWithEncoding = ParamOption() appendOptionWithEncoding.append = true appendOptionWithEncoding.encode = true _ = self.tracker.setParam(HitParam.JSON.rawValue, value: LifeCycle.getMetrics(), options: appendOptionWithEncoding) // Add crash report if available in stc variable let report = (Crash.compute() as NSDictionary?) as! [String: Any]? if let optReport = report { _ = self.tracker.setParam(HitParam.JSON.rawValue, value: optReport, options: appendOptionWithEncoding) } // Add persistent identified visitor data if required let userDefaults = UserDefaults.standard if let conf = self.tracker.configuration.parameters[IdentifiedVisitorHelperKey.Configuration.rawValue] { if conf == "true" { if let num = userDefaults.object(forKey: IdentifiedVisitorHelperKey.Numeric.rawValue) as? String { _ = self.tracker.setParam(HitParam.VisitorIdentifierNumeric.rawValue, value: num) } if let tex = userDefaults.object(forKey: IdentifiedVisitorHelperKey.Text.rawValue) as? String { let encodingOption = ParamOption() encodingOption.encode = true _ = self.tracker.setParam(HitParam.VisitorIdentifierText.rawValue, value: tex, options:encodingOption) } if let cat = userDefaults.object(forKey: IdentifiedVisitorHelperKey.Category.rawValue) as? String { _ = self.tracker.setParam(HitParam.VisitorCategory.rawValue, value: cat) } } } // Creation of hit builder task to execute in background thread let builder = Builder(tracker: self.tracker, volatileParameters: Tool.copyParamArray(self.tracker.buffer.volatileParameters), persistentParameters: Tool.copyParamArray(self.tracker.buffer.persistentParameters)) // Remove all non persistent parameters from buffer self.tracker.buffer.volatileParameters.removeAll(keepingCapacity: false) // Add hit builder task to queue TrackerQueue.sharedInstance.queue.addOperation(builder) // Set level2 context param back in case level2 id were overriden for one hit self.tracker.context.level2 = self.tracker.context.level2 } }
mit
1d1e87a6346957ba643da81d6bc24f8c
44.230769
218
0.600602
5.210634
false
false
false
false
EdwaRen/Med-Sync
Med-Sync/MedSync4.0/MedSync4.0/DocViewController.swift
1
1505
// // DocViewController.swift // MedSync4.0 // // Created by - on 2017/01/06. // Copyright © 2017 Danth. All rights reserved. // import UIKit class DocViewController: UIViewController { @IBOutlet weak var detailImageView: UIImageView! @IBOutlet weak var detailTitle: UILabel! //@IBOutlet weak var detailDescription: UITextView! @IBOutlet weak var detailDescription2: UILabel! @IBOutlet weak var scrollView: UIScrollView! var sentData1: String! var sentData2: String! var sentData3: String! override func viewDidLoad() { super.viewDidLoad() detailTitle.text = sentData1 detailImageView.image = UIImage(named: sentData2) detailDescription2.text = sentData3 scrollView.contentInset = UIEdgeInsetsMake(0, 0, 200, 0) self.navigationItem.title = "My Directory" // Do any additional setup after loading the view. } 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
ac8a2539b7487210cb0658ba9514e3a2
24.931034
106
0.655585
4.805112
false
false
false
false
Beaver/BeaverCodeGen
Sources/BeaverCodeGen/Generator/InfoPList.swift
1
3462
struct ModuleInfoPList: Generating { let moduleName: String let isTest: Bool var path: String { return "Module/\(moduleName.typeName)/\(moduleName.typeName)\(isTest ? "Tests" : "")/Info.plist" } } extension ModuleInfoPList { var description: String { return """ <?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>CFBundleDevelopmentRegion</key> <string>$(DEVELOPMENT_LANGUAGE)</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>FMWK</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleVersion</key> <string>$(CURRENT_PROJECT_VERSION)</string> <key>NSPrincipalClass</key> <string></string> </dict> </plist> """ } } struct AppInfoPList: Generating { let isTest: Bool var path: String { return "App\(isTest ? "Tests" : "")/Info.plist" } } extension AppInfoPList { var description: String { return """ <?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>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleVersion</key> <string>1</string> <key>LSRequiresIPhoneOS</key> <true/> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIRequiredDeviceCapabilities</key> <array> <string>armv7</string> </array> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> </dict> </plist> """ } }
mit
45e4783fbb70263de25ffcc8625a57b5
33.969697
110
0.559214
4.496104
false
true
false
false
StachkaConf/ios-app
StachkaIOS/StachkaIOS/Classes/Entities/Author/Author.swift
1
944
// // Author.swift // StachkaIOS // // Created by m.rakhmanov on 07.04.17. // Copyright © 2017 m.rakhmanov. All rights reserved. // import Foundation import ObjectMapper import ObjectMapper_Realm class Author: AutoObject, Mappable { dynamic var name: String = "" dynamic var position: String = "" dynamic var fullDescription: String = "" dynamic var email: String = "" dynamic var city: String = "" dynamic var skype: String = "" dynamic var phone: String = "" dynamic var imageUrlString: String = "" required convenience init?(map: Map) { self.init() } func mapping(map: Map) { name <- map["product"] fullDescription <- map["full_description"] email <- map["email"] city <- map["city"] skype <- map["skype"] phone <- map["phone"] position <- map["position"] imageUrlString <- map["main_pair.icon.image_path"] } }
mit
b24d1418ca45dd0ec6b1637c3b611fbd
23.815789
58
0.604454
4.1
false
false
false
false
bumpersfm/handy
Handy/NSAttributedString.swift
1
1012
// // Created by Dani Postigo on 12/15/16. // import Foundation import UIKit extension NSMutableAttributedString { public func replaceAttribute(attribute: String, value: AnyObject?) { guard var attributes = self.attributes else { return } if let value = value { attributes[attribute] = value } else { attributes.removeValueForKey(attribute) } self.attributes = attributes } override public var attributes: [String:AnyObject]? { get { return super.attributes } set { guard self.length > 0, let newValue = newValue else { return } self.setAttributes(newValue, range: self.stringRange) } } } extension NSAttributedString { private var stringRange: NSRange { return NSMakeRange(0, self.length) } public var attributes: [String:AnyObject]? { guard self.length > 0 else { return nil } return self.attributesAtIndex(0, longestEffectiveRange: nil, inRange: self.stringRange) } }
mit
03ea7e9835a3f83eb94325f9f1bbd711
27.914286
111
0.660079
4.685185
false
false
false
false
metova/MetovaTestKit
MetovaTestKit/UIKitTesting/CellTesting/MTKCollectionViewTestCell.swift
1
3414
// // MTKTableViewTestCell.swift // MetovaTestKit // // Created by Nick Griffith on 2018-12-14 // Copyright © 2018 Metova. All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import XCTest /// This method attempts to produce a collection view cell from the collection view at the specified index path. It then attempts to cast the cell to the specified type. If either of these two fail, this function will produce a test failure and the test block will not be executed. If both pass, the resulting cell, cast to the specified type, will be passed into the testBlock where the developer can run further assertions on the cell. /// /// - Parameters: /// - collectionView: Collection view to grab cell from. /// - indexPath: IndexPath to grab a cell from. /// - cellType: Type of cell to cast to before passing into test block. /// - file: The file the test is called from. /// - line: The line the test is called from. /// - testBlock: A block of code containing tests to run. This block is not guaranteed to execute. If it does not execute, this method will fail the test. /// - Throws: Rethrows any error thrown by the test block. Does not throw any errors on its own. public func MTKTestCell<T: UICollectionViewCell>( in collectionView: UICollectionView, at indexPath: IndexPath, as cellType: T.Type = T.self, file: StaticString = #file, line: UInt = #line, test testBlock: (T) throws -> Void ) rethrows { guard let dataSource = collectionView.dataSource else { XCTFail("\(collectionView) does not have a dataSource", file: file, line: line) return } let collectionSectionCount = dataSource.numberOfSections?(in: collectionView) ?? 1 guard indexPath.section < collectionSectionCount, indexPath.item < dataSource.collectionView(collectionView, numberOfItemsInSection: indexPath.section) else { XCTFail("\(collectionView) does not have a cell at \(indexPath)", file: file, line: line) return } let cell = dataSource.collectionView(collectionView, cellForItemAt: indexPath) guard let typedCell = cell as? T else { XCTFail("Cell at \(indexPath) expected to be \(T.self) was actually \(type(of: cell))", file: file, line: line) return } try testBlock(typedCell) }
mit
3156a735df9c922711bef7d1f86648ec
47.070423
440
0.717258
4.403871
false
true
false
false
easyui/EZPlayer
EZPlayer/EZPlayer.swift
1
65738
// // EZPlayer.swift // EZPlayer // // Created by yangjun zhu on 2016/12/28. // Copyright © 2016年 yangjun zhu. All rights reserved. // import Foundation import AVFoundation import AVKit /// 播放器错误类型 public enum EZPlayerError: Error { case invalidContentURL //错误的url case playerFail // AVPlayer failed to load the asset. } /// 播放器的状态 public enum EZPlayerState { case unknown // 播放前 case error(EZPlayerError) // 出现错误 case readyToPlay // 可以播放 case buffering // 缓冲中 case bufferFinished // 缓冲完毕 case playing // 播放 case seekingForward // 快进 case seekingBackward // 快退 case pause // 播放暂停 case stopped // 播放结束 } //播放器浮框模式 public enum EZPlayerFloatMode { case none case auto //支持系统pip的就是system,否则是window case system //iPhone在ios14一下不显示 case window } //播放器显示模式类型 public enum EZPlayerDisplayMode { case none case embedded case fullscreen case float } //播放器全屏模式类型 public enum EZPlayerFullScreenMode { case portrait case landscape } //播放器流的显示比例 public enum EZPlayerVideoGravity : String { case aspect = "AVLayerVideoGravityResizeAspect" //视频值 ,等比例填充,直到一个维度到达区域边界 case aspectFill = "AVLayerVideoGravityResizeAspectFill" //等比例填充,直到填充满整个视图区域,其中一个维度的部分区域会被裁剪 case scaleFill = "AVLayerVideoGravityResize" //非均匀模式。两个维度完全填充至整个视图区域 } //播放器结束原因 public enum EZPlayerPlaybackDidFinishReason { case playbackEndTime case playbackError case stopByUser } //屏幕左右上下划动时的类型 public enum EZPlayerSlideTrigger{ case none case volume case brightness } //public enum EZPlayerFileType: String { // case unknown // case mp4 // case m3u8 // //} open class EZPlayer: NSObject { // MARK: - player utils public static var showLog = true//是否显示log // MARK: - player setting open weak var delegate: EZPlayerDelegate? open var videoGravity = EZPlayerVideoGravity.aspect{ didSet { if let layer = self.playerView?.layer as? AVPlayerLayer{ layer.videoGravity = AVLayerVideoGravity(rawValue: videoGravity.rawValue) } } } /// 设置url会自动播放 open var autoPlay = true /// 设备横屏时自动旋转(phone) open var autoLandscapeFullScreenLandscape = UIDevice.current.userInterfaceIdiom == .phone /// 浮框的模式 open var floatMode = EZPlayerFloatMode.auto /// 全屏的模式 open var fullScreenMode = EZPlayerFullScreenMode.landscape /// 全屏时status bar的样式 open var fullScreenPreferredStatusBarStyle = UIStatusBarStyle.lightContent /// 全屏时status bar的背景色 open var fullScreenStatusbarBackgroundColor = UIColor.black.withAlphaComponent(0.3) /// 支持airplay open var allowsExternalPlayback = true{ didSet{ guard let avplayer = self.player else { return } avplayer.allowsExternalPlayback = allowsExternalPlayback } } /// airplay连接状态 open var isExternalPlaybackActive: Bool { guard let avplayer = self.player else { return false } return avplayer.isExternalPlaybackActive } private var timeObserver: Any?//addPeriodicTimeObserver的返回值 private var timer : Timer?//.EZPlayerHeartbeat使用 // MARK: - player resource open var contentItem: EZPlayerContentItem? open private(set) var contentURL :URL?{//readonly didSet{ guard let url = contentURL else { return } self.isM3U8 = url.absoluteString.hasSuffix(".m3u8") } } open private(set) var player: AVPlayer? open private(set) var playerasset: AVAsset?{ didSet{ if oldValue != playerasset{ if playerasset != nil { self.imageGenerator = AVAssetImageGenerator(asset: playerasset!) }else{ self.imageGenerator = nil } } } } open private(set) var playerItem: AVPlayerItem?{ willSet{ if playerItem != newValue{ if let item = playerItem{ NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item) item.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status)) item.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges)) item.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackBufferEmpty)) item.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp)) } } } didSet { if playerItem != oldValue{ if let item = playerItem{ NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidPlayToEnd(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem) item.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: NSKeyValueObservingOptions.new, context: nil) //缓冲区大小 item.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges), options: NSKeyValueObservingOptions.new, context: nil) // 缓冲区空了,需要等待数据 item.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackBufferEmpty), options: NSKeyValueObservingOptions.new, context: nil) // 缓冲区有足够数据可以播放了 item.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp), options: NSKeyValueObservingOptions.new, context: nil) } } } } /// 视频截图 open private(set) var imageGenerator: AVAssetImageGenerator? /// 视频截图m3u8 open private(set) var videoOutput: AVPlayerItemVideoOutput? open private(set) var isM3U8 = false open var isLive: Bool? { if let duration = self.duration { return duration.isNaN } return nil } /// 上下滑动屏幕的控制类型 open var slideTrigger = (left:EZPlayerSlideTrigger.volume,right:EZPlayerSlideTrigger.brightness) /// 左右滑动屏幕改变视频进度 open var canSlideProgress = true // MARK: - player component //只读 open var controlView : UIView?{ if let view = self.controlViewForIntercept{ return view } switch self.displayMode { case .embedded: return self.controlViewForEmbedded case .fullscreen: return self.controlViewForFullscreen case .float: return self.controlViewForFloat case .none: return self.controlViewForEmbedded } } /// 拦截原来的各种controlView,作用:比如你要插入一个广告的view,广告结束置空即可 open var controlViewForIntercept : UIView? { didSet{ self.updateCustomView() } } ///cactus todo EZPlayerControlView /// 嵌入模式的控制皮肤 open var controlViewForEmbedded : UIView? /// 浮动模式的控制皮肤 open var controlViewForFloat : UIView? /// 全屏模式的控制皮肤 open var controlViewForFullscreen : UIView? /// 全屏模式控制器 open private(set) var fullScreenViewController : EZPlayerFullScreenViewController? /// 视频控制器视图 fileprivate var playerView: EZPlayerView? open var view: UIView{ if self.playerView == nil{ self.playerView = EZPlayerView(controlView: self.controlView) } return self.playerView! } /// 嵌入模式的容器 open weak var embeddedContentView: UIView? /// 嵌入模式的显示隐藏 open private(set) var controlsHidden = false /// 过多久自动消失控件,设置为<=0不消失 open var autohiddenTimeInterval: TimeInterval = 8 /// 返回按钮block open var backButtonBlock:(( _ fromDisplayMode: EZPlayerDisplayMode) -> Void)? open var floatContainer: EZPlayerWindowContainer? open var floatContainerRootViewController: EZPlayerWindowContainerRootViewController? open var floatInitFrame = CGRect(x: UIScreen.main.bounds.size.width - 213 - 10, y: UIScreen.main.bounds.size.height - 120 - 49 - 34 - 10, width: 213, height: 120) // autohideTimeInterval// // MARK: - player status open fileprivate(set) var state = EZPlayerState.unknown{ didSet{ printLog("old state: \(oldValue)") printLog("new state: \(state)") if oldValue != state{ (self.controlView as? EZPlayerDelegate)?.player(self, playerStateDidChange: state) self.delegate?.player(self, playerStateDidChange: state) NotificationCenter.default.post(name: .EZPlayerStatusDidChange, object: self, userInfo: [Notification.Key.EZPlayerNewStateKey: state,Notification.Key.EZPlayerOldStateKey: oldValue]) var loading = false; switch state { case .readyToPlay,.playing ,.pause,.seekingForward,.seekingBackward,.stopped,.bufferFinished://cactus todo loading = false; break default: loading = true; break } (self.controlView as? EZPlayerDelegate)?.player(self, showLoading: loading) self.delegate?.player(self, showLoading: loading) NotificationCenter.default.post(name: .EZPlayerLoadingDidChange, object: self, userInfo: [Notification.Key.EZPlayerLoadingDidChangeKey: loading]) if case .error(_) = state { NotificationCenter.default.post(name: .EZPlayerPlaybackDidFinish, object: self, userInfo: [Notification.Key.EZPlayerPlaybackDidFinishReasonKey: EZPlayerPlaybackDidFinishReason.playbackError]) } } } } open private(set) var displayMode = EZPlayerDisplayMode.none{ didSet{ if oldValue != displayMode{ (self.controlView as? EZPlayerDelegate)?.player(self, playerDisplayModeDidChange: displayMode) self.delegate?.player(self, playerDisplayModeDidChange: displayMode) NotificationCenter.default.post(name: .EZPlayerDisplayModeDidChange, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeDidChangeKey: displayMode]) } } } open private(set) var lastDisplayMode = EZPlayerDisplayMode.none open var isPlaying:Bool{ guard let player = self.player else { return false } if #available(iOS 10.0, *) { return player.timeControlStatus == .playing; }else{ return player.rate > Float(0) && player.error == nil } } /// 视频长度,live是NaN open var duration: TimeInterval? { if let duration = self.player?.duration { return duration } return nil } /// 视频进度 open var currentTime: TimeInterval? { if let currentTime = self.player?.currentTime { return currentTime } return nil } /// 视频播放速率 open var rate: Float{ get { if let player = self.player { return player.rate } return .nan } set { if let player = self.player { player.rate = newValue } } } /// 系统音量 open var systemVolume: Float{ get { return systemVolumeSlider.value } set { systemVolumeSlider.value = newValue } } private let systemVolumeSlider = EZPlayerUtils.systemVolumeSlider open weak var scrollView: UITableView?{ willSet{ if scrollView != newValue{ if let view = scrollView{ view.removeObserver(self, forKeyPath: #keyPath(UITableView.contentOffset)) } } } didSet { if playerItem != oldValue{ if let view = scrollView{ view.addObserver(self, forKeyPath: #keyPath(UITableView.contentOffset), options: NSKeyValueObservingOptions.new, context: nil) } } } } open var indexPath: IndexPath? // MARK: - Picture in Picture open var pipController: AVPictureInPictureController? fileprivate var startPIPWithCompletion : ((Error?) -> Void)? fileprivate var endPIPWithCompletion : (() -> Void)? // MARK: - Life cycle deinit { NotificationCenter.default.removeObserver(self) self.timer?.invalidate() self.timer = nil self.releasePlayerResource() } public override init() { super.init() self.commonInit() } public init(controlView: UIView? ) { super.init() if controlView == nil{ self.controlViewForEmbedded = UIView() }else{ self.controlViewForEmbedded = controlView } self.commonInit() } // MARK: - Player action open func playWithURL(_ url: URL,embeddedContentView contentView: UIView? = nil, title: String? = nil) { self.contentItem = EZPlayerContentItem(url: url, title: title) self.contentURL = url self.prepareToPlay() if contentView != nil { self.embeddedContentView = contentView self.embeddedContentView!.addSubview(self.view) self.view.frame = self.embeddedContentView!.bounds self.displayMode = .embedded }else{ self.toFull() } } open func replaceToPlayWithURL(_ url: URL, title: String? = nil) { self.resetPlayerResource() self.contentItem = EZPlayerContentItem(url: url, title: title) self.contentURL = url guard let url = self.contentURL else { self.state = .error(.invalidContentURL) return } self.playerasset = AVAsset(url: url) let keys = ["tracks","duration","commonMetadata","availableMediaCharacteristicsWithMediaSelectionOptions"] self.playerItem = AVPlayerItem(asset: self.playerasset!, automaticallyLoadedAssetKeys: keys) self.player?.replaceCurrentItem(with: self.playerItem) self.setControlsHidden(false, animated: true) } open func play(){ self.state = .playing self.player?.play() } open func pause(){ self.state = .pause self.player?.pause() } open func stop(){ let lastState = self.state self.state = .stopped self.player?.pause() self.releasePlayerResource() guard case .error(_) = lastState else{ if lastState != .stopped { NotificationCenter.default.post(name: .EZPlayerPlaybackDidFinish, object: self, userInfo: [Notification.Key.EZPlayerPlaybackDidFinishReasonKey: EZPlayerPlaybackDidFinishReason.stopByUser]) } return } } open func seek(to time: TimeInterval, completionHandler: ((Bool) -> Swift.Void )? = nil){ guard let player = self.player else { return } let lastState = self.state if let currentTime = self.currentTime { if currentTime > time { self.state = .seekingBackward }else if currentTime < time { self.state = .seekingForward } } playerItem?.cancelPendingSeeks() playerasset?.cancelLoading() player.seek(to: CMTimeMakeWithSeconds(time,preferredTimescale: CMTimeScale(NSEC_PER_SEC)), toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero, completionHandler: { [weak self] (finished) in guard let weakSelf = self else { return } switch (weakSelf.state) { case .seekingBackward,.seekingForward: weakSelf.state = lastState default: break } completionHandler?(finished) }) } private var isChangingDisplayMode = false open func toFull(_ orientation:UIDeviceOrientation = .landscapeLeft, animated: Bool = true ,completion: ((Bool) -> Swift.Void)? = nil) { if self.isChangingDisplayMode == true { completion?(false) return } if self.displayMode == .fullscreen { completion?(false) return } guard let activityViewController = EZPlayerUtils.activityViewController() else { completion?(false) return } func __toFull(from view: UIView) { self.isChangingDisplayMode = true self.updateCustomView(toDisplayMode: .fullscreen) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.fullscreen]) self.setControlsHidden(true, animated: false) self.fullScreenViewController = EZPlayerFullScreenViewController() self.fullScreenViewController!.preferredlandscapeForPresentation = orientation == .landscapeRight ? .landscapeLeft : .landscapeRight self.fullScreenViewController!.player = self if animated { let rect = view.convert(self.view.frame, to: activityViewController.view) let x = activityViewController.view.bounds.size.width - rect.size.width - rect.origin.x let y = activityViewController.view.bounds.size.height - rect.size.height - rect.origin.y self.fullScreenViewController!.modalPresentationStyle = .fullScreen activityViewController.present(self.fullScreenViewController!, animated: false, completion: { self.view.removeFromSuperview() self.fullScreenViewController!.view.addSubview(self.view) self.fullScreenViewController!.view.sendSubviewToBack(self.view) if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{ self.view.transform = CGAffineTransform(rotationAngle:orientation == .landscapeRight ? CGFloat(Double.pi / 2) : -CGFloat(Double.pi / 2)) self.view.frame = orientation == .landscapeRight ? CGRect(x: y, y: rect.origin.x, width: rect.size.height, height: rect.size.width) : CGRect(x: rect.origin.y, y: x, width: rect.size.height, height: rect.size.width) }else{ self.view.frame = rect } UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: { if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{ self.view.transform = CGAffineTransform.identity } self.view.bounds = self.fullScreenViewController!.view.bounds self.view.center = self.fullScreenViewController!.view.center }, completion: {finished in self.setControlsHidden(false, animated: true) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.fullscreen]) completion?(finished) self.isChangingDisplayMode = false }) }) }else{ self.fullScreenViewController!.modalPresentationStyle = .fullScreen activityViewController.present(self.fullScreenViewController!, animated: false, completion: { self.view.removeFromSuperview() self.fullScreenViewController!.view.addSubview(self.view) self.fullScreenViewController!.view.sendSubviewToBack(self.view) self.view.bounds = self.fullScreenViewController!.view.bounds self.view.center = self.fullScreenViewController!.view.center self.setControlsHidden(false, animated: true) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.fullscreen]) completion?(true) self.isChangingDisplayMode = false }) } } let lastDisplayModeTemp = self.displayMode if lastDisplayModeTemp == .embedded{ guard let embeddedContentView = self.embeddedContentView else { completion?(false) return } self.lastDisplayMode = lastDisplayModeTemp __toFull(from: embeddedContentView) }else if lastDisplayModeTemp == .float{ let floatModelSupported = EZPlayerUtils.floatModelSupported(self) if floatModelSupported == .system{ self.lastDisplayMode = .fullscreen//特殊处理:设置目标 self.stopPIP { } }else{ guard let floatContainer = self.floatContainer else { completion?(false) return } self.lastDisplayMode = lastDisplayModeTemp floatContainer.hidden() __toFull(from: floatContainer.floatWindow) } }else{ //直接进入全屏 self.updateCustomView(toDisplayMode: .fullscreen) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.fullscreen]) self.setControlsHidden(true, animated: false) self.fullScreenViewController = EZPlayerFullScreenViewController() self.fullScreenViewController!.preferredlandscapeForPresentation = orientation == .landscapeRight ? .landscapeLeft : .landscapeRight self.fullScreenViewController!.player = self self.view.frame = self.fullScreenViewController!.view.bounds self.fullScreenViewController!.view.addSubview(self.view) self.fullScreenViewController!.view.sendSubviewToBack(self.view) self.fullScreenViewController!.modalPresentationStyle = .fullScreen activityViewController.present(self.fullScreenViewController!, animated: animated, completion: { self.floatContainer?.hidden() self.setControlsHidden(false, animated: true) completion?(true) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.fullscreen]) }) } } open func toEmbedded(animated: Bool = true , completion: ((Bool) -> Swift.Void)? = nil){ if self.isChangingDisplayMode == true { completion?(false) return } if self.displayMode == .embedded { completion?(false) return } guard let embeddedContentView = self.embeddedContentView else{ completion?(false) return } func __endToEmbedded(finished :Bool) { self.view.removeFromSuperview() embeddedContentView.addSubview(self.view) self.view.frame = embeddedContentView.bounds self.setControlsHidden(false, animated: true) self.fullScreenViewController = nil completion?(finished) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.embedded]) self.isChangingDisplayMode = false } let lastDisplayModeTemp = self.displayMode if lastDisplayModeTemp == .fullscreen{ guard let fullScreenViewController = self.fullScreenViewController else{ completion?(false) return } self.lastDisplayMode = lastDisplayModeTemp self.isChangingDisplayMode = true self.updateCustomView(toDisplayMode: .embedded) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.embedded]) self.setControlsHidden(true, animated: false) if animated { let rect = fullScreenViewController.view.bounds self.view.removeFromSuperview() UIApplication.shared.keyWindow?.addSubview(self.view) fullScreenViewController.dismiss(animated: false, completion: { if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{ self.view.transform = CGAffineTransform(rotationAngle : fullScreenViewController.currentOrientation == .landscapeLeft ? CGFloat(Double.pi / 2) : -CGFloat(Double.pi / 2)) self.view.frame = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.height, height: rect.size.width) }else{ self.view.bounds = embeddedContentView.bounds } UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: { if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{ self.view.transform = CGAffineTransform.identity } var center = embeddedContentView.center if let embeddedContentSuperview = embeddedContentView.superview { center = embeddedContentSuperview.convert(embeddedContentView.center, to: UIApplication.shared.keyWindow) } self.view.bounds = embeddedContentView.bounds self.view.center = center }, completion: {finished in __endToEmbedded(finished: finished) }) }) }else{ fullScreenViewController.dismiss(animated: false, completion: { __endToEmbedded(finished: true) }) } }else if lastDisplayModeTemp == .float{ let floatModelSupported = EZPlayerUtils.floatModelSupported(self) if floatModelSupported == .system{ self.lastDisplayMode = .embedded//特殊处理:设置目标 self.stopPIP { } }else{ guard let floatContainer = self.floatContainer else { completion?(false) return } self.lastDisplayMode = lastDisplayModeTemp floatContainer.hidden() // self.controlView = Bundle(for: EZPlayerControlView.self).loadNibNamed(String(describing: EZPlayerControlView.self), owner: self, options: nil)?.last as? EZPlayerControlView // self.displayMode = .embedded self.isChangingDisplayMode = true self.updateCustomView(toDisplayMode: .embedded) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.embedded]) self.setControlsHidden(true, animated: false) if animated { let rect = floatContainer.floatWindow.convert(self.view.frame, to: UIApplication.shared.keyWindow) self.view.removeFromSuperview() UIApplication.shared.keyWindow?.addSubview(self.view) self.view.frame = rect UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: { self.view.bounds = embeddedContentView.bounds self.view.center = embeddedContentView.center }, completion: {finished in __endToEmbedded(finished: finished) }) }else{ __endToEmbedded(finished: true) } } }else{ completion?(false) } } /// 进入浮层模式, /// - Parameters: /// - animated: <#animated description#> /// - completion: <#completion description#> open func toFloat(animated: Bool = true, completion: ((Bool) -> Swift.Void)? = nil) { if self.floatMode == .none { completion?(false) return } if self.isChangingDisplayMode == true { completion?(false) return } if self.displayMode == .float { completion?(false) return } let floatModelSupported = EZPlayerUtils.floatModelSupported(self) if floatModelSupported == .system{ self.isChangingDisplayMode = true NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.displayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.float]) self.startPIP { [weak self] error in guard let weakSelf = self else{ return } weakSelf.isChangingDisplayMode = false weakSelf.lastDisplayMode = weakSelf.displayMode if weakSelf.lastDisplayMode == .fullscreen{ guard let fullScreenViewController = weakSelf.fullScreenViewController else{ return } fullScreenViewController.dismiss(animated: false) { weakSelf.fullScreenViewController = nil } }else if weakSelf.lastDisplayMode == .embedded{ // weakSelf.view.removeFromSuperview() // weakSelf.controlViewForEmbedded = nil weakSelf.view.isHidden = true } weakSelf.updateCustomView(toDisplayMode: .float) completion?(error != nil ? true : false) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: weakSelf, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : weakSelf.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : error != nil ? weakSelf.lastDisplayMode : EZPlayerDisplayMode.float]) } }else{ self.toWindow(animated: animated, completion: completion) } } // MARK: - public open func setControlsHidden(_ hidden: Bool, animated: Bool = false){ self.controlsHidden = hidden (self.controlView as? EZPlayerDelegate)?.player(self, playerControlsHiddenDidChange: hidden ,animated: animated ) self.delegate?.player(self, playerControlsHiddenDidChange: hidden,animated: animated) NotificationCenter.default.post(name: .EZPlayerControlsHiddenDidChange, object: self, userInfo: [Notification.Key.EZPlayerControlsHiddenDidChangeKey: hidden,Notification.Key.EZPlayerControlsHiddenDidChangeByAnimatedKey: animated]) } open func updateCustomView(toDisplayMode: EZPlayerDisplayMode? = nil){ var nextDisplayMode = self.displayMode if toDisplayMode != nil{ nextDisplayMode = toDisplayMode! } if let view = self.controlViewForIntercept{ self.playerView?.controlView = view self.displayMode = nextDisplayMode return } switch nextDisplayMode { case .embedded: //playerView加问号,其实不关心playerView存不存在,存在就更新 if self.playerView?.controlView == nil || self.playerView?.controlView != self.controlViewForEmbedded{ if self.controlViewForEmbedded == nil { self.controlViewForEmbedded = self.controlViewForFullscreen ?? Bundle(for: EZPlayerControlView.self).loadNibNamed(String(describing: EZPlayerControlView.self), owner: self, options: nil)?.last as? EZPlayerControlView } } self.playerView?.controlView = self.controlViewForEmbedded case .fullscreen: if self.playerView?.controlView == nil || self.playerView?.controlView != self.controlViewForFullscreen{ if self.controlViewForFullscreen == nil { self.controlViewForFullscreen = self.controlViewForEmbedded ?? Bundle(for: EZPlayerControlView.self).loadNibNamed(String(describing: EZPlayerControlView.self), owner: self, options: nil)?.last as? EZPlayerControlView } } self.playerView?.controlView = self.controlViewForFullscreen case .float: // if self.controlViewForFloat == nil { // self.controlViewForFloat = Bundle(for: EZPlayerFloatView.self).loadNibNamed(String(describing: EZPlayerFloatView.self), owner: self, options: nil)?.last as? UIView // } let floatModelSupported = EZPlayerUtils.floatModelSupported(self) if self.playerView?.controlView == nil || self.playerView?.controlView != self.controlViewForFloat{ if self.controlViewForFloat == nil { self.controlViewForFloat = floatModelSupported == .window ? Bundle(for: EZPlayerWindowView.self).loadNibNamed(String(describing: EZPlayerWindowView.self), owner: self, options: nil)?.last as? UIView : Bundle(for: EZPlayerControlView.self).loadNibNamed(String(describing: EZPlayerControlView.self), owner: self, options: nil)?.last as? EZPlayerControlView } } self.playerView?.controlView = self.controlViewForFloat break case .none: //初始化的时候 if self.controlView == nil { self.controlViewForEmbedded = Bundle(for: EZPlayerControlView.self).loadNibNamed(String(describing: EZPlayerControlView.self), owner: self, options: nil)?.last as? EZPlayerControlView } } self.displayMode = nextDisplayMode } // MARK: - private private func commonInit() { self.updateCustomView()//走case .none:,防止没有初始化 NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillResignActive(_:)), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidEnterBackground(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil) UIDevice.current.beginGeneratingDeviceOrientationNotifications() NotificationCenter.default.addObserver(self, selector: #selector(self.deviceOrientationDidChange(_:)), name: UIDevice.orientationDidChangeNotification, object: nil) // NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidPlayToEnd(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem) self.timer?.invalidate() self.timer = nil self.timer = Timer.timerWithTimeInterval(0.5, block: { [weak self] in // guard let weakself = self, let player = weakself.pl guard let weakSelf = self, let _ = weakSelf.player, let playerItem = weakSelf.playerItem else{ return } if !playerItem.isPlaybackLikelyToKeepUp && weakSelf.state == .playing{ weakSelf.state = .buffering } if playerItem.isPlaybackLikelyToKeepUp && (weakSelf.state == .buffering || weakSelf.state == .readyToPlay){ weakSelf.state = .bufferFinished if weakSelf.autoPlay { weakSelf.state = .playing } } (weakSelf.controlView as? EZPlayerDelegate)?.playerHeartbeat(weakSelf) weakSelf.delegate?.playerHeartbeat(weakSelf) NotificationCenter.default.post(name: .EZPlayerHeartbeat, object: self, userInfo:nil) }, repeats: true) RunLoop.current.add(self.timer!, forMode: RunLoop.Mode.common) } private func prepareToPlay(){ guard let url = self.contentURL else { self.state = .error(.invalidContentURL) return } self.releasePlayerResource() self.playerasset = AVAsset(url: url) let keys = ["tracks","duration","commonMetadata","availableMediaCharacteristicsWithMediaSelectionOptions"] self.playerItem = AVPlayerItem(asset: self.playerasset!, automaticallyLoadedAssetKeys: keys) self.player = AVPlayer(playerItem: playerItem!) // if #available(iOS 10.0, *) { // self.player!.automaticallyWaitsToMinimizeStalling = false // } self.player!.allowsExternalPlayback = self.allowsExternalPlayback if self.playerView == nil { self.playerView = EZPlayerView(controlView: self.controlView ) } (self.playerView?.layer as! AVPlayerLayer).videoGravity = AVLayerVideoGravity(rawValue: self.videoGravity.rawValue) self.playerView?.config(player: self) (self.controlView as? EZPlayerDelegate)?.player(self, showLoading: true) self.delegate?.player(self, showLoading: true) NotificationCenter.default.post(name: .EZPlayerLoadingDidChange, object: self, userInfo: [Notification.Key.EZPlayerLoadingDidChangeKey: true]) self.addPlayerItemTimeObserver() } private func addPlayerItemTimeObserver(){ self.timeObserver = self.player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(0.5, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main, using: { [weak self] time in guard let weakSelf = self else { return } (weakSelf.controlView as? EZPlayerDelegate)?.player(weakSelf, currentTime: weakSelf.currentTime ?? 0, duration: weakSelf.duration ?? 0) weakSelf.delegate?.player(weakSelf, currentTime: weakSelf.currentTime ?? 0, duration: weakSelf.duration ?? 0) NotificationCenter.default.post(name: .EZPlayerPlaybackTimeDidChange, object: self, userInfo:nil) }) } private func resetPlayerResource() { self.contentItem = nil self.contentURL = nil if self.videoOutput != nil { self.playerItem?.remove(self.videoOutput!) } self.videoOutput = nil self.playerasset = nil self.playerItem = nil self.player?.replaceCurrentItem(with: nil) self.playerView?.layer.removeAllAnimations() (self.controlView as? EZPlayerDelegate)?.player(self, bufferDurationDidChange: 0, totalDuration: 0) self.delegate?.player(self, bufferDurationDidChange: 0, totalDuration: 0) (self.controlView as? EZPlayerDelegate)?.player(self, currentTime:0, duration: 0) self.delegate?.player(self, currentTime: 0, duration: 0) NotificationCenter.default.post(name: .EZPlayerPlaybackTimeDidChange, object: self, userInfo:nil) } private func releasePlayerResource() { self.releasePIPResource() if self.fullScreenViewController != nil { self.fullScreenViewController!.dismiss(animated: true, completion: { }) } self.scrollView = nil self.indexPath = nil if self.videoOutput != nil { self.playerItem?.remove(self.videoOutput!) } self.videoOutput = nil self.playerasset = nil self.playerItem = nil self.player?.replaceCurrentItem(with: nil) self.playerView?.layer.removeAllAnimations() self.playerView?.removeFromSuperview() self.playerView = nil if self.timeObserver != nil{ self.player?.removeTimeObserver(self.timeObserver!) self.timeObserver = nil } } } // MARK: - Notification extension EZPlayer { @objc fileprivate func playerDidPlayToEnd(_ notifiaction: Notification) { self.state = .stopped NotificationCenter.default.post(name: .EZPlayerPlaybackDidFinish, object: self, userInfo: [Notification.Key.EZPlayerPlaybackDidFinishReasonKey: EZPlayerPlaybackDidFinishReason.playbackEndTime]) } @objc fileprivate func deviceOrientationDidChange(_ notifiaction: Notification){ // if !self.autoLandscapeFullScreenLandscape || self.embeddedContentView == nil{ //app前后台切换 if UIApplication.shared.applicationState != UIApplication.State.active { return } if !self.autoLandscapeFullScreenLandscape || self.fullScreenMode == .portrait { return } switch UIDevice.current.orientation { case .portrait: //如果后台切回前台保持原来竖屏状态 if self.displayMode == .embedded || self.displayMode == .float { return } if self.lastDisplayMode == .embedded{ self.toEmbedded() }else if self.lastDisplayMode == .float{ self.toFloat() } case .landscapeLeft: self.toFull(UIDevice.current.orientation) case .landscapeRight: self.toFull(UIDevice.current.orientation) default: break } } @objc fileprivate func applicationWillEnterForeground(_ notifiaction: Notification){ } @objc fileprivate func applicationDidBecomeActive(_ notifiaction: Notification){ } @objc fileprivate func applicationWillResignActive(_ notifiaction: Notification){ } @objc fileprivate func applicationDidEnterBackground(_ notifiaction: Notification){ } } // MARK: - KVO extension EZPlayer { override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let item = object as? AVPlayerItem, let keyPath = keyPath { if item == self.playerItem { switch keyPath { case #keyPath(AVPlayerItem.status): //todo check main thread //3)然后是kAVPlayerItemStatus的变化,从0变为1,即变为readyToPlay printLog("AVPlayerItem's status is changed: \(item.status.rawValue)") if item.status == .readyToPlay {//可以播放 let lastState = self.state if self.state != .playing{ self.state = .readyToPlay } //自动播放 if self.autoPlay && lastState == .unknown{ self.play() } } else if item.status == .failed { self.state = .error(.playerFail) } case #keyPath(AVPlayerItem.loadedTimeRanges): printLog("AVPlayerItem's loadedTimeRanges is changed") (self.controlView as? EZPlayerDelegate)?.player(self, bufferDurationDidChange: item.bufferDuration ?? 0, totalDuration: self.duration ?? 0) self.delegate?.player(self, bufferDurationDidChange: item.bufferDuration ?? 0, totalDuration: self.duration ?? 0) case #keyPath(AVPlayerItem.isPlaybackBufferEmpty): //1)首先是观察到kAVPlayerItemPlaybackBufferEmpty的变化,从1变为0,说有缓存到内容了,已经有loadedTimeRanges了,但这时候还不一定能播放,因为数据可能还不够播放; printLog("AVPlayerItem's playbackBufferEmpty is changed") case #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp): //2)然后是kAVPlayerItemPlaybackLikelyToKeepUp,从0变到1,说明可以播放了,这时候会自动开始播放 printLog("AVPlayerItem's playbackLikelyToKeepUp is changed") default: break } } }else if let view = object as? UITableView ,let keyPath = keyPath{ switch keyPath { case #keyPath(UITableView.contentOffset): if isChangingDisplayMode == true{ return } if view == self.scrollView { if let index = self.indexPath { let cellrectInTable = view.rectForRow(at: index) let cellrectInTableSuperView = view.convert(cellrectInTable, to: view.superview) if cellrectInTableSuperView.origin.y + cellrectInTableSuperView.size.height/2 < view.frame.origin.y + view.contentInset.top || cellrectInTableSuperView.origin.y + cellrectInTableSuperView.size.height/2 > view.frame.origin.y + view.frame.size.height - view.contentInset.bottom{ self.toFloat() }else{ if let cell = view.cellForRow(at: index){ if !self.view.isDescendant(of: cell){ self.view.removeFromSuperview() self.embeddedContentView = self.embeddedContentView ?? cell.contentView self.embeddedContentView!.addSubview(self.view) } self.toEmbedded(animated: false, completion: { flag in }) } } } } default: break } } } } // MARK: - generateThumbnails extension EZPlayer { //不支持m3u8 open func generateThumbnails(times: [TimeInterval],maximumSize: CGSize, completionHandler: @escaping (([EZPlayerThumbnail]) -> Swift.Void )){ guard let imageGenerator = self.imageGenerator else { return } var values = [NSValue]() for time in times { values.append(NSValue(time: CMTimeMakeWithSeconds(time,preferredTimescale: CMTimeScale(NSEC_PER_SEC)))) } var thumbnailCount = values.count var thumbnails = [EZPlayerThumbnail]() imageGenerator.cancelAllCGImageGeneration() imageGenerator.appliesPreferredTrackTransform = true// 截图的时候调整到正确的方向 imageGenerator.maximumSize = maximumSize//设置后可以获取缩略图 imageGenerator.generateCGImagesAsynchronously(forTimes:values) { (requestedTime: CMTime,image: CGImage?,actualTime: CMTime,result: AVAssetImageGenerator.Result,error: Error?) in let thumbnail = EZPlayerThumbnail(requestedTime: requestedTime, image: image == nil ? nil : UIImage(cgImage: image!) , actualTime: actualTime, result: result, error: error) thumbnails.append(thumbnail) thumbnailCount -= 1 if thumbnailCount == 0 { DispatchQueue.main.async { completionHandler(thumbnails) } } } } //支持m3u8 open func snapshotImage() -> UIImage? { guard let playerItem = self.playerItem else { //playerItem is AVPlayerItem return nil } if self.videoOutput == nil { self.videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: nil) playerItem.remove(self.videoOutput!) playerItem.add(self.videoOutput!) } guard let videoOutput = self.videoOutput else { return nil } let time = videoOutput.itemTime(forHostTime: CACurrentMediaTime()) if videoOutput.hasNewPixelBuffer(forItemTime: time) { let lastSnapshotPixelBuffer = videoOutput.copyPixelBuffer(forItemTime: time, itemTimeForDisplay: nil) if lastSnapshotPixelBuffer != nil { let ciImage = CIImage(cvPixelBuffer: lastSnapshotPixelBuffer!) let context = CIContext(options: nil) let rect = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(CVPixelBufferGetWidth(lastSnapshotPixelBuffer!)), height: CGFloat(CVPixelBufferGetHeight(lastSnapshotPixelBuffer!))) let cgImage = context.createCGImage(ciImage, from: rect) if cgImage != nil { return UIImage(cgImage: cgImage!) } } } return nil } } // MARK: - display Mode extension EZPlayer { private func configFloatVideo(){ if self.floatContainerRootViewController == nil { self.floatContainerRootViewController = EZPlayerWindowContainerRootViewController(nibName: String(describing: EZPlayerWindowContainerRootViewController.self), bundle: Bundle(for: EZPlayerWindowContainerRootViewController.self)) } if self.floatContainer == nil { self.floatContainer = EZPlayerWindowContainer(frame: self.floatInitFrame, rootViewController: self.floatContainerRootViewController!) } } open func toWindow(animated: Bool = true, completion: ((Bool) -> Swift.Void)? = nil) { func __endToWindow(finished :Bool) { self.view.removeFromSuperview() self.floatContainerRootViewController?.addVideoView(self.view) self.floatContainer?.show() self.setControlsHidden(false, animated: true) self.fullScreenViewController = nil completion?(finished) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.float]) self.isChangingDisplayMode = false } self.lastDisplayMode = self.displayMode if self.lastDisplayMode == .embedded { self.configFloatVideo() self.isChangingDisplayMode = true self.updateCustomView(toDisplayMode: .float) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.float]) self.setControlsHidden(true, animated: false) if animated{ let rect = self.embeddedContentView!.convert(self.view.frame, to: UIApplication.shared.keyWindow) self.view.removeFromSuperview() UIApplication.shared.keyWindow?.addSubview(self.view) self.view.frame = rect UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: { self.view.bounds = self.floatContainer!.floatWindow.bounds self.view.center = self.floatContainer!.floatWindow.center }, completion: {finished in __endToWindow(finished: finished) }) }else{ __endToWindow(finished: true) } }else if self.lastDisplayMode == .fullscreen{ guard let fullScreenViewController = self.fullScreenViewController else{ completion?(false) return } self.configFloatVideo() self.isChangingDisplayMode = true self.updateCustomView(toDisplayMode: .float) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.float]) self.setControlsHidden(true, animated: false) if animated{ let rect = fullScreenViewController.view.bounds self.view.removeFromSuperview() UIApplication.shared.keyWindow?.addSubview(self.view) fullScreenViewController.dismiss(animated: false, completion: { if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{ self.view.transform = CGAffineTransform(rotationAngle : fullScreenViewController.currentOrientation == .landscapeLeft ? CGFloat(Double.pi / 2) : -CGFloat(Double.pi / 2)) self.view.frame = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.height, height: rect.size.width) }else{ self.view.bounds = self.floatContainer!.floatWindow.bounds } UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: { if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{ self.view.transform = CGAffineTransform.identity } self.view.bounds = self.floatContainer!.floatWindow.bounds self.view.center = self.floatContainer!.floatWindow.center }, completion: {finished in __endToWindow(finished: finished) }) }) }else{ fullScreenViewController.dismiss(animated: false, completion: { __endToWindow(finished: true) }) } }else{ completion?(false) } } } // MARK: - Picture in Picture Mode extension EZPlayer: AVPictureInPictureControllerDelegate { /// 是否支持pip open var isPIPSupported: Bool{ return AVPictureInPictureController.isPictureInPictureSupported() } /// 当前是否处于画中画状态显示在屏幕上 open var isPIPActive: Bool{ return self.pipController?.isPictureInPictureActive ?? false } /// 当前画中画是否被挂起。如果你的app因为其他的app在使用PiP而导致你的视频后台播放播放状态为暂停并且不可见,将会返回true。当其他的app离开了PiP时,你的视频会被重新播放 open var isPIPSuspended: Bool{ return self.pipController?.isPictureInPictureSuspended ?? false } /// 告诉你画中画窗口是可用的。如果其他的app再使用PiP模式,他将会返回false。这个实行也能够通过KVO来观察,同样通过观察这种状态的改变,你也能够很好地额处理PiP按钮的的隐藏于展示。 open var isPIPPossible: Bool{ return self.pipController?.isPictureInPicturePossible ?? false } open func startPIP(completion: ((Error?) -> Void)? = nil){ self.configPIP() self.startPIPWithCompletion = completion //isPIPSupported和isPIPPossible为true才有效 // self.pipController?.startPictureInPicture() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) { self.pipController?.startPictureInPicture() } } open func stopPIP(completion: (() -> Void)? = nil){ self.endPIPWithCompletion = completion self.pipController?.stopPictureInPicture() } private func configPIP(){ if isPIPSupported && playerView != nil && pipController == nil { pipController = AVPictureInPictureController(playerLayer: playerView!.layer as! AVPlayerLayer) pipController?.delegate = self } } private func releasePIPResource() { pipController?.delegate = nil pipController = nil } /// 即将开启画中画 /// - Parameter pictureInPictureController: <#pictureInPictureController description#> public func pictureInPictureControllerWillStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) { printLog("pip 即将开启画中画") (self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureControllerWillStartPictureInPicture: pictureInPictureController) self.delegate?.player(self, pictureInPictureControllerWillStartPictureInPicture: pictureInPictureController) NotificationCenter.default.post(name: .EZPlayerPIPControllerWillStart, object: self, userInfo: nil) } /// 已经开启画中画 /// - Parameter pictureInPictureController: <#pictureInPictureController description#> public func pictureInPictureControllerDidStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) { printLog("pip 已经开启画中画") self.startPIPWithCompletion?(nil) (self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureControllerDidStartPictureInPicture: pictureInPictureController) self.delegate?.player(self, pictureInPictureControllerDidStartPictureInPicture: pictureInPictureController) NotificationCenter.default.post(name: .EZPlayerPIPControllerDidStart, object: self, userInfo: nil) } /// 开启画中画失败 /// - Parameters: /// - pictureInPictureController: <#pictureInPictureController description#> /// - error: <#error description#> public func pictureInPictureController(_ pictureInPictureController: AVPictureInPictureController, failedToStartPictureInPictureWithError error: Error) { printLog("pip 开启画中画失败") self.releasePIPResource() self.startPIPWithCompletion?(error) (self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureController: pictureInPictureController, failedToStartPictureInPictureWithError: error) self.delegate?.player(self, pictureInPictureController: pictureInPictureController, failedToStartPictureInPictureWithError: error) NotificationCenter.default.post(name: .EZPlayerPIPFailedToStart, object: self, userInfo: [Notification.Key.EZPlayerPIPFailedToStart: error]) } /// 即将关闭画中画 /// - Parameter pictureInPictureController: <#pictureInPictureController description#> public func pictureInPictureControllerWillStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) { printLog("pip 即将关闭画中画") self.isChangingDisplayMode = true NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.displayMode, Notification.Key.EZPlayerDisplayModeChangedTo : self.lastDisplayMode]) (self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureControllerWillStopPictureInPicture: pictureInPictureController) self.delegate?.player(self, pictureInPictureControllerWillStopPictureInPicture: pictureInPictureController) NotificationCenter.default.post(name: .EZPlayerPIPControllerWillEnd, object: self, userInfo: nil) } /// 已经关闭画中画 /// - Parameter pictureInPictureController: <#pictureInPictureController description#> public func pictureInPictureControllerDidStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) { printLog("pip 已经关闭画中画") self.releasePIPResource() // 按钮last float x , last x float self.isChangingDisplayMode = false // if self.lastDisplayMode != .float{ let lastDisPlayModeTemp = self.lastDisplayMode self.lastDisplayMode = .float self.updateCustomView(toDisplayMode: lastDisPlayModeTemp) // }else{ // self.updateCustomView(toDisplayMode: lastDisPlayModeTemp) // self.updateCustomView(toDisplayMode: self.displayMode) // } // self.view.removeFromSuperview() // self.embeddedContentView!.addSubview(self.view) // self.view.frame = self.embeddedContentView!.bounds self.endPIPWithCompletion?() NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : .float, Notification.Key.EZPlayerDisplayModeChangedTo : self.displayMode]) (self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureControllerDidStopPictureInPicture: pictureInPictureController) self.delegate?.player(self, pictureInPictureControllerDidStopPictureInPicture: pictureInPictureController) NotificationCenter.default.post(name: .EZPlayerPIPControllerDidEnd, object: self, userInfo: nil) if self.displayMode == .fullscreen{ if self.state == .playing { self.play() } if self.fullScreenViewController == nil { self.fullScreenViewController = EZPlayerFullScreenViewController() self.fullScreenViewController!.preferredlandscapeForPresentation = UIDevice.current.orientation == .landscapeRight ? .landscapeLeft : .landscapeRight self.fullScreenViewController!.player = self } // guard let fullScreenViewController = self.fullScreenViewController else{ // return // } self.fullScreenViewController!.modalPresentationStyle = .fullScreen guard let activityViewController = EZPlayerUtils.activityViewController() else { return } activityViewController.present(self.fullScreenViewController!, animated: false) { // self.view.removeFromSuperview() self.fullScreenViewController!.view.addSubview(self.view) self.fullScreenViewController!.view.sendSubviewToBack(self.view) self.view.bounds = self.fullScreenViewController!.view.bounds self.view.center = self.fullScreenViewController!.view.center self.view.isHidden = false self.setControlsHidden(false, animated: true) } }else if self.displayMode == .embedded{ self.view.isHidden = false } } /// 关闭画中画且恢复播放界面 /// - Parameters: /// - pictureInPictureController: <#pictureInPictureController description#> /// - completionHandler: <#completionHandler description#> public func pictureInPictureController(_ pictureInPictureController: AVPictureInPictureController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) { printLog("pip 关闭画中画且恢复播放界面") // completionHandler(true) (self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureController: pictureInPictureController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler: completionHandler) self.delegate?.player(self, pictureInPictureController: pictureInPictureController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler: completionHandler) NotificationCenter.default.post(name: .EZPlayerPIPRestoreUserInterfaceForStop, object: self, userInfo: [Notification.Key.EZPlayerPIPStopWithCompletionHandler: completionHandler]) } }
mit
82b50749e1af2d96ea7d7fbf268033be
41.475399
375
0.634144
5.228169
false
false
false
false
makeandbuild/watchkit-activity-builder
WatchCoreDataProxy/WatchCoreDataProxy.swift
1
4661
// // WatchCoreDataProxy.swift // ActivityBuilder // // Created by Lindsay Thurmond on 2/24/15. // Copyright (c) 2015 Make and Build. All rights reserved. // import CoreData public class WatchCoreDataProxy: NSObject { let sharedAppGroup:String = "group.com.makeandbuild.activitybuilder" public class var sharedInstance : WatchCoreDataProxy { struct Static { static let instance : WatchCoreDataProxy = WatchCoreDataProxy() } return Static.instance } // MARK: - Core Data stack public lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.makeandbuild.ActivityBuilder" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() public lazy var managedObjectModel: NSManagedObjectModel = { let proxyBundle = NSBundle(identifier: "com.makeandbuild.WatchCoreDataProxy") // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = proxyBundle?.URLForResource("Model", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL!)! }() public lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. var error: NSError? = nil var sharedContainerURL: NSURL? = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(self.sharedAppGroup) if let sharedContainerURL = sharedContainerURL { let storeURL = sharedContainerURL.URLByAppendingPathComponent("Model.sqlite") var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil { var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data." dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator } return nil }() public lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support public func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
apache-2.0
e5d2ef23d9378b9764998aab6a3ea891
50.21978
290
0.681613
5.768564
false
false
false
false
CoderST/XMLYDemo
XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/PopularViewController/View/PromotionCell.swift
1
2685
// // PromotionCell.swift // XMLYDemo // // Created by xiudou on 2016/12/26. // Copyright © 2016年 CoderST. All rights reserved. // 推广 import UIKit private let iconImageViewHeight : CGFloat = 110 class PromotionCell: UICollectionViewCell { fileprivate lazy var iconImageView : UIImageView = { let iconImageView = UIImageView() iconImageView.contentMode = .scaleAspectFill iconImageView.clipsToBounds = true return iconImageView }() fileprivate lazy var titleLabel : UILabel = { let titleLabel = UILabel() titleLabel.font = UIFont.systemFont(ofSize: 14) titleLabel.numberOfLines = 2 return titleLabel }() fileprivate lazy var playCountLabel : UILabel = { let playCountLabel = UILabel() playCountLabel.font = UIFont.systemFont(ofSize: 12) return playCountLabel }() fileprivate lazy var bottomLabel : UILabel = { let bottomLabel = UILabel() bottomLabel.font = UIFont.systemFont(ofSize: 12) bottomLabel.textColor = UIColor.gray return bottomLabel }() var promotionSubItem : HotSubModel?{ didSet{ iconImageView.sd_setImage( with: URL(string: promotionSubItem?.cover ?? ""), placeholderImage: UIImage(named: "placeholder_image")) titleLabel.text = promotionSubItem?.name bottomLabel.text = promotionSubItem?.mydescription } } override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(iconImageView) contentView.addSubview(titleLabel) contentView.addSubview(playCountLabel) contentView.addSubview(bottomLabel) iconImageView.snp.makeConstraints { (make) in make.top.left.equalTo(contentView).offset(10) make.right.equalTo(contentView).offset(-10) make.height.equalTo(iconImageViewHeight) make.width.equalTo(stScreenW - 20) } titleLabel.snp.makeConstraints { (make) in make.left.equalTo(iconImageView) make.right.equalTo(iconImageView) make.top.equalTo(iconImageView.snp.bottom).offset(5) } bottomLabel.snp.makeConstraints { (make) in make.left.equalTo(iconImageView) make.right.equalTo(iconImageView) make.bottom.equalTo(contentView).offset(-10) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
a1965cae1c406a85e5a4f45258c243c0
28.108696
143
0.609783
5.220273
false
false
false
false
huonw/swift
test/SILGen/class_bound_protocols.swift
1
12154
// RUN: %target-swift-emit-silgen -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s enum Optional<T> { case some(T) case none } precedencegroup AssignmentPrecedence {} typealias AnyObject = Builtin.AnyObject // -- Class-bound archetypes and existentials are *not* address-only and can // be manipulated using normal reference type value semantics. protocol NotClassBound { func notClassBoundMethod() } protocol ClassBound : class { func classBoundMethod() } protocol ClassBound2 : class { func classBound2Method() } class ConcreteClass : NotClassBound, ClassBound, ClassBound2 { func notClassBoundMethod() {} func classBoundMethod() {} func classBound2Method() {} } class ConcreteSubclass : ConcreteClass { } // CHECK-LABEL: sil hidden @$Ss19class_bound_generic{{[_0-9a-zA-Z]*}}F func class_bound_generic<T : ClassBound>(x: T) -> T { var x = x // CHECK: bb0([[X:%.*]] : $T): // CHECK: [[X_ADDR:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ClassBound> { var τ_0_0 } <T> // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[X_COPY:%.*]] = copy_value [[X]] // CHECK: store [[X_COPY]] to [init] [[PB]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: destroy_value [[X_ADDR]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @$Ss21class_bound_generic_2{{[_0-9a-zA-Z]*}}F func class_bound_generic_2<T : ClassBound & NotClassBound>(x: T) -> T { var x = x // CHECK: bb0([[X:%.*]] : $T): // CHECK: [[X_ADDR:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ClassBound, τ_0_0 : NotClassBound> { var τ_0_0 } <T> // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[X_COPY:%.*]] = copy_value [[X]] // CHECK: store [[X_COPY]] to [init] [[PB]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @$Ss20class_bound_protocol{{[_0-9a-zA-Z]*}}F func class_bound_protocol(x: ClassBound) -> ClassBound { var x = x // CHECK: bb0([[X:%.*]] : $ClassBound): // CHECK: [[X_ADDR:%.*]] = alloc_box ${ var ClassBound } // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[X_COPY:%.*]] = copy_value [[X]] // CHECK: store [[X_COPY]] to [init] [[PB]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*ClassBound // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @$Ss32class_bound_protocol_composition{{[_0-9a-zA-Z]*}}F func class_bound_protocol_composition(x: ClassBound & NotClassBound) -> ClassBound & NotClassBound { var x = x // CHECK: bb0([[X:%.*]] : $ClassBound & NotClassBound): // CHECK: [[X_ADDR:%.*]] = alloc_box ${ var ClassBound & NotClassBound } // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[X_COPY:%.*]] = copy_value [[X]] // CHECK: store [[X_COPY]] to [init] [[PB]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*ClassBound & NotClassBound // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @$Ss19class_bound_erasure{{[_0-9a-zA-Z]*}}F func class_bound_erasure(x: ConcreteClass) -> ClassBound { return x // CHECK: [[PROTO:%.*]] = init_existential_ref {{%.*}} : $ConcreteClass, $ClassBound // CHECK: return [[PROTO]] } // CHECK-LABEL: sil hidden @$Ss30class_bound_existential_upcast1xs10ClassBound_psAC_s0E6Bound2p_tF : func class_bound_existential_upcast(x: ClassBound & ClassBound2) -> ClassBound { return x // CHECK: bb0([[ARG:%.*]] : $ClassBound & ClassBound2): // CHECK: [[OPENED:%.*]] = open_existential_ref [[ARG]] : $ClassBound & ClassBound2 to [[OPENED_TYPE:\$@opened(.*) ClassBound & ClassBound2]] // CHECK: [[OPENED_COPY:%.*]] = copy_value [[OPENED]] // CHECK: [[PROTO:%.*]] = init_existential_ref [[OPENED_COPY]] : [[OPENED_TYPE]] : [[OPENED_TYPE]], $ClassBound // CHECK: return [[PROTO]] } // CHECK: } // end sil function '$Ss30class_bound_existential_upcast1xs10ClassBound_psAC_s0E6Bound2p_tF' // CHECK-LABEL: sil hidden @$Ss41class_bound_to_unbound_existential_upcast1xs13NotClassBound_ps0hI0_sACp_tF : // CHECK: bb0([[ARG0:%.*]] : $*NotClassBound, [[ARG1:%.*]] : $ClassBound & NotClassBound): // CHECK: [[X_OPENED:%.*]] = open_existential_ref [[ARG1]] : $ClassBound & NotClassBound to [[OPENED_TYPE:\$@opened(.*) ClassBound & NotClassBound]] // CHECK: [[PAYLOAD_ADDR:%.*]] = init_existential_addr [[ARG0]] : $*NotClassBound, [[OPENED_TYPE]] // CHECK: [[X_OPENED_COPY:%.*]] = copy_value [[X_OPENED]] // CHECK: store [[X_OPENED_COPY]] to [init] [[PAYLOAD_ADDR]] func class_bound_to_unbound_existential_upcast (x: ClassBound & NotClassBound) -> NotClassBound { return x } // CHECK-LABEL: sil hidden @$Ss18class_bound_method1xys10ClassBound_p_tF : // CHECK: bb0([[ARG:%.*]] : $ClassBound): func class_bound_method(x: ClassBound) { var x = x x.classBoundMethod() // CHECK: [[XBOX:%.*]] = alloc_box ${ var ClassBound }, var, name "x" // CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: store [[ARG_COPY]] to [init] [[XBOX_PB]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[XBOX_PB]] : $*ClassBound // CHECK: [[X:%.*]] = load [copy] [[READ]] : $*ClassBound // CHECK: [[PROJ:%.*]] = open_existential_ref [[X]] : $ClassBound to $[[OPENED:@opened(.*) ClassBound]] // CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #ClassBound.classBoundMethod!1 // CHECK: apply [[METHOD]]<[[OPENED]]>([[PROJ]]) // CHECK: destroy_value [[PROJ]] // CHECK: destroy_value [[XBOX]] } // CHECK: } // end sil function '$Ss18class_bound_method1xys10ClassBound_p_tF' // rdar://problem/31858378 struct Value {} protocol HasMutatingMethod { mutating func mutateMe() var mutatingCounter: Value { get set } var nonMutatingCounter: Value { get nonmutating set } } protocol InheritsMutatingMethod : class, HasMutatingMethod {} func takesInOut<T>(_: inout T) {} // CHECK-LABEL: sil hidden @$Ss27takesInheritsMutatingMethod1x1yys0bcD0_pz_s5ValueVtF : $@convention(thin) (@inout InheritsMutatingMethod, Value) -> () { func takesInheritsMutatingMethod(x: inout InheritsMutatingMethod, y: Value) { // CHECK: [[X_ADDR:%.*]] = begin_access [modify] [unknown] %0 : $*InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") InheritsMutatingMethod, #HasMutatingMethod.mutateMe!1 : <Self where Self : HasMutatingMethod> (inout Self) -> () -> (), [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@inout τ_0_0) -> () // CHECK-NEXT: apply [[METHOD]]<@opened("{{.*}}") InheritsMutatingMethod>([[TEMPORARY]]) : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@inout τ_0_0) -> () // CHECK-NEXT: [[X_PAYLOAD:%.*]] = load [take] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = init_existential_ref [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@opened("{{.*}}") InheritsMutatingMethod, $InheritsMutatingMethod // CHECK-NEXT: assign [[X_VALUE]] to [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod x.mutateMe() // CHECK-NEXT: [[RESULT_BOX:%.*]] = alloc_stack $Value // CHECK-NEXT: [[RESULT:%.*]] = mark_uninitialized [var] [[RESULT_BOX]] : $*Value // CHECK-NEXT: [[X_ADDR:%.*]] = begin_access [read] [unknown] %0 : $*InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[X_PAYLOAD_RELOADED:%.*]] = load [take] [[TEMPORARY]] // // ** *NOTE* This extra copy is here since RValue invariants enforce that all // ** loadable objects are actually loaded. So we form the RValue and // ** load... only to then need to store the value back in a stack location to // ** pass to an in_guaranteed method. PredictableMemOpts is able to handle this // ** type of temporary codegen successfully. // CHECK-NEXT: [[TEMPORARY_2:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: store [[X_PAYLOAD_RELOADED:%.*]] to [init] [[TEMPORARY_2]] // // CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") InheritsMutatingMethod, #HasMutatingMethod.mutatingCounter!getter.1 : <Self where Self : HasMutatingMethod> (Self) -> () -> Value, [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@in_guaranteed τ_0_0) -> Value // CHECK-NEXT: [[RESULT_VALUE:%.*]] = apply [[METHOD]]<@opened("{{.*}}") InheritsMutatingMethod>([[TEMPORARY_2]]) : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@in_guaranteed τ_0_0) -> Value // CHECK-NEXT: destroy_addr [[TEMPORARY_2]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: dealloc_stack [[TEMPORARY_2]] // CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: assign [[RESULT_VALUE]] to [[RESULT]] : $*Value // CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: dealloc_stack [[RESULT_BOX]] : $*Value _ = x.mutatingCounter // CHECK-NEXT: [[X_ADDR:%.*]] = begin_access [modify] [unknown] %0 : $*InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") InheritsMutatingMethod, #HasMutatingMethod.mutatingCounter!setter.1 : <Self where Self : HasMutatingMethod> (inout Self) -> (Value) -> (), [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (Value, @inout τ_0_0) -> () // CHECK-NEXT: apply [[METHOD]]<@opened("{{.*}}") InheritsMutatingMethod>(%1, [[TEMPORARY]]) : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (Value, @inout τ_0_0) -> () // CHECK-NEXT: [[X_PAYLOAD:%.*]] = load [take] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = init_existential_ref [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@opened("{{.*}}") InheritsMutatingMethod, $InheritsMutatingMethod // CHECK-NEXT: assign [[X_VALUE]] to [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod x.mutatingCounter = y takesInOut(&x.mutatingCounter) _ = x.nonMutatingCounter x.nonMutatingCounter = y takesInOut(&x.nonMutatingCounter) }
apache-2.0
2895beafd214d977e14694cfcd3c580d
54.637615
382
0.628329
3.676569
false
false
false
false
Paladinfeng/leetcode
leetcode/Merge Two Sorted Lists/main.swift
1
2751
// // main.swift // Merge Two Sorted Lists // // Created by xuezhaofeng on 15/08/2017. // Copyright © 2017 paladinfeng. All rights reserved. // import Foundation /** * Definition for singly-linked list. */ public class ListNode { public var val: Int public var next: ListNode? public init(_ val: Int) { self.val = val self.next = nil } } class Solution { func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { // var temp: ListNode? // // var l1 = l1 // var l2 = l2 // while l1 != nil && l2 != nil { // // if l1?.val >= l2?.val { // // } // // l1 = l1?.next // l2 = l2?.next // // } // while temp != nil { // if let a = temp { // print(a.val) // } // temp = temp?.next // } // while temp != nil { // // if(temp?.next == nil) { // break // } // // temp = temp?.next // } let dummy = ListNode(0) var node = dummy var l1 = l1 var l2 = l2 while l1 != nil && l2 != nil{ // node.next = l1 // print(node.next?.val) // l1 = l1?.next // node = node.next! // print(l1?.val, l2?.val) // l1 = l1?.next // l2 = l2?.next if let v1 = l1?.val, let v2 = l2?.val { if v1 <= v2 { node.next = l1 l1 = l1?.next } else { node.next = l2 l2 = l2?.next } node = node.next! } } // while l1 != nil && l2 != nil { // if l1!.val < l2!.val { // node.next = l1 // l1 = l1!.next // } else { // node.next = l2 // l2 = l2!.next // } // // node = node.next! // print(dummy.val) // } // while node != nil { // print(node.val) // node = node.next! // } node.next = l1 ?? l2 return dummy.next // print(temp?.val) // temp?.next = l2 // return temp } } var l1 = ListNode(1) l1.next = ListNode(2) l1.next?.next = ListNode(5) var l2 = ListNode(2) l2.next = ListNode(4) l2.next?.next = ListNode(6) var result = Solution().mergeTwoLists(l1, l2) //var result: ListNode? = l1 while result != nil { // print(test?.val) if let a = result { print(a.val) } result = result?.next }
mit
08e0db3f2e5ae888ae421c61eea8825b
17.965517
71
0.387273
3.370098
false
false
false
false
jasoncabot/hackernews-ios
HackerNews/Model/Story.swift
1
1681
// // Story.swift // HackerNews // // Created by Jason Cabot on 15/02/2015. // Copyright (c) 2015 Jason Cabot. All rights reserved. // import Foundation struct Story : Equatable { let position: Int let id: Int let title: String let points: Int let by: String let timeAgo: String let numberOfComments: Int let url: URL? let site: String init(position: Int, id: Int, title: String, points: Int, by: String, timeAgo: String, numberOfComments: Int, url: URL?, site: String, unread: Bool, commentsUnread: Bool) { self.position = position self.id = id self.title = title self.points = points self.by = by self.timeAgo = timeAgo self.numberOfComments = numberOfComments self.url = url self.site = site } init?(data: AnyObject) { guard let position = data["position"] as? Int, let id = data["id"] as? Int, let title = data["title"] as? String, let points = data["score"] as? Int, let author = data["by"] as? String, let timeAgo = data["when"] as? String, let urlString = data["url"] as? String, let site = data["site"] as? String else { return nil } self.position = position self.id = id self.title = title self.points = points self.by = author self.timeAgo = timeAgo self.numberOfComments = data["comments"] as? Int ?? 0 self.url = URL(string: urlString) self.site = site } } func ==(a:Story, b:Story) -> Bool { return a.id == b.id }
mit
0a439b47bb517d6c3ec680b3f1666c6c
26.557377
175
0.554432
3.973995
false
false
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/CompanyCard/Views/GirdView.swift
1
4800
// // GirdView.swift // DaDaXTStuMo // // Created by 黄伯驹 on 2017/8/23. // Copyright © 2017年 dadaabc. All rights reserved. // import UIKit import Kingfisher struct GirdItem { let imageName: String let title: String } protocol GirdViewDelegate: AnyObject { func didSelectItem<T>(at indexPath: IndexPath, item: T) } protocol GirdCellType { associatedtype ViewData func updateCell(with item: ViewData) } class GirdView<C>: UIView, UICollectionViewDataSource, UICollectionViewDelegate where C: UICollectionViewCell, C: GirdCellType { public weak var girdItemDelegate: GirdViewDelegate? /// Default items.count public var numberOfCols = 0 public var items: [C.ViewData] = [] public var layout = UICollectionViewFlowLayout() { didSet { if layout == oldValue { return } collectionView.collectionViewLayout = layout collectionView.reloadData() } } public var cellBackgroundColor: UIColor? { didSet { refreshUI() } } override var backgroundColor: UIColor? { didSet { collectionView.backgroundColor = backgroundColor } } private lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = .clear collectionView.register(C.self, forCellWithReuseIdentifier: "cellID") return collectionView }() convenience init(items: [C.ViewData]) { self.init(frame: .zero) numberOfCols = items.count layout.minimumInteritemSpacing = 0 collectionView.collectionViewLayout = layout addSubview(collectionView) self.items = items } override func layoutSubviews() { super.layoutSubviews() collectionView.frame = bounds let oldSize = layout.itemSize if oldSize != layout.itemSize { collectionView.reloadData() } let width = collectionView.fixSlit(cols: numberOfCols) layout.itemSize = CGSize(width: width, height: bounds.height) } public func refreshUI() { collectionView.reloadData() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) (cell as? C)?.updateCell(with: items[indexPath.row]) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) let item = items[indexPath.row] girdItemDelegate?.didSelectItem(at: indexPath, item: item) } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { cell.backgroundColor = cellBackgroundColor let backgroundView = UIView(frame: cell.bounds) backgroundView.backgroundColor = UIColor(white: 0.9, alpha: 1) cell.selectedBackgroundView = backgroundView } } class GirdViewCell: UICollectionViewCell, GirdCellType { private lazy var imageView: UIImageView = { let imageView = UIImageView() return imageView }() private lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.textAlignment = .center titleLabel.textColor = UIColor(hex: 0x4A4A4A) titleLabel.font = UIFontMake(12) return titleLabel }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white let superView = UIView() contentView.addSubview(superView) superView.snp.makeConstraints { (make) in make.center.equalToSuperview() } superView.addSubview(imageView) superView.addSubview(titleLabel) imageView.snp.makeConstraints { (make) in make.top.centerX.equalToSuperview() } titleLabel.snp.makeConstraints { (make) in make.top.equalTo(imageView.snp.bottom).offset(16) make.bottom.centerX.equalToSuperview() } } func updateCell(with item: GirdItem) { imageView.image = UIImage(named: item.imageName) titleLabel.text = item.title } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
2313b1922fd70faf70684c5a888d1a61
26.534483
133
0.659153
5.091392
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureSettings/Sources/FeatureSettingsUI/SettingsScreen/SectionPresenters/SecuritySectionPresenter.swift
1
3382
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import DIKit import FeatureSettingsDomain import PlatformKit import PlatformUIKit import RxSwift import ToolKit import WalletPayloadKit final class SecuritySectionPresenter: SettingsSectionPresenting { let sectionType: SettingsSectionType = .security var state: Observable<SettingsSectionLoadingState> { nativeWalletFlagEnabled() .asObservable() .flatMap { [weak self] isEnabled -> Observable<SettingsSectionLoadingState> in guard let self = self else { return .empty() } let showsAddressOption: Bool = !isEnabled let top: [SettingsCellViewModel] = [ .init(cellType: .switch(.sms2FA, self.smsTwoFactorSwitchCellPresenter)), .init(cellType: .switch(.cloudBackup, self.cloudBackupSwitchCellPresenter)), .init(cellType: .common(.changePassword)), .init(cellType: .badge(.recoveryPhrase, self.recoveryCellPresenter)), .init(cellType: .common(.changePIN)), .init(cellType: .switch(.bioAuthentication, self.bioAuthenticationCellPresenter)) ] let optional: [SettingsCellViewModel] = showsAddressOption ? [.init(cellType: .common(.addresses))] : [] let afterOptional = [SettingsCellViewModel(cellType: .common(.userDeletion))] let items = top + optional + afterOptional return .just( .loaded(next: .some( .init( sectionType: self.sectionType, items: items ) ) ) ) } } private let recoveryCellPresenter: RecoveryStatusCellPresenter private let bioAuthenticationCellPresenter: BioAuthenticationSwitchCellPresenter private let smsTwoFactorSwitchCellPresenter: SMSTwoFactorSwitchCellPresenter private let cloudBackupSwitchCellPresenter: CloudBackupSwitchCellPresenter init( smsTwoFactorService: SMSTwoFactorSettingsServiceAPI, credentialsStore: CredentialsStoreAPI, biometryProvider: BiometryProviding, settingsAuthenticater: AppSettingsAuthenticating, recoveryPhraseStatusProvider: RecoveryPhraseStatusProviding, authenticationCoordinator: AuthenticationCoordinating, appSettings: BlockchainSettings.App = resolve() ) { smsTwoFactorSwitchCellPresenter = SMSTwoFactorSwitchCellPresenter( service: smsTwoFactorService ) bioAuthenticationCellPresenter = BioAuthenticationSwitchCellPresenter( biometryProviding: biometryProvider, appSettingsAuthenticating: settingsAuthenticater, authenticationCoordinator: authenticationCoordinator ) recoveryCellPresenter = RecoveryStatusCellPresenter( recoveryStatusProviding: recoveryPhraseStatusProvider ) cloudBackupSwitchCellPresenter = CloudBackupSwitchCellPresenter( appSettings: appSettings, credentialsStore: credentialsStore ) } }
lgpl-3.0
06b65d194f7b3d6d979b6c660e26ef2a
41.2625
101
0.634723
6.136116
false
false
false
false
brentsimmons/Evergreen
iOS/Article/ArticleExtractorButton.swift
1
2509
// // ArticleExtractorButton.swift // NetNewsWire-iOS // // Created by Maurice Parker on 9/24/19. // Copyright © 2019 Ranchero Software. All rights reserved. // import UIKit enum ArticleExtractorButtonState { case error case animated case on case off } class ArticleExtractorButton: UIButton { private var animatedLayer: CALayer? var buttonState: ArticleExtractorButtonState = .off { didSet { if buttonState != oldValue { switch buttonState { case .error: stripAnimatedSublayer() setImage(AppAssets.articleExtractorError, for: .normal) case .animated: setImage(nil, for: .normal) setNeedsLayout() case .on: stripAnimatedSublayer() setImage(AppAssets.articleExtractorOn, for: .normal) case .off: stripAnimatedSublayer() setImage(AppAssets.articleExtractorOff, for: .normal) } } } } override var accessibilityLabel: String? { get { switch buttonState { case .error: return NSLocalizedString("Error - Reader View", comment: "Error - Reader View") case .animated: return NSLocalizedString("Processing - Reader View", comment: "Processing - Reader View") case .on: return NSLocalizedString("Selected - Reader View", comment: "Selected - Reader View") case .off: return NSLocalizedString("Reader View", comment: "Reader View") } } set { super.accessibilityLabel = newValue } } override func layoutSubviews() { super.layoutSubviews() guard case .animated = buttonState else { return } stripAnimatedSublayer() addAnimatedSublayer(to: layer) } private func stripAnimatedSublayer() { animatedLayer?.removeFromSuperlayer() } private func addAnimatedSublayer(to hostedLayer: CALayer) { let image1 = AppAssets.articleExtractorOffTinted.cgImage! let image2 = AppAssets.articleExtractorOnTinted.cgImage! let images = [image1, image2, image1] animatedLayer = CALayer() let imageSize = AppAssets.articleExtractorOff.size animatedLayer!.bounds = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height) animatedLayer!.position = CGPoint(x: bounds.midX, y: bounds.midY) hostedLayer.addSublayer(animatedLayer!) let animation = CAKeyframeAnimation(keyPath: "contents") animation.calculationMode = CAAnimationCalculationMode.linear animation.keyTimes = [0, 0.5, 1] animation.duration = 2 animation.values = images as [Any] animation.repeatCount = HUGE animatedLayer!.add(animation, forKey: "contents") } }
mit
c3ba656b6f1744e8d2dc21123c1e8425
25.125
94
0.717703
3.777108
false
false
false
false
pauljohanneskraft/Math
CoreMath/Classes/Automata/NFA.swift
1
1324
// // NFA.swift // Math // // Created by Paul Kraft on 06.05.17. // Copyright © 2017 pauljohanneskraft. All rights reserved. // extension NFA { public struct State { public init(transition: @escaping (Character) -> Set<Int>) { self.transition = transition } var transition: (Character) -> Set<Int> } } public struct NFA<Character> { let initialStates: Set<Int> let states: [Int: State] let finalStates: Set<Int> public init(states: [Int: State], initialStates: Set<Int>, finalStates: Set<Int>) { self.states = states self.initialStates = initialStates self.finalStates = Set(finalStates) } public func accepts<S: Sequence>(word: S) throws -> Bool where S.Iterator.Element == Character { var indices = initialStates var nextIndices = Set<Int>() for character in word { nextIndices.removeAll() for index in indices { guard let next = states[index]?.transition(character) else { throw DFAError.statesIncomplete } nextIndices.formUnion(next) } indices = nextIndices } return !finalStates.isDisjoint(with: indices) } enum DFAError: Error { case statesIncomplete } }
mit
3d84e2319877a24c1a0a7dbea5674ba2
27.148936
110
0.595616
4.226837
false
false
false
false
daaavid/TIY-Assignments
19--Forecaster/Forecaster/Forecaster/Location.swift
1
2946
// // Weather.swift // Forecaster // // Created by david on 10/29/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import Foundation let kCityKey = "city" let kStateKey = "state" let kLatKey = "lat" let kLngKey = "lng" class Location: NSObject, NSCoding { let city: String let lat: String let lng: String let state: String var weather: Weather? var imgHasBeenAnimated = false init(city: String, state: String, lat: String, lng: String, weather: Weather?) { self.city = city self.state = state self.lat = lat self.lng = lng if let _ = weather { self.weather = weather! } } // MARK: - NSCoding required convenience init?(coder aDecoder: NSCoder) { guard let city = aDecoder.decodeObjectForKey(kCityKey) as? String, let state = aDecoder.decodeObjectForKey(kStateKey) as? String, let lat = aDecoder.decodeObjectForKey(kLatKey) as? String, let lng = aDecoder.decodeObjectForKey(kLngKey) as? String else { return nil } self.init(city: city, state: state, lat: lat, lng: lng, weather: nil) } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.city, forKey: kCityKey) aCoder.encodeObject(self.state, forKey: kStateKey) aCoder.encodeObject(self.lng, forKey: kLngKey) aCoder.encodeObject(self.lat, forKey: kLatKey) } static func locationWithJSON(results: NSArray) -> Location { var location: Location var city = "" var state = "" var latStr = "" var lngStr = "" if results.count > 0 { for result in results { if let formattedAddress = result["formatted_address"] as? String { let addressComponentsForCity = formattedAddress.componentsSeparatedByString(",") city = String(addressComponentsForCity[0]) let stateZip = String(addressComponentsForCity[1]) state = stateZip.componentsSeparatedByString(" ")[1] } if let geometry = result["geometry"] as? NSDictionary { let latLong = geometry["location"] as? NSDictionary if latLong != nil { let lat = latLong?["lat"] as! Double let lng = latLong?["lng"] as! Double latStr = String(lat) lngStr = String(lng) } } } } location = Location(city: city, state: state, lat: latStr, lng: lngStr, weather: nil) return location } }
cc0-1.0
5212720c5bc1fb457be29873725835c2
27.047619
100
0.522581
4.75
false
false
false
false
MillmanY/MMLocalization
MMLocalization/Classes/UINavigationItem+Localize.swift
1
1419
// // UINavigationItem+Localize.swift // ETNews // // Created by Millman YANG on 2017/4/20. // Copyright © 2017年 Sen Informatoin co. All rights reserved. // import UIKit private var titleTextKey = "UINavigationItem+Text+Key" extension UINavigationItem { private var textKey: String? { set { objc_setAssociatedObject(self, &titleTextKey, newValue, .OBJC_ASSOCIATION_RETAIN) } get { guard let key = objc_getAssociatedObject(self, &titleTextKey) as? String else { return nil } return key } } static func replaceSetText(){ var originalSelector = #selector(setter: UINavigationItem.title) var swizzledSelector = #selector(UINavigationItem.itemTitle(_:)) self.replaceSelector(from: originalSelector, to: swizzledSelector) originalSelector = #selector(getter: UINavigationItem.title) swizzledSelector = #selector(UINavigationItem.getItemTitle) self.replaceSelector(from: originalSelector, to: swizzledSelector) } @objc func getItemTitle() -> String? { return self.textKey?.localize() } @objc func itemTitle(_ input: String?) { if let t = input { let local = t.localize() self.textKey = t self.itemTitle(local) } else { self.textKey = nil } } }
mit
19e3923c6c0d39d5dcdd61ba6eacd174
28.5
93
0.615113
4.735786
false
false
false
false
austinzheng/swift
test/TypeCoercion/subtyping.swift
57
2586
// RUN: %target-typecheck-verify-swift protocol CustomStringConvertible { func print() } struct TestFormat {} protocol FormattedPrintable : CustomStringConvertible { func print(_: TestFormat) } struct IsPrintable1 : CustomStringConvertible { func print() {} } func accept_creates_Printable (_: () -> CustomStringConvertible) {} func accept_creates_FormattedPrintable (_: () -> FormattedPrintable) {} func fp_to_p(_ fp: FormattedPrintable) -> CustomStringConvertible { return fp; } func p_to_fp(_ p: CustomStringConvertible) -> FormattedPrintable { } func p_to_ip1(_ p: CustomStringConvertible) -> IsPrintable1 { } func protocolConformance(ac1: @autoclosure () -> CustomStringConvertible, ac2: @autoclosure () -> FormattedPrintable, ip1: @autoclosure () -> IsPrintable1) { var f1 : (_ fp : FormattedPrintable) -> CustomStringConvertible = fp_to_p var f2 : (_ p : CustomStringConvertible) -> FormattedPrintable = p_to_fp let f3 : (_ p : CustomStringConvertible) -> IsPrintable1 = p_to_ip1 // FIXME: closures make ABI conversions explicit. rdar://problem/19517003 f1 = { f2($0) } // okay f1 = { f3($0) } // okay f2 = f1 // expected-error{{cannot assign value of type '(FormattedPrintable) -> CustomStringConvertible' to type '(CustomStringConvertible) -> FormattedPrintable'}} accept_creates_Printable(ac1) accept_creates_Printable({ ac2() }) accept_creates_Printable({ ip1() }) accept_creates_FormattedPrintable(ac1) // expected-error{{cannot convert value of type '() -> CustomStringConvertible' to expected argument type '() -> FormattedPrintable'}} accept_creates_FormattedPrintable(ac2) accept_creates_FormattedPrintable(ip1) // expected-error{{cannot convert value of type '() -> IsPrintable1' to expected argument type '() -> FormattedPrintable'}} } func p_gen_to_fp(_: () -> CustomStringConvertible) -> FormattedPrintable {} func fp_gen_to_p(_: () -> FormattedPrintable) -> CustomStringConvertible {} func nonTrivialNested() { // FIXME: closures make ABI conversions explicit. rdar://problem/19517003 var f1 : (_ : () -> CustomStringConvertible) -> CustomStringConvertible = { p_gen_to_fp($0) } let f2 : (_ : () -> CustomStringConvertible) -> FormattedPrintable = p_gen_to_fp let f3 : (_ : () -> FormattedPrintable) -> CustomStringConvertible = fp_gen_to_p f1 = { f2($0) } // okay f1 = f3 // expected-error{{cannot assign value of type '(() -> FormattedPrintable) -> CustomStringConvertible' to type '(() -> CustomStringConvertible) -> CustomStringConvertible'}} _ = f1 }
apache-2.0
7f4816df37608ceb0aad4bc1a405d1d0
45.178571
183
0.695282
4.211726
false
false
false
false
swipe-org/swipe
browser/SwipeBrowser.swift
2
18036
// // SwipeBrowser.swift // sample // // Created by satoshi on 10/8/15. // Copyright © 2015 Satoshi Nakajima. All rights reserved. // #if os(OSX) // WARNING: OSX support is not done yet import Cocoa public typealias UIViewController = NSViewController #else import UIKit #endif // // Change s_verbosLevel to 1 to see debug messages for this class // private func MyLog(_ text:String, level:Int = 0) { let s_verbosLevel = 0 if level <= s_verbosLevel { print(text) } } protocol SwipeBrowserDelegate: NSObjectProtocol { func documentDidLoad(browser:SwipeBrowser) } // // SwipeBrowser is the main UIViewController that is pushed into the navigation stack. // SwipeBrowser "hosts" another UIViewController, which supports SwipeDocumentViewer protocol. // class SwipeBrowser: UIViewController, SwipeDocumentViewerDelegate { // // This is the place you can add more document types. // Those UIViewControllers MUST support SwipeDocumentViewer protocol. // static private var typeMapping:[String:() -> UIViewController] = [ "net.swipe.list": { return SwipeTableViewController(nibName:"SwipeTableViewController", bundle:nil) }, "net.swipe.swipe": { return SwipeViewController() }, ] static var stack = [SwipeBrowser]() static func register(type:String, factory:@escaping () -> UIViewController) { typeMapping[type] = factory } public weak var delegate:SwipeBrowserDelegate? var notificationManager = SNNotificationManager() #if os(iOS) private var fVisibleUI = true @IBOutlet var toolbar:UIView? @IBOutlet var bottombar:UIView? @IBOutlet var slider:UISlider? @IBOutlet var labelTitle:UILabel? @IBOutlet var btnExport:UIButton? @IBOutlet var btnMore:UIButton? private var landscapeMode = false #elseif os(tvOS) override weak var preferredFocusedView: UIView? { return controller?.view } #endif @IBOutlet var viewLoading:UIView? @IBOutlet var progress:UIProgressView? @IBOutlet var labelLoading:UILabel? @IBOutlet var btnLanguage:UIButton? private var resourceRequest:NSBundleResourceRequest? var url:URL? = Bundle.main.url(forResource: "index.swipe", withExtension: nil) var jsonDocument:[String:Any]? var controller:UIViewController? var documentViewer:SwipeDocumentViewer? var ignoreViewState = false func browseTo(_ url:URL) { let browser = SwipeBrowser(nibName: "SwipeBrowser", bundle: nil) browser.delegate = self.delegate browser.url = url // //MyLog("SWBrows url \(browser.url!)") #if os(OSX) self.presentViewControllerAsSheet(browser) #else self.present(browser, animated: true) { () -> Void in SwipeBrowser.stack.append(browser) MyLog("SWBrows push \(SwipeBrowser.stack.count)", level: 1) } #endif } deinit { if let request = self.resourceRequest { request.endAccessingResources() } MyLog("SWBrows deinit", level:1) } override func viewDidLoad() { super.viewDidLoad() viewLoading?.alpha = 0 btnLanguage?.isEnabled = false if SwipeBrowser.stack.count == 0 { SwipeBrowser.stack.append(self) // special case for the first one MyLog("SWBrows push first \(SwipeBrowser.stack.count)", level: 1) } #if os(iOS) btnExport?.isEnabled = false slider?.isHidden = true #endif if let document = self.jsonDocument { self.openDocument(document, localResource: true) } else if let url = self.url { if url.scheme == "file" { if let data = try? Data(contentsOf: url) { self.openData(data, localResource: true) } else { // On-demand resource support if let urlLocal = Bundle.main.url(forResource: url.lastPathComponent, withExtension: nil), let data = try? Data(contentsOf: urlLocal) { self.openData(data, localResource: true) } else { self.processError("Missing resource:".localized + "\(url)") } } } else { let manager = SwipeAssetManager.sharedInstance() manager.loadAsset(url, prefix: "", bypassCache:true) { (urlLocal:URL?, error:NSError?) -> Void in if let urlL = urlLocal, error == nil, let data = try? Data(contentsOf: urlL) { self.openData(data, localResource: false) } else { self.processError(error?.localizedDescription ?? "") } } } } else { MyLog("SWBrows nil URL") processError("No URL to load".localized) } } // NOTE: documentViewer and vc always points to the same UIController. private func loadDocumentView(_ documentViewer:SwipeDocumentViewer, vc:UIViewController, document:[String:Any]) { #if os(iOS) if let title = documentViewer.documentTitle() { labelTitle?.text = title } else { labelTitle?.text = url?.lastPathComponent } #endif if let languages = documentViewer.languages(), languages.count > 0 { btnLanguage?.isEnabled = true } controller = vc self.addChild(vc) vc.view.autoresizingMask = UIView.AutoresizingMask([.flexibleWidth, .flexibleHeight]) #if os(OSX) self.view.addSubview(vc.view, positioned: .Below, relativeTo: nil) #else self.view.insertSubview(vc.view, at: 0) #endif var rcFrame = self.view.bounds #if os(iOS) if let _ = controller as? SwipeViewController { btnExport?.isEnabled = true } if documentViewer.hideUI() { let tap = UITapGestureRecognizer(target: self, action: #selector(SwipeBrowser.tapped)) self.view.addGestureRecognizer(tap) hideUI() } else if let toolbar = self.toolbar, let bottombar = self.bottombar { rcFrame.origin.y = toolbar.bounds.size.height rcFrame.size.height -= rcFrame.origin.y + bottombar.bounds.size.height } #endif vc.view.frame = rcFrame delegate?.documentDidLoad(browser: self) } private func openDocumentViewer(_ document:[String:Any]) { var documentType = "net.swipe.swipe" // default if let type = document["type"] as? String { documentType = type } guard let type = SwipeBrowser.typeMapping[documentType] else { return processError("Unknown type:".localized + "\(String(describing: SwipeBrowser.typeMapping[documentType])).") } let vc = type() guard let documentViewer = vc as? SwipeDocumentViewer else { return processError("Programming Error: Not SwipeDocumentViewer.".localized) } self.documentViewer = documentViewer documentViewer.setDelegate(self) do { let defaults = UserDefaults.standard var state:[String:Any]? = nil if let url = self.url, ignoreViewState == false { state = defaults.object(forKey: url.absoluteString) as? [String:Any] } self.viewLoading?.alpha = 1.0 self.labelLoading?.text = "Loading Network Resources...".localized try documentViewer.loadDocument(document, size:self.view.frame.size, url: url, state:state) { (progress:Float, error:NSError?) -> (Void) in self.progress?.progress = progress if progress >= 1 { UIView.animate(withDuration: 0.2, animations: { () -> Void in self.viewLoading?.alpha = 0.0 }, completion: { (_:Bool) -> Void in self.loadDocumentView(documentViewer, vc:vc, document: document) }) } } } catch let error as NSError { self.viewLoading?.alpha = 0.0 return processError("Load Document Error:".localized + "\(error.localizedDescription).") } } private func openDocumentWithODR(_ document:[String:Any], localResource:Bool) { if let tags = document["resources"] as? [String], localResource { //NSLog("tags = \(tags)") let request = NSBundleResourceRequest(tags: Set<String>(tags)) self.resourceRequest = request request.conditionallyBeginAccessingResources() { (resourcesAvailable:Bool) -> Void in MyLog("SWBrows resourceAvailable(\(tags)) = \(resourcesAvailable)", level:1) DispatchQueue.main.async { if resourcesAvailable { self.openDocumentViewer(document) } else { let alert = UIAlertController(title: "Swipe", message: "Loading Resources...".localized, preferredStyle: UIAlertController.Style.alert) self.present(alert, animated: true) { () -> Void in request.beginAccessingResources() { (error:Swift.Error?) -> Void in DispatchQueue.main.async { self.dismiss(animated: false, completion: nil) if let e = error { MyLog("SWBrows resource error=\(String(describing: error))", level:0) return self.processError(e.localizedDescription) } else { self.openDocumentViewer(document) } } } } } } } } else { self.openDocumentViewer(document) } } private func openDocument(_ document:[String:Any], localResource:Bool) { var deferred = false #if os(iOS) if let orientation = document["orientation"] as? String, orientation == "landscape" { self.landscapeMode = true if !localResource { // HACK ALERT: If the resource is remote and the orientation is landscape, it is too late to specify // the allowed orientations. Until iOS7, we could just call attemptRotationToDeviceOrientation(), // but it no longer works. Therefore, we work-around by presenting a dummy VC, and dismiss it // before opening the document. deferred = true //UIViewController.attemptRotationToDeviceOrientation() // NOTE: attempt but not working let vcDummy = UIViewController() self.present(vcDummy, animated: false, completion: { () -> Void in self.dismiss(animated: false, completion: nil) self.openDocumentWithODR(document, localResource: localResource) }) } } #endif if !deferred { self.openDocumentWithODR(document, localResource: localResource) } } private func openData(_ dataRetrieved:Data?, localResource:Bool) { guard let data = dataRetrieved else { return processError("Failed to open: No data".localized) } do { guard let document = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [String:Any] else { return processError("Not a dictionary.".localized) } openDocument(document, localResource: localResource) } catch let error as NSError { let value = error.userInfo["NSDebugDescription"]! processError("Invalid JSON file".localized + "\(error.localizedDescription). \(value)") return } } #if os(iOS) override var prefersStatusBarHidden: Bool { return true } // NOTE: This function and supportedInterfaceOrientations will not be called on iPad // as long as the app supports multitasking. override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if let documentViewer = self.documentViewer, documentViewer.landscape() { return UIInterfaceOrientationMask.landscape } return landscapeMode ? UIInterfaceOrientationMask.landscape : UIInterfaceOrientationMask.portrait } @IBAction func tapped() { MyLog("SWBrows tapped", level: 1) if fVisibleUI { hideUI() } else { showUI() } } private func showUI() { fVisibleUI = true UIView.animate(withDuration: 0.2, animations: { () -> Void in self.toolbar?.alpha = 1.0 self.bottombar?.alpha = 1.0 }) } private func hideUI() { fVisibleUI = false UIView.animate(withDuration: 0.2, animations: { () -> Void in self.toolbar?.alpha = 0.0 self.bottombar?.alpha = 0.0 }) } @IBAction func slided(_ sender:UISlider) { MyLog("SWBrows \(sender.value)") } #else func tapped() { } #endif private func processError(_ message:String) { DispatchQueue.main.async { #if !os(OSX) // REVIEW let alert = UIAlertController(title: "Can't open the document.", message: message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default) { (_:UIAlertAction) -> Void in self.presentingViewController?.dismiss(animated: true, completion: nil) }) self.present(alert, animated: true, completion: nil) #endif } } #if !os(OSX) override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } #endif override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if self.isBeingDismissed { if let documentViewer = self.documentViewer, let state = documentViewer.saveState(), let url = self.url { MyLog("SWBrows state=\(state)", level:1) let defaults = UserDefaults.standard defaults.set(state, forKey: url.absoluteString) defaults.synchronize() } _ = SwipeBrowser.stack.popLast() MyLog("SWBrows pop \(SwipeBrowser.stack.count)", level:1) if SwipeBrowser.stack.count == 1 { // Wait long enough (200ms > 1/30fps) and check the memory leak. // This gives the timerTick() in SwipePage to complete the shutdown sequence DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(200 * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC)) { () -> Void in SwipePage.checkMemoryLeak() SwipeElement.checkMemoryLeak() } } } } @IBAction func close(_ sender:Any) { #if os(OSX) self.presentingViewController!.dismissViewController(self) #else self.presentingViewController!.dismiss(animated: true, completion: nil) #endif } func becomeZombie() { if let documentViewer = self.documentViewer { documentViewer.becomeZombie() } } static func openURL(_ urlString:String) { NSLog("SWBrose openURL \(SwipeBrowser.stack.count) \(urlString)") #if os(OSX) while SwipeBrowser.stack.count > 1 { let lastVC = SwipeBrowser.stack.last! lastVC.becomeZombie() SwipeBrowser.stack.last!.dismissViewController(lastVC) } #else if SwipeBrowser.stack.count > 1 { let lastVC = SwipeBrowser.stack.last! lastVC.becomeZombie() SwipeBrowser.stack.last!.dismiss(animated: false, completion: { () -> Void in openURL(urlString) }) return } #endif DispatchQueue.main.async { () -> Void in if let url = URL.url(urlString, baseURL: nil) { SwipeBrowser.stack.last!.browseTo(url) } } } @IBAction func language() { if let languages = documentViewer?.languages() { let alert = UIAlertController(title: "Swipe", message: "Choose a language", preferredStyle: UIAlertController.Style.actionSheet) alert.popoverPresentationController?.sourceView = self.view alert.popoverPresentationController?.sourceRect = btnLanguage!.frame for language in languages { guard let title = language["title"] as? String, let langId = language["id"] as? String else { continue } alert.addAction(UIAlertAction(title: title, style: UIAlertAction.Style.default, handler: { (_:UIAlertAction) -> Void in //print("SwipeB language selected \(langId)") self.documentViewer?.reloadWithLanguageId(langId) #if os(iOS) if let documentViewer = self.documentViewer, documentViewer.hideUI() { self.hideUI() } #endif })) } self.present(alert, animated: true, completion: nil) } } }
mit
4c0ff66eff48a51e6535ae331a1b6bd5
37.784946
163
0.579928
4.932987
false
false
false
false
lorentey/swift
test/Interpreter/SDK/CGImportAsMember.swift
49
1376
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // REQUIRES: OS=macosx import Foundation import CoreGraphics class Colors { static var black = CGColor.black static var white = CGColor.white static var clear = CGColor.clear class func printColors() { print("Colors") // CHECK: Colors print(black) // CHECK: Generic Gray Profile print(white) // CHECK: Generic Gray Profile print(clear) // CHECK: Generic Gray Profile } } // TODO: ColorSpaces with their empty-argument-label pattern, when issue is // fixed. class Events { static var mouseDefault = CGEventMouseSubtype.defaultType static var mouseTabletPoint = CGEventMouseSubtype.tabletPoint static var tapDefault = CGEventTapOptions.defaultTap static var tapListenOnly = CGEventTapOptions.listenOnly static var privateID = CGEventSourceStateID.privateState static var combinedSessionID = CGEventSourceStateID.combinedSessionState class func printEvents() { print("Events") // CHECK-LABEL: Events print(mouseDefault.rawValue) // CHECK: 0 print(mouseTabletPoint.rawValue) // CHECK: 1 print(tapDefault.rawValue) // CHECK: 0 print(tapListenOnly.rawValue) // CHECK: 1 print(privateID.rawValue) // CHECK: -1 print(combinedSessionID.rawValue) // CHECK: 0 } } Colors.printColors() Events.printEvents()
apache-2.0
ba63a7b5692a39b362adf40eac51f7dd
28.913043
76
0.726744
3.832869
false
false
false
false
lorentey/swift
test/SILGen/opaque_values_silgen_lib.swift
12
4355
// RUN: %target-swift-emit-silgen -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s precedencegroup AssignmentPrecedence { assignment: true } enum Optional<Wrapped> { case none case some(Wrapped) } protocol EmptyP {} struct String { var ptr: Builtin.NativeObject } // Tests Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value) // --- // CHECK-LABEL: sil hidden [ossa] @$ss21s010______PAndS_casesyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[MTYPE:%.*]] = metatype $@thin PAndSEnum.Type // CHECK: [[EAPPLY:%.*]] = apply {{.*}}([[MTYPE]]) : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum // CHECK: destroy_value [[EAPPLY]] // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '$ss21s010______PAndS_casesyyF' func s010______PAndS_cases() { _ = PAndSEnum.A } // Test emitBuiltinReinterpretCast. // --- // CHECK-LABEL: sil hidden [ossa] @$ss21s020__________bitCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U { // CHECK: bb0([[ARG:%.*]] : @guaranteed $T, // CHECK: [[COPY:%.*]] = copy_value [[ARG]] : $T // CHECK: [[CAST:%.*]] = unchecked_bitwise_cast [[COPY]] : $T to $U // CHECK: [[RET:%.*]] = copy_value [[CAST]] : $U // CHECK: destroy_value [[COPY]] : $T // CHECK: return [[RET]] : $U // CHECK-LABEL: } // end sil function '$ss21s020__________bitCast_2toq_x_q_mtr0_lF' func s020__________bitCast<T, U>(_ x: T, to type: U.Type) -> U { return Builtin.reinterpretCast(x) } // Test emitBuiltinCastReference // --- // CHECK-LABEL: sil hidden [ossa] @$ss21s030__________refCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U { // CHECK: bb0([[ARG:%.*]] : @guaranteed $T, %1 : $@thick U.Type): // CHECK: [[COPY:%.*]] = copy_value [[ARG]] : $T // CHECK: [[SRC:%.*]] = alloc_stack $T // CHECK: store [[COPY]] to [init] [[SRC]] : $*T // CHECK: [[DEST:%.*]] = alloc_stack $U // CHECK: unchecked_ref_cast_addr T in [[SRC]] : $*T to U in [[DEST]] : $*U // CHECK: [[LOAD:%.*]] = load [take] [[DEST]] : $*U // CHECK: dealloc_stack [[DEST]] : $*U // CHECK: dealloc_stack [[SRC]] : $*T // CHECK-NOT: destroy_value [[ARG]] : $T // CHECK: return [[LOAD]] : $U // CHECK-LABEL: } // end sil function '$ss21s030__________refCast_2toq_x_q_mtr0_lF' func s030__________refCast<T, U>(_ x: T, to: U.Type) -> U { return Builtin.castReference(x) } // Init of Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value) // --- // CHECK-LABEL: sil shared [transparent] [ossa] @$ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmF : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum { // CHECK: bb0([[ARG0:%.*]] : @owned $EmptyP, [[ARG1:%.*]] : @owned $String, [[ARG2:%.*]] : $@thin PAndSEnum.Type): // CHECK: [[RTUPLE:%.*]] = tuple ([[ARG0]] : $EmptyP, [[ARG1]] : $String) // CHECK: [[RETVAL:%.*]] = enum $PAndSEnum, #PAndSEnum.A!enumelt.1, [[RTUPLE]] : $(EmptyP, String) // CHECK: return [[RETVAL]] : $PAndSEnum // CHECK-LABEL: } // end sil function '$ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmF' // CHECK-LABEL: sil shared [transparent] [thunk] [ossa] @$ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmFTc : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum { // CHECK: bb0([[ARG:%.*]] : $@thin PAndSEnum.Type): // CHECK: [[RETVAL:%.*]] = partial_apply [callee_guaranteed] {{.*}}([[ARG]]) : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum // CHECK: [[CANONICAL_THUNK_FN:%.*]] = function_ref @$ss6EmptyP_pSSs9PAndSEnumOIegixr_sAA_pSSACIegngr_TR : $@convention(thin) (@in_guaranteed EmptyP, @guaranteed String, @guaranteed @callee_guaranteed (@in EmptyP, @owned String) -> @out PAndSEnum) -> @out PAndSEnum // CHECK: [[CANONICAL_THUNK:%.*]] = partial_apply [callee_guaranteed] [[CANONICAL_THUNK_FN]]([[RETVAL]]) // CHECK: return [[CANONICAL_THUNK]] : $@callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum // CHECK-LABEL: } // end sil function '$ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmFTc' enum PAndSEnum { case A(EmptyP, String) }
apache-2.0
1e72d18d0fd496d66d52858ac9947d39
55.558442
267
0.628932
3.211652
false
false
false
false
heilb1314/500px_Challenge
PhotoWall_500px_challenge/PhotoWall_500px_challenge/PhotoWallViewController.swift
1
7366
// // PhotoWallViewController.swift // PhotoWall_500px_challenge // // Created by Jianxiong Wang on 2/1/17. // Copyright © 2017 JianxiongWang. All rights reserved. // import UIKit class PhotoWallViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! fileprivate var photos:[Photo]! fileprivate var gridSizes: [CGSize]! fileprivate var itemsPerRow: Int = 3 fileprivate var lastViewdIndexPath: IndexPath? fileprivate var isLandscape = false fileprivate var isLoading = false fileprivate var searchController: UISearchController! fileprivate var searchTerm: String = CATEGORIES[0] fileprivate var page: Int = 1 private var pageSize: Int = 30 private var photoSizes: [Int] = [3,4] private var selectedIndex: Int? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.barStyle = .default self.navigationController?.navigationBar.titleTextAttributes = nil let rightBarItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(changeTerm(sender:))) rightBarItem.tintColor = UIColor.orange self.navigationItem.rightBarButtonItem = rightBarItem self.navigationItem.title = searchTerm.capitalized self.updateCollectionViewLayout() } func changeTerm(sender: UIBarButtonItem) { self.performSegue(withIdentifier: "showCategories", sender: self) } override func viewDidLoad() { super.viewDidLoad() self.isLandscape = UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) if let layout = collectionView?.collectionViewLayout as? PhotoWallLayout { layout.delegate = self } self.photos = [Photo]() getPhotos(resetPhotos: true, completionHandler: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /// Get next page Photos. Auto reload collectionView. fileprivate func getPhotos(resetPhotos: Bool, completionHandler handler: (()->())?) { QueryModel.getPhotos(forSearchTerm: searchTerm, page: page, resultsPerPage: pageSize, photoSizes: photoSizes) { (photos, error) in if(photos != nil) { self.page += 1 resetPhotos ? self.photos = photos : self.photos.append(contentsOf: photos!) self.collectionView.layoutIfNeeded() self.collectionView.reloadData() } else { let alert = UIAlertController(title: "Oops", message: error?.localizedDescription, preferredStyle: .alert) let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addAction(cancel) self.present(alert, animated: true, completion: nil) } handler?() } } /// update collectionView layout and move to last viewed indexPath if any. fileprivate func updateCollectionViewLayout() { self.collectionView.collectionViewLayout.invalidateLayout() let curOrientation = UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) if self.lastViewdIndexPath != nil && self.isLandscape != curOrientation { self.isLandscape = curOrientation DispatchQueue.main.async { self.collectionView.scrollToItem(at: self.lastViewdIndexPath!, at: curOrientation ? .right : .bottom, animated: false) } } } // MARK: - UIScrollView Delegates func scrollViewDidScroll(_ scrollView: UIScrollView) { self.lastViewdIndexPath = self.collectionView.indexPathsForVisibleItems.last // load next page when scrollView reaches the end guard self.isLoading == false else { return } var offset:CGFloat = 0 var sizeLength:CGFloat = 0 if UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) { offset = scrollView.contentOffset.x sizeLength = scrollView.contentSize.width - scrollView.frame.size.width } else { offset = scrollView.contentOffset.y sizeLength = scrollView.contentSize.height - scrollView.frame.size.height } if offset >= sizeLength { self.isLoading = true self.getPhotos(resetPhotos: false, completionHandler: { self.isLoading = false }) } } // MARK: - UICollectionView DataSources func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.photos?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PhotoThumbnailCollectionViewCell cell.photo = self.photos?[indexPath.row] return cell } // MARK: - UICollectionView Delegates func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.selectedIndex = indexPath.row performSegue(withIdentifier: "showPhotoDetail", sender: self) } // Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showPhotoDetail" { let svc = segue.destination as! PhotoDetailViewController if self.photos != nil && self.selectedIndex != nil && self.selectedIndex! < self.photos!.count { svc.photo = self.photos![self.selectedIndex!] } } else if segue.identifier == "showCategories" { let svc = segue.destination as! SearchTermTableViewController svc.delegate = self } } } // MARK: Extension - PhotoWallLayoutDelegate extension PhotoWallViewController: PhotoWallLayoutDelegate { func collectionView(collectionView: UICollectionView, sizeForPhotoAtIndexPath indexPath: IndexPath) -> CGSize { return photos[indexPath.item].getPhotoSize() } // Update grids when device rotates override func viewWillLayoutSubviews() { if self.isLandscape != UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) { updateCollectionViewLayout() } } override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) { updateCollectionViewLayout() } } // MARK: Extension - SearchTerm Delegate extension PhotoWallViewController: SearchTermDelegate { func searchTermDidChange(sender: SearchTermTableViewController, newTerm: String) { if newTerm != self.searchTerm { self.searchTerm = newTerm self.page = 1 self.getPhotos(resetPhotos: true, completionHandler: { self.collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .top, animated: false) }) } } }
mit
019b3d862d31010927fda05b10b0deea
38.175532
138
0.664902
5.475836
false
false
false
false
Moya/Moya
Sources/CombineMoya/MoyaPublisher.swift
1
1437
#if canImport(Combine) import Combine import Moya // This should be already provided in Combine, but it's not. // Ideally we would like to remove it, in favor of a framework-provided solution, ASAP. @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) internal class MoyaPublisher<Output>: Publisher { internal typealias Failure = MoyaError private class Subscription: Combine.Subscription { private let performCall: () -> Moya.Cancellable? private var cancellable: Moya.Cancellable? init(subscriber: AnySubscriber<Output, MoyaError>, callback: @escaping (AnySubscriber<Output, MoyaError>) -> Moya.Cancellable?) { performCall = { callback(subscriber) } } func request(_ demand: Subscribers.Demand) { guard demand > .none else { return } cancellable = performCall() } func cancel() { cancellable?.cancel() } } private let callback: (AnySubscriber<Output, MoyaError>) -> Moya.Cancellable? init(callback: @escaping (AnySubscriber<Output, MoyaError>) -> Moya.Cancellable?) { self.callback = callback } internal func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input { let subscription = Subscription(subscriber: AnySubscriber(subscriber), callback: callback) subscriber.receive(subscription: subscription) } } #endif
mit
7b9151d00d2c5c8e444a69278764444e
30.933333
137
0.666667
4.518868
false
false
false
false
KaiCode2/swift-corelibs-foundation
Foundation/NSXMLParser.swift
1
37250
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // It is necessary to explicitly cast strlen to UInt to match the type // of prefixLen because currently, strlen (and other functions that // rely on swift_ssize_t) use the machine word size (int on 32 bit and // long in on 64 bit). I've filed a bug at bugs.swift.org: // https://bugs.swift.org/browse/SR-314 #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif import CoreFoundation public enum NSXMLParserExternalEntityResolvingPolicy : UInt { case ResolveExternalEntitiesNever // default case ResolveExternalEntitiesNoNetwork case ResolveExternalEntitiesSameOriginOnly //only applies to NSXMLParser instances initialized with -initWithContentsOfURL: case ResolveExternalEntitiesAlways } extension _CFXMLInterface { var parser: NSXMLParser { return unsafeBitCast(self, to: NSXMLParser.self) } } extension NSXMLParser { internal var interface: _CFXMLInterface { return unsafeBitCast(self, to: _CFXMLInterface.self) } } private func UTF8STRING(_ bytes: UnsafePointer<UInt8>) -> String? { let len = strlen(UnsafePointer<Int8>(bytes)) let str = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: bytes, count: Int(len))) return str } internal func _NSXMLParserCurrentParser() -> _CFXMLInterface? { if let parser = NSXMLParser.currentParser() { return parser.interface } else { return nil } } internal func _NSXMLParserExternalEntityWithURL(_ interface: _CFXMLInterface, urlStr: UnsafePointer<Int8>, identifier: UnsafePointer<Int8>, context: _CFXMLInterfaceParserContext, originalLoaderFunction: _CFXMLInterfaceExternalEntityLoader) -> _CFXMLInterfaceParserInput? { let parser = interface.parser let policy = parser.externalEntityResolvingPolicy var a: NSURL? if let allowedEntityURLs = parser.allowedExternalEntityURLs { if let url = NSURL(string: String(urlStr)) { a = url if let scheme = url.scheme { if scheme == "file" { a = NSURL(fileURLWithPath: url.path!) } } } if let url = a { let allowed = allowedEntityURLs.contains(url) if allowed || policy != .ResolveExternalEntitiesSameOriginOnly { if allowed { return originalLoaderFunction(urlStr, identifier, context) } } } } switch policy { case .ResolveExternalEntitiesSameOriginOnly: guard let url = parser._url else { break } if a == nil { a = NSURL(string: String(urlStr)) } guard let aUrl = a else { break } var matches: Bool if let aHost = aUrl.host, host = url.host { matches = host == aHost } else { return nil } if matches { if let aPort = aUrl.port, port = url.port { matches = port == aPort } else { return nil } } if matches { if let aScheme = aUrl.scheme, scheme = url.scheme { matches = scheme == aScheme } else { return nil } } if !matches { return nil } break case .ResolveExternalEntitiesAlways: break case .ResolveExternalEntitiesNever: return nil case .ResolveExternalEntitiesNoNetwork: return _CFXMLInterfaceNoNetExternalEntityLoader(urlStr, identifier, context) } return originalLoaderFunction(urlStr, identifier, context) } internal func _NSXMLParserGetContext(_ ctx: _CFXMLInterface) -> _CFXMLInterfaceParserContext { return ctx.parser._parserContext! } internal func _NSXMLParserInternalSubset(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, ExternalID: UnsafePointer<UInt8>, SystemID: UnsafePointer<UInt8>) -> Void { _CFXMLInterfaceSAX2InternalSubset(ctx.parser._parserContext, name, ExternalID, SystemID) } internal func _NSXMLParserIsStandalone(_ ctx: _CFXMLInterface) -> Int32 { return _CFXMLInterfaceIsStandalone(ctx.parser._parserContext) } internal func _NSXMLParserHasInternalSubset(_ ctx: _CFXMLInterface) -> Int32 { return _CFXMLInterfaceHasInternalSubset(ctx.parser._parserContext) } internal func _NSXMLParserHasExternalSubset(_ ctx: _CFXMLInterface) -> Int32 { return _CFXMLInterfaceHasExternalSubset(ctx.parser._parserContext) } internal func _NSXMLParserGetEntity(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>) -> _CFXMLInterfaceEntity? { let parser = ctx.parser let context = _NSXMLParserGetContext(ctx) var entity = _CFXMLInterfaceGetPredefinedEntity(name) if entity == nil { entity = _CFXMLInterfaceSAX2GetEntity(context, name) } if entity == nil { if let delegate = parser.delegate { let entityName = UTF8STRING(name)! // if the systemID was valid, we would already have the correct entity (since we're loading external dtds) so this callback is a bit of a misnomer let result = delegate.parser(parser, resolveExternalEntityName: entityName, systemID: nil) if _CFXMLInterfaceHasDocument(context) != 0 { if let data = result { // unfortunately we can't add the entity to the doc to avoid further lookup since the delegate can change under us _NSXMLParserCharacters(ctx, ch: UnsafePointer<UInt8>(data.bytes), len: Int32(data.length)) } } } } return entity } internal func _NSXMLParserNotationDecl(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, publicId: UnsafePointer<UInt8>, systemId: UnsafePointer<UInt8>) -> Void { let parser = ctx.parser if let delegate = parser.delegate { let notationName = UTF8STRING(name)! let publicIDString = UTF8STRING(publicId) let systemIDString = UTF8STRING(systemId) delegate.parser(parser, foundNotationDeclarationWithName: notationName, publicID: publicIDString, systemID: systemIDString) } } internal func _NSXMLParserAttributeDecl(_ ctx: _CFXMLInterface, elem: UnsafePointer<UInt8>, fullname: UnsafePointer<UInt8>, type: Int32, def: Int32, defaultValue: UnsafePointer<UInt8>, tree: _CFXMLInterfaceEnumeration) -> Void { let parser = ctx.parser if let delegate = parser.delegate { let elementString = UTF8STRING(elem)! let nameString = UTF8STRING(fullname)! let typeString = "" // FIXME! let defaultValueString = UTF8STRING(defaultValue) delegate.parser(parser, foundAttributeDeclarationWithName: nameString, forElement: elementString, type: typeString, defaultValue: defaultValueString) } // in a regular sax implementation tree is added to an attribute, which takes ownership of it; in our case we need to make sure to release it _CFXMLInterfaceFreeEnumeration(tree) } internal func _NSXMLParserElementDecl(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, type: Int32, content: _CFXMLInterfaceElementContent) -> Void { let parser = ctx.parser if let delegate = parser.delegate { let nameString = UTF8STRING(name)! let modelString = "" // FIXME! delegate.parser(parser, foundElementDeclarationWithName: nameString, model: modelString) } } internal func _NSXMLParserUnparsedEntityDecl(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, publicId: UnsafePointer<UInt8>, systemId: UnsafePointer<UInt8>, notationName: UnsafePointer<UInt8>) -> Void { let parser = ctx.parser let context = _NSXMLParserGetContext(ctx) // Add entities to the libxml2 doc so they'll resolve properly _CFXMLInterfaceSAX2UnparsedEntityDecl(context, name, publicId, systemId, notationName) if let delegate = parser.delegate { let declName = UTF8STRING(name)! let publicIDString = UTF8STRING(publicId) let systemIDString = UTF8STRING(systemId) let notationNameString = UTF8STRING(notationName) delegate.parser(parser, foundUnparsedEntityDeclarationWithName: declName, publicID: publicIDString, systemID: systemIDString, notationName: notationNameString) } } internal func _NSXMLParserStartDocument(_ ctx: _CFXMLInterface) -> Void { let parser = ctx.parser if let delegate = parser.delegate { delegate.parserDidStartDocument(parser) } } internal func _NSXMLParserEndDocument(_ ctx: _CFXMLInterface) -> Void { let parser = ctx.parser if let delegate = parser.delegate { delegate.parserDidEndDocument(parser) } } internal func _colonSeparatedStringFromPrefixAndSuffix(_ prefix: UnsafePointer<UInt8>, _ prefixlen: UInt, _ suffix: UnsafePointer<UInt8>, _ suffixLen: UInt) -> String { let prefixString = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: prefix, count: Int(prefixlen))) let suffixString = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: suffix, count: Int(suffixLen))) return "\(prefixString!):\(suffixString!)" } internal func _NSXMLParserStartElementNs(_ ctx: _CFXMLInterface, localname: UnsafePointer<UInt8>, prefix: UnsafePointer<UInt8>?, URI: UnsafePointer<UInt8>, nb_namespaces: Int32, namespaces: UnsafeMutablePointer<UnsafePointer<UInt8>?>, nb_attributes: Int32, nb_defaulted: Int32, attributes: UnsafeMutablePointer<UnsafePointer<UInt8>?>) -> Void { let parser = ctx.parser let reportQNameURI = parser.shouldProcessNamespaces let reportNamespaces = parser.shouldReportNamespacePrefixes let prefixLen = prefix != nil ? UInt(strlen(UnsafePointer<Int8>(prefix!))) : 0 let localnameString = (prefixLen == 0 || reportQNameURI) ? UTF8STRING(localname) : nil let qualifiedNameString = prefixLen != 0 ? _colonSeparatedStringFromPrefixAndSuffix(prefix!, UInt(prefixLen), localname, UInt(strlen(UnsafePointer<Int8>(localname)))) : localnameString let namespaceURIString = reportQNameURI ? UTF8STRING(URI) : nil var nsDict = [String:String]() var attrDict = [String:String]() if nb_attributes + nb_namespaces > 0 { for idx in stride(from: 0, to: Int(nb_namespaces) * 2, by: 2) { var namespaceNameString: String? var asAttrNamespaceNameString: String? if let ns = namespaces[idx] { if reportNamespaces { namespaceNameString = UTF8STRING(ns) } asAttrNamespaceNameString = _colonSeparatedStringFromPrefixAndSuffix("xmlns", 5, ns, UInt(strlen(UnsafePointer<Int8>(ns)))) } else { namespaceNameString = "" asAttrNamespaceNameString = "xmlns" } let namespaceValueString = namespaces[idx + 1] != nil ? UTF8STRING(namespaces[idx + 1]!) : "" if reportNamespaces { if let k = namespaceNameString, v = namespaceValueString { nsDict[k] = v } } if !reportQNameURI { if let k = asAttrNamespaceNameString, v = namespaceValueString { attrDict[k] = v } } } } if reportNamespaces { parser._pushNamespaces(nsDict) } for idx in stride(from: 0, to: Int(nb_attributes) * 5, by: 5) { if attributes[idx] == nil { continue } var attributeQName: String let attrLocalName = attributes[idx]! let attrPrefix = attributes[idx + 1] let attrPrefixLen = attrPrefix != nil ? strlen(UnsafePointer<Int8>(attrPrefix!)) : 0 if attrPrefixLen != 0 { attributeQName = _colonSeparatedStringFromPrefixAndSuffix(attrPrefix!, UInt(attrPrefixLen), attrLocalName, UInt(strlen((UnsafePointer<Int8>(attrLocalName))))) } else { attributeQName = UTF8STRING(attrLocalName)! } // idx+2 = URI, which we throw away // idx+3 = value, i+4 = endvalue // By using XML_PARSE_NOENT the attribute value string will already have entities resolved var attributeValue = "" if attributes[idx + 3] != nil && attributes[idx + 4] != nil { let numBytesWithoutTerminator = attributes[idx + 4]! - attributes[idx + 3]! let numBytesWithTerminator = numBytesWithoutTerminator + 1 if numBytesWithoutTerminator != 0 { var chars = [Int8](repeating: 0, count: numBytesWithTerminator) attributeValue = chars.withUnsafeMutableBufferPointer({ (buffer: inout UnsafeMutableBufferPointer<Int8>) -> String in strncpy(buffer.baseAddress!, UnsafePointer<Int8>(attributes[idx + 3]!), numBytesWithoutTerminator) //not strlcpy because attributes[i+3] is not Nul terminated return UTF8STRING(UnsafePointer<UInt8>(buffer.baseAddress!))! }) } attrDict[attributeQName] = attributeValue } } if let delegate = parser.delegate { if reportQNameURI { delegate.parser(parser, didStartElement: localnameString!, namespaceURI: (namespaceURIString != nil ? namespaceURIString : ""), qualifiedName: (qualifiedNameString != nil ? qualifiedNameString : ""), attributes: attrDict) } else { delegate.parser(parser, didStartElement: qualifiedNameString!, namespaceURI: nil, qualifiedName: nil, attributes: attrDict) } } } internal func _NSXMLParserEndElementNs(_ ctx: _CFXMLInterface , localname: UnsafePointer<UInt8>, prefix: UnsafePointer<UInt8>?, URI: UnsafePointer<UInt8>) -> Void { let parser = ctx.parser let reportQNameURI = parser.shouldProcessNamespaces let prefixLen = prefix != nil ? strlen(UnsafePointer<Int8>(prefix!)) : 0 let localnameString = (prefixLen == 0 || reportQNameURI) ? UTF8STRING(localname) : nil let nilStr: String? = nil let qualifiedNameString = (prefixLen != 0) ? _colonSeparatedStringFromPrefixAndSuffix(prefix!, UInt(prefixLen), localname, UInt(strlen(UnsafePointer<Int8>(localname)))) : nilStr let namespaceURIString = reportQNameURI ? UTF8STRING(URI) : nilStr if let delegate = parser.delegate { if reportQNameURI { // When reporting namespace info, the delegate parameters are not passed in nil delegate.parser(parser, didEndElement: localnameString!, namespaceURI: namespaceURIString == nil ? "" : namespaceURIString, qualifiedName: qualifiedNameString == nil ? "" : qualifiedNameString) } else { delegate.parser(parser, didEndElement: qualifiedNameString!, namespaceURI: nil, qualifiedName: nil) } } // Pop the last namespaces that were pushed (safe since XML is balanced) parser._popNamespaces() } internal func _NSXMLParserCharacters(_ ctx: _CFXMLInterface, ch: UnsafePointer<UInt8>, len: Int32) -> Void { let parser = ctx.parser let context = parser._parserContext! if _CFXMLInterfaceInRecursiveState(context) != 0 { _CFXMLInterfaceResetRecursiveState(context) } else { if let delegate = parser.delegate { let str = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: ch, count: Int(len))) delegate.parser(parser, foundCharacters: str!) } } } internal func _NSXMLParserProcessingInstruction(_ ctx: _CFXMLInterface, target: UnsafePointer<UInt8>, data: UnsafePointer<UInt8>) -> Void { let parser = ctx.parser if let delegate = parser.delegate { let targetString = UTF8STRING(target)! let dataString = UTF8STRING(data) delegate.parser(parser, foundProcessingInstructionWithTarget: targetString, data: dataString) } } internal func _NSXMLParserCdataBlock(_ ctx: _CFXMLInterface, value: UnsafePointer<UInt8>, len: Int32) -> Void { let parser = ctx.parser if let delegate = parser.delegate { delegate.parser(parser, foundCDATA: NSData(bytes: UnsafePointer<Void>(value), length: Int(len))) } } internal func _NSXMLParserComment(_ ctx: _CFXMLInterface, value: UnsafePointer<UInt8>) -> Void { let parser = ctx.parser if let delegate = parser.delegate { let comment = UTF8STRING(value)! delegate.parser(parser, foundComment: comment) } } internal func _NSXMLParserExternalSubset(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, ExternalID: UnsafePointer<UInt8>, SystemID: UnsafePointer<UInt8>) -> Void { _CFXMLInterfaceSAX2ExternalSubset(ctx.parser._parserContext, name, ExternalID, SystemID) } internal func _structuredErrorFunc(_ interface: _CFXMLInterface, error: _CFXMLInterfaceError) { let err = _CFErrorCreateFromXMLInterface(error)._nsObject let parser = interface.parser parser._parserError = err if let delegate = parser.delegate { delegate.parser(parser, parseErrorOccurred: err) } } public class NSXMLParser : NSObject { private var _handler: _CFXMLInterfaceSAXHandler internal var _stream: NSInputStream? internal var _data: NSData? internal var _chunkSize = Int(4096 * 32) // a suitably large number for a decent chunk size internal var _haveDetectedEncoding = false internal var _bomChunk: NSData? private var _parserContext: _CFXMLInterfaceParserContext? internal var _delegateAborted = false internal var _url: NSURL? internal var _namespaces = [[String:String]]() // initializes the parser with the specified URL. public convenience init?(contentsOfURL url: NSURL) { if url.fileURL { if let stream = NSInputStream(URL: url) { self.init(stream: stream) _url = url } } else { if let data = NSData(contentsOfURL: url) { self.init(data: data) self._url = url } } return nil } // create the parser from data public init(data: NSData) { _CFSetupXMLInterface() _data = data.copy() as? NSData _handler = _CFXMLInterfaceCreateSAXHandler() _parserContext = nil } deinit { _CFXMLInterfaceDestroySAXHandler(_handler) _CFXMLInterfaceDestroyContext(_parserContext) } //create a parser that incrementally pulls data from the specified stream and parses it. public init(stream: NSInputStream) { _CFSetupXMLInterface() _stream = stream _handler = _CFXMLInterfaceCreateSAXHandler() _parserContext = nil } public weak var delegate: NSXMLParserDelegate? public var shouldProcessNamespaces: Bool = false public var shouldReportNamespacePrefixes: Bool = false //defaults to NSXMLNodeLoadExternalEntitiesNever public var externalEntityResolvingPolicy: NSXMLParserExternalEntityResolvingPolicy = .ResolveExternalEntitiesNever public var allowedExternalEntityURLs: Set<NSURL>? internal static func currentParser() -> NSXMLParser? { if let current = NSThread.currentThread().threadDictionary["__CurrentNSXMLParser"] { return current as? NSXMLParser } else { return nil } } internal static func setCurrentParser(_ parser: NSXMLParser?) { if let p = parser { NSThread.currentThread().threadDictionary["__CurrentNSXMLParser"] = p } else { NSThread.currentThread().threadDictionary.removeValue(forKey: "__CurrentNSXMLParser") } } internal func _handleParseResult(_ parseResult: Int32) -> Bool { return true /* var result = true if parseResult != 0 { if parseResult != -1 { // TODO: determine if this result is a fatal error from libxml via the CF implementations } } return result */ } internal func parseData(_ data: NSData) -> Bool { _CFXMLInterfaceSetStructuredErrorFunc(interface, _structuredErrorFunc) var result = true /* The vast majority of this method just deals with ensuring we do a single parse on the first 4 received bytes before continuing on to the actual incremental section */ if _haveDetectedEncoding { var totalLength = data.length if let chunk = _bomChunk { totalLength += chunk.length } if (totalLength < 4) { if let chunk = _bomChunk { let newData = NSMutableData() newData.append(chunk) newData.append(data) _bomChunk = newData } else { _bomChunk = data } } else { var allExistingData: NSData if let chunk = _bomChunk { let newData = NSMutableData() newData.append(chunk) newData.append(data) allExistingData = newData } else { allExistingData = data } var handler: _CFXMLInterfaceSAXHandler? = nil if delegate != nil { handler = _handler } _parserContext = _CFXMLInterfaceCreatePushParserCtxt(handler, interface, UnsafePointer<Int8>(allExistingData.bytes), 4, nil) var options = _kCFXMLInterfaceRecover | _kCFXMLInterfaceNoEnt // substitute entities, recover on errors if shouldResolveExternalEntities { options |= _kCFXMLInterfaceDTDLoad } if handler == nil { options |= (_kCFXMLInterfaceNoError | _kCFXMLInterfaceNoWarning) } _CFXMLInterfaceCtxtUseOptions(_parserContext, options) _haveDetectedEncoding = true _bomChunk = nil if (totalLength > 4) { let remainingData = NSData(bytesNoCopy: UnsafeMutablePointer<Void>(allExistingData.bytes.advanced(by: 4)), length: totalLength - 4, freeWhenDone: false) let _ = parseData(remainingData) } } } else { let parseResult = _CFXMLInterfaceParseChunk(_parserContext, UnsafePointer<Int8>(data.bytes), Int32(data.length), 0) result = _handleParseResult(parseResult) } _CFXMLInterfaceSetStructuredErrorFunc(interface, nil) return result } internal func parseFromStream() -> Bool { var result = true NSXMLParser.setCurrentParser(self) if let stream = _stream { stream.open() let buffer = malloc(_chunkSize)! var len = stream.read(UnsafeMutablePointer<UInt8>(buffer), maxLength: _chunkSize) if len != -1 { while len > 0 { let data = NSData(bytesNoCopy: buffer, length: len, freeWhenDone: false) result = parseData(data) len = stream.read(UnsafeMutablePointer<UInt8>(buffer), maxLength: _chunkSize) } } else { result = false } free(buffer) stream.close() } else if let data = _data { let buffer = malloc(_chunkSize)! var range = NSMakeRange(0, min(_chunkSize, data.length)) while result { data.getBytes(buffer, range: range) let chunk = NSData(bytesNoCopy: buffer, length: range.length, freeWhenDone: false) result = parseData(chunk) if range.location + range.length >= data.length { break } range = NSMakeRange(range.location + range.length, min(_chunkSize, data.length - (range.location + range.length))) } free(buffer) } else { result = false } NSXMLParser.setCurrentParser(nil) return result } // called to start the event-driven parse. Returns YES in the event of a successful parse, and NO in case of error. public func parse() -> Bool { return parseFromStream() } // called by the delegate to stop the parse. The delegate will get an error message sent to it. public func abortParsing() { if let context = _parserContext { _CFXMLInterfaceStopParser(context) _delegateAborted = true } } internal var _parserError: NSError? /*@NSCopying*/ public var parserError: NSError? { return _parserError } // can be called after a parse is over to determine parser state. //Toggles between disabling external entities entirely, and the current setting of the 'externalEntityResolvingPolicy'. //The 'externalEntityResolvingPolicy' property should be used instead of this, unless targeting 10.9/7.0 or earlier public var shouldResolveExternalEntities: Bool = false // Once a parse has begun, the delegate may be interested in certain parser state. These methods will only return meaningful information during parsing, or after an error has occurred. public var publicID: String? { return nil } public var systemID: String? { return nil } public var lineNumber: Int { return Int(_CFXMLInterfaceSAX2GetLineNumber(_parserContext)) } public var columnNumber: Int { return Int(_CFXMLInterfaceSAX2GetColumnNumber(_parserContext)) } internal func _pushNamespaces(_ ns: [String:String]) { _namespaces.append(ns) if let del = self.delegate { ns.forEach { del.parser(self, didStartMappingPrefix: $0.0, toURI: $0.1) } } } internal func _popNamespaces() { let ns = _namespaces.removeLast() if let del = self.delegate { ns.forEach { del.parser(self, didEndMappingPrefix: $0.0) } } } } /* For the discussion of event methods, assume the following XML: <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type='text/css' href='cvslog.css'?> <!DOCTYPE cvslog SYSTEM "cvslog.dtd"> <cvslog xmlns="http://xml.apple.com/cvslog"> <radar:radar xmlns:radar="http://xml.apple.com/radar"> <radar:bugID>2920186</radar:bugID> <radar:title>API/NSXMLParser: there ought to be an NSXMLParser</radar:title> </radar:radar> </cvslog> */ // The parser's delegate is informed of events through the methods in the NSXMLParserDelegateEventAdditions category. public protocol NSXMLParserDelegate : class { // Document handling methods func parserDidStartDocument(_ parser: NSXMLParser) // sent when the parser begins parsing of the document. func parserDidEndDocument(_ parser: NSXMLParser) // sent when the parser has completed parsing. If this is encountered, the parse was successful. // DTD handling methods for various declarations. func parser(_ parser: NSXMLParser, foundNotationDeclarationWithName name: String, publicID: String?, systemID: String?) func parser(_ parser: NSXMLParser, foundUnparsedEntityDeclarationWithName name: String, publicID: String?, systemID: String?, notationName: String?) func parser(_ parser: NSXMLParser, foundAttributeDeclarationWithName attributeName: String, forElement elementName: String, type: String?, defaultValue: String?) func parser(_ parser: NSXMLParser, foundElementDeclarationWithName elementName: String, model: String) func parser(_ parser: NSXMLParser, foundInternalEntityDeclarationWithName name: String, value: String?) func parser(_ parser: NSXMLParser, foundExternalEntityDeclarationWithName name: String, publicID: String?, systemID: String?) func parser(_ parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) // sent when the parser finds an element start tag. // In the case of the cvslog tag, the following is what the delegate receives: // elementName == cvslog, namespaceURI == http://xml.apple.com/cvslog, qualifiedName == cvslog // In the case of the radar tag, the following is what's passed in: // elementName == radar, namespaceURI == http://xml.apple.com/radar, qualifiedName == radar:radar // If namespace processing >isn't< on, the xmlns:radar="http://xml.apple.com/radar" is returned as an attribute pair, the elementName is 'radar:radar' and there is no qualifiedName. func parser(_ parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) // sent when an end tag is encountered. The various parameters are supplied as above. func parser(_ parser: NSXMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String) // sent when the parser first sees a namespace attribute. // In the case of the cvslog tag, before the didStartElement:, you'd get one of these with prefix == @"" and namespaceURI == @"http://xml.apple.com/cvslog" (i.e. the default namespace) // In the case of the radar:radar tag, before the didStartElement: you'd get one of these with prefix == @"radar" and namespaceURI == @"http://xml.apple.com/radar" func parser(_ parser: NSXMLParser, didEndMappingPrefix prefix: String) // sent when the namespace prefix in question goes out of scope. func parser(_ parser: NSXMLParser, foundCharacters string: String) // This returns the string of the characters encountered thus far. You may not necessarily get the longest character run. The parser reserves the right to hand these to the delegate as potentially many calls in a row to -parser:foundCharacters: func parser(_ parser: NSXMLParser, foundIgnorableWhitespace whitespaceString: String) // The parser reports ignorable whitespace in the same way as characters it's found. func parser(_ parser: NSXMLParser, foundProcessingInstructionWithTarget target: String, data: String?) // The parser reports a processing instruction to you using this method. In the case above, target == @"xml-stylesheet" and data == @"type='text/css' href='cvslog.css'" func parser(_ parser: NSXMLParser, foundComment comment: String) // A comment (Text in a <!-- --> block) is reported to the delegate as a single string func parser(_ parser: NSXMLParser, foundCDATA CDATABlock: NSData) // this reports a CDATA block to the delegate as an NSData. func parser(_ parser: NSXMLParser, resolveExternalEntityName name: String, systemID: String?) -> NSData? // this gives the delegate an opportunity to resolve an external entity itself and reply with the resulting data. func parser(_ parser: NSXMLParser, parseErrorOccurred parseError: NSError) // ...and this reports a fatal error to the delegate. The parser will stop parsing. func parser(_ parser: NSXMLParser, validationErrorOccurred validationError: NSError) } extension NSXMLParserDelegate { func parserDidStartDocument(_ parser: NSXMLParser) { } func parserDidEndDocument(_ parser: NSXMLParser) { } func parser(_ parser: NSXMLParser, foundNotationDeclarationWithName name: String, publicID: String?, systemID: String?) { } func parser(_ parser: NSXMLParser, foundUnparsedEntityDeclarationWithName name: String, publicID: String?, systemID: String?, notationName: String?) { } func parser(_ parser: NSXMLParser, foundAttributeDeclarationWithName attributeName: String, forElement elementName: String, type: String?, defaultValue: String?) { } func parser(_ parser: NSXMLParser, foundElementDeclarationWithName elementName: String, model: String) { } func parser(_ parser: NSXMLParser, foundInternalEntityDeclarationWithName name: String, value: String?) { } func parser(_ parser: NSXMLParser, foundExternalEntityDeclarationWithName name: String, publicID: String?, systemID: String?) { } func parser(_ parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { } func parser(_ parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { } func parser(_ parser: NSXMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String) { } func parser(_ parser: NSXMLParser, didEndMappingPrefix prefix: String) { } func parser(_ parser: NSXMLParser, foundCharacters string: String) { } func parser(_ parser: NSXMLParser, foundIgnorableWhitespace whitespaceString: String) { } func parser(_ parser: NSXMLParser, foundProcessingInstructionWithTarget target: String, data: String?) { } func parser(_ parser: NSXMLParser, foundComment comment: String) { } func parser(_ parser: NSXMLParser, foundCDATA CDATABlock: NSData) { } func parser(_ parser: NSXMLParser, resolveExternalEntityName name: String, systemID: String?) -> NSData? { return nil } func parser(_ parser: NSXMLParser, parseErrorOccurred parseError: NSError) { } func parser(_ parser: NSXMLParser, validationErrorOccurred validationError: NSError) { } } // If validation is on, this will report a fatal validation error to the delegate. The parser will stop parsing. public let NSXMLParserErrorDomain: String = "NSXMLParserErrorDomain" // for use with NSError. // Error reporting public enum NSXMLParserError : Int { case InternalError case OutOfMemoryError case DocumentStartError case EmptyDocumentError case PrematureDocumentEndError case InvalidHexCharacterRefError case InvalidDecimalCharacterRefError case InvalidCharacterRefError case InvalidCharacterError case CharacterRefAtEOFError case CharacterRefInPrologError case CharacterRefInEpilogError case CharacterRefInDTDError case EntityRefAtEOFError case EntityRefInPrologError case EntityRefInEpilogError case EntityRefInDTDError case ParsedEntityRefAtEOFError case ParsedEntityRefInPrologError case ParsedEntityRefInEpilogError case ParsedEntityRefInInternalSubsetError case EntityReferenceWithoutNameError case EntityReferenceMissingSemiError case ParsedEntityRefNoNameError case ParsedEntityRefMissingSemiError case UndeclaredEntityError case UnparsedEntityError case EntityIsExternalError case EntityIsParameterError case UnknownEncodingError case EncodingNotSupportedError case StringNotStartedError case StringNotClosedError case NamespaceDeclarationError case EntityNotStartedError case EntityNotFinishedError case LessThanSymbolInAttributeError case AttributeNotStartedError case AttributeNotFinishedError case AttributeHasNoValueError case AttributeRedefinedError case LiteralNotStartedError case LiteralNotFinishedError case CommentNotFinishedError case ProcessingInstructionNotStartedError case ProcessingInstructionNotFinishedError case NotationNotStartedError case NotationNotFinishedError case AttributeListNotStartedError case AttributeListNotFinishedError case MixedContentDeclNotStartedError case MixedContentDeclNotFinishedError case ElementContentDeclNotStartedError case ElementContentDeclNotFinishedError case XMLDeclNotStartedError case XMLDeclNotFinishedError case ConditionalSectionNotStartedError case ConditionalSectionNotFinishedError case ExternalSubsetNotFinishedError case DOCTYPEDeclNotFinishedError case MisplacedCDATAEndStringError case CDATANotFinishedError case MisplacedXMLDeclarationError case SpaceRequiredError case SeparatorRequiredError case NMTOKENRequiredError case NAMERequiredError case PCDATARequiredError case URIRequiredError case PublicIdentifierRequiredError case LTRequiredError case GTRequiredError case LTSlashRequiredError case EqualExpectedError case TagNameMismatchError case UnfinishedTagError case StandaloneValueError case InvalidEncodingNameError case CommentContainsDoubleHyphenError case InvalidEncodingError case ExternalStandaloneEntityError case InvalidConditionalSectionError case EntityValueRequiredError case NotWellBalancedError case ExtraContentError case InvalidCharacterInEntityError case ParsedEntityRefInInternalError case EntityRefLoopError case EntityBoundaryError case InvalidURIError case URIFragmentError case NoDTDError case DelegateAbortedParseError }
apache-2.0
940aa3856c7b2d51940e97b99348ce9b
42.720657
344
0.676752
5.028348
false
false
false
false
dche/GLMath
Sources/Float.swift
1
5235
// // GLMath - Float.swift // // Float scalar and vector types. // // Copyright (c) 2017 The GLMath authors. // Licensed under MIT License. /// Approximate equatable. public protocol ApproxEquatable { /// The underlying float pointing number type for comparison. associatedtype InexactNumber: FloatingPoint /// Approximate comparison. /// /// - parameter to: Other number to be compared. /// - parameter tolerance: If `to` is zero, this is the maximal absolute /// difference, other wise, it is the maximal relative error. On the /// latter case, `1.ulp` or its small mutiple are appropriate values. /// - returns: `true` if `self` is close to `to`. func isClose(to: Self, tolerance: InexactNumber) -> Bool } /// Approximate equality operator. /// /// The default implementation provided by `ApproxEquatable` just calls /// `isClose(to:tolerance:)` with `tolerance` set to `.epsilon`. infix operator ~== : ComparisonPrecedence extension ApproxEquatable { public static func ~== (lhs: Self, rhs: Self) -> Bool { return lhs.isClose(to: rhs, tolerance: Self.InexactNumber.ulpOfOne) } } /// Generic floating point number type that applies to both scalar and /// vector numbers. public protocol GenericFloat: GenericSignedNumber, ApproxEquatable, Interpolatable { var fract: Self { get } var recip: Self { get } var rsqrt: Self { get } func step(_ edge: Self) -> Self } /// Type for primitive floating point types. Adopted by `Float` and `Double`. public protocol BaseFloat: BaseNumber, GenericFloat, BinaryFloatingPoint where InexactNumber == Self, InterpolatableNumber == Self { var sin: Self { get } var cos: Self { get } var acos: Self { get } var sqrt: Self { get } var frexp: (Self, Int) { get } func ldexp(_ exp: Int) -> Self } extension BaseFloat { public var signum: Self { guard self != 0 else { return Self.zero } switch self.sign { case .minus: return -Self.one case .plus: return Self.one } } public func isClose(to other: Self, tolerance: Self = Self.epsilon) -> Bool { if other.isZero { return abs(self) <= tolerance } let diff = abs(self - other) let m = max(abs(self), abs(other)) return diff <= m * tolerance } public func interpolate(_ y: Self, t: Self) -> Self { return self * (Self.one - t) + y * t } } extension Float: BaseFloat { public typealias InexactNumber = Float public typealias InterpolatableNumber = Float public static let zero: Float = 0 public static let one: Float = 1 } extension Double: BaseFloat { public typealias InexactNumber = Double public typealias InterpolatableNumber = Double public static let zero: Double = 0 public static let one: Double = 1 } /// Float number vector. public protocol FloatVector: NumericVector, GenericFloat where Component: BaseFloat, Component == InexactNumber { var length: Component { get } var normalize: Self { get } func distance(to other: Self) -> Component func dot(_ other: Self) -> Component func mix(_ other: Self, t: Self) -> Self func smoothstep(_ edge0: Self, _ edge1: Self) -> Self } extension FloatVector { public func isClose( to other: Self, tolerance: Component = .epsilon ) -> Bool { for i in 0 ..< Self.dimension { guard self[i].isClose(to: other[i], tolerance: tolerance) else { return false } } return true } } extension FloatVector where Component == InterpolatableNumber { public func interpolate(_ y: Self, t: Component) -> Self { return self.mix(y, t: Self(t)) } /// Geometric Slerp. public func slerp(_ y: Self, t: Component) -> Self { let theta = self.angle(between: y) if theta ~== 0 || theta ~== .pi { return self.interpolate(y, t: t) } let a = (theta - t * theta).sin let b = (t * theta).sin let c = (theta).sin.recip let d = self * a let e = y * b return (d + e) * c } } public protocol FloatVector2: FloatVector, Vector2 {} extension FloatVector2 { public static var x: Self { return self.init(1, 0) } public static var y: Self { return self.init(0, 1) } } public protocol FloatVector3: FloatVector, Vector3 where AssociatedVector2: FloatVector2 { // Generic `cross` method declaration. func cross(_ y: Self) -> Self } extension FloatVector3 { public static var x: Self { return self.init(1, 0, 0) } public static var y: Self { return self.init(0, 1, 0) } public static var z: Self { return self.init(0, 0, 1) } } public protocol FloatVector4: FloatVector, Vector4 where AssociatedVector2: FloatVector2, AssociatedVector3: FloatVector3 {} extension FloatVector4 { public static var x: Self { return self.init(1, 0, 0, 0) } public static var y: Self { return self.init(0, 1, 0, 0) } public static var z: Self { return self.init(0, 0, 1, 0) } public static var w: Self { return self.init(0, 0, 0, 1) } }
mit
79ee7b86f2df60a33a7937a23504cefa
25.846154
84
0.627125
3.89799
false
false
false
false
michals92/iOS_skautIS
skautIS/AddressBookSearchVC.swift
1
9737
// // AdressBookSearchVC.swift // skautIS // // Copyright (c) 2015, Michal Simik // All rights reserved. // import UIKit import SWXMLHash class AdressBookSearchVC: UITableViewController, UITextFieldDelegate, NSURLConnectionDelegate, UIPickerViewDataSource, UIPickerViewDelegate { //variables @IBOutlet weak var nameField: UITextField! @IBOutlet weak var phoneField: UITextField! @IBOutlet weak var emailField: UITextField! @IBOutlet weak var areaField: UITextField! @IBOutlet weak var activityField: UITextField! @IBOutlet weak var unitNameField: UITextField! @IBOutlet weak var numberUnitField: UITextField! var registrationNumberStartWith:Bool = true var result : String! var dataObject : [String] = ["všechny", "Angličtina", "Ekonomika", "Francouzština", "Informatika", "Jiný cizí jazyk", "Lékařství", "Němčina", "Pedagogika", "Právo", "Překladatelství", "Přírodní vědy", "Ruština", "Řemeslo", "Stavebnictví", "Španělština", "Teologie", "Veřejná správa", "Žurnalistika"]; /** Initial method. Delegates all fields to variables in class. */ override func viewDidLoad() { activityField.text = "všechny" super.viewDidLoad() let picker = UIPickerView() picker.delegate = self picker.dataSource = self self.activityField.inputView = picker self.phoneField.delegate = self; self.nameField.delegate = self; self.emailField.delegate = self; self.areaField.delegate = self; self.activityField.delegate = self; self.unitNameField.delegate = self; self.numberUnitField.delegate = self; } override func viewWillAppear(animated: Bool){ super.viewWillAppear(animated) self.navigationController?.setToolbarHidden(false, animated: animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /** Starts search in web service on button tap. @param sender is tapped search button */ @IBAction func actionSearch(sender: UIBarButtonItem) { var name = nameField.text var area = areaField.text var phone = phoneField.text var email = emailField.text var activity = activityField.text var unitName = unitNameField.text var registrationNumber = numberUnitField.text var storage = Storage() var login = storage.loader("login") var somethingFilled:Bool = false var personAllCatalog = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><PersonAllCatalog xmlns='https://is.skaut.cz/'><personAllCatalogInput><ID_Login>\(login)</ID_Login>" //appends all parameters if name != "" { personAllCatalog += "<Name>\(name)</Name>" somethingFilled = true } if area != "" { personAllCatalog += "<City>\(area)</City>" somethingFilled = true } if registrationNumber != "" { personAllCatalog += "<RegistrationNumber>\(registrationNumber)</RegistrationNumber>" somethingFilled = true } if registrationNumberStartWith == true { personAllCatalog += "<RegistrationNumberStartWith>\(registrationNumberStartWith)</RegistrationNumberStartWith>" } if unitName != "" { personAllCatalog += "<Unit>\(unitName)</Unit>" somethingFilled = true } if phone != "" { personAllCatalog += "<Phone>\(phone)</Phone>" somethingFilled = true } if email != "" { personAllCatalog += "<Email>\(email)</Email>" somethingFilled = true } if activity != "" { switch activity { case "Angličtina": personAllCatalog += "<ID_OfferType>16</ID_OfferType>" case "Ekonomika": personAllCatalog += "<ID_OfferType>5</ID_OfferType>" case "Francouzština": personAllCatalog += "<ID_OfferType>18</ID_OfferType>" case "Informatika": personAllCatalog += "<ID_OfferType>9</ID_OfferType>" case "Jiný cizí jazyk": personAllCatalog += "<ID_OfferType>21</ID_OfferType>" case "Lékařství": personAllCatalog += "<ID_OfferType>6</ID_OfferType>" case "Němčina": personAllCatalog += "<ID_OfferType>17</ID_OfferType>" case "Pedagogika": personAllCatalog += "<ID_OfferType>15</ID_OfferType>" case "Právo": personAllCatalog += "<ID_OfferType>4</ID_OfferType>" case "Překladatelství": personAllCatalog += "<ID_OfferType>10</ID_OfferType>" case "Přírodní vědy": personAllCatalog += "<ID_OfferType>11</ID_OfferType>" case "Ruština": personAllCatalog += "<ID_OfferType>20</ID_OfferType>" case "Řemeslo": personAllCatalog += "<ID_OfferType>14</ID_OfferType>" case "Stavebnictví": personAllCatalog += "<ID_OfferType>13</ID_OfferType>" case "Španělština": personAllCatalog += "<ID_OfferType>19</ID_OfferType>" case "Teologie": personAllCatalog += "<ID_OfferType>12</ID_OfferType>" case "Veřejná správa": personAllCatalog += "<ID_OfferType>8</ID_OfferType>" case "Žurnalistika": personAllCatalog += "<ID_OfferType>7</ID_OfferType>" default: personAllCatalog += "" } } //if no parameter was specified if (somethingFilled == false) { var alertTitle = "Nebyly zadány parametry hledání" var message = "Zadejte, prosím, více parametrů." var okText = "Rozumím" let alert = UIAlertController(title: alertTitle, message: message, preferredStyle: UIAlertControllerStyle.Alert) let okButton = UIAlertAction(title: okText, style: UIAlertActionStyle.Cancel, handler: nil) alert.addAction(okButton) presentViewController(alert, animated: true, completion: nil) } else { //appends end of request personAllCatalog += "</personAllCatalogInput></PersonAllCatalog></soap:Body></soap:Envelope>" //performs request var urlString = "http://test-is.skaut.cz/JunakWebservice/OrganizationUnit.asmx" var request: Request = Request(request: personAllCatalog,urlString: urlString) result = request.getAnswer(self) //parses returned string, if nothing was found show error var xml = SWXMLHash.parse(result) if (xml["soap:Envelope"]["soap:Body"]["PersonAllCatalogResponse"]["PersonAllCatalogResult"]["PersonAllCatalogOutput"].all.count == 0) { var alertTitle = "Nic nenalezeno" var message = "Zkuste opakovat hledání s jinými parametry." var okText = "Rozumím" let alert = UIAlertController(title: alertTitle, message: message, preferredStyle: UIAlertControllerStyle.Alert) let okButton = UIAlertAction(title: okText, style: UIAlertActionStyle.Cancel, handler: nil) alert.addAction(okButton) presentViewController(alert, animated: true, completion: nil) } else { self.performSegueWithIdentifier("listVC", sender: self) } } } /** UISwitch method. */ @IBAction func stateChanged(sender: UISwitch) { if sender.on { registrationNumberStartWith = true } else { registrationNumberStartWith = false } } /** Prepare for segue to listVC of loaded contacts */ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if (segue.identifier == "listVC"){ let vc = segue.destinationViewController as! AddressBookShowVC vc.stringData = self.result! } } /** Pickerview methods. */ func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1; } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return self.dataObject.count; } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { return self.dataObject[row]; } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { self.activityField.text = self.dataObject[row]; self.activityField.endEditing(true) } func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEditing(true); return false; } }
bsd-3-clause
b209b3bbe8da40d0b1226b3f185af8c9
36.343629
350
0.579301
4.618911
false
false
false
false
caronae/caronae-ios
Caronae/Place selection/ZoneSelectionInputViewController.swift
1
1246
import UIKit class ZoneSelectionInputViewController: UIViewController { weak var delegate: SelectionDelegate? @IBOutlet weak var neighborhoodTextField: CaronaeTextField! override func loadView() { Bundle.main.loadNibNamed("ZoneSelectionInput", owner: self, options: nil) } override func viewDidLoad() { super.viewDidLoad() self.title = "Outra região" self.navigationController?.view.backgroundColor = .white self.navigationController?.navigationBar.backgroundColor = .white self.edgesForExtendedLayout = [] navigationItem.rightBarButtonItem = UIBarButtonItem(title: "OK", style: .done, target: self, action: #selector(didTapDoneButton)) neighborhoodTextField.becomeFirstResponder() } func finishSelection() { self.navigationController?.popToRootViewController(animated: true) delegate?.hasSelected(selections: [self.neighborhoodTextField.text!], inFirstLevel: CaronaeOtherNeighborhoodsText) } @objc func didTapDoneButton() { if let location = neighborhoodTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines), !location.isEmpty { finishSelection() } } }
gpl-3.0
b0bbef6a606fa26adc2c02db23d7fb21
34.571429
137
0.700402
5.209205
false
false
false
false
oacastefanita/PollsFramework
Example/PollsFramework/AppDelegate.swift
1
8460
// // AppDelegate.swift // PollsFramework // // Created by oacastefanita on 06/27/2017. // Copyright (c) 2017 oacastefanita. All rights reserved. // import UIKit import PollsFramework import UserNotifications import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var window: UIWindow? var persistentContainer: NSPersistentContainer! func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. PollsFrameworkController.sharedInstance.setupWithBaseURL("https://demo.honeyshyam.com/api/v1", window: window!) PollsFrameworkController.sharedInstance.dataController().initializeManagedObjectContext(context:managedObjectContext) requestNotificationsPermission() MKStoreKit.shared().startProductRequest() 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. do{ try PollsFrameworkController.sharedInstance.dataController().managedObjectContext.save() } catch { print(error) } } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { var newToken: String = "" for i in 0..<deviceToken.count { newToken += String(format: "%02.2hhx", deviceToken[i] as CVarArg) } APP_SESSION.pushNotificationsToken = newToken PollsFrameworkController.sharedInstance.setupDevice(newToken, name: UIDevice.current.name, systemVersion: UIDevice.current.systemName, OSX: false) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print(error) APP_SESSION.pushNotificationsToken = "Notifications are not suported in the simulator" PollsFrameworkController.sharedInstance.setupDevice(APP_SESSION.pushNotificationsToken!, name: UIDevice.current.name, systemVersion: UIDevice.current.systemName, OSX: false) } @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { } @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { } func requestNotificationsPermission(){ if #available(iOS 10.0, *) { let center = UNUserNotificationCenter.current() center.delegate = self center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in if error == nil{ DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } } else { UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)) UIApplication.shared.registerForRemoteNotifications() } } lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.yachtingtrader.Yachting_Trader" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let frameworkBundle = Bundle(identifier: "org.cocoapods.PollsFramework") let modelURL = frameworkBundle!.url(forResource: "PollsFrameworkDataModel", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") //CustomAlertView.showAlert("\(wrappedError.userInfo)", subtitle: "Please remove and install again the app.", firstBtnTitle: "Ok",type: .warning, completionHandler: { (accept) in abort() //}) } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() }
mit
3aad739b2a8cc85245f8109b6e7501f7
55.02649
291
0.71643
5.774744
false
false
false
false
freshOS/ws
Sources/ws/WSError.swift
2
3526
// // WSError.swift // ws // // Created by Sacha Durand Saint Omer on 06/04/16. // Copyright © 2016 s4cha. All rights reserved. // import Arrow import Foundation public struct WSError: Error { public enum Status: Int { case unknown = -1 case networkUnreachable = 0 case unableToParseResponse = 1 // 4xx Client Error case badRequest = 400 case unauthorized = 401 case paymentRequired = 402 case forbidden = 403 case notFound = 404 case methodNotAllowed = 405 case notAcceptable = 406 case proxyAuthenticationRequired = 407 case requestTimeout = 408 case conflict = 409 case gone = 410 case lengthRequired = 411 case preconditionFailed = 412 case payloadTooLarge = 413 case uriTooLong = 414 case unsupportedMediaType = 415 case rangeNotSatisfiable = 416 case expectationFailed = 417 case teapot = 418 case misdirectedRequest = 421 case unprocessableEntity = 422 case locked = 423 case failedDependency = 424 case upgradeRequired = 426 case preconditionRequired = 428 case tooManyRequests = 429 case requestHeaderFieldsTooLarge = 431 case unavailableForLegalReasons = 451 // 4xx nginx case noResponse = 444 case sslCertificateError = 495 case sslCertificateRequired = 496 case httpRequestSentToHTTPSPort = 497 case clientClosedRequest = 499 // 5xx Server Error case internalServerError = 500 case notImplemented = 501 case badGateway = 502 case serviceUnavailable = 503 case gatewayTimeout = 504 case httpVersionNotSupported = 505 case variantAlsoNegotiates = 506 case insufficientStorage = 507 case loopDetected = 508 case notExtended = 510 case networkAuthenticationRequired = 511 } public var status: Status public var code: Int { return status.rawValue } public var jsonPayload: JSON? public var responseData: Data? public init(httpStatusCode: Int) { self.status = Status(rawValue: httpStatusCode) ?? .unknown } } extension WSError: CustomStringConvertible { public var description: String { return String(describing: self.status) .replacingOccurrences(of: "(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", with: " ", options: [.regularExpression]) .capitalized } } extension WSError { public static var unableToParseResponse: WSError { return WSError(httpStatusCode: Status.unableToParseResponse.rawValue) } }
mit
a49a20e7631424cbbc1ef93bc8c1cfc2
33.558824
85
0.491064
5.875
false
false
false
false
lukaszwas/mcommerce-api
Sources/App/Models/CategoryFilter.swift
1
3357
import Vapor import FluentProvider import HTTP final class CategoryFilter: Model { static let name = "CatFil" let storage = Storage() // Columns var categoryId: Identifier var name: String var description: String var categoryFilterValues: Children<CategoryFilter, CategoryFilterValue> { return children(foreignIdKey: CategoryFilterValue.categoryFilterIdKey) } // Column names static let idKey = "id" static let categoryIdKey = "category_id" static let nameKey = "name" static let descriptionKey = "description" static let valuesKey = "values" // Init init( categoryId: Identifier, name: String, description: String ) { self.categoryId = categoryId self.name = name self.description = description } init(row: Row) throws { categoryId = try row.get(CategoryFilter.categoryIdKey) name = try row.get(CategoryFilter.nameKey) description = try row.get(CategoryFilter.descriptionKey) } // Serialize func makeRow() throws -> Row { var row = Row() try row.set(CategoryFilter.categoryIdKey, categoryId) try row.set(CategoryFilter.nameKey, name) try row.set(CategoryFilter.descriptionKey, description) return row } } // Preparation extension CategoryFilter: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.parent(Category.self, optional: true, unique: false, foreignIdKey: CategoryFilter.categoryIdKey) builder.string(CategoryFilter.nameKey) builder.string(CategoryFilter.descriptionKey) } } static func revert(_ database: Database) throws { try database.delete(self) } } // Json extension CategoryFilter: JSONConvertible { convenience init(json: JSON) throws { try self.init( categoryId: json.get(CategoryFilter.categoryIdKey), name: json.get(CategoryFilter.nameKey), description: json.get(CategoryFilter.descriptionKey) ) } func makeJSON() throws -> JSON { var json = JSON() try json.set(CategoryFilter.idKey, id) try json.set(CategoryFilter.categoryIdKey, categoryId) try json.set(CategoryFilter.nameKey, name) try json.set(CategoryFilter.descriptionKey, description) try json.set(CategoryFilter.valuesKey, categoryFilterValues.all().makeJSON()) return json } } // Http extension CategoryFilter: ResponseRepresentable { } // Update extension CategoryFilter: Updateable { public static var updateableKeys: [UpdateableKey<CategoryFilter>] { return [ UpdateableKey(CategoryFilter.nameKey, String.self) { categoryFilter, name in categoryFilter.name = name }, UpdateableKey(CategoryFilter.descriptionKey, String.self) { categoryFilter, description in categoryFilter.description = description }, UpdateableKey(CategoryFilter.categoryIdKey, Identifier.self) { categoryFilter, categoryId in categoryFilter.categoryId = categoryId } ] } }
mit
6aa76674894659d5228ecdf07b95b991
28.973214
116
0.640453
4.844156
false
false
false
false
LY-Coder/LYPlayer
LYPlayerExample/Item2/TableViewCell.swift
1
1103
// // TableViewCell.swift // LYPlayerExample // // Created by LY_Coder on 2017/11/28. // Copyright © 2017年 LYCoder. All rights reserved. // import UIKit class TableViewCell: UITableViewCell { var urlString: String = "" override func layoutSubviews() { super.layoutSubviews() // // 添加视频播放器 // contentView.addSubview(playerView) // // 设置视频播放器位置、大小 // playerView.snp.makeConstraints { (make) in // make.top.equalTo(contentView) // make.left.right.equalTo(contentView) // make.height.equalTo(playerView.snp.width).multipliedBy(9.0/16.0).priority(750) // } // // let url = URL(string: urlString) // player.replaceCurrentUrl(with: url) } // 播放视图 // lazy var playerView: LYHeadlineView = { // let playerView = LYHeadlineView(player: self.player) // // return playerView // }() // 播放器 // lazy var player: LYPlayer = { // let player = LYPlayer() // // return player // }() }
mit
4e192498495940ed1717dc3bf260057b
22.288889
88
0.579198
3.716312
false
false
false
false
CoderYLiu/30DaysOfSwift
Project 16 - SlideMenu/SlideMenu/MenuTransitionManager.swift
1
3072
// // MenuTransitionManager.swift // SlideMenu <https://github.com/DeveloperLY/30DaysOfSwift> // // Created by Liu Y on 16/4/22. // Copyright © 2016年 DeveloperLY. All rights reserved. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // import UIKit @objc protocol MenuTransitionManagerDelegate { func dismiss() } class MenuTransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { var duration = 0.5 var isPresenting = false var snapshot:UIView? { didSet { if let _delegate = delegate { let tapGestureRecognizer = UITapGestureRecognizer(target: _delegate, action: #selector(MenuTransitionManagerDelegate.dismiss)) snapshot?.addGestureRecognizer(tapGestureRecognizer) } } } var delegate:MenuTransitionManagerDelegate? func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)! let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)! let container = transitionContext.containerView let moveDown = CGAffineTransform(translationX: 0, y: container.frame.height - 150) let moveUp = CGAffineTransform(translationX: 0, y: -50) if isPresenting { toView.transform = moveUp snapshot = fromView.snapshotView(afterScreenUpdates: true) container.addSubview(toView) container.addSubview(snapshot!) } UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.3, options: UIViewAnimationOptions(), animations: { if self.isPresenting { self.snapshot?.transform = moveDown toView.transform = CGAffineTransform.identity } else { self.snapshot?.transform = CGAffineTransform.identity fromView.transform = moveUp } }, completion: { finished in transitionContext.completeTransition(true) if !self.isPresenting { self.snapshot?.removeFromSuperview() } }) } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = false return self } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = true return self } }
mit
d3bda03293d5e744dc07ff73d20f6338
33.1
170
0.643206
6.101392
false
false
false
false
NorthernRealities/ColorSenseRainbow
ColorSenseRainbow/RGBCalculatedSeeker.swift
1
6842
// // RGBCalculatedSeeker.swift // ColorSenseRainbow // // Created by Reid Gravelle on 2015-04-23. // Copyright (c) 2015 Northern Realities Inc. All rights reserved. // import AppKit class RGBCalculatedSeeker: Seeker { override init () { super.init() var error : NSError? var regex: NSRegularExpression? // Defines how the RGB component of the colour is specified for numbers >= zero. Numbers may be integer or floating point and intended to be between 0 and 255 inclusive but no bounds checking is performed. // Valid values: 0; 0.0; 255; 127.55 let swiftRBGComponentConst = "([0-9]+|[0-9]+\\.[0-9]+)" // Defines how the RGB component of the colour is specified for numbers >= zero. Numbers may be integer or floating point and intended to be between 0 and 255 inclusive but no bounds checking is performed. // The f is outside of the capture group so that converting the string to a number in the Builder will work. // Valid values: 0; 0.0; 255; 127.55, 0.0f 0.f 134.0 154.f 39.0f let objcRBGComponentConst = "([0-9]+|[0-9]+\\.[0-9]+)(?:f|\\.f)?" // Swift let commonSwiftRegex = "ed:\\s*" + swiftRBGComponentConst + "\\s*\\/\\s*" + swiftRBGComponentConst + "\\s*,\\s*green:\\s*" + swiftRBGComponentConst + "\\s*\\/\\s*" + swiftRBGComponentConst + "\\s*,\\s*blue:\\s*" + swiftRBGComponentConst + "\\s*\\/\\s*" + swiftRBGComponentConst + "\\s*" do { regex = try NSRegularExpression ( pattern: "(?:NS|UI)Color" + swiftInit + "\\s*\\(\\s*r" + commonSwiftRegex + ",\\s*alpha:\\s*" + swiftAlphaConst + "\\s*\\)", options: []) } catch let error1 as NSError { error = error1 regex = nil } if regex == nil { print ( "Error creating Swift RGB calculated float with alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } do { regex = try NSRegularExpression ( pattern: "(?:NS|UI)Color" + swiftInit + "\\s*\\(\\s*r" + commonSwiftRegex + "\\)", options: []) } catch let error1 as NSError { error = error1 regex = nil } if regex == nil { print ( "Error creating Swift RGB calculated float without alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } do { regex = try NSRegularExpression ( pattern: "NSColor" + swiftInit + "\\s*\\(\\s*(?:calibrated|device|SRGB)R" + commonSwiftRegex + ",\\s*alpha:\\s*" + swiftAlphaConst + "\\s*\\)", options: []) } catch let error1 as NSError { error = error1 regex = nil } if regex == nil { print ( "Error creating Swift NSColor calibrated, device, SRGB calculated float regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } // Objective-C - Only functions with alpha defined let commonObjCRegex = "Red:\\s*" + objcRBGComponentConst + "\\s*\\/\\s*" + objcRBGComponentConst + "\\s*green:\\s*" + objcRBGComponentConst + "\\s*\\/\\s*" + objcRBGComponentConst + "\\s*blue:\\s*" + objcRBGComponentConst + "\\s*\\/\\s*" + objcRBGComponentConst + "\\s*alpha:\\s*" + objcAlphaConst + "\\s*\\]" do { regex = try NSRegularExpression ( pattern: "\\[\\s*(?:NS|UI)Color\\s*colorWith" + commonObjCRegex, options: []) } catch let error1 as NSError { error = error1 regex = nil } if regex == nil { print ( "Error creating Objective-C RGB calculated float with alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } do { // Don't care about saving the Calibrated, Device, or SRGB since we assume that any function that // replace the values will do so selectively instead of overwriting the whole string. regex = try NSRegularExpression ( pattern: "\\[\\s*NSColor\\s*colorWith(?:Calibrated|Device|SRGB)" + commonObjCRegex, options: []) } catch let error1 as NSError { error = error1 regex = nil } if regex == nil { print ( "Error creating Objective-C calibrated, device, SRGB calculated float with alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } } override func processMatch ( match : NSTextCheckingResult, line : String ) -> SearchResult? { if ( ( match.numberOfRanges == 7 ) || ( match.numberOfRanges == 8 ) ) { var alphaValue : CGFloat = 1.0 let matchString = stringFromRange( match.range, line: line ) let redNomString = stringFromRange( match.rangeAtIndex( 1 ), line: line ) let redDenomString = stringFromRange( match.rangeAtIndex( 2 ), line: line ) let greenNomString = stringFromRange( match.rangeAtIndex( 3 ), line: line ) let greenDenomString = stringFromRange( match.rangeAtIndex( 4 ), line: line ) let blueNomString = stringFromRange( match.rangeAtIndex( 5 ), line: line ) let blueDenomString = stringFromRange( match.rangeAtIndex( 6 ), line: line ) var capturedStrings = [ matchString, redNomString, redDenomString, greenNomString, greenDenomString, blueNomString, blueDenomString ] if ( match.numberOfRanges == 8 ) { let alphaString = stringFromRange( match.rangeAtIndex( 7 ), line: line ) alphaValue = CGFloat ( ( alphaString as NSString).doubleValue ) capturedStrings.append( alphaString ) } let redValue = CGFloat ( ( ( redNomString as NSString).doubleValue ) / ( ( redDenomString as NSString ).doubleValue ) ) let greenValue = CGFloat ( ( ( greenNomString as NSString).doubleValue ) / ( ( greenDenomString as NSString ).doubleValue ) ) let blueValue = CGFloat ( ( ( blueNomString as NSString).doubleValue ) / ( ( blueDenomString as NSString ).doubleValue ) ) let color = NSColor ( red: redValue, green: greenValue, blue: blueValue, alpha: alphaValue ) var searchResult = SearchResult ( color: color, textCheckingResult: match, capturedStrings: capturedStrings ) searchResult.creationType = .RGBCalculated return searchResult } return nil } }
mit
f4e5e374ffae2a1584d53c1056b3b1ea
44.013158
317
0.570009
4.534129
false
false
false
false
GENG-GitHub/weibo-gd
GDWeibo/Class/Module/Compose/View/GDPlaceHolderTextView.swift
1
1974
// // GDPlaceHolderTextView.swift // GDWeibo // // Created by geng on 15/11/6. // Copyright © 2015年 geng. All rights reserved. // import UIKit class GDPlaceHolderTextView: UITextView { //MARK: - 属性 var placeholder: String? { didSet { //设置占位文本 placeholderLabel.text = placeholder placeholderLabel.sizeToFit() } } //MARK: - 构造方法 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) //设置UI prepareUI() //设置通知 NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewDidChange:", name: UITextViewTextDidChangeNotification, object: self) } //注销通知 deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } //MARK: - 准备UI private func prepareUI() { //添加子控件 addSubview(placeholderLabel) //设置约束 placeholderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: self, size: nil, offset: CGPoint(x: 5, y: 8)) } //MARK: - 懒加载 //添加占位文本 private lazy var placeholderLabel: UILabel = { let label = UILabel() //设置占位label属性 label.textColor = UIColor.lightGrayColor() label.font = UIFont.systemFontOfSize(18) label.sizeToFit() return label }() } //MARK: - UITextViewDelegate extension GDPlaceHolderTextView: UITextViewDelegate { func textViewDidChange(textView: UITextView) { //如果文本框有文字时,就隐藏label placeholderLabel.hidden = hasText() } }
apache-2.0
e71ef71ab32ff2fb526a21bdad3ba39b
19.775281
151
0.583559
4.878628
false
false
false
false
kstaring/swift
test/IDE/complete_value_expr.swift
3
104788
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_DOT_1 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_DOT_2 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_DOT_3 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_DOT_4 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_DOT_5 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_NO_DOT_1 | %FileCheck %s -check-prefix=FOO_OBJECT_NO_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_NO_DOT_2 | %FileCheck %s -check-prefix=FOO_OBJECT_NO_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_STRUCT_DOT_1 | %FileCheck %s -check-prefix=FOO_STRUCT_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_STRUCT_NO_DOT_1 | %FileCheck %s -check-prefix=FOO_STRUCT_NO_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_FUNC_0 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_FUNC_0 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_FUNC_1 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_FUNC_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_FUNC_2 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_FUNC_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_VARARG_FUNC_0 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_VARARG_FUNC_0 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_VARARG_FUNC_1 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_VARARG_FUNC_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_VARARG_FUNC_2 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_VARARG_FUNC_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_OVERLOADED_FUNC_1 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_OVERLOADED_FUNC_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_OVERLOADED_FUNC_2 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_OVERLOADED_FUNC_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_SWITCH_CASE_1 | %FileCheck %s -check-prefix=IN_SWITCH_CASE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_SWITCH_CASE_2 | %FileCheck %s -check-prefix=IN_SWITCH_CASE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_SWITCH_CASE_3 | %FileCheck %s -check-prefix=IN_SWITCH_CASE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_SWITCH_CASE_4 | %FileCheck %s -check-prefix=IN_SWITCH_CASE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VF1 | %FileCheck %s -check-prefix=VF1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VF2 | %FileCheck %s -check-prefix=VF2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=BASE_MEMBERS | %FileCheck %s -check-prefix=BASE_MEMBERS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=BASE_MEMBERS_STATIC | %FileCheck %s -check-prefix=BASE_MEMBERS_STATIC // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_NO_DOT_1 | %FileCheck %s -check-prefix=PROTO_MEMBERS_NO_DOT_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_NO_DOT_2 | %FileCheck %s -check-prefix=PROTO_MEMBERS_NO_DOT_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_NO_DOT_3 | %FileCheck %s -check-prefix=PROTO_MEMBERS_NO_DOT_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_1 | %FileCheck %s -check-prefix=PROTO_MEMBERS_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_2 | %FileCheck %s -check-prefix=PROTO_MEMBERS_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_3 | %FileCheck %s -check-prefix=PROTO_MEMBERS_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_4 | %FileCheck %s -check-prefix=PROTO_MEMBERS_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_0 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_0 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_1 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_2 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_3 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_4 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_5 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_6 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_6 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_7 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_7 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_8 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_8 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_9 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_9 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_10 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_10 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_11 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_11 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_12 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_12 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_VARARG_FUNCTION_CALL_1 | %FileCheck %s -check-prefix=INSIDE_VARARG_FUNCTION_CALL_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_VARARG_FUNCTION_CALL_2 | %FileCheck %s -check-prefix=INSIDE_VARARG_FUNCTION_CALL_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_VARARG_FUNCTION_CALL_3 | %FileCheck %s -check-prefix=INSIDE_VARARG_FUNCTION_CALL_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_OVERLOADED_FUNCTION_CALL_1 | %FileCheck %s -check-prefix=INSIDE_OVERLOADED_FUNCTION_CALL_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_1 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_2 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_3 | %FileCheck %s -check-prefix=RESOLVE_FUNC_PARAM_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_4 | %FileCheck %s -check-prefix=RESOLVE_FUNC_PARAM_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_5 | %FileCheck %s -check-prefix=RESOLVE_FUNC_PARAM_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_6 | %FileCheck %s -check-prefix=RESOLVE_FUNC_PARAM_6 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_CONSTRUCTOR_PARAM_1 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_CONSTRUCTOR_PARAM_2 | %FileCheck %s -check-prefix=RESOLVE_CONSTRUCTOR_PARAM_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_CONSTRUCTOR_PARAM_3 | %FileCheck %s -check-prefix=RESOLVE_CONSTRUCTOR_PARAM_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_PAREN_PATTERN_1 | %FileCheck %s -check-prefix=FUNC_PAREN_PATTERN_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_PAREN_PATTERN_2 | %FileCheck %s -check-prefix=FUNC_PAREN_PATTERN_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_PAREN_PATTERN_3 | %FileCheck %s -check-prefix=FUNC_PAREN_PATTERN_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CHAINED_CALLS_1 | %FileCheck %s -check-prefix=CHAINED_CALLS_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CHAINED_CALLS_2 | %FileCheck %s -check-prefix=CHAINED_CALLS_2 // Disabled because we aren't handling failures well. // FIXME: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CHAINED_CALLS_3 | %FileCheck %s -check-prefix=CHAINED_CALLS_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_1 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_2 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_3 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_4 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_5 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_ERROR_1 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_ERROR_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_1_STATIC | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_1_STATIC // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_2_STATIC | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_2_STATIC // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_3_STATIC | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_3_STATIC // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_4_STATIC | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_4_STATIC // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_5_STATIC | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_5_STATIC // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_UNSOLVED_VARIABLES_1 | %FileCheck %s -check-prefix=TC_UNSOLVED_VARIABLES_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_UNSOLVED_VARIABLES_2 | %FileCheck %s -check-prefix=TC_UNSOLVED_VARIABLES_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_UNSOLVED_VARIABLES_3 | %FileCheck %s -check-prefix=TC_UNSOLVED_VARIABLES_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_UNSOLVED_VARIABLES_4 | %FileCheck %s -check-prefix=TC_UNSOLVED_VARIABLES_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_MODULES_1 | %FileCheck %s -check-prefix=RESOLVE_MODULES_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INTERPOLATED_STRING_1 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_WILLCONFORMP1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_WILLCONFORMP1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_DIDCONFORMP2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_DIDCONFORMP2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_DIDCONFORMP3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_DIDCONFORMP3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_GENERICP1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_GENERICP1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_GENERICP2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_GENERICP2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_GENERICP3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_GENERICP3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P4 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONCRETE1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONCRETE2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONSTRAINED_GENERIC_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONSTRAINED_GENERIC_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INSIDE_CONCRETE1_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INSIDE_CONCRETE1_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONCRETE3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONCRETE3_SUB | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME_SUB // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONCRETE4 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONSTRAINED_GENERIC_3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONSTRAINED_GENERIC_3_SUB | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME_SUB // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INSIDE_CONCRETE2_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INSIDE_CONCRETE2_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_TA_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_TA // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_TA_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_TA // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INIT_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_INIT_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INIT_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_INIT_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P4_DOT_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P4_DOT_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P4_T_DOT_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_T_DOT_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_UNUSABLE_EXISTENTIAL | %FileCheck %s -check-prefix=PROTOCOL_EXT_UNUSABLE_EXISTENTIAL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_DEDUP_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_DEDUP_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_DEDUP_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_DEDUP_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_DEDUP_3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_DEDUP_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=THROWS1 | %FileCheck %s -check-prefix=THROWS1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=THROWS2 | %FileCheck %s -check-prefix=THROWS2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER_THROWS1 | %FileCheck %s -check-prefix=MEMBER_THROWS1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER_THROWS2 | %FileCheck %s -check-prefix=MEMBER_THROWS2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER_THROWS3 | %FileCheck %s -check-prefix=MEMBER_THROWS3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_THROWS1 | %FileCheck %s -check-prefix=INIT_THROWS1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AUTOCLOSURE1 > %t.autoclosure1 // RUN: %FileCheck %s -check-prefix=AUTOCLOSURE_STRING < %t.autoclosure1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AUTOCLOSURE2 > %t.autoclosure2 // RUN: %FileCheck %s -check-prefix=AUTOCLOSURE_STRING < %t.autoclosure2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AUTOCLOSURE3 > %t.autoclosure3 // RUN: %FileCheck %s -check-prefix=AUTOCLOSURE_STRING < %t.autoclosure3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AUTOCLOSURE4 > %t.autoclosure4 // RUN: %FileCheck %s -check-prefix=AUTOCLOSURE_STRING < %t.autoclosure4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AUTOCLOSURE5 > %t.autoclosure5 // RUN: %FileCheck %s -check-prefix=AUTOCLOSURE_STRING < %t.autoclosure5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GENERIC_TYPEALIAS_1 | %FileCheck %s -check-prefix=GENERIC_TYPEALIAS_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GENERIC_TYPEALIAS_2 | %FileCheck %s -check-prefix=GENERIC_TYPEALIAS_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=DEPRECATED_1 | %FileCheck %s -check-prefix=DEPRECATED_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=DOT_EXPR_NON_NOMINAL_1 | %FileCheck %s -check-prefix=DOT_EXPR_NON_NOMINAL_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=DOT_EXPR_NON_NOMINAL_2 | %FileCheck %s -check-prefix=DOT_EXPR_NON_NOMINAL_2 // Test code completion of expressions that produce a value. struct FooStruct { lazy var lazyInstanceVar = 0 var instanceVar = 0 mutating func instanceFunc0() {} mutating func instanceFunc1(_ a: Int) {} mutating func instanceFunc2(_ a: Int, b: inout Double) {} mutating func instanceFunc3(_ a: Int, _: (Float, Double)) {} mutating func instanceFunc4(_ a: Int?, b: Int!, c: inout Int?, d: inout Int!) {} mutating func instanceFunc5() -> Int? {} mutating func instanceFunc6() -> Int! {} mutating func instanceFunc7(a a: Int) {} mutating func instanceFunc8(_ a: (Int, Int)) {} mutating func instanceFunc9(@autoclosure a: () -> Int) {} mutating func varargInstanceFunc0(_ v: Int...) {} mutating func varargInstanceFunc1(_ a: Float, v: Int...) {} mutating func varargInstanceFunc2(_ a: Float, b: Double, v: Int...) {} mutating func overloadedInstanceFunc1() -> Int {} mutating func overloadedInstanceFunc1() -> Double {} mutating func overloadedInstanceFunc2(_ x: Int) -> Int {} mutating func overloadedInstanceFunc2(_ x: Double) -> Int {} mutating func builderFunc1(_ a: Int) -> FooStruct { return self } subscript(i: Int) -> Double { get { return Double(i) } set(v) { instanceVar = i } } subscript(i: Int, j: Int) -> Double { get { return Double(i + j) } set(v) { instanceVar = i + j } } mutating func selectorVoidFunc1(_ a: Int, b x: Float) {} mutating func selectorVoidFunc2(_ a: Int, b x: Float, c y: Double) {} mutating func selectorVoidFunc3(_ a: Int, b _: (Float, Double)) {} mutating func selectorStringFunc1(_ a: Int, b x: Float) -> String {} mutating func selectorStringFunc2(_ a: Int, b x: Float, c y: Double) -> String {} mutating func selectorStringFunc3(_ a: Int, b _: (Float, Double)) -> String{} struct NestedStruct {} class NestedClass {} enum NestedEnum {} // Cannot declare a nested protocol. // protocol NestedProtocol {} typealias NestedTypealias = Int static var staticVar: Int = 4 static func staticFunc0() {} static func staticFunc1(_ a: Int) {} static func overloadedStaticFunc1() -> Int {} static func overloadedStaticFunc1() -> Double {} static func overloadedStaticFunc2(_ x: Int) -> Int {} static func overloadedStaticFunc2(_ x: Double) -> Int {} } extension FooStruct { var extProp: Int { get { return 42 } set(v) {} } mutating func extFunc0() {} static var extStaticProp: Int { get { return 42 } set(v) {} } static func extStaticFunc0() {} struct ExtNestedStruct {} class ExtNestedClass {} enum ExtNestedEnum { case ExtEnumX(Int) } typealias ExtNestedTypealias = Int } var fooObject: FooStruct // FOO_OBJECT_DOT: Begin completions // FOO_OBJECT_DOT-NEXT: Decl[InstanceVar]/CurrNominal: lazyInstanceVar[#Int#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc2({#(a): Int#}, {#b: &Double#})[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc3({#(a): Int#}, {#(Float, Double)#})[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc4({#(a): Int?#}, {#b: Int!#}, {#c: &Int?#}, {#d: &Int!#})[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc5()[#Int?#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc6()[#Int!#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc7({#a: Int#})[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc8({#(a): (Int, Int)#})[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc9({#a: Int#})[#Void#]{{; name=.+$}} // // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc0({#(v): Int...#})[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc1({#(a): Float#}, {#v: Int...#})[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc2({#(a): Float#}, {#b: Double#}, {#v: Int...#})[#Void#]{{; name=.+$}} // // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc1()[#Int#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc1()[#Double#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc2({#(x): Int#})[#Int#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc2({#(x): Double#})[#Int#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: builderFunc1({#(a): Int#})[#FooStruct#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc1({#(a): Int#}, {#b: Float#})[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc2({#(a): Int#}, {#b: Float#}, {#c: Double#})[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc3({#(a): Int#}, {#b: (Float, Double)#})[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc1({#(a): Int#}, {#b: Float#})[#String#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc2({#(a): Int#}, {#b: Float#}, {#c: Double#})[#String#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc3({#(a): Int#}, {#b: (Float, Double)#})[#String#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceVar]/CurrNominal: extProp[#Int#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: extFunc0()[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: End completions // FOO_OBJECT_NO_DOT: Begin completions // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceVar]/CurrNominal: .lazyInstanceVar[#Int#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc0()[#Void#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc2({#(a): Int#}, {#b: &Double#})[#Void#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc3({#(a): Int#}, {#(Float, Double)#})[#Void#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc4({#(a): Int?#}, {#b: Int!#}, {#c: &Int?#}, {#d: &Int!#})[#Void#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc5()[#Int?#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc6()[#Int!#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc7({#a: Int#})[#Void#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc8({#(a): (Int, Int)#})[#Void#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc9({#a: Int#})[#Void#]{{; name=.+$}} // // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc0({#(v): Int...#})[#Void#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc1({#(a): Float#}, {#v: Int...#})[#Void#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc2({#(a): Float#}, {#b: Double#}, {#v: Int...#})[#Void#]{{; name=.+$}} // // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc1()[#Int#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc1()[#Double#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc2({#(x): Int#})[#Int#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc2({#(x): Double#})[#Int#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .builderFunc1({#(a): Int#})[#FooStruct#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}][#Double#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}, {#Int#}][#Double#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc1({#(a): Int#}, {#b: Float#})[#Void#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc2({#(a): Int#}, {#b: Float#}, {#c: Double#})[#Void#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc3({#(a): Int#}, {#b: (Float, Double)#})[#Void#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc1({#(a): Int#}, {#b: Float#})[#String#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc2({#(a): Int#}, {#b: Float#}, {#c: Double#})[#String#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc3({#(a): Int#}, {#b: (Float, Double)#})[#String#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceVar]/CurrNominal: .extProp[#Int#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .extFunc0()[#Void#]{{; name=.+$}} // FOO_OBJECT_NO_DOT-NEXT: BuiltinOperator/None: = {#Foo // FOO_OBJECT_NO_DOT-NEXT: End completions // FOO_STRUCT_DOT: Begin completions // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc0({#self: &FooStruct#})[#() -> Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#self: &FooStruct#})[#(Int) -> Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc2({#self: &FooStruct#})[#(Int, b: inout Double) -> Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc3({#self: &FooStruct#})[#(Int, (Float, Double)) -> Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc4({#self: &FooStruct#})[#(Int?, b: Int!, c: inout Int?, d: inout Int!) -> Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc5({#self: &FooStruct#})[#() -> Int?#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc6({#self: &FooStruct#})[#() -> Int!#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc7({#self: &FooStruct#})[#(a: Int) -> Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc8({#self: &FooStruct#})[#((Int, Int)) -> Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc9({#self: &FooStruct#})[#(a: @autoclosure () -> Int) -> Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc0({#self: &FooStruct#})[#(Int...) -> Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc1({#self: &FooStruct#})[#(Float, v: Int...) -> Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc2({#self: &FooStruct#})[#(Float, b: Double, v: Int...) -> Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc1({#self: &FooStruct#})[#() -> Int#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc1({#self: &FooStruct#})[#() -> Double#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc2({#self: &FooStruct#})[#(Int) -> Int#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc2({#self: &FooStruct#})[#(Double) -> Int#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: builderFunc1({#self: &FooStruct#})[#(Int) -> FooStruct#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc1({#self: &FooStruct#})[#(Int, b: Float) -> Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc2({#self: &FooStruct#})[#(Int, b: Float, c: Double) -> Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc3({#self: &FooStruct#})[#(Int, b: (Float, Double)) -> Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc1({#self: &FooStruct#})[#(Int, b: Float) -> String#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc2({#self: &FooStruct#})[#(Int, b: Float, c: Double) -> String#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc3({#self: &FooStruct#})[#(Int, b: (Float, Double)) -> String#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[Struct]/CurrNominal: NestedStruct[#FooStruct.NestedStruct#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[Class]/CurrNominal: NestedClass[#FooStruct.NestedClass#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[Enum]/CurrNominal: NestedEnum[#FooStruct.NestedEnum#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[StaticVar]/CurrNominal: staticVar[#Int#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: staticFunc0()[#Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: staticFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: overloadedStaticFunc1()[#Int#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: overloadedStaticFunc1()[#Double#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: overloadedStaticFunc2({#(x): Int#})[#Int#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: overloadedStaticFunc2({#(x): Double#})[#Int#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[Constructor]/CurrNominal: init({#lazyInstanceVar: Int?#}, {#instanceVar: Int#})[#FooStruct#]; name=init(lazyInstanceVar: Int?, instanceVar: Int){{$}} // FOO_STRUCT_DOT-NEXT: Decl[Constructor]/CurrNominal: init()[#FooStruct#]; name=init(){{$}} // FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: extFunc0({#self: &FooStruct#})[#() -> Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[StaticVar]/CurrNominal: extStaticProp[#Int#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: extStaticFunc0()[#Void#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[Struct]/CurrNominal: ExtNestedStruct[#FooStruct.ExtNestedStruct#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[Class]/CurrNominal: ExtNestedClass[#FooStruct.ExtNestedClass#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[Enum]/CurrNominal: ExtNestedEnum[#FooStruct.ExtNestedEnum#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: Decl[TypeAlias]/CurrNominal: ExtNestedTypealias[#Int#]{{; name=.+$}} // FOO_STRUCT_DOT-NEXT: End completions // FOO_STRUCT_NO_DOT: Begin completions // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc0({#self: &FooStruct#})[#() -> Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc1({#self: &FooStruct#})[#(Int) -> Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc2({#self: &FooStruct#})[#(Int, b: inout Double) -> Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc3({#self: &FooStruct#})[#(Int, (Float, Double)) -> Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc4({#self: &FooStruct#})[#(Int?, b: Int!, c: inout Int?, d: inout Int!) -> Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc5({#self: &FooStruct#})[#() -> Int?#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc6({#self: &FooStruct#})[#() -> Int!#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc7({#self: &FooStruct#})[#(a: Int) -> Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc8({#self: &FooStruct#})[#((Int, Int)) -> Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc9({#self: &FooStruct#})[#(a: @autoclosure () -> Int) -> Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc0({#self: &FooStruct#})[#(Int...) -> Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc1({#self: &FooStruct#})[#(Float, v: Int...) -> Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc2({#self: &FooStruct#})[#(Float, b: Double, v: Int...) -> Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc1({#self: &FooStruct#})[#() -> Int#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc1({#self: &FooStruct#})[#() -> Double#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc2({#self: &FooStruct#})[#(Int) -> Int#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc2({#self: &FooStruct#})[#(Double) -> Int#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .builderFunc1({#self: &FooStruct#})[#(Int) -> FooStruct#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc1({#self: &FooStruct#})[#(Int, b: Float) -> Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc2({#self: &FooStruct#})[#(Int, b: Float, c: Double) -> Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc3({#self: &FooStruct#})[#(Int, b: (Float, Double)) -> Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc1({#self: &FooStruct#})[#(Int, b: Float) -> String#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc2({#self: &FooStruct#})[#(Int, b: Float, c: Double) -> String#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc3({#self: &FooStruct#})[#(Int, b: (Float, Double)) -> String#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[Struct]/CurrNominal: .NestedStruct[#FooStruct.NestedStruct#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[Class]/CurrNominal: .NestedClass[#FooStruct.NestedClass#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[Enum]/CurrNominal: .NestedEnum[#FooStruct.NestedEnum#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[TypeAlias]/CurrNominal: .NestedTypealias[#Int#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .staticVar[#Int#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .staticFunc0()[#Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .staticFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .overloadedStaticFunc1()[#Int#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .overloadedStaticFunc1()[#Double#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .overloadedStaticFunc2({#(x): Int#})[#Int#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .overloadedStaticFunc2({#(x): Double#})[#Int#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[Constructor]/CurrNominal: ({#lazyInstanceVar: Int?#}, {#instanceVar: Int#})[#FooStruct#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[Constructor]/CurrNominal: ()[#FooStruct#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .extFunc0({#self: &FooStruct#})[#() -> Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .extStaticProp[#Int#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .extStaticFunc0()[#Void#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[Struct]/CurrNominal: .ExtNestedStruct[#FooStruct.ExtNestedStruct#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[Class]/CurrNominal: .ExtNestedClass[#FooStruct.ExtNestedClass#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[Enum]/CurrNominal: .ExtNestedEnum[#FooStruct.ExtNestedEnum#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: Decl[TypeAlias]/CurrNominal: .ExtNestedTypealias[#Int#]{{; name=.+$}} // FOO_STRUCT_NO_DOT-NEXT: End completions func testObjectExpr() { fooObject.#^FOO_OBJECT_DOT_1^# } func testDotDotTokenSplitWithCodeCompletion() { fooObject.#^FOO_OBJECT_DOT_2^#.bar } func testObjectExprBuilderStyle1() { fooObject .#^FOO_OBJECT_DOT_3^# } func testObjectExprBuilderStyle2() { fooObject .builderFunc1(42).#^FOO_OBJECT_DOT_4^# } func testObjectExprBuilderStyle3() { fooObject .builderFunc1(42) .#^FOO_OBJECT_DOT_5^# } func testObjectExprWithoutDot() { fooObject#^FOO_OBJECT_NO_DOT_1^# } func testObjectExprWithoutSpaceAfterCodeCompletion() { fooObject#^FOO_OBJECT_NO_DOT_2^#.bar } func testMetatypeExpr() { FooStruct.#^FOO_STRUCT_DOT_1^# } func testMetatypeExprWithoutDot() { FooStruct#^FOO_STRUCT_NO_DOT_1^# } func testImplicitlyCurriedFunc(_ fs: inout FooStruct) { FooStruct.instanceFunc0(&fs)#^IMPLICITLY_CURRIED_FUNC_0^# // IMPLICITLY_CURRIED_FUNC_0: Begin completions // IMPLICITLY_CURRIED_FUNC_0-NEXT: Pattern/ExprSpecific: ()[#Void#]{{; name=.+$}} // IMPLICITLY_CURRIED_FUNC_0-NEXT: End completions FooStruct.instanceFunc1(&fs)#^IMPLICITLY_CURRIED_FUNC_1^# // IMPLICITLY_CURRIED_FUNC_1: Begin completions // IMPLICITLY_CURRIED_FUNC_1-NEXT: Pattern/ExprSpecific: ({#(a): Int#})[#Void#]{{; name=.+$}} // IMPLICITLY_CURRIED_FUNC_1-NEXT: End completions FooStruct.instanceFunc2(&fs)#^IMPLICITLY_CURRIED_FUNC_2^# // IMPLICITLY_CURRIED_FUNC_2: Begin completions // IMPLICITLY_CURRIED_FUNC_2-NEXT: Pattern/ExprSpecific: ({#(a): Int#}, {#b: &Double#})[#Void#]{{; name=.+$}} // IMPLICITLY_CURRIED_FUNC_2-NEXT: End completions FooStruct.varargInstanceFunc0(&fs)#^IMPLICITLY_CURRIED_VARARG_FUNC_0^# // IMPLICITLY_CURRIED_VARARG_FUNC_0: Begin completions // IMPLICITLY_CURRIED_VARARG_FUNC_0-NEXT: Pattern/ExprSpecific: ({#(v): Int...#})[#Void#]{{; name=.+$}} // IMPLICITLY_CURRIED_VARARG_FUNC_0-NEXT: End completions FooStruct.varargInstanceFunc1(&fs)#^IMPLICITLY_CURRIED_VARARG_FUNC_1^# // IMPLICITLY_CURRIED_VARARG_FUNC_1: Begin completions // IMPLICITLY_CURRIED_VARARG_FUNC_1-NEXT: Pattern/ExprSpecific: ({#(a): Float#}, {#v: Int...#})[#Void#]{{; name=.+$}} // IMPLICITLY_CURRIED_VARARG_FUNC_1-NEXT: End completions FooStruct.varargInstanceFunc2(&fs)#^IMPLICITLY_CURRIED_VARARG_FUNC_2^# // IMPLICITLY_CURRIED_VARARG_FUNC_2: Begin completions // IMPLICITLY_CURRIED_VARARG_FUNC_2-NEXT: Pattern/ExprSpecific: ({#(a): Float#}, {#b: Double#}, {#v: Int...#})[#Void#]{{; name=.+$}} // IMPLICITLY_CURRIED_VARARG_FUNC_2-NEXT: End completions // This call is ambiguous, and the expression is invalid. // Ensure that we don't suggest to call the result. FooStruct.overloadedInstanceFunc1(&fs)#^IMPLICITLY_CURRIED_OVERLOADED_FUNC_1^# // IMPLICITLY_CURRIED_OVERLOADED_FUNC_1: found code completion token // IMPLICITLY_CURRIED_OVERLOADED_FUNC_1-NOT: Begin completions // This call is ambiguous, and the expression is invalid. // Ensure that we don't suggest to call the result. FooStruct.overloadedInstanceFunc2(&fs)#^IMPLICITLY_CURRIED_OVERLOADED_FUNC_2^# // IMPLICITLY_CURRIED_OVERLOADED_FUNC_2: found code completion token // IMPLICITLY_CURRIED_OVERLOADED_FUNC_2-NOT: Begin completions } //===--- //===--- Test that we can complete inside 'case'. //===--- func testSwitch1() { switch fooObject { case #^IN_SWITCH_CASE_1^# } switch fooObject { case 1, #^IN_SWITCH_CASE_2^# } switch unknown_var { case #^IN_SWITCH_CASE_3^# } switch { case #^IN_SWITCH_CASE_4^# } } // IN_SWITCH_CASE: Begin completions // IN_SWITCH_CASE-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // IN_SWITCH_CASE-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // IN_SWITCH_CASE: End completions //===--- Helper types that are used in this test struct FooGenericStruct<T> { init(t: T) { fooInstanceVarT = t } var fooInstanceVarT: T var fooInstanceVarTBrackets: [T] mutating func fooVoidInstanceFunc1(_ a: T) {} mutating func fooTInstanceFunc1(_ a: T) -> T { return a } mutating func fooUInstanceFunc1<U>(_ a: U) -> U { return a } static var fooStaticVarT: Int = 0 static var fooStaticVarTBrackets: [Int] = [0] static func fooVoidStaticFunc1(_ a: T) {} static func fooTStaticFunc1(_ a: T) -> T { return a } static func fooUInstanceFunc1<U>(_ a: U) -> U { return a } } class FooClass { var fooClassInstanceVar = 0 func fooClassInstanceFunc0() {} func fooClassInstanceFunc1(_ a: Int) {} } enum FooEnum { } protocol FooProtocol { var fooInstanceVar1: Int { get set } var fooInstanceVar2: Int { get } typealias FooTypeAlias1 func fooInstanceFunc0() -> Double func fooInstanceFunc1(_ a: Int) -> Double subscript(i: Int) -> Double { get set } } class FooProtocolImpl : FooProtocol { var fooInstanceVar1 = 0 val fooInstanceVar2 = 0 typealias FooTypeAlias1 = Float init() {} func fooInstanceFunc0() -> Double { return 0.0 } func fooInstanceFunc1(_ a: Int) -> Double { return Double(a) } subscript(i: Int) -> Double { return 0.0 } } protocol FooExProtocol : FooProtocol { func fooExInstanceFunc0() -> Double } protocol BarProtocol { var barInstanceVar: Int { get set } typealias BarTypeAlias1 func barInstanceFunc0() -> Double func barInstanceFunc1(_ a: Int) -> Double } protocol BarExProtocol : BarProtocol { func barExInstanceFunc0() -> Double } protocol BazProtocol { func bazInstanceFunc0() -> Double } typealias BarBazProtocolComposition = BarProtocol & BazProtocol let fooProtocolInstance: FooProtocol = FooProtocolImpl() let fooBarProtocolInstance: FooProtocol & BarProtocol let fooExBarExProtocolInstance: FooExProtocol & BarExProtocol typealias FooTypealias = Int //===--- Test that we can code complete inside function calls. func testInsideFunctionCall0() { ERROR(#^INSIDE_FUNCTION_CALL_0^# // INSIDE_FUNCTION_CALL_0: Begin completions // INSIDE_FUNCTION_CALL_0-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_0: End completions } func testInsideFunctionCall1() { var a = FooStruct() a.instanceFunc0(#^INSIDE_FUNCTION_CALL_1^# // There should be no other results here because the function call // unambiguously resolves to overload that takes 0 arguments. // INSIDE_FUNCTION_CALL_1: Begin completions // INSIDE_FUNCTION_CALL_1-NEXT: Pattern/ExprSpecific: ['('])[#Void#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_1-NEXT: End completions } func testInsideFunctionCall2() { var a = FooStruct() a.instanceFunc1(#^INSIDE_FUNCTION_CALL_2^# // INSIDE_FUNCTION_CALL_2: Begin completions // FIXME: we should print the non-API param name rdar://20962472 // INSIDE_FUNCTION_CALL_2-DAG: Pattern/ExprSpecific: ['(']{#Int#})[#Void#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_2-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_2: End completions } func testInsideFunctionCall3() { FooStruct().instanceFunc1(42, #^INSIDE_FUNCTION_CALL_3^# // INSIDE_FUNCTION_CALL_3: Begin completions // FIXME: There should be no results here because the function call // unambiguously resolves to overload that takes 1 argument. // INSIDE_FUNCTION_CALL_3-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_3: End completions } func testInsideFunctionCall4() { var a = FooStruct() a.instanceFunc2(#^INSIDE_FUNCTION_CALL_4^# // INSIDE_FUNCTION_CALL_4: Begin completions // FIXME: we should print the non-API param name rdar://20962472 // INSIDE_FUNCTION_CALL_4-DAG: Pattern/ExprSpecific: ['(']{#Int#}, {#b: &Double#})[#Void#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_4-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_4: End completions } func testInsideFunctionCall5() { FooStruct().instanceFunc2(42, #^INSIDE_FUNCTION_CALL_5^# // INSIDE_FUNCTION_CALL_5: Begin completions // INSIDE_FUNCTION_CALL_5-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_5: End completions } func testInsideFunctionCall6() { var a = FooStruct() a.instanceFunc7(#^INSIDE_FUNCTION_CALL_6^# // INSIDE_FUNCTION_CALL_6: Begin completions // INSIDE_FUNCTION_CALL_6-NEXT: Pattern/ExprSpecific: ['(']{#a: Int#})[#Void#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_6-NEXT: End completions } func testInsideFunctionCall7() { var a = FooStruct() a.instanceFunc8(#^INSIDE_FUNCTION_CALL_7^# // INSIDE_FUNCTION_CALL_7: Begin completions // FIXME: we should print the non-API param name rdar://20962472 // INSIDE_FUNCTION_CALL_7: Pattern/ExprSpecific: ['(']{#(Int, Int)#})[#Void#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_7: End completions } func testInsideFunctionCall8(_ x: inout FooStruct) { x.instanceFunc0(#^INSIDE_FUNCTION_CALL_8^#) // Since we already have '()', there is no pattern to complete. // INSIDE_FUNCTION_CALL_8-NOT: Pattern/{{.*}}: } func testInsideFunctionCall9(_ x: inout FooStruct) { x.instanceFunc1(#^INSIDE_FUNCTION_CALL_9^#) // Annotated ')' // INSIDE_FUNCTION_CALL_9: Begin completions // INSIDE_FUNCTION_CALL_9-DAG: Pattern/ExprSpecific: ['(']{#Int#}[')'][#Void#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_9-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_9: End completions } func testInsideFunctionCall10(_ x: inout FooStruct) { x.instanceFunc2(#^INSIDE_FUNCTION_CALL_10^#) // Annotated ')' // INSIDE_FUNCTION_CALL_10: Begin completions // INSIDE_FUNCTION_CALL_10-DAG: Pattern/ExprSpecific: ['(']{#Int#}, {#b: &Double#}[')'][#Void#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_10-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_10: End completions } func testInsideFunctionCall11(_ x: inout FooStruct) { x.instanceFunc2(#^INSIDE_FUNCTION_CALL_11^#, // INSIDE_FUNCTION_CALL_11-NOT: Pattern/{{.*}}:{{.*}}({{.*}}{#Int#} } func testInsideFunctionCall12(_ x: inout FooStruct) { x.instanceFunc2(#^INSIDE_FUNCTION_CALL_12^#<#placeholder#> // INSIDE_FUNCTION_CALL_12-NOT: Pattern/{{.*}}:{{.*}}({{.*}}{#Int#} } func testInsideVarargFunctionCall1() { var a = FooStruct() a.varargInstanceFunc0(#^INSIDE_VARARG_FUNCTION_CALL_1^# // INSIDE_VARARG_FUNCTION_CALL_1: Begin completions // FIXME: we should print the non-API param name rdar://20962472 // INSIDE_VARARG_FUNCTION_CALL_1-DAG: Pattern/ExprSpecific: ['(']{#Int...#})[#Void#]{{; name=.+$}} // INSIDE_VARARG_FUNCTION_CALL_1-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // INSIDE_VARARG_FUNCTION_CALL_1: End completions } func testInsideVarargFunctionCall2() { FooStruct().varargInstanceFunc0(42, #^INSIDE_VARARG_FUNCTION_CALL_2^# // INSIDE_VARARG_FUNCTION_CALL_2: Begin completions // INSIDE_VARARG_FUNCTION_CALL_2-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // INSIDE_VARARG_FUNCTION_CALL_2: End completions } func testInsideVarargFunctionCall3() { FooStruct().varargInstanceFunc0(42, 4242, #^INSIDE_VARARG_FUNCTION_CALL_3^# // INSIDE_VARARG_FUNCTION_CALL_3: Begin completions // INSIDE_VARARG_FUNCTION_CALL_3-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // INSIDE_VARARG_FUNCTION_CALL_3: End completions } func testInsideOverloadedFunctionCall1() { var a = FooStruct() a.overloadedInstanceFunc2(#^INSIDE_OVERLOADED_FUNCTION_CALL_1^# // INSIDE_OVERLOADED_FUNCTION_CALL_1: Begin completions // FIXME: produce call patterns here. // INSIDE_OVERLOADED_FUNCTION_CALL_1-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // INSIDE_OVERLOADED_FUNCTION_CALL_1: End completions } func testInsideFunctionCallOnClassInstance1(_ a: FooClass) { a.fooClassInstanceFunc1(#^INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1^# // INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1: Begin completions // FIXME: we should print the non-API param name rdar://20962472 // INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1-DAG: Pattern/ExprSpecific: ['(']{#Int#})[#Void#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1: End completions } //===--- Variables that have function types. class FuncTypeVars { var funcVar1: () -> Double var funcVar2: (a: Int) -> Double // adding the label is erroneous. } var funcTypeVarsObject: FuncTypeVars func testFuncTypeVars() { funcTypeVarsObject.funcVar1#^VF1^# // VF1: Begin completions // VF1-NEXT: Pattern/ExprSpecific: ()[#Double#]{{; name=.+$}} // VF1-NEXT: BuiltinOperator/None: = {#() -> Double##() -> Double#}[#Void#] // VF1-NEXT: End completions funcTypeVarsObject.funcVar2#^VF2^# // VF2: Begin completions // VF2-NEXT: Pattern/ExprSpecific: ({#Int#})[#Double#]{{; name=.+$}} // VF2-NEXT: BuiltinOperator/None: = {#(Int) -> Double##(Int) -> Double#}[#Void#] // VF2-NEXT: End completions } //===--- Check that we look into base classes. class MembersBase { var baseVar = 0 func baseInstanceFunc() {} class func baseStaticFunc() {} } class MembersDerived : MembersBase { var derivedVar = 0 func derivedInstanceFunc() {} class func derivedStaticFunc() {} } var membersDerived: MembersDerived func testLookInBase() { membersDerived.#^BASE_MEMBERS^# // BASE_MEMBERS: Begin completions // BASE_MEMBERS-NEXT: Decl[InstanceVar]/CurrNominal: derivedVar[#Int#]{{; name=.+$}} // BASE_MEMBERS-NEXT: Decl[InstanceMethod]/CurrNominal: derivedInstanceFunc()[#Void#]{{; name=.+$}} // BASE_MEMBERS-NEXT: Decl[InstanceVar]/Super: baseVar[#Int#]{{; name=.+$}} // BASE_MEMBERS-NEXT: Decl[InstanceMethod]/Super: baseInstanceFunc()[#Void#]{{; name=.+$}} // BASE_MEMBERS-NEXT: End completions } func testLookInBaseStatic() { MembersDerived.#^BASE_MEMBERS_STATIC^# // BASE_MEMBERS_STATIC: Begin completions // BASE_MEMBERS_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: derivedInstanceFunc({#self: MembersDerived#})[#() -> Void#]{{; name=.+$}} // BASE_MEMBERS_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: derivedStaticFunc()[#Void#]{{; name=.+$}} // BASE_MEMBERS_STATIC-NEXT: Decl[Constructor]/CurrNominal: init()[#MembersDerived#]; name=init(){{$}} // BASE_MEMBERS_STATIC-NEXT: Decl[InstanceMethod]/Super: baseInstanceFunc({#self: MembersBase#})[#() -> Void#]{{; name=.+$}} // BASE_MEMBERS_STATIC-NEXT: Decl[StaticMethod]/Super: baseStaticFunc()[#Void#]{{; name=.+$}} // BASE_MEMBERS_STATIC-NEXT: End completions } //===--- Check that we can look into protocols. func testLookInProtoNoDot1() { fooProtocolInstance#^PROTO_MEMBERS_NO_DOT_1^# // PROTO_MEMBERS_NO_DOT_1: Begin completions // PROTO_MEMBERS_NO_DOT_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVar1[#Int#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVar2[#Int#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_1-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}][#Double#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_1-NEXT: End completions } func testLookInProtoNoDot2() { fooBarProtocolInstance#^PROTO_MEMBERS_NO_DOT_2^# // PROTO_MEMBERS_NO_DOT_2: Begin completions // PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceVar]/CurrNominal: .barInstanceVar[#Int#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .barInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVar1[#Int#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVar2[#Int#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}][#Double#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_2-NEXT: End completions } func testLookInProtoNoDot3() { fooExBarExProtocolInstance#^PROTO_MEMBERS_NO_DOT_3^# // PROTO_MEMBERS_NO_DOT_3: Begin completions // PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceVar]/Super: .barInstanceVar[#Int#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/Super: .barInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/Super: .barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/CurrNominal: .barExInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceVar]/Super: .fooInstanceVar1[#Int#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceVar]/Super: .fooInstanceVar2[#Int#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/Super: .fooInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/Super: .fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[Subscript]/Super: [{#Int#}][#Double#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/CurrNominal: .fooExInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_NO_DOT_3-NEXT: End completions } func testLookInProto1() { fooProtocolInstance.#^PROTO_MEMBERS_1^# // PROTO_MEMBERS_1: Begin completions // PROTO_MEMBERS_1-NEXT: Decl[InstanceVar]/CurrNominal: fooInstanceVar1[#Int#]{{; name=.+$}} // PROTO_MEMBERS_1-NEXT: Decl[InstanceVar]/CurrNominal: fooInstanceVar2[#Int#]{{; name=.+$}} // PROTO_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: fooInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // PROTO_MEMBERS_1-NEXT: End completions } func testLookInProto2() { fooBarProtocolInstance.#^PROTO_MEMBERS_2^# // PROTO_MEMBERS_2: Begin completions // PROTO_MEMBERS_2-NEXT: Decl[InstanceVar]/CurrNominal: barInstanceVar[#Int#]{{; name=.+$}} // PROTO_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: barInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // PROTO_MEMBERS_2-NEXT: Decl[InstanceVar]/CurrNominal: fooInstanceVar1[#Int#]{{; name=.+$}} // PROTO_MEMBERS_2-NEXT: Decl[InstanceVar]/CurrNominal: fooInstanceVar2[#Int#]{{; name=.+$}} // PROTO_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: fooInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // PROTO_MEMBERS_2-NEXT: End completions } func testLookInProto3() { fooExBarExProtocolInstance.#^PROTO_MEMBERS_3^# // PROTO_MEMBERS_3: Begin completions // PROTO_MEMBERS_3-NEXT: Decl[InstanceVar]/Super: barInstanceVar[#Int#]{{; name=.+$}} // PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/CurrNominal: barExInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}} // PROTO_MEMBERS_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}} // PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/CurrNominal: fooExInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_3-NEXT: End completions } func testLookInProto4(_ a: FooProtocol & BarBazProtocolComposition) { a.#^PROTO_MEMBERS_4^# // PROTO_MEMBERS_4: Begin completions // PROTO_MEMBERS_4-DAG: Decl[InstanceMethod]/CurrNominal: fooInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_4-DAG: Decl[InstanceMethod]/CurrNominal: barInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_4-DAG: Decl[InstanceMethod]/CurrNominal: bazInstanceFunc0()[#Double#]{{; name=.+$}} // PROTO_MEMBERS_4: End completions } //===--- Check that we can resolve function parameters. func testResolveFuncParam1(_ fs: FooStruct) { fs.#^RESOLVE_FUNC_PARAM_1^# } class TestResolveFuncParam2 { func testResolveFuncParam2a(_ fs: FooStruct) { fs.#^RESOLVE_FUNC_PARAM_2^# } } func testResolveFuncParam3<Foo : FooProtocol>(_ foo: Foo) { foo.#^RESOLVE_FUNC_PARAM_3^# // RESOLVE_FUNC_PARAM_3: Begin completions // RESOLVE_FUNC_PARAM_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_3-NEXT: End completions } func testResolveFuncParam4<FooBar : FooProtocol & BarProtocol>(_ fooBar: FooBar) { fooBar.#^RESOLVE_FUNC_PARAM_4^# // RESOLVE_FUNC_PARAM_4: Begin completions // RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceVar]/Super: barInstanceVar[#Int#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc0()[#Double#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_4-NEXT: End completions } func testResolveFuncParam5<FooExBarEx : FooExProtocol & BarExProtocol>(_ a: FooExBarEx) { a.#^RESOLVE_FUNC_PARAM_5^# // RESOLVE_FUNC_PARAM_5: Begin completions // RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceVar]/Super: barInstanceVar[#Int#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc0()[#Double#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: barExInstanceFunc0()[#Double#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: fooExInstanceFunc0()[#Double#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_5-NEXT: End completions } func testResolveFuncParam6<Foo : FooProtocol where Foo : FooClass>(_ foo: Foo) { foo.#^RESOLVE_FUNC_PARAM_6^# // RESOLVE_FUNC_PARAM_6: Begin completions // RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceVar]/Super: fooClassInstanceVar[#Int#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceMethod]/Super: fooClassInstanceFunc0()[#Void#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceMethod]/Super: fooClassInstanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // RESOLVE_FUNC_PARAM_6-NEXT: End completions } class TestResolveConstructorParam1 { init(fs: FooStruct) { fs.#^RESOLVE_CONSTRUCTOR_PARAM_1^# } } class TestResolveConstructorParam2 { init<Foo : FooProtocol>(foo: Foo) { foo.#^RESOLVE_CONSTRUCTOR_PARAM_2^# // RESOLVE_CONSTRUCTOR_PARAM_2: Begin completions // RESOLVE_CONSTRUCTOR_PARAM_2-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}} // RESOLVE_CONSTRUCTOR_PARAM_2-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}} // RESOLVE_CONSTRUCTOR_PARAM_2-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}} // RESOLVE_CONSTRUCTOR_PARAM_2-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // RESOLVE_CONSTRUCTOR_PARAM_2-NEXT: End completions } } class TestResolveConstructorParam3<Foo : FooProtocol> { init(foo: Foo) { foo.#^RESOLVE_CONSTRUCTOR_PARAM_3^# // RESOLVE_CONSTRUCTOR_PARAM_3: Begin completions // RESOLVE_CONSTRUCTOR_PARAM_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}} // RESOLVE_CONSTRUCTOR_PARAM_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}} // RESOLVE_CONSTRUCTOR_PARAM_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}} // RESOLVE_CONSTRUCTOR_PARAM_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}} // RESOLVE_CONSTRUCTOR_PARAM_3-NEXT: End completions } } //===--- Check that we can handle ParenPattern in function arguments. struct FuncParenPattern { init(_: Int) {} init(_: (Int, Int)) {} mutating func instanceFunc(_: Int) {} subscript(_: Int) -> Int { get { return 0 } } } func testFuncParenPattern1(_ fpp: FuncParenPattern) { fpp#^FUNC_PAREN_PATTERN_1^# // FUNC_PAREN_PATTERN_1: Begin completions // FUNC_PAREN_PATTERN_1-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#Int#})[#Void#]{{; name=.+$}} // FUNC_PAREN_PATTERN_1-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}][#Int#]{{; name=.+$}} // FUNC_PAREN_PATTERN_1-NEXT: End completions } func testFuncParenPattern2(_ fpp: FuncParenPattern) { FuncParenPattern#^FUNC_PAREN_PATTERN_2^# // FUNC_PAREN_PATTERN_2: Begin completions // FUNC_PAREN_PATTERN_2-NEXT: Decl[Constructor]/CurrNominal: ({#Int#})[#FuncParenPattern#]{{; name=.+$}} // FUNC_PAREN_PATTERN_2-NEXT: Decl[Constructor]/CurrNominal: ({#(Int, Int)#})[#FuncParenPattern#]{{; name=.+$}} // FUNC_PAREN_PATTERN_2-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#self: &FuncParenPattern#})[#(Int) -> Void#]{{; name=.+$}} // FUNC_PAREN_PATTERN_2-NEXT: End completions } func testFuncParenPattern3(_ fpp: inout FuncParenPattern) { fpp.instanceFunc#^FUNC_PAREN_PATTERN_3^# // FUNC_PAREN_PATTERN_3: Begin completions // FUNC_PAREN_PATTERN_3-NEXT: Pattern/ExprSpecific: ({#Int#})[#Void#]{{; name=.+$}} // FUNC_PAREN_PATTERN_3-NEXT: End completions } //===--- Check that we can code complete after function calls struct SomeBuilder { init(a: Int) {} func doFoo() -> SomeBuilder { return self } func doBar() -> SomeBuilder { return self } func doBaz(_ z: Double) -> SomeBuilder { return self } } func testChainedCalls1() { SomeBuilder(42)#^CHAINED_CALLS_1^# // CHAINED_CALLS_1: Begin completions // CHAINED_CALLS_1-DAG: Decl[InstanceMethod]/CurrNominal: .doFoo()[#SomeBuilder#]{{; name=.+$}} // CHAINED_CALLS_1-DAG: Decl[InstanceMethod]/CurrNominal: .doBar()[#SomeBuilder#]{{; name=.+$}} // CHAINED_CALLS_1-DAG: Decl[InstanceMethod]/CurrNominal: .doBaz({#(z): Double#})[#SomeBuilder#]{{; name=.+$}} // CHAINED_CALLS_1: End completions } func testChainedCalls2() { SomeBuilder(42).doFoo()#^CHAINED_CALLS_2^# // CHAINED_CALLS_2: Begin completions // CHAINED_CALLS_2-DAG: Decl[InstanceMethod]/CurrNominal: .doFoo()[#SomeBuilder#]{{; name=.+$}} // CHAINED_CALLS_2-DAG: Decl[InstanceMethod]/CurrNominal: .doBar()[#SomeBuilder#]{{; name=.+$}} // CHAINED_CALLS_2-DAG: Decl[InstanceMethod]/CurrNominal: .doBaz({#(z): Double#})[#SomeBuilder#]{{; name=.+$}} // CHAINED_CALLS_2: End completions } func testChainedCalls3() { // doBaz() takes a Double. Check that we can recover. SomeBuilder(42).doFoo().doBaz(SomeBuilder(24))#^CHAINED_CALLS_3^# // CHAINED_CALLS_3: Begin completions // CHAINED_CALLS_3-DAG: Decl[InstanceMethod]/CurrNominal: .doFoo()[#SomeBuilder#]{{; name=.+$}} // CHAINED_CALLS_3-DAG: Decl[InstanceMethod]/CurrNominal: .doBar()[#SomeBuilder#]{{; name=.+$}} // CHAINED_CALLS_3-DAG: Decl[InstanceMethod]/CurrNominal: .doBaz({#z: Double#})[#SomeBuilder#]{{; name=.+$}} // CHAINED_CALLS_3: End completions } //===--- Check that we can code complete expressions that have generic parameters func testResolveGenericParams1() { FooGenericStruct<FooStruct>()#^RESOLVE_GENERIC_PARAMS_1^# // RESOLVE_GENERIC_PARAMS_1: Begin completions // RESOLVE_GENERIC_PARAMS_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarT[#FooStruct#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarTBrackets[#[FooStruct]#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#(a): FooStruct#})[#Void#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#(a): FooStruct#})[#FooStruct#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_1-NEXT: End completions FooGenericStruct<FooStruct>#^RESOLVE_GENERIC_PARAMS_1_STATIC^# // RESOLVE_GENERIC_PARAMS_1_STATIC: Begin completions // RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[Constructor]/CurrNominal: ({#t: FooStruct#})[#FooGenericStruct<FooStruct>#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#FooStruct -> Void#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#FooStruct -> FooStruct#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#(U) -> U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarT[#Int#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarTBrackets[#[Int]#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooVoidStaticFunc1({#(a): FooStruct#})[#Void#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooTStaticFunc1({#(a): FooStruct#})[#FooStruct#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: End completions } func testResolveGenericParams2<Foo : FooProtocol>(_ foo: Foo) { FooGenericStruct<Foo>()#^RESOLVE_GENERIC_PARAMS_2^# // RESOLVE_GENERIC_PARAMS_2: Begin completions // RESOLVE_GENERIC_PARAMS_2-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarT[#FooProtocol#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_2-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarTBrackets[#[FooProtocol]#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#(a): FooProtocol#})[#Void#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#(a): FooProtocol#})[#FooProtocol#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_2-NEXT: End completions FooGenericStruct<Foo>#^RESOLVE_GENERIC_PARAMS_2_STATIC^# // RESOLVE_GENERIC_PARAMS_2_STATIC: Begin completions // RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[Constructor]/CurrNominal: ({#t: FooProtocol#})[#FooGenericStruct<FooProtocol>#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#self: &FooGenericStruct<FooProtocol>#})[#FooProtocol -> Void#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#self: &FooGenericStruct<FooProtocol>#})[#FooProtocol -> FooProtocol#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#self: &FooGenericStruct<FooProtocol>#})[#(U) -> U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarT[#Int#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarTBrackets[#[Int]#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooVoidStaticFunc1({#(a): FooProtocol#})[#Void#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooTStaticFunc1({#(a): FooProtocol#})[#FooProtocol#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: End completions } struct TestResolveGenericParams3_4<T> { func testResolveGenericParams3() { FooGenericStruct<FooStruct>()#^RESOLVE_GENERIC_PARAMS_3^# // RESOLVE_GENERIC_PARAMS_3: Begin completions // RESOLVE_GENERIC_PARAMS_3-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarT[#FooStruct#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_3-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarTBrackets[#[FooStruct]#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_3-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#(a): FooStruct#})[#Void#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_3-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#(a): FooStruct#})[#FooStruct#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_3-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_3-NEXT: End completions FooGenericStruct<FooStruct>#^RESOLVE_GENERIC_PARAMS_3_STATIC^# // RESOLVE_GENERIC_PARAMS_3_STATIC: Begin completions, 9 items // RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[Constructor]/CurrNominal: ({#t: FooStruct#})[#FooGenericStruct<FooStruct>#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#FooStruct -> Void#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#FooStruct -> FooStruct#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#(U) -> U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarT[#Int#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarTBrackets[#[Int]#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooVoidStaticFunc1({#(a): FooStruct#})[#Void#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooTStaticFunc1({#(a): FooStruct#})[#FooStruct#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: End completions } func testResolveGenericParams4(_ t: T) { FooGenericStruct<T>(t)#^RESOLVE_GENERIC_PARAMS_4^# // RESOLVE_GENERIC_PARAMS_4: Begin completions // RESOLVE_GENERIC_PARAMS_4-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarT[#T#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_4-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarTBrackets[#[T]#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_4-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#(a): T#})[#Void#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_4-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#(a): T#})[#T#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_4-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_4-NEXT: End completions FooGenericStruct<T>#^RESOLVE_GENERIC_PARAMS_4_STATIC^# // RESOLVE_GENERIC_PARAMS_4_STATIC: Begin completions // RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[Constructor]/CurrNominal: ({#t: T#})[#FooGenericStruct<T>#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#self: &FooGenericStruct<T>#})[#T -> Void#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#self: &FooGenericStruct<T>#})[#T -> T#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#self: &FooGenericStruct<T>#})[#(U) -> U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarT[#Int#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarTBrackets[#[Int]#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooVoidStaticFunc1({#(a): T#})[#Void#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooTStaticFunc1({#(a): T#})[#T#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: End completions } func testResolveGenericParams5<U>(_ u: U) { FooGenericStruct<U>(u)#^RESOLVE_GENERIC_PARAMS_5^# // RESOLVE_GENERIC_PARAMS_5: Begin completions // RESOLVE_GENERIC_PARAMS_5-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarT[#U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_5-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarTBrackets[#[U]#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_5-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#(a): U#})[#Void#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_5-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_5-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_5-NEXT: End completions FooGenericStruct<U>#^RESOLVE_GENERIC_PARAMS_5_STATIC^# // RESOLVE_GENERIC_PARAMS_5_STATIC: Begin completions // RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[Constructor]/CurrNominal: ({#t: U#})[#FooGenericStruct<U>#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#self: &FooGenericStruct<U>#})[#U -> Void#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#self: &FooGenericStruct<U>#})[#U -> U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#self: &FooGenericStruct<U>#})[#(U) -> U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarT[#Int#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarTBrackets[#[Int]#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooVoidStaticFunc1({#(a): U#})[#Void#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooTStaticFunc1({#(a): U#})[#U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}} // RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: End completions } } func testResolveGenericParamsError1() { // There is no type 'Foo'. Check that we don't crash. // FIXME: we could also display correct completion results here, because // swift does not have specialization, and the set of completion results does // not depend on the generic type argument. FooGenericStruct<NotDefinedType>()#^RESOLVE_GENERIC_PARAMS_ERROR_1^# // RESOLVE_GENERIC_PARAMS_ERROR_1: found code completion token // RESOLVE_GENERIC_PARAMS_ERROR_1-NOT: Begin completions } //===--- Check that we can code complete expressions that have unsolved type variables. class BuilderStyle<T> { var count = 0 func addString(_ s: String) -> BuilderStyle<T> { count += 1 return self } func add(_ t: T) -> BuilderStyle<T> { count += 1 return self } func get() -> Int { return count } } func testTypeCheckWithUnsolvedVariables1() { BuilderStyle().#^TC_UNSOLVED_VARIABLES_1^# } // TC_UNSOLVED_VARIABLES_1: Begin completions // TC_UNSOLVED_VARIABLES_1-NEXT: Decl[InstanceVar]/CurrNominal: count[#Int#]{{; name=.+$}} // TC_UNSOLVED_VARIABLES_1-NEXT: Decl[InstanceMethod]/CurrNominal: addString({#(s): String#})[#BuilderStyle<T>#]{{; name=.+$}} // TC_UNSOLVED_VARIABLES_1-NEXT: Decl[InstanceMethod]/CurrNominal: add({#(t): T#})[#BuilderStyle<T>#]{{; name=.+$}} // TC_UNSOLVED_VARIABLES_1-NEXT: Decl[InstanceMethod]/CurrNominal: get()[#Int#]{{; name=.+$}} // TC_UNSOLVED_VARIABLES_1-NEXT: End completions func testTypeCheckWithUnsolvedVariables2() { BuilderStyle().addString("abc").#^TC_UNSOLVED_VARIABLES_2^# } // TC_UNSOLVED_VARIABLES_2: Begin completions // TC_UNSOLVED_VARIABLES_2-NEXT: Decl[InstanceVar]/CurrNominal: count[#Int#]{{; name=.+$}} // TC_UNSOLVED_VARIABLES_2-NEXT: Decl[InstanceMethod]/CurrNominal: addString({#(s): String#})[#BuilderStyle<T>#]{{; name=.+$}} // TC_UNSOLVED_VARIABLES_2-NEXT: Decl[InstanceMethod]/CurrNominal: add({#(t): T#})[#BuilderStyle<T>#]{{; name=.+$}} // TC_UNSOLVED_VARIABLES_2-NEXT: Decl[InstanceMethod]/CurrNominal: get()[#Int#]{{; name=.+$}} // TC_UNSOLVED_VARIABLES_2-NEXT: End completions func testTypeCheckWithUnsolvedVariables3() { BuilderStyle().addString("abc").add(42).#^TC_UNSOLVED_VARIABLES_3^# } // TC_UNSOLVED_VARIABLES_3: Begin completions // TC_UNSOLVED_VARIABLES_3-NEXT: Decl[InstanceVar]/CurrNominal: count[#Int#]{{; name=.+$}} // TC_UNSOLVED_VARIABLES_3-NEXT: Decl[InstanceMethod]/CurrNominal: addString({#(s): String#})[#BuilderStyle<Int>#]{{; name=.+$}} // TC_UNSOLVED_VARIABLES_3-NEXT: Decl[InstanceMethod]/CurrNominal: add({#(t): Int#})[#BuilderStyle<Int>#]{{; name=.+$}} // TC_UNSOLVED_VARIABLES_3-NEXT: Decl[InstanceMethod]/CurrNominal: get()[#Int#]{{; name=.+$}} // TC_UNSOLVED_VARIABLES_3-NEXT: End completions func testTypeCheckNil() { nil#^TC_UNSOLVED_VARIABLES_4^# } // TC_UNSOLVED_VARIABLES_4-NOT: Decl{{.*}}: .{{[a-zA-Z]}} //===--- Check that we can look up into modules func testResolveModules1() { Swift#^RESOLVE_MODULES_1^# // RESOLVE_MODULES_1: Begin completions // RESOLVE_MODULES_1-DAG: Decl[Struct]/OtherModule[Swift]: .Int8[#Int8#]{{; name=.+$}} // RESOLVE_MODULES_1-DAG: Decl[Struct]/OtherModule[Swift]: .Int16[#Int16#]{{; name=.+$}} // RESOLVE_MODULES_1-DAG: Decl[Struct]/OtherModule[Swift]: .Int32[#Int32#]{{; name=.+$}} // RESOLVE_MODULES_1-DAG: Decl[Struct]/OtherModule[Swift]: .Int64[#Int64#]{{; name=.+$}} // RESOLVE_MODULES_1-DAG: Decl[Struct]/OtherModule[Swift]: .Bool[#Bool#]{{; name=.+$}} // RESOLVE_MODULES_1-DAG: Decl[TypeAlias]/OtherModule[Swift]: .Float32[#Float#]{{; name=.+$}} // RESOLVE_MODULES_1: End completions } //===--- Check that we can complete inside interpolated string literals func testInterpolatedString1() { "\(fooObject.#^INTERPOLATED_STRING_1^#)" } // FOO_OBJECT_DOT1: Begin completions // FOO_OBJECT_DOT1-DAG: Decl[InstanceVar]/CurrNominal: lazyInstanceVar[#Int#]{{; name=.+$}} // FOO_OBJECT_DOT1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: instanceFunc0()[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: instanceFunc2({#(a): Int#}, {#b: &Double#})[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: instanceFunc3({#(a): Int#}, {#(Float, Double)#})[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: instanceFunc4({#(a): Int?#}, {#b: Int!#}, {#c: &Int?#}, {#d: &Int!#})[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc5()[#Int?#]{{; name=.+$}} // FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc6()[#Int!#]{{; name=.+$}} //===--- Check protocol extensions struct WillConformP1 { } protocol P1 { func reqP1() } protocol P2 : P1 { func reqP2() } protocol P3 : P1, P2 { } extension P1 { final func extP1() {} } extension P2 { final func extP2() {} } extension P3 { final func reqP1() {} final func reqP2() {} final func extP3() {} } extension WillConformP1 : P1 { func reqP1() {} } struct DidConformP2 : P2 { func reqP1() {} func reqP2() {} } struct DidConformP3 : P3 { } func testProtocol1(_ x: P1) { x.#^PROTOCOL_EXT_P1^# } // PROTOCOL_EXT_P1: Begin completions // PROTOCOL_EXT_P1-DAG: Decl[InstanceMethod]/CurrNominal: reqP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_P1-DAG: Decl[InstanceMethod]/CurrNominal: extP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_P1: End completions func testProtocol2(_ x: P2) { x.#^PROTOCOL_EXT_P2^# } // PROTOCOL_EXT_P2: Begin completions // PROTOCOL_EXT_P2-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_P2-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_P2-DAG: Decl[InstanceMethod]/CurrNominal: reqP2()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_P2-DAG: Decl[InstanceMethod]/CurrNominal: extP2()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_P2: End completions func testProtocol3(_ x: P3) { x.#^PROTOCOL_EXT_P3^# } // PROTOCOL_EXT_P3: Begin completions // FIXME: the next two should both be "CurrentNominal" // PROTOCOL_EXT_P3-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_P3-DAG: Decl[InstanceMethod]/Super: reqP2()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_P3-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_P3-DAG: Decl[InstanceMethod]/Super: extP2()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_P3-DAG: Decl[InstanceMethod]/CurrNominal: extP3()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_P3: End completions func testConformingConcrete1(_ x: WillConformP1) { x.#^PROTOCOL_EXT_WILLCONFORMP1^# } // PROTOCOL_EXT_WILLCONFORMP1: Begin completions // PROTOCOL_EXT_WILLCONFORMP1-DAG: Decl[InstanceMethod]/CurrNominal: reqP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_WILLCONFORMP1-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_WILLCONFORMP1: End completions func testConformingConcrete2(_ x: DidConformP2) { x.#^PROTOCOL_EXT_DIDCONFORMP2^# } // PROTOCOL_EXT_DIDCONFORMP2: Begin completions // PROTOCOL_EXT_DIDCONFORMP2-DAG: Decl[InstanceMethod]/CurrNominal: reqP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_DIDCONFORMP2-DAG: Decl[InstanceMethod]/CurrNominal: reqP2()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_DIDCONFORMP2-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_DIDCONFORMP2-DAG: Decl[InstanceMethod]/Super: extP2()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_DIDCONFORMP2: End completions func testConformingConcrete3(_ x: DidConformP3) { x.#^PROTOCOL_EXT_DIDCONFORMP3^# } // PROTOCOL_EXT_DIDCONFORMP3: Begin completions // FIXME: the next two should both be "CurrentNominal" // PROTOCOL_EXT_DIDCONFORMP3-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_DIDCONFORMP3-DAG: Decl[InstanceMethod]/Super: reqP2()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_DIDCONFORMP3-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_DIDCONFORMP3-DAG: Decl[InstanceMethod]/Super: extP2()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_DIDCONFORMP3-DAG: Decl[InstanceMethod]/Super: extP3()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_DIDCONFORMP3: End completions func testGenericConforming1<T: P1>(x: T) { x.#^PROTOCOL_EXT_GENERICP1^# } // PROTOCOL_EXT_GENERICP1: Begin completions // PROTOCOL_EXT_GENERICP1-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_GENERICP1-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_GENERICP1: End completions func testGenericConforming2<T: P2>(x: T) { x.#^PROTOCOL_EXT_GENERICP2^# } // PROTOCOL_EXT_GENERICP2: Begin completions // PROTOCOL_EXT_GENERICP2-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_GENERICP2-DAG: Decl[InstanceMethod]/Super: reqP2()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_GENERICP2-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_GENERICP2-DAG: Decl[InstanceMethod]/Super: extP2()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_GENERICP2: End completions func testGenericConforming3<T: P3>(x: T) { x.#^PROTOCOL_EXT_GENERICP3^# } // PROTOCOL_EXT_GENERICP3: Begin completions // PROTOCOL_EXT_GENERICP3-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_GENERICP3-DAG: Decl[InstanceMethod]/Super: reqP2()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_GENERICP3-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_GENERICP3-DAG: Decl[InstanceMethod]/Super: extP2()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_GENERICP3-DAG: Decl[InstanceMethod]/Super: extP3()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_GENERICP3: End completions struct OnlyMe {} protocol P4 { associatedtype T } extension P4 where Self.T : P1 { final func extP4WhenP1() {} final var x: Int { return 1 } init() {} } extension P4 where Self.T : P1 { init(x: Int) {} } extension P4 where Self.T == OnlyMe { final func extP4OnlyMe() {} final subscript(x: Int) -> Int { return 2 } } struct Concrete1 : P4 { typealias T = WillConformP1 } struct Generic1<S: P1> : P4 { typealias T = S } struct Concrete2 : P4 { typealias T = OnlyMe } struct Generic2<S> : P4 { typealias T = S } func testConstrainedP4(_ x: P4) { x.#^PROTOCOL_EXT_P4^# } // PROTOCOL_EXT_P4-NOT: extP4 func testConstrainedConcrete1(_ x: Concrete1) { x.#^PROTOCOL_EXT_CONCRETE1^# } func testConstrainedConcrete2(_ x: Generic1<WillConformP1>) { x.#^PROTOCOL_EXT_CONCRETE2^# } func testConstrainedGeneric1<S: P1>(x: Generic1<S>) { x.#^PROTOCOL_EXT_CONSTRAINED_GENERIC_1^# } func testConstrainedGeneric2<S: P4 where S.T : P1>(x: S) { x.#^PROTOCOL_EXT_CONSTRAINED_GENERIC_2^# } extension Concrete1 { func testInsideConstrainedConcrete1_1() { #^PROTOCOL_EXT_INSIDE_CONCRETE1_1^# } func testInsideConstrainedConcrete1_2() { self.#^PROTOCOL_EXT_INSIDE_CONCRETE1_2^# } } // PROTOCOL_EXT_P4_P1: Begin completions // PROTOCOL_EXT_P4_P1-NOT: extP4OnlyMe() // PROTOCOL_EXT_P4_P1-DAG: Decl[InstanceMethod]/Super: extP4WhenP1()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_P4_P1-DAG: Decl[InstanceVar]/Super: x[#Int#]{{; name=.+$}} // PROTOCOL_EXT_P4_P1-NOT: extP4OnlyMe() // PROTOCOL_EXT_P4_P1: End completions func testConstrainedConcrete3(_ x: Concrete2) { x.#^PROTOCOL_EXT_CONCRETE3^# } func testConstrainedConcrete3_sub(_ x: Concrete2) { x#^PROTOCOL_EXT_CONCRETE3_SUB^# } func testConstrainedConcrete4(_ x: Generic2<OnlyMe>) { x.#^PROTOCOL_EXT_CONCRETE4^# } func testConstrainedGeneric1<S: P4 where S.T == OnlyMe>(x: S) { x.#^PROTOCOL_EXT_CONSTRAINED_GENERIC_3^# } func testConstrainedGeneric1_sub<S: P4 where S.T == OnlyMe>(x: S) { x#^PROTOCOL_EXT_CONSTRAINED_GENERIC_3_SUB^# } extension Concrete2 { func testInsideConstrainedConcrete2_1() { #^PROTOCOL_EXT_INSIDE_CONCRETE2_1^# } func testInsideConstrainedConcrete2_2() { self.#^PROTOCOL_EXT_INSIDE_CONCRETE2_2^# } } // PROTOCOL_EXT_P4_ONLYME: Begin completions // PROTOCOL_EXT_P4_ONLYME-NOT: extP4WhenP1() // PROTOCOL_EXT_P4_ONLYME-NOT: x[#Int#] // PROTOCOL_EXT_P4_ONLYME-DAG: Decl[InstanceMethod]/Super: extP4OnlyMe()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_P4_ONLYME-NOT: extP4WhenP1() // PROTOCOL_EXT_P4_ONLYME-NOT: x[#Int#] // PROTOCOL_EXT_P4_ONLYME: End completions // PROTOCOL_EXT_P4_ONLYME_SUB: Begin completions // PROTOCOL_EXT_P4_ONLYME_SUB: Decl[Subscript]/Super: [{#Int#}][#Int#]{{; name=.+$}} // PROTOCOL_EXT_P4_ONLYME_SUB: End completions func testTypealias1() { Concrete1.#^PROTOCOL_EXT_TA_1^# } func testTypealias1<S: P4 where S.T == WillConformP1>() { S.#^PROTOCOL_EXT_TA_2^# } // PROTOCOL_EXT_TA: Begin completions // PROTOCOL_EXT_TA_2-DAG: Decl[AssociatedType]/{{Super|CurrNominal}}: T // PROTOCOL_EXT_TA: End completions func testProtExtInit1() { Concrete1(#^PROTOCOL_EXT_INIT_1^# } // PROTOCOL_EXT_INIT_1: Begin completions // PROTOCOL_EXT_INIT_1: Decl[Constructor]/Super: ['('])[#Concrete1#]{{; name=.+$}} // PROTOCOL_EXT_INIT_1: Decl[Constructor]/Super: ['(']{#x: Int#})[#Concrete1#]{{; name=.+$}} // PROTOCOL_EXT_INIT_1: End completions func testProtExtInit2<S: P4 where S.T : P1>() { S(#^PROTOCOL_EXT_INIT_2^# } // PROTOCOL_EXT_INIT_2: Begin completions // PROTOCOL_EXT_INIT_2: Decl[Constructor]/Super: ['('])[#P4#]{{; name=.+$}} // PROTOCOL_EXT_INIT_2: Decl[Constructor]/Super: ['(']{#x: Int#})[#P4#]{{; name=.+$}} // PROTOCOL_EXT_INIT_2: End completions extension P4 where Self.T == OnlyMe { final func test1() { self.#^PROTOCOL_EXT_P4_DOT_1^# } final func test2() { #^PROTOCOL_EXT_P4_DOT_2^# } } // PROTOCOL_EXT_P4_DOT: Begin completions // PROTOCOL_EXT_P4_DOT-NOT: extP4WhenP1() // PROTOCOL_EXT_P4_DOT-DAG: Decl[InstanceMethod]/Super: extP4OnlyMe()[#Void#]{{; name=.+$}} // PROTOCOL_EXT_P4_DOT-NOT: extP4WhenP1() // PROTOCOL_EXT_P4_DOT: End completions extension P4 where Self.T == WillConformP1 { final func test() { T.#^PROTOCOL_EXT_P4_T_DOT_1^# } } // PROTOCOL_EXT_P4_T_DOT_1: Begin completions // PROTOCOL_EXT_P4_T_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: reqP1({#self: WillConformP1#})[#() -> Void#]{{; name=.+$}} // PROTOCOL_EXT_P4_T_DOT_1-DAG: Decl[InstanceMethod]/Super: extP1({#self: WillConformP1#})[#() -> Void#]{{; name=.+$}} // PROTOCOL_EXT_P4_T_DOT_1: End completions protocol PWithT { associatedtype T func foo(_ x: T) -> T } extension PWithT { final func bar(_ x: T) -> T { return x } } // Note: PWithT cannot actually be used as an existential type because it has // an associated type. But we should still be able to give code completions. func testUnusableProtExt(_ x: PWithT) { x.#^PROTOCOL_EXT_UNUSABLE_EXISTENTIAL^# } // PROTOCOL_EXT_UNUSABLE_EXISTENTIAL: Begin completions // PROTOCOL_EXT_UNUSABLE_EXISTENTIAL: Decl[InstanceMethod]/CurrNominal: foo({#(x): PWithT.T#})[#PWithT.T#]{{; name=.+}} // PROTOCOL_EXT_UNUSABLE_EXISTENTIAL: Decl[InstanceMethod]/CurrNominal: bar({#(x): PWithT.T#})[#PWithT.T#]{{; name=.+}} // PROTOCOL_EXT_UNUSABLE_EXISTENTIAL: End completions protocol dedupP { associatedtype T func foo() -> T var bar: T {get} subscript(x: T) -> T {get} } extension dedupP { func foo() -> T { return T() } var bar: T { return T() } subscript(x: T) -> T { return T() } } struct dedupS : dedupP { func foo() -> Int { return T() } var bar: Int = 5 subscript(x: Int) -> Int { return 10 } } func testDeDuped(_ x: dedupS) { x#^PROTOCOL_EXT_DEDUP_1^# // PROTOCOL_EXT_DEDUP_1: Begin completions, 3 items // PROTOCOL_EXT_DEDUP_1: Decl[InstanceMethod]/CurrNominal: .foo()[#Int#]; name=foo() // PROTOCOL_EXT_DEDUP_1: Decl[InstanceVar]/CurrNominal: .bar[#Int#]; name=bar // PROTOCOL_EXT_DEDUP_1: Decl[Subscript]/CurrNominal: [{#Int#}][#Int#]; name=[Int] // PROTOCOL_EXT_DEDUP_1: End completions } func testDeDuped2(_ x: dedupP) { x#^PROTOCOL_EXT_DEDUP_2^# // PROTOCOL_EXT_DEDUP_2: Begin completions, 4 items // PROTOCOL_EXT_DEDUP_2: Decl[InstanceMethod]/CurrNominal: .foo()[#dedupP.T#]; name=foo() // PROTOCOL_EXT_DEDUP_2: Decl[InstanceVar]/CurrNominal: .bar[#dedupP.T#]; name=bar // PROTOCOL_EXT_DEDUP_2: Decl[Subscript]/CurrNominal: [{#Self.T#}][#Self.T#]; name=[Self.T] // FIXME: duplicate subscript on protocol type rdar://problem/22086900 // PROTOCOL_EXT_DEDUP_2: Decl[Subscript]/CurrNominal: [{#Self.T#}][#Self.T#]; name=[Self.T] // PROTOCOL_EXT_DEDUP_2: End completions } func testDeDuped3<T : dedupP where T.T == Int>(_ x: T) { x#^PROTOCOL_EXT_DEDUP_3^# // PROTOCOL_EXT_DEDUP_3: Begin completions, 3 items // PROTOCOL_EXT_DEDUP_3: Decl[InstanceMethod]/Super: .foo()[#Int#]; name=foo() // PROTOCOL_EXT_DEDUP_3: Decl[InstanceVar]/Super: .bar[#Int#]; name=bar // PROTOCOL_EXT_DEDUP_3: Decl[Subscript]/Super: [{#Self.T#}][#Self.T#]; name=[Self.T] // PROTOCOL_EXT_DEDUP_3: End completions } //===--- Check calls that may throw func globalFuncThrows() throws {} func globalFuncRethrows(_ x: () throws -> ()) rethrows {} struct HasThrowingMembers { func memberThrows() throws {} func memberRethrows(_ x: () throws -> ()) rethrows {} init() throws {} init(x: () throws -> ()) rethrows {} } func testThrows001() { globalFuncThrows#^THROWS1^# // THROWS1: Begin completions // THROWS1: Pattern/ExprSpecific: ()[' throws'][#Void#]; name=() throws // THROWS1: End completions } func testThrows002() { globalFuncRethrows#^THROWS2^# // THROWS2: Begin completions // THROWS2: Pattern/ExprSpecific: ({#(x): () throws -> ()##() throws -> ()#})[' rethrows'][#Void#]; name=(x: () throws -> ()) rethrows // THROWS2: End completions } func testThrows003(_ x: HasThrowingMembers) { x.#^MEMBER_THROWS1^# // MEMBER_THROWS1: Begin completions // MEMBER_THROWS1-DAG: Decl[InstanceMethod]/CurrNominal: memberThrows()[' throws'][#Void#] // MEMBER_THROWS1-DAG: Decl[InstanceMethod]/CurrNominal: memberRethrows({#(x): () throws -> ()##() throws -> ()#})[' rethrows'][#Void#] // MEMBER_THROWS1: End completions } func testThrows004(_ x: HasThrowingMembers) { x.memberThrows#^MEMBER_THROWS2^# // MEMBER_THROWS2: Begin completions // MEMBER_THROWS2: Pattern/ExprSpecific: ()[' throws'][#Void#]; name=() throws // MEMBER_THROWS2: End completions } func testThrows005(_ x: HasThrowingMembers) { x.memberRethrows#^MEMBER_THROWS3^# // MEMBER_THROWS3: Begin completions // MEMBER_THROWS3: Pattern/ExprSpecific: ({#(x): () throws -> ()##() throws -> ()#})[' rethrows'][#Void#]; name=(x: () throws -> ()) rethrows // MEMBER_THROWS3: End completions } func testThrows006() { HasThrowingMembers(#^INIT_THROWS1^# // INIT_THROWS1: Begin completions // INIT_THROWS1: Decl[Constructor]/CurrNominal: ['('])[' throws'][#HasThrowingMembers#] // INIT_THROWS1: Decl[Constructor]/CurrNominal: ['(']{#x: () throws -> ()##() throws -> ()#})[' rethrows'][#HasThrowingMembers#] // INIT_THROWS1: End completions } // rdar://21346928 // Just sample some String API to sanity check. // AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: characters[#String.CharacterView#] // AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: utf16[#String.UTF16View#] // AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: utf8[#String.UTF8View#] func testWithAutoClosure1(_ x: String?) { (x ?? "autoclosure").#^AUTOCLOSURE1^# } func testWithAutoClosure2(_ x: String?) { let y = (x ?? "autoclosure").#^AUTOCLOSURE2^# } func testWithAutoClosure3(_ x: String?) { let y = (x ?? "autoclosure".#^AUTOCLOSURE3^#) } func testWithAutoClosure4(_ x: String?) { let y = { let z = (x ?? "autoclosure").#^AUTOCLOSURE4^# } } func testWithAutoClosure5(_ x: String?) { if let y = (x ?? "autoclosure").#^AUTOCLOSURE5^# { } } func testGenericTypealias1() { typealias MyPair<T> = (T, T) var x: MyPair<Int> x.#^GENERIC_TYPEALIAS_1^# } // GENERIC_TYPEALIAS_1: Pattern/CurrNominal: 0[#Int#]; // GENERIC_TYPEALIAS_1: Pattern/CurrNominal: 1[#Int#]; func testGenericTypealias2() { struct Enclose { typealias MyPair<T> = (T, T) } Enclose.#^GENERIC_TYPEALIAS_2^# } // GENERIC_TYPEALIAS_2: Decl[TypeAlias]/CurrNominal: MyPair[#(T, T)#]; struct Deprecated { @available(*, deprecated) func deprecated(x: Deprecated) { x.#^DEPRECATED_1^# } } // DEPRECATED_1: Decl[InstanceMethod]/CurrNominal/NotRecommended: deprecated({#x: Deprecated#})[#Void#]; struct Person { var firstName: String } class Other { var nameFromOther: Int = 1 } class TestDotExprWithNonNominal { var other: Other func test1() { let person = Person(firstName: other.#^DOT_EXPR_NON_NOMINAL_1^#) // DOT_EXPR_NON_NOMINAL_1-NOT: Instance // DOT_EXPR_NON_NOMINAL_1: Decl[InstanceVar]/CurrNominal: nameFromOther[#Int#]; // DOT_EXPR_NON_NOMINAL_1-NOT: Instance } func test2() { let person = Person(firstName: 1.#^DOT_EXPR_NON_NOMINAL_2^#) // DOT_EXPR_NON_NOMINAL_2-NOT: other // DOT_EXPR_NON_NOMINAL_2-NOT: firstName // DOT_EXPR_NON_NOMINAL_2: Decl[InstanceVar]/CurrNominal: hashValue[#Int#]; // DOT_EXPR_NON_NOMINAL_2-NOT: other // DOT_EXPR_NON_NOMINAL_2-NOT: firstName } }
apache-2.0
e8594b6b0a66487d324e69d2eadf53bc
57.247916
202
0.695824
3.436686
false
true
false
false
fgengine/quickly
Quickly/Table/Default/Cell/QCompositionTableCell.swift
1
7642
// // Quickly // public enum QCompositionTableRowSizeBehaviour { case dynamic case full case fixed(height: CGFloat) case bound(minimum: CGFloat, maximum: CGFloat) } open class QCompositionTableRow< Composable: IQComposable > : QBackgroundColorTableRow { public var composable: Composable public var selectedComposable: Composable? public var sizeBehaviour: QCompositionTableRowSizeBehaviour public init( composable: Composable, selectedComposable: Composable? = nil, sizeBehaviour: QCompositionTableRowSizeBehaviour = .dynamic, backgroundColor: UIColor? = nil, selectedBackgroundColor: UIColor? = nil, canSelect: Bool = true, canEdit: Bool = false, canMove: Bool = false, selectionStyle: UITableViewCell.SelectionStyle = .default, editingStyle: UITableViewCell.EditingStyle = .none ) { self.composable = composable self.selectedComposable = selectedComposable self.sizeBehaviour = sizeBehaviour super.init( backgroundColor: backgroundColor, selectedBackgroundColor: selectedBackgroundColor, canSelect: canSelect, canEdit: canEdit, canMove: canMove, selectionStyle: selectionStyle, editingStyle: editingStyle ) } @available(iOS 11.0, *) public init( composable: Composable, selectedComposable: Composable? = nil, sizeBehaviour: QCompositionTableRowSizeBehaviour = .dynamic, backgroundColor: UIColor? = nil, selectedBackgroundColor: UIColor? = nil, canSelect: Bool = true, canEdit: Bool = false, canMove: Bool = false, selectionStyle: UITableViewCell.SelectionStyle = .default, editingStyle: UITableViewCell.EditingStyle = .none, leadingSwipeConfiguration: UISwipeActionsConfiguration? = nil, trailingSwipeConfiguration: UISwipeActionsConfiguration? = nil ) { self.composable = composable self.selectedComposable = selectedComposable self.sizeBehaviour = sizeBehaviour super.init( backgroundColor: backgroundColor, selectedBackgroundColor: selectedBackgroundColor, canSelect: canSelect, canEdit: canEdit, canMove: canMove, selectionStyle: selectionStyle, editingStyle: editingStyle, leadingSwipeConfiguration: leadingSwipeConfiguration, trailingSwipeConfiguration: trailingSwipeConfiguration ) } } open class QCompositionTableCell< Composition: IQComposition > : QBackgroundColorTableCell< QCompositionTableRow< Composition.Composable > >, IQTextFieldObserver, IQMultiTextFieldObserver, IQListFieldObserver, IQDateFieldObserver { public private(set) var composition: Composition! open override class func height(row: RowType, spec: IQContainerSpec) -> CGFloat { switch row.sizeBehaviour { case .dynamic: return Composition.height(composable: row.composable, spec: spec) case .full: return spec.containerSize.height case .fixed(let height): return height case .bound(let minimum, let maximum): let height = Composition.height(composable: row.composable, spec: spec) return max(maximum, min(height, minimum)) } } open override func setup() { super.setup() self.clipsToBounds = true self.composition = Composition(contentView: self.contentView, owner: self) } open override func prepareForReuse() { self.composition.cleanup() super.prepareForReuse() } open override func prepare(row: RowType, spec: IQContainerSpec, animated: Bool) { super.prepare(row: row, spec: spec, animated: animated) self._prepareComposition(row: row, spec: spec, highlighted: self.isHighlighted, selected: self.isSelected, animated: animated) } open override func setHighlighted(_ highlighted: Bool, animated: Bool) { super.setHighlighted(highlighted, animated: animated) if let row = self.row, let spec = self.composition.spec { self._prepareComposition(row: row, spec: spec, highlighted: highlighted, selected: self.isSelected, animated: animated) } } open override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if let row = self.row, let spec = self.composition.spec { self._prepareComposition(row: row, spec: spec, highlighted: self.isHighlighted, selected: selected, animated: animated) } } // MARK: IQTextFieldObserver open func beginEditing(textField: QTextField) { self._scroll(animated: true) } open func editing(textField: QTextField) { } open func endEditing(textField: QTextField) { } open func pressed(textField: QTextField, action: QFieldAction) { } open func pressedClear(textField: QTextField) { } open func pressedReturn(textField: QTextField) { } open func select(textField: QTextField, suggestion: String) { } // MARK: IQMultiTextFieldObserver open func beginEditing(multiTextField: QMultiTextField) { self._scroll(animated: true) } open func editing(multiTextField: QMultiTextField) { } open func endEditing(multiTextField: QMultiTextField) { } open func pressed(multiTextField: QMultiTextField, action: QFieldAction) { } open func changed(multiTextField: QMultiTextField, height: CGFloat) { guard let row = self.row, let section = row.section, let controller = section.controller else { return } controller.performBatchUpdates({ row.resetCacheHeight() }) } // MARK: IQListFieldObserver open func beginEditing(listField: QListField) { self._scroll(animated: true) } open func select(listField: QListField, row: QListFieldPickerRow) { } open func endEditing(listField: QListField) { } open func pressed(listField: QListField, action: QFieldAction) { } // MARK: IQDateFieldObserver open func beginEditing(dateField: QDateField) { self._scroll(animated: true) } open func select(dateField: QDateField, date: Date) { } open func endEditing(dateField: QDateField) { } open func pressed(dateField: QDateField, action: QFieldAction) { } // MARK: Private private func _prepareComposition(row: RowType, spec: IQContainerSpec, highlighted: Bool, selected: Bool, animated: Bool) { let composable = self._currentComposable(row: row, highlighted: highlighted, selected: selected) self.composition.prepare( composable: composable, spec: spec, animated: animated ) } private func _currentComposable(row: RowType, highlighted: Bool, selected: Bool) -> Composition.Composable { if selected == true || highlighted == true { if let selectedComposable = row.selectedComposable { return selectedComposable } } return row.composable } private func _scroll(animated: Bool) { guard let row = self.row, let controller = row.section?.controller else { return } controller.scroll(row: row, scroll: .middle, animated: animated) } }
mit
c8fd29831bc334c39b43dd212464c62a
32.517544
231
0.651531
5.198639
false
false
false
false
AckeeCZ/ACKategories
ACKategories-iOS/GradientView.swift
1
2726
// // GradientView.swift // ACKategories // // Created by Marek Fořt on 10/5/18. // Copyright © 2018 Ackee, s.r.o. All rights reserved. // import UIKit /** This view creates a gradient view with the defined colors - Warning: Please note that if one of your colors is clear, you should usually define to which "clear color" it should go to - i.e. if you want to go from white to clear, write: `[UIColor.white, UIColor.white.withAlphaComponent(0)]` */ open class GradientView: UIView { override open class var layerClass: Swift.AnyClass { CAGradientLayer.self } // MARK: - Private properties /// The axis of the gradient: `.vertical` for bottom-to-top gradient, `.horizontal` for left-to-right gradient. /// /// Default value is `.vertical` public var axis: NSLayoutConstraint.Axis { didSet { setupAxis() } } /// The colors to be used for the gradient public var colors: [UIColor] { didSet { setupGradientColors() } } // MARK: - Initializers /** Creates a gradient view with colors and axis - Parameters: - colors: The colors to be used for the gradient. - axis: The axis of the gradient: `.vertical` for bottom-to-top gradient, `.horizontal` for left-to-right gradient. */ public init(colors: [UIColor] = [], axis: NSLayoutConstraint.Axis = .vertical) { self.axis = axis self.colors = colors super.init(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) guard let gradientLayer = layer as? CAGradientLayer else { return } gradientLayer.frame = bounds isUserInteractionEnabled = false setupAxis() setupGradientColors() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View lifecycle open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) setupGradientColors() } // MARK: - Helpers private func setupGradientColors() { guard let gradientLayer = layer as? CAGradientLayer else { return } gradientLayer.colors = colors.map { $0.cgColor } } private func setupAxis() { guard let gradientLayer = layer as? CAGradientLayer else { return } if axis == .vertical { gradientLayer.startPoint = CGPoint(x: 0.5, y: 0) gradientLayer.endPoint = CGPoint(x: 0.5, y: 1) } else { gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5) } } }
mit
ed8be94c7af55b14c9e90160f9472717
29.606742
181
0.629589
4.407767
false
false
false
false
tokorom/SegueContext
Example/SliderViewController.swift
1
1138
// // SliderViewController.swift // // Created by ToKoRo on 2015-07-14. // import UIKit import SegueContext class SliderViewController: UIViewController { var value: Int = 0 { didSet { self.label?.text = String(value) } } @IBOutlet weak var label: UILabel? @IBOutlet weak var slider: UISlider? override func viewDidLoad() { super.viewDidLoad() if let value: Int = contextValue() { self.value = value if let slider = slider { slider.value = max(slider.minimumValue, min(slider.maximumValue, Float(value))) } } } @IBAction func sliderDidChange(_ slider: UISlider) { self.value = Int(slider.value) } @IBAction func buttonDidTap(_ sender: AnyObject) { if let callback: (Int) -> Void = callback() { callback(value) } dismiss(animated: true, completion: nil) } @IBAction func othersButtonDidTap(_ sender: AnyObject) { relayPresent(viewControllerIdentifier: "NavigationController", context: context, anyCallback: anyCallback) } }
mit
69adc90761965c807a904a58fd80a943
23.73913
114
0.605448
4.428016
false
false
false
false
asp2insp/CodePathFinalProject
Pretto/ZoomableCollectionView.swift
1
9272
// // ZoomableCollectionViewController.swift // ZoomableCollectionsView // // Created by Josiah Gaskin on 6/1/15. // Copyright (c) 2015 asp2insp. All rights reserved. // import UIKit import AudioToolbox class ZoomableCollectionViewController: UIViewController, UICollectionViewDelegate { @IBOutlet weak var collectionView: UICollectionView! let flowLayout = UICollectionViewFlowLayout() var baseSize : CGSize! var maxSize : CGSize! var minSize : CGSize! // Long press handling var selectionStart : NSIndexPath! var previousRange : [NSIndexPath]? var previousIndex : NSIndexPath? // Set to enable/disable selection and checkboxes var allowsSelection : Bool = true var selectedPaths = NSMutableSet() override func viewDidLoad() { super.viewDidLoad() collectionView.setCollectionViewLayout(flowLayout, animated: false) collectionView.allowsMultipleSelection = true flowLayout.sectionInset = UIEdgeInsetsMake(8, 8, 8, 8) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) maxSize = CGSizeMake(view.bounds.size.width/2 - 2*flowLayout.minimumInteritemSpacing, view.bounds.size.height/2 - 2*flowLayout.minimumLineSpacing) minSize = CGSizeMake(view.bounds.size.width/5 - 5*flowLayout.minimumInteritemSpacing, view.bounds.size.height/5 - 5*flowLayout.minimumLineSpacing) } internal func onSelectionChange() { // Override this in subclasses to respond to selection change } @IBAction func didPinch(sender: UIPinchGestureRecognizer) { switch sender.state { case .Began: baseSize = flowLayout.itemSize case .Changed: flowLayout.itemSize = aspectScaleWithConstraints(baseSize, scale: sender.scale, max: maxSize, min: minSize) case .Ended, .Cancelled: flowLayout.itemSize = aspectScaleWithConstraints(baseSize, scale: sender.scale, max: maxSize, min: minSize) default: return } } func aspectScaleWithConstraints(size: CGSize, scale: CGFloat, max: CGSize, min: CGSize) -> CGSize { let maxHScale = fmax(max.width / size.width, 1.0) let maxVScale = fmax(max.height / size.height, 1.0) let scaleBoundedByMax = fmin(fmin(scale, maxHScale), maxVScale) let minHScale = fmin(min.width / size.width, 1.0) let minVScale = fmin(min.height / size.height, 1.0) let scaleBoundedByMin = fmax(fmax(scaleBoundedByMax, minHScale), minVScale) return CGSizeMake(size.width * scaleBoundedByMin, size.height * scaleBoundedByMin) } @IBAction func didLongPressAndDrag(sender: UILongPressGestureRecognizer) { let touchCoords = sender.locationInView(collectionView) switch sender.state { case .Began, .Changed: let currentIndex = pointToIndexPath(touchCoords, fuzzySize: 5) if currentIndex != nil { if selectionStart == nil { selectionStart = currentIndex selectItemAtIndexPathIfNecessary(selectionStart) AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) return } // Change detection if currentIndex != previousIndex { let itemsToSelect = getIndexRange(start: selectionStart, end: currentIndex!) let itemsToDeselect = difference(previousRange, minus: itemsToSelect) for path in itemsToDeselect { deselectItemAtIndexPathIfNecessary(path) } for path in itemsToSelect { selectItemAtIndexPathIfNecessary(path) } previousRange = itemsToSelect previousIndex = currentIndex } } case .Cancelled, .Ended: selectionStart = nil previousRange = nil previousIndex = nil default: return } } func selectItemAtIndexPathIfNecessary(path: NSIndexPath) { if !allowsSelection { return } if let cell = collectionView.cellForItemAtIndexPath(path) as? SelectableImageCell { if !cell.selected { collectionView.selectItemAtIndexPath(path, animated: true, scrollPosition: UICollectionViewScrollPosition.None) } cell.checkbox.checkState = M13CheckboxStateChecked cell.animateStateChange() } self.selectedPaths.addObject(path) onSelectionChange() } func deselectItemAtIndexPathIfNecessary(path: NSIndexPath) { if !allowsSelection { return } if let cell = collectionView.cellForItemAtIndexPath(path) as? SelectableImageCell { if (cell.selected) { collectionView.deselectItemAtIndexPath(path, animated: true) } cell.checkbox.checkState = M13CheckboxStateUnchecked cell.animateStateChange() } self.selectedPaths.removeObject(path) onSelectionChange() } // Return the difference of the given arrays of index paths func difference(a: [NSIndexPath]?, minus b: [NSIndexPath]?) -> [NSIndexPath] { if a == nil { return [] } if b == nil { return a! } var final = a! for item in b! { if let index = find(final, item) { final.removeAtIndex(index) } } return final } // Return an array of NSIndexPaths between the given start and end, inclusive func getIndexRange(#start: NSIndexPath, end: NSIndexPath) -> [NSIndexPath] { var range : [NSIndexPath] = [] let numItems = abs(start.row - end.row) let section = start.section for var i = 0; i <= numItems; i++ { let newRow = start.row < end.row ? start.row+i : start.row-i if newRow >= 0 && newRow < collectionView.numberOfItemsInSection(section) { range.append(NSIndexPath(forRow: newRow, inSection: section)) } } return range } // Convert a touch point to an index path of the cell under the point. // Returns nil if no cell exists under the given point. func pointToIndexPath(point: CGPoint, fuzzySize: CGFloat) -> NSIndexPath? { let fingerRect = CGRectMake(point.x-fuzzySize, point.y-fuzzySize, fuzzySize*2, fuzzySize*2) for item in collectionView.visibleCells() { let cell = item as! SelectableImageCell if CGRectIntersectsRect(fingerRect, cell.frame) { return collectionView.indexPathForCell(cell) } } return nil } } // UICollectionViewDelegate Extension extension ZoomableCollectionViewController { func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { deselectItemAtIndexPathIfNecessary(indexPath) } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { selectItemAtIndexPathIfNecessary(indexPath) } func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { if let c = cell as? SelectableImageCell { c.showCheckbox = self.allowsSelection } } } class SelectableImageCell : UICollectionViewCell { var image: PFImageView! var checkbox: M13Checkbox! var showCheckbox : Bool = true { didSet { self.checkbox.hidden = !showCheckbox self.checkbox.setNeedsDisplay() } } override func awakeFromNib() { image = PFImageView(frame: self.bounds) image.contentMode = UIViewContentMode.ScaleAspectFill checkbox = M13Checkbox(frame: CGRectMake(0, 0, 20, 20)) checkbox.center = CGPointMake(25, 25) checkbox.userInteractionEnabled = false checkbox.checkState = selected ? M13CheckboxStateChecked : M13CheckboxStateUnchecked checkbox.radius = 0.5 * checkbox.frame.size.width; checkbox.flat = true // checkbox.tintColor = checkbox.strokeColor // checkbox.checkColor = UIColor.whiteColor() checkbox.strokeColor = UIColor.clearColor() checkbox.tintColor = UIColor.prettoOrange() checkbox.checkColor = UIColor.prettoBlue() self.addSubview(image) self.addSubview(checkbox) } override func layoutSubviews() { super.layoutSubviews() image.frame = self.bounds } func animateStateChange() { UIView.animateWithDuration(0.5, animations: { () -> Void in self.checkbox.transform = CGAffineTransformMakeScale(2, 2) self.checkbox.transform = CGAffineTransformMakeScale(1, 1) }) } func updateCheckState() { checkbox.checkState = selected ? M13CheckboxStateChecked : M13CheckboxStateUnchecked } }
mit
403eb37df69cffc3ff7e5fca5bd0fdaf
36.84898
154
0.633089
5.179888
false
false
false
false
xmartlabs/Eureka
Source/Rows/StepperRow.swift
1
5688
// // StepperRow.swift // Eureka // // Created by Andrew Holt on 3/4/16. // Copyright © 2016 Xmartlabs. All rights reserved. // import UIKit // MARK: StepperCell open class StepperCell: Cell<Double>, CellType { @IBOutlet open weak var stepper: UIStepper! @IBOutlet open weak var valueLabel: UILabel! @IBOutlet open weak var titleLabel: UILabel! private var awakeFromNibCalled = false required public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .value1, reuseIdentifier: reuseIdentifier) NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: nil) { [weak self] _ in guard let me = self else { return } if me.shouldShowTitle { me.titleLabel = me.textLabel me.setNeedsUpdateConstraints() } } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) awakeFromNibCalled = true } open override func setup() { super.setup() if !awakeFromNibCalled { let title = textLabel textLabel?.translatesAutoresizingMaskIntoConstraints = false textLabel?.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) self.titleLabel = title let stepper = UIStepper() stepper.translatesAutoresizingMaskIntoConstraints = false stepper.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) self.stepper = stepper if shouldShowTitle { contentView.addSubview(titleLabel) } setupValueLabel() contentView.addSubview(stepper) setNeedsUpdateConstraints() } selectionStyle = .none stepper.addTarget(self, action: #selector(StepperCell.valueChanged), for: .valueChanged) } open func setupValueLabel() { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.setContentHuggingPriority(UILayoutPriority(500), for: .horizontal) label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.5 self.valueLabel = label contentView.addSubview(valueLabel) } open override func update() { super.update() detailTextLabel?.text = nil stepper.isEnabled = !row.isDisabled titleLabel.isHidden = !shouldShowTitle stepper.value = row.value ?? 0 stepper.alpha = row.isDisabled ? 0.3 : 1.0 valueLabel?.textColor = tintColor valueLabel?.alpha = row.isDisabled ? 0.3 : 1.0 valueLabel?.text = row.displayValueFor?(row.value) } @objc(stepperValueDidChange) func valueChanged() { row.value = stepper.value row.updateCell() } var shouldShowTitle: Bool { return row?.title?.isEmpty == false } private var stepperRow: StepperRow { return row as! StepperRow } deinit { stepper.removeTarget(self, action: nil, for: .allEvents) guard !awakeFromNibCalled else { return } NotificationCenter.default.removeObserver(self, name: UIContentSizeCategory.didChangeNotification, object: nil) } open override func updateConstraints() { customConstraints() super.updateConstraints() } open var dynamicConstraints = [NSLayoutConstraint]() open func customConstraints() { guard !awakeFromNibCalled else { return } contentView.removeConstraints(dynamicConstraints) dynamicConstraints = [] var views: [String : Any] = ["titleLabel": titleLabel!, "stepper": stepper!, "valueLabel": valueLabel!] let metrics = ["spacing": 15.0] valueLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) titleLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) let title = shouldShowTitle ? "[titleLabel]-(>=15@250)-" : "" if let imageView = imageView, let _ = imageView.image { views["imageView"] = imageView let hContraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[imageView]-(15)-\(title)[valueLabel]-[stepper]-|", options: .alignAllCenterY, metrics: metrics, views: views) imageView.translatesAutoresizingMaskIntoConstraints = false dynamicConstraints.append(contentsOf: hContraints) } else { let hContraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-\(title)[valueLabel]-[stepper]-|", options: .alignAllCenterY, metrics: metrics, views: views) dynamicConstraints.append(contentsOf: hContraints) } let vContraint = NSLayoutConstraint(item: stepper!, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0) dynamicConstraints.append(vContraint) contentView.addConstraints(dynamicConstraints) } } // MARK: StepperRow open class _StepperRow: Row<StepperCell> { required public init(tag: String?) { super.init(tag: tag) displayValueFor = { value in guard let value = value else { return nil } return DecimalFormatter().string(from: NSNumber(value: value)) } } } /// Double row that has a UIStepper as accessoryType public final class StepperRow: _StepperRow, RowType { required public init(tag: String?) { super.init(tag: tag) } }
mit
9052681fedccce29e3a11e7d0466a6e6
35.22293
194
0.645331
5.309991
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/ContactsUI/ContactsViewController.swift
1
7777
// // Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit final class ContactsViewController: UIViewController { let dataSource = ContactsDataSource() typealias PeoplePicker = L10n.Localizable.Peoplepicker typealias ContactsUI = L10n.Localizable.ContactsUi typealias LabelColors = SemanticColors.Label typealias ViewColors = SemanticColors.View let bottomContainerView = UIView() let bottomContainerSeparatorView = UIView() let noContactsLabel = DynamicFontLabel(text: PeoplePicker.noContactsTitle, fontSpec: .headerRegularFont, color: LabelColors.textSettingsPasswordPlaceholder) let searchHeaderViewController = SearchHeaderViewController(userSelection: .init()) let separatorView = UIView() let tableView = UITableView() let inviteOthersButton = Button(style: .accentColorTextButtonStyle, cornerRadius: 16, fontSpec: .normalSemiboldFont) let emptyResultsLabel = DynamicFontLabel(text: PeoplePicker.noMatchingResultsAfterAddressBookUploadTitle, fontSpec: .headerRegularFont, color: LabelColors.textSettingsPasswordPlaceholder) var bottomEdgeConstraint: NSLayoutConstraint? var bottomContainerBottomConstraint: NSLayoutConstraint? // MARK: - Life Cycle init() { super.init(nibName: nil, bundle: nil) dataSource.delegate = self tableView.dataSource = dataSource } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupViews() setupLayout() setupStyle() observeKeyboardFrame() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) showKeyboardIfNeeded() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) _ = searchHeaderViewController.tokenField.resignFirstResponder() } // MARK: - Setup private func setupViews() { setupSearchHeader() view.addSubview(separatorView) setupTableView() setupEmptyResultsLabel() setupNoContactsLabel() setupBottomContainer() } private func setupSearchHeader() { searchHeaderViewController.delegate = self searchHeaderViewController.allowsMultipleSelection = false searchHeaderViewController.view.backgroundColor = ViewColors.backgroundDefault addToSelf(searchHeaderViewController) } private func setupTableView() { tableView.dataSource = dataSource tableView.delegate = self tableView.allowsSelection = false tableView.rowHeight = 52 tableView.keyboardDismissMode = .onDrag tableView.sectionIndexMinimumDisplayRowCount = Int(ContactsDataSource.MinimumNumberOfContactsToDisplaySections) ContactsCell.register(in: tableView) ContactsSectionHeaderView.register(in: tableView) let bottomContainerHeight: CGFloat = 56.0 + UIScreen.safeArea.bottom tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: bottomContainerHeight, right: 0) view.addSubview(tableView) } private func setupEmptyResultsLabel() { emptyResultsLabel.textAlignment = .center view.addSubview(emptyResultsLabel) } private func setupNoContactsLabel() { view.addSubview(noContactsLabel) } private func setupBottomContainer() { view.addSubview(bottomContainerView) bottomContainerView.addSubview(bottomContainerSeparatorView) inviteOthersButton.addTarget(self, action: #selector(sendIndirectInvite), for: .touchUpInside) inviteOthersButton.setTitle(ContactsUI.inviteOthers.capitalized, for: .normal) bottomContainerView.addSubview(inviteOthersButton) } private func setupStyle() { navigationItem.setupNavigationBarTitle(title: ContactsUI.title.capitalized) view.backgroundColor = .clear tableView.backgroundColor = .clear tableView.separatorStyle = .none tableView.sectionIndexBackgroundColor = .clear tableView.sectionIndexColor = .accent() bottomContainerSeparatorView.backgroundColor = ViewColors.backgroundSeparatorCell bottomContainerView.backgroundColor = ViewColors.backgroundUserCell } // MARK: - Methods private func showKeyboardIfNeeded() { if tableView.numberOfTotalRows > StartUIViewController.InitiallyShowsKeyboardConversationThreshold { _ = searchHeaderViewController.tokenField.becomeFirstResponder() } } func updateEmptyResults(hasResults: Bool) { let searchQueryExist = !dataSource.searchQuery.isEmpty noContactsLabel.isHidden = hasResults || searchQueryExist setEmptyResultsHidden(hasResults) } private func setEmptyResultsHidden(_ hidden: Bool) { let completion: (Bool) -> Void = { _ in self.emptyResultsLabel.isHidden = hidden self.tableView.isHidden = !hidden } UIView.animate(withDuration: 0.25, delay: 0, options: .beginFromCurrentState, animations: { self.emptyResultsLabel.alpha = hidden ? 0 : 1 }, completion: completion) } // MARK: - Keyboard Observation private func observeKeyboardFrame() { // Subscribing to the notification may cause "zero frame" animations to occur before the initial layout // of the view. We can avoid this by laying out the view first. view.layoutIfNeeded() NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameWillChange), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) } @objc func keyboardFrameWillChange(_ notification: Notification) { guard let userInfo = notification.userInfo, let beginFrame = userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as? CGRect, let endFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return } let willAppear = (beginFrame.minY - endFrame.minY) > 0 let padding: CGFloat = 12 UIView.animate(withKeyboardNotification: notification, in: view, animations: { [weak self] keyboardFrame in guard let weakSelf = self else { return } weakSelf.bottomContainerBottomConstraint?.constant = -(willAppear ? keyboardFrame.height : 0) weakSelf.bottomEdgeConstraint?.constant = -padding - (willAppear ? 0 : UIScreen.safeArea.bottom) weakSelf.view.layoutIfNeeded() }) } }
gpl-3.0
aa49b8317206a8da9ec773d7e2313960
36.752427
119
0.670824
5.558971
false
false
false
false
kingka/SwiftWeiBo
SwiftWeiBo/SwiftWeiBo/Classes/Home/StatusesForwordCell.swift
1
2885
// // StatusesForwordCell.swift // SwiftWeiBo // // Created by Imanol on 16/4/27. // Copyright © 2016年 imanol. All rights reserved. // import UIKit class StatusesForwordCell: StatusesCell { //重写属性的didSet方法,是不会覆盖父类原有的方法,并且也只能重写父类里面属性原有的方法,比如父类只有get,那么也只能重写get override var statuses : Statuses?{ didSet{ let name = statuses?.retweeted_status?.user?.name ?? "" let text = statuses?.retweeted_status?.text ?? "" //forwordLabel.text = "@"+name+": "+text forwordLabel.attributedText = EmoticonPackage.changeText2AttributeText(name + ": " + text) } } override func setupUI() { super.setupUI() //addSubview contentView.insertSubview(forwordButton, belowSubview: picView) contentView.insertSubview(forwordLabel, aboveSubview: forwordButton) //setting autoLayout forwordButton.snp_makeConstraints { (make) -> Void in make.left.equalTo(context) make.right.equalTo(context) make.top.equalTo(context.snp_bottom).offset(10) make.bottom.equalTo(bottomView.snp_top) } forwordLabel.snp_makeConstraints { (make) -> Void in make.left.equalTo(context) make.top.equalTo(forwordButton).offset(10) } picView.snp_makeConstraints { (make) -> Void in make.left.equalTo(context) } widthConstraint = NSLayoutConstraint(item: picView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 150) topConstraint = NSLayoutConstraint(item: picView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: forwordLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10) heightConstraint = NSLayoutConstraint(item: picView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 150) picView.addConstraint(widthConstraint!) picView.addConstraint(heightConstraint!) contentView.addConstraint(topConstraint!) } //MARK:- lazy loading lazy var forwordLabel : UILabel = { let label = UILabel.createLabel(UIColor.darkGrayColor(), fontSize: 15) label.numberOfLines = 0 label.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 20 label.text = "just for test!" return label }() lazy var forwordButton : UIButton = { let btn = UIButton() btn.backgroundColor = UIColor(white: 0.8, alpha: 0.7) return btn }() }
mit
dae0eda5cd07ea1da857e3ea15300f90
38.657143
220
0.65562
4.611296
false
false
false
false
xmartlabs/Opera
Example/Example/Controllers/RepositoryIssueFilterController.swift
1
2898
// RepositoryIssueFilterController.swift // Example-iOS ( https://github.com/xmartlabs/Example-iOS ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit import RxSwift import RxCocoa class RepositoryIssueFilterController: UITableViewController { @IBOutlet weak var stateSegmentControl: UISegmentedControl! @IBOutlet weak var sortBySegmentControl: UISegmentedControl! @IBOutlet weak var sortDirectionSegmentControl: UISegmentedControl! @IBOutlet weak var issueCreatorTextField: UITextField! @IBOutlet weak var issueMentionedUserTextField: UITextField! var filter: Variable<IssuesFilter>! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) stateSegmentControl.selectedSegmentIndex = filter.value.state.rawValue sortBySegmentControl.selectedSegmentIndex = filter.value.sortBy.rawValue sortDirectionSegmentControl.selectedSegmentIndex = filter.value.sortDirection.rawValue issueCreatorTextField.text = filter.value.issueCreator issueMentionedUserTextField.text = filter.value.userMentioned } @IBAction func dismiss(_ sender: UIBarButtonItem) { let newFilter = IssuesFilter() newFilter.state = IssuesFilter.State(rawValue: stateSegmentControl.selectedSegmentIndex) ?? .open newFilter.sortBy = IssuesFilter.Sort(rawValue: sortBySegmentControl.selectedSegmentIndex) ?? .created newFilter.sortDirection = IssuesFilter.Direction(rawValue: sortDirectionSegmentControl.selectedSegmentIndex) ?? .descendant newFilter.issueCreator = issueCreatorTextField.text newFilter.userMentioned = issueMentionedUserTextField.text filter.value = newFilter self.dismiss(animated: true, completion: nil) } }
mit
34b85832a15bd8d0c5db117ea9be1b07
43.584615
131
0.766391
4.97084
false
false
false
false
chipsandtea/MarineBioViewController
MarineBioViewController/SubmitDataViewController.swift
1
5484
// // SubmitDataViewController.swift // MarineBioViewController // // Created by Christopher Hsiao on 2/10/15. // Copyright (c) 2015 Chips&Tea. All rights reserved. // import UIKit class SubmitDataViewController: UIViewController { @IBOutlet var bannerLabel: UILabel! var groupName = String() override func viewDidLoad() { super.viewDidLoad() bannerLabel.text = "Submit Data for: " + groupName + " ?" // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func submitFormData(sender: AnyObject) { var json = JSON(sharedData()) self.sendRequest(json) } func get(completedFunction : (json: JSON) ->()) { let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration() /* Create session, and optionally set a NSURLSessionDelegate. */ let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil) /* Create the Request: My API (2) (POST http://oneillseaodyssey.org/testing.php) */ var URL = NSURL(string: "http://oneillseaodyssey.org/applications.php") let request = NSMutableURLRequest(URL: URL!) request.HTTPMethod = "GET" var myJson = JSON([1,2]) /* Start a new Task */ let task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData!, response : NSURLResponse!, error : NSError!) -> Void in if (error == nil) { // Success let statusCode = (response as NSHTTPURLResponse).statusCode let json = JSON(data: data) dispatch_async(dispatch_get_main_queue(), { for (key: String, subJson: JSON) in json { //self.contents.append(subJson["school"].stringValue) //self.dict[subJson["school"].stringValue] = subJson["id"].stringValue } //if(self.schoolPicker != nil) { // self.schoolPicker.reloadAllComponents() //} }) } else { println("URL Session Task Failed: %@", error.localizedDescription); } }) task.resume() } func sendRequest(params : JSON) { let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration() /* Create session, and optionally set a NSURLSessionDelegate. */ let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil) /* Create the Request: My API (2) (POST http://oneillseaodyssey.org/testing.php) */ var URL = NSURL(string: "http://oneillseaodyssey.org/parsetest.php") let request = NSMutableURLRequest(URL: URL!) request.HTTPMethod = "POST" var foo = params.rawString(options:nil) if let string : String = foo { let bodyParameters = [ "data" : string ] println(string) let bodyString = stringFromQueryParameters(bodyParameters) println ("bodyString:", bodyString); request.HTTPBody = bodyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) /* Start a new Task */ let task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData!, response : NSURLResponse!, error : NSError!) -> Void in if (error == nil) { // Success let statusCode = (response as NSHTTPURLResponse).statusCode println("URL Session Task Succeeded: HTTP \(statusCode)") println("returned data, should be identical:") var results = NSString(data: data, encoding: NSUTF8StringEncoding)! results = results.stringByReplacingOccurrencesOfString("\\", withString: "") println(results) } else { // Failure println("URL Session Task Failed: %@", error.localizedDescription); } }) task.resume() } } func stringFromQueryParameters(queryParameters : Dictionary<String, String>) -> String { var parts: [String] = [] for (name, value) in queryParameters { var part = NSString(format: "%@=%@", name.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!, value.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!) parts.append(part) } return "&".join(parts) } func NSURLByAppendingQueryParameters(URL : NSURL!, queryParameters : Dictionary<String, String>) -> NSURL { let URLString : NSString = NSString(format: "%@?%@", URL.absoluteString!, stringFromQueryParameters(queryParameters)) return NSURL(string: URLString)! } /* // 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
29a2db37ddda69efdf2d5fe985ef0154
34.380645
150
0.599015
5.237822
false
true
false
false
Codeido/swift-basics
Playground Codebase/Array.playground/section-1.swift
1
821
// Playground - noun: a place where people can play import UIKit // ARRAY var shoppingList = ["catfish", "water", "lemons"] shoppingList[1] = "bottle of water" // update shoppingList.count // size of array (3) shoppingList.append("eggs") shoppingList += ["milk"] // Array slicing var fibList = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 5] fibList[4...6] // [3, 5]. Note: the end range value is exclusive fibList[0...fibList.endIndex-1] // all except last item // Subscripting returns the Slice type, instead of the Array type. // You may need to cast it to Array in order to satisfy the type checker Array(fibList[0...4]) // Variants of creating an array. All three are equivalent. var emptyArray1 = [String]() var emptyArray2: [String] = [] var emptyArray3: [String] = [String]()
gpl-2.0
358d5905e94ff529412a33b3ca71847b
34.73913
72
0.655298
3.523605
false
false
false
false
hq7781/MoneyBook
MoneyBook/Controller/Record/AccountTableViewCell.swift
1
714
// // AccountTableViewCell.swift // MoneyBook // // Created by HongQuan on 2017/05/01. // Copyright © 2017年 Roan.Hong. All rights reserved. // import UIKit class AccountTableViewCell: UITableViewCell { //MARK: - ========== var define ========== @IBOutlet var imgAcc: UIImageView! @IBOutlet var lblNameAcc: UILabel! @IBOutlet var lblMoney: UILabel! //MARK: - ========== override methods ========== override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
85f47d5398da50bf24ab362fe7930001
24.392857
65
0.627286
4.283133
false
false
false
false
CosmicMind/MaterialKit
Sources/iOS/BaseButtonGroup.swift
1
2857
// // BaseButtonGroup.swift // Material // // Created by Orkhan Alikhanov on 12/24/17. // Copyright © 2017 CosmicMind, Inc. All rights reserved. // import UIKit open class BaseButtonGroup<T: Button>: View { /// Holds reference to buttons within the group. open var buttons: [T] = [] { didSet { oldValue.forEach { $0.removeFromSuperview() $0.removeTarget(self, action: #selector(didTap(_:)), for: .touchUpInside) } prepareButtons() grid.views = buttons grid.axis.rows = buttons.count } } /// Initializes group with the provided buttons. /// /// - Parameter buttons: Array of buttons. public convenience init(buttons: [T]) { self.init(frame: .zero) defer { self.buttons = buttons } // defer allows didSet to be called } open override func prepare() { super.prepare() grid.axis.direction = .vertical grid.axis.columns = 1 } open override var intrinsicContentSize: CGSize { return sizeThatFits(bounds.size) } open override func sizeThatFits(_ size: CGSize) -> CGSize { let size = CGSize(width: size.width == 0 ? .greatestFiniteMagnitude : size.width, height: size.height == 0 ? .greatestFiniteMagnitude : size.height) let availableW = size.width - grid.contentEdgeInsets.left - grid.contentEdgeInsets.right - grid.layoutEdgeInsets.left - grid.layoutEdgeInsets.right let maxW = buttons.reduce(0) { max($0, $1.sizeThatFits(.init(width: availableW, height: .greatestFiniteMagnitude)).width) } let h = buttons.reduce(0) { $0 + $1.sizeThatFits(.init(width: maxW, height: .greatestFiniteMagnitude)).height } + grid.contentEdgeInsets.top + grid.contentEdgeInsets.bottom + grid.layoutEdgeInsets.top + grid.layoutEdgeInsets.bottom + CGFloat(buttons.count - 1) * grid.interimSpace return CGSize(width: maxW + grid.contentEdgeInsets.left + grid.contentEdgeInsets.right + grid.layoutEdgeInsets.left + grid.layoutEdgeInsets.right, height: min(h, size.height)) } open override func layoutSubviews() { super.layoutSubviews() grid.reload() } open func didTap(button: T, at index: Int) { } @objc private func didTap(_ sender: Button) { guard let sender = sender as? T, let index = buttons.index(of: sender) else { return } didTap(button: sender, at: index) } } private extension BaseButtonGroup { func prepareButtons() { buttons.forEach { addSubview($0) $0.removeTarget(nil, action: nil, for: .allEvents) $0.addTarget(self, action: #selector(didTap(_:)), for: .touchUpInside) } } }
bsd-3-clause
a6746689c6ce4d3c2d6c6a5511a4b93b
34.259259
183
0.613445
4.387097
false
false
false
false
RemyDCF/tpg-offline
tpg offline/Routes/RouteResultsDetailTableViewCell.swift
1
2171
// // RouteResultDetailTableViewCell.swift // tpg offline // // Created by Rémy Da Costa Faro on 21/09/2017. // Copyright © 2018 Rémy Da Costa Faro. All rights reserved. // import UIKit class RouteResultDetailsTableViewCell: UITableViewCell { @IBOutlet weak var departureStopLabel: UILabel! @IBOutlet weak var departureHourLabel: UILabel! @IBOutlet weak var arrivalStopLabel: UILabel! @IBOutlet weak var arrivalHourLabel: UILabel! @IBOutlet var images: [UIImageView]! var section: RouteConnection.Sections? = nil { didSet { guard let section = section else { return } departureStopLabel.textColor = App.textColor departureHourLabel.textColor = App.textColor arrivalStopLabel.textColor = App.textColor arrivalHourLabel.textColor = App.textColor for image in images { image.image = image.image?.maskWith(color: App.textColor) } self.backgroundColor = App.cellBackgroundColor let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" departureStopLabel.text = (App.stops.filter({ $0.sbbId == section.departure.station.id })[safe: 0]?.name) ?? section.departure.station.name departureHourLabel.text = dateFormatter.string(from: Date(timeIntervalSince1970: TimeInterval(section.departure.departureTimestamp ?? 0))) arrivalStopLabel.text = (App.stops.filter({ $0.sbbId == section.arrival.station.id })[safe: 0]?.name) ?? section.arrival.station.name arrivalHourLabel.text = dateFormatter.string(from: Date(timeIntervalSince1970: TimeInterval(section.arrival.arrivalTimestamp ?? 0))) self.accessoryType = .disclosureIndicator } } override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = App.cellBackgroundColor selectionStyle = .none departureStopLabel.textColor = App.textColor departureHourLabel.textColor = App.textColor arrivalStopLabel.textColor = App.textColor arrivalHourLabel.textColor = App.textColor for image in images { image.image = image.image?.maskWith(color: App.textColor) } } }
mit
b6f8cdb7d22180d23e77e3879c599485
30.42029
84
0.706181
4.442623
false
false
false
false
gkye/TheMovieDatabaseSwiftWrapper
Sources/TMDBSwift/OldModels/TVSeasonsMDB.swift
1
3194
// // SeasonsMDB.swift // MDBSwiftWrapper // // Created by George Kye on 2016-02-17. // Copyright © 2016 George Kye. All rights reserved. // import Foundation public struct TVSeasonsMDB: Decodable { public var air_date: String? public var episodes: [TVEpisodesMDB]? public var name: String? public var overview: String? public var id: Int? public var poster_path: String? public var season_number: Int? /// Get the primary information about a TV season by its season number. public static func season_number(tvShowId: Int!, seasonNumber: Int!, language: String?, completion: @escaping (_ clientReturn: ClientReturn, _ data: TVSeasonsMDB?) -> Void) { let urltype = String(tvShowId) + "/season/" + String(seasonNumber) Client.Seasons(urltype, language: language) { apiReturn in let data: TVSeasonsMDB? = apiReturn.decode() completion(apiReturn, data) } } /// Get the cast & crew credits for a TV season by season number. public static func credits(tvShowId: Int!, seasonNumber: Int!, language: String?, completion: @escaping (_ clientReturn: ClientReturn, _ data: TVCreditsMDB?) -> Void) { // [/tv/11/season/1/credits] let urltype = String(tvShowId) + "/season/" + String(seasonNumber) + "/credits" Client.Seasons(urltype, language: language) { apiReturn in let data: TVCreditsMDB? = apiReturn.decode() completion(apiReturn, data) } } /// Get the external ids that we have stored for a TV season by season number. public static func externalIDS(tvShowId: Int!, seasonNumber: Int!, language: String?, completion: @escaping (_ clientReturn: ClientReturn, _ data: ExternalIdsMDB?) -> Void) { let urltype = String(tvShowId) + "/season/" + String(seasonNumber) + "/external_ids" Client.Seasons(urltype, language: language) { apiReturn in let data: ExternalIdsMDB? = apiReturn.decode() completion(apiReturn, data) } } /// Get the images (posters) that we have stored for a TV season by season number. **[backdrops] returned in ImagesMDB will be `nil` public static func images(tvShowId: Int!, seasonNumber: Int!, language: String?, completion: @escaping (_ clientReturn: ClientReturn, _ data: ImagesMDB?) -> Void) { let urltype = String(tvShowId) + "/season/" + String(seasonNumber) + "/images" Client.Seasons(urltype, language: language) { apiReturn in let data: ImagesMDB? = apiReturn.decode() completion(apiReturn, data) } } /// Get the videos that have been added to a TV season (trailers, teasers, etc...) public static func videos(tvShowId: Int!, seasonNumber: Int!, language: String?, completion: @escaping (_ clientReturn: ClientReturn, _ data: [VideosMDB]?) -> Void) { // [/tv/11/season/1/credits] let urltype = String(tvShowId) + "/season/" + String(seasonNumber) + "/videos" Client.Seasons(urltype, language: language) { apiReturn in let results: [VideosMDB]? = apiReturn.decodeResults() completion(apiReturn, results) } } }
mit
7509766d89e549e641cd20bb806a2c7e
45.955882
178
0.652365
4.05203
false
false
false
false
Cookiezby/YiIndex
YiIndex/View/YiIndexView.swift
1
4683
// // YiIndexView.swift // YiIndex // // Created by cookie on 19/07/2017. // Copyright © 2017 cookie. All rights reserved. // import Foundation import UIKit let BLOCK_SIZE: CGFloat = 20 protocol YiIndexProtocol { var yiIndex: YiIndex! { get } var tableView: UITableView { get } var hudView: YiHudView { get } func indexChanged(newIndex: Int) func indexConfirmed() } extension YiIndexProtocol { func indexChanged(newIndex: Int) { hudView.isHidden = false hudView.updateLabel(text: String(UnicodeScalar(UInt8(64 + newIndex)))) if let index = yiIndex.indexDict[hudView.currLabel] { tableView.scrollToRow(at: index, at: .top, animated: false) } } func indexConfirmed() { hudView.insertLabel() } } class YiIndexView: UIView { class YiBlock: UIView { var label: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 10) label.textColor = UIColor.darkGray label.textAlignment = .center return label }() override init(frame: CGRect) { super.init(frame: frame) addSubview(label) } override func layoutSubviews() { label.frame = self.bounds super.layoutSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // paramaters var sideBlocks = [YiBlock]() var curIndex: Int = -1 var curIndexList: [Int] = [0, 0, 0, 0] var delegate: YiIndexProtocol! var blockSize: CGSize // forceFeedBack for iPhone6s+ let forceFeedBack: UISelectionFeedbackGenerator = { let feedBack = UISelectionFeedbackGenerator() feedBack.prepare() return feedBack }() // size let topPadding: CGFloat let indexHeight: CGFloat // check for long press var longPressTimeInterval: CGFloat = 0.8 var checkLongPress: DispatchWorkItem? init(frame: CGRect, blockSize: CGSize) { self.blockSize = blockSize self.indexHeight = 26 * blockSize.height self.topPadding = (frame.height - indexHeight) / 2 super.init(frame: frame) initBlocks() } func initBlocks() { let originY = topPadding for i in 0...25 { let block = YiBlock(frame: CGRect(x: frame.width - blockSize.width, y: originY + CGFloat(i) * blockSize.height, width: blockSize.width, height: blockSize.height)) block.label.text = String(UnicodeScalar(UInt8(65 + i))) sideBlocks.append(block) addSubview(block) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let point = touches.first?.location(in: self) let index = Int(( (point?.y)! - topPadding) / blockSize.height) + 1 updateIndex(index) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { let point = touches.first?.location(in: self) let index = Int(( (point?.y)! - topPadding ) / blockSize.height) + 1 updateIndex(index) } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { delegate.hudView.isHidden = true delegate.hudView.resetHud() cancelLongPressCheck() } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { delegate.hudView.isHidden = true delegate.hudView.resetHud() cancelLongPressCheck() } func updateIndex(_ index: Int) { if (index != curIndex && index <= 26 && index >= 1) { curIndex = index forceFeedBack.selectionChanged() delegate.indexChanged(newIndex: index) cancelLongPressCheck() checkLongPress = DispatchWorkItem { [weak self] _ in self?.confimCurIndex(index) } let when = DispatchTime.now() + TimeInterval(longPressTimeInterval) DispatchQueue.main.asyncAfter(deadline: when, execute: checkLongPress!) } } func cancelLongPressCheck() { if checkLongPress != nil { if !checkLongPress!.isCancelled { checkLongPress!.cancel() } } } func confimCurIndex(_ index: Int) { if(index == curIndex) { delegate.indexConfirmed() } } }
mit
5b6dd7d728c4c206cb57a748db077b1d
28.632911
174
0.587997
4.506256
false
false
false
false
bartekchlebek/SwiftHelpers
Source/Diff/Diff.swift
1
1177
public struct Diff<T> { public var oldItems: [T] public var newItems: [T] public var added: [T] public var removed: [T] public var updated: [ChangeDescriptor<T>] public init(_ context: DiffContext<T>) { self.oldItems = context.oldItems self.newItems = context.newItems let newItemsContainItem = context.newItemsContainItem let oldItemsContainItem = context.oldItemsContainItem let isEqualComparator = context.isEqualComparator let newItemWithSameIDAsItem = context.newItemWithSameIDAsItem var removedItems: [T] = [] var addedItems: [T] = [] var updatedItems: [ChangeDescriptor<T>] = [] for oldItem in oldItems { if !newItemsContainItem(oldItem) { removedItems.append(oldItem) } } for newItem in newItems { if !oldItemsContainItem(newItem) { addedItems.append(newItem) } } for oldItem in oldItems { if let newItem = newItemWithSameIDAsItem(oldItem), !isEqualComparator(oldItem, newItem) { let itemUpdateInfo = ChangeDescriptor(from: oldItem, to: newItem) updatedItems.append(itemUpdateInfo) } } self.removed = removedItems self.added = addedItems self.updated = updatedItems } }
mit
26eac62ebb2cdfb17b4e62c713e144e2
25.155556
92
0.718777
3.566667
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Controller/Parking/ParkingTableViewCell.swift
1
1611
// // ParkingTableViewCell.swift // SASAbus // // Copyright (C) 2011-2015 Raiffeisen Online GmbH (Norman Marmsoler, Jürgen Sprenger, Aaron Falk) <[email protected]> // // This file is part of SASAbus. // // SASAbus is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // SASAbus is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with SASAbus. If not, see <http://www.gnu.org/licenses/>. // import UIKit class ParkingTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var progressView: UIProgressView! @IBOutlet weak var phoneLabel: UITextView! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var iconImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() self.titleLabel.textColor = Theme.darkGrey self.messageLabel.textColor = Theme.darkGrey self.addressLabel.textColor = Theme.darkGrey self.phoneLabel.tintColor = nil self.progressView.progressTintColor = Theme.orange self.iconImageView.tint(with: Theme.orange) self.backgroundColor = .white } }
gpl-3.0
4a14c3047bf6d5356a8cb149811777ce
33.255319
118
0.726708
4.327957
false
false
false
false
mnito/random-number-game-example-swift
Sources/ConsoleHelper.swift
1
1757
/** * ConsoleHelper class * @author Michael P. Nitowski <[email protected]> * * Performs some basic display functions and contains useful tools * for parsing command line arguments */ public class ConsoleHelper { public static var headerLength = 50 public static func getHorizontalRule() -> String { let s = "-" return s.repeatStr(headerLength); } public static func getHorizontalRule(s: String) -> String { let factor = Int(headerLength / s.characters.count) return s.repeatStr(factor) } public static func associateFlags(arguments: [String]) -> [String: String] { var flagDict = [String: String]() var current = "" for argument in arguments { if(argument.substring(0, length: 1) == "-") { current = argument.substring(1) if(current.characters.count > 1) { for c in current.characters { current = String(c) flagDict[current] = current } continue } flagDict[current] = current continue } if(current != "") { flagDict[current] = argument } } return flagDict } //Set<String> to explictly define a set, not a dictionary or array public static func associateFlags(arguments: [String], wordFlags: Set<String>) -> [String: String] { var flagDict = [String: String]() var current = "" for argument in arguments { if argument.substring(0, length: 1) == "-" { current = argument.substring(1) //Contains is a set function if current.characters.count > 1 && !wordFlags.contains(current) { for c in current.characters { current = String(c) flagDict[current] = current } continue } flagDict[current] = current continue } if(current != "") { flagDict[current] = argument } } return flagDict } }
mit
09dd345ed48ea3078aa178f1f3294e6f
24.463768
101
0.656801
3.418288
false
false
false
false
wangjianquan/wjq-weibo
weibo_wjq/Home/Controllers/HomeViewController.swift
1
11567
// // HomeViewController.swift // weibo_wjq // // Created by landixing on 2017/5/16. // Copyright © 2017年 WJQ. All rights reserved. // import UIKit import SVProgressHUD import SDWebImage import MJRefresh class HomeViewController: BaseViewController { //MARK: -- 懒加载 // 标题按钮 fileprivate lazy var titleBtn : TitleButton = { let titleBtn = TitleButton() let title = UserAccount.loadAccount()?.screen_name titleBtn.setTitle(title, for: .normal) titleBtn.addTarget(self, action: #selector(HomeViewController.titleBtnClick(btn:)), for: .touchUpInside) return titleBtn }() //MARK: -- 标题动画 fileprivate lazy var popAnimation : PopAnimation = PopAnimation() //MARK: -- tableView fileprivate lazy var homeTableView: UITableView = { let tableview = UITableView() tableview.delegate = self tableview.dataSource = self tableview.separatorStyle = UITableViewCellSeparatorStyle.none tableview.register(UINib.init(nibName: "HomeCell", bundle: nil), forCellReuseIdentifier: "cell") //预设值cell高度 tableview.estimatedRowHeight = 400 self.view.addSubview(tableview) tableview.snp.makeConstraints { (make) in make.edges.equalTo(0) } return tableview }() //MARK: -- 保存所有微博数据 fileprivate lazy var dataSource: [StatusViewModel] = [StatusViewModel]() fileprivate lazy var tipLabel: UILabel = { let tipLabel : UILabel = UILabel() // self.navigationController?.navigationBar.insertSubview(tipLabel, at: 0) self.view.insertSubview(tipLabel, aboveSubview: self.homeTableView) tipLabel.frame = CGRect(x: 0, y: 10, width: UIScreen.main.bounds.width, height: 32) tipLabel.backgroundColor = UIColor.orange tipLabel.textColor = UIColor.white tipLabel.font = UIFont.systemFont(ofSize: 14) tipLabel.textAlignment = .center tipLabel.isHidden = true return tipLabel }() /// 缓存行高 fileprivate var rowHeightCaches = [String : CGFloat]() fileprivate var photoBrowerAnimator: PhotoBrowserAnimator = PhotoBrowserAnimator() override func viewDidLoad() { super.viewDidLoad() //没有登录时 if !isLogin { visitorView.addRotationAnim() return } //导航栏设置 setupNavigationBar() //下拉刷新, 上拉加载 setupHeaderView() setupFooterView() NotificationCenter.default.addObserver(self, selector: #selector(HomeViewController.showPhotoBrowser(_:)), name: NSNotification.Name(rawValue: showPhotoBrowserNotification), object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // 释放缓存数据 rowHeightCaches.removeAll() } } //MARK: -- 设置UI extension HomeViewController { fileprivate func setupNavigationBar() { //MARK: -- 1. 导航栏按钮 //左侧按钮 navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action:#selector(HomeViewController.leftBarButtonItemClick)) //右侧按钮 navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action:#selector(HomeViewController.rightBarButtonItemClick)) //MARK: -- 2. 标题按钮 (闭包) navigationItem.titleView = titleBtn } fileprivate func setupHeaderView() { let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadNewData)) header?.setTitle("下拉刷新", for: .idle) header?.setTitle("释放更新", for: .pulling) header?.setTitle("加载中...", for: .refreshing) homeTableView.mj_header = header homeTableView.mj_header.beginRefreshing() } fileprivate func setupFooterView() { homeTableView.mj_footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadMoreData)) } } //MARK: -- 代理方法 extension HomeViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! HomeCell cell.viewModel = dataSource[indexPath.row] return cell } func numberOfSections(in tableView: UITableView) -> Int { return 1 } } extension HomeViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let viewModel = dataSource[indexPath.row] // 1.从缓存中取行高 guard let height = rowHeightCaches[viewModel.status.idstr ?? "-1" ] else { //缓存中没有,计算高度 let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! HomeCell //缓存行高 let temp = cell.calculateRowHeight(viewModel) rowHeightCaches[viewModel.status.idstr ?? "-1"] = temp return temp } return height } } //MAKR: -- 网络请求 extension HomeViewController { /// 加载最新的数据 @objc fileprivate func loadNewData() { loadData(true) } /// 加载最新的数据 @objc fileprivate func loadMoreData() { loadData(false) } //MARK: -- loadData 网络请求 fileprivate func loadData(_ isNewData: Bool) { //获取 var since_id = 0 //下拉 var max_id = 0 if isNewData { since_id = dataSource.first?.status.mid ?? 0 } else { max_id = dataSource.last?.status.mid ?? 0 max_id = max_id == 0 ? 0 : (max_id - 1) } NetworkTools.shareInstance.loadStatus(since_id:since_id, max_id: max_id) { (result, error) in // 1.安全校验 if error != nil { SVProgressHUD.showError(withStatus: "获取微博数据失败") return } // 2.获取可选类型中的数据 guard let arr = result else { return } // 3.将字典数组转换为模型数组 //3.1 临时数组 var tempDataArray = [StatusViewModel]() for dict in arr { let status = Status(dict: dict) let viewModel = StatusViewModel(status: status) tempDataArray.append(viewModel) //数据添加到临时数组中 } //4. 将数据添加到总得dataSource中 if isNewData{ //第一次加载及下拉刷新 self.dataSource = tempDataArray + self.dataSource }else { self.dataSource += tempDataArray } //缓存图片 先下载后刷新 self.cachesImage(dataArr: tempDataArray) } } //MARK: -- cachesImage 缓存图片 fileprivate func cachesImage(dataArr: [StatusViewModel]) { //1 let group = DispatchGroup() //2.遍历数组,取model for viewModel in dataArr { //2. 从配图数组(pic_urls)中取出图片 for url in viewModel.thumbnail_pic { //2.1 将当前的下载操作添加到组中 group.enter() SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, error, _, _, _) in // 将当前下载操作从组中移除 group.leave() }) } } //3. 监听下载操作, 当全部下载完后刷新表单 // 监听下载 操作 group.notify(queue: DispatchQueue.main) { () -> Void in Dlog("全部下载完成") // 刷新表格 self.homeTableView.reloadData() self.homeTableView.mj_header.endRefreshing() self.homeTableView.mj_footer.endRefreshing() // 显示刷新的微博条数 self.showTipLabel(dataArr.count) } } //显示更新的微博条数 fileprivate func showTipLabel(_ count: Int) { tipLabel.isHidden = false tipLabel.text = count == 0 ? "没有新数据" : "\(count) 条微博" //执行动画 UIView.animate(withDuration: 1.0, animations: { self.tipLabel.frame.origin.y = 70 }) { (_) in UIView.animate(withDuration: 1.0, animations: { self.tipLabel.frame.origin.y = 10 }, completion: { (_) in self.tipLabel.isHidden = true }) } } } //MARK: -- 点击事件 extension HomeViewController{ //MARK: --标题按钮 @objc fileprivate func titleBtnClick(btn: TitleButton) { //1. . 弹出视图 let popview = UIStoryboard(name: "PopViewController", bundle: nil) guard let menuView = popview.instantiateInitialViewController() else { return } popAnimation.presentedFrame = CGRect(x: 100, y: 64, width: 180, height: 230) popAnimation.presentedCallBack = {[weak self] (isPresented) -> () in self?.titleBtn.isSelected = isPresented } //3. 设置代理, 并自定义 menuView.transitioningDelegate = popAnimation menuView.modalPresentationStyle = .custom present(menuView, animated: true, completion: nil) } //MARK: -- 左侧item事件 @objc fileprivate func leftBarButtonItemClick() { Dlog("leftBarButtonItemClick") } //MARK: -- 右侧item事件 @objc fileprivate func rightBarButtonItemClick() { let QRCodeVC = UIStoryboard(name: "QRCode", bundle: nil) guard let qrcodeView = QRCodeVC.instantiateInitialViewController() else { return } present(qrcodeView, animated: true, completion: nil) } @objc fileprivate func showPhotoBrowser(_ note : Notification){ guard let picUrls = note.userInfo![showPhotoBrowserNotificationURLs] as? [URL], let indexPath = note.userInfo![showPhotoBrowserNotificationIndexPath] as? IndexPath, let objc = note.object as? AnimatorPresentDelegate else { return } let photoBrowseVC = PhotoBrowseController(indexPath: indexPath, picUrls:picUrls) photoBrowseVC.modalPresentationStyle = .custom photoBrowseVC.transitioningDelegate = photoBrowerAnimator photoBrowerAnimator.setIndexPath(indexPath, presentedDelegate: objc, dismissDelegate: photoBrowseVC) present(photoBrowseVC, animated: true, completion: nil) } }
apache-2.0
d1f17b4c1a02498c47bcde6f2d01b6a4
29.539326
231
0.584805
5.068531
false
false
false
false
wvteijlingen/Spine
Spine/ResourceField.swift
1
2643
// // ResourceAttribute.swift // Spine // // Created by Ward van Teijlingen on 30-12-14. // Copyright (c) 2014 Ward van Teijlingen. All rights reserved. // import Foundation public func fieldsFromDictionary(_ dictionary: [String: Field]) -> [Field] { return dictionary.map { (name, field) in field.name = name return field } } /// Base field. /// Do not use this field type directly, instead use a specific subclass. open class Field { /// The name of the field as it appears in the model class. /// This is declared as an implicit optional to support the `fieldsFromDictionary` function, /// however it should *never* be nil. public internal(set) var name: String! = nil /// The name of the field that will be used for formatting to the JSON key. /// This can be nil, in which case the regular name will be used. public internal(set) var serializedName: String { get { return _serializedName ?? name } set { _serializedName = newValue } } fileprivate var _serializedName: String? var isReadOnly: Bool = false fileprivate init() {} /// Sets the serialized name. /// /// - parameter name: The serialized name to use. /// /// - returns: The field. public func serializeAs(_ name: String) -> Self { serializedName = name return self } public func readOnly() -> Self { isReadOnly = true return self } } // MARK: - Built in fields /// A basic attribute field. open class Attribute: Field { override public init() {} } /// A URL attribute that maps to an URL property. /// You can optionally specify a base URL to which relative /// URLs will be made absolute. public class URLAttribute: Attribute { let baseURL: URL? public init(baseURL: URL? = nil) { self.baseURL = baseURL } } /// A date attribute that maps to an NSDate property. /// By default, it uses ISO8601 format `yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ`. /// You can specify a custom format by passing it to the initializer. public class DateAttribute: Attribute { let format: String public init(format: String = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ") { self.format = format } } /// A boolean attribute that maps to an NSNumber property. public class BooleanAttribute: Attribute {} /// A basic relationship field. /// Do not use this field type directly, instead use either `ToOneRelationship` or `ToManyRelationship`. public class Relationship: Field { let linkedType: Resource.Type public init(_ type: Resource.Type) { linkedType = type } } /// A to-one relationship field. public class ToOneRelationship: Relationship { } /// A to-many relationship field. public class ToManyRelationship: Relationship { }
mit
bf62cc19884a30cea47cdcb7f3a920eb
24.413462
104
0.704881
3.635488
false
false
false
false
julienbodet/wikipedia-ios
Wikipedia/Code/WMFContentGroup+DetailViewControllers.swift
1
2684
import Foundation extension WMFContentGroup { public func detailViewControllerForPreviewItemAtIndex(_ index: Int, dataStore: MWKDataStore, theme: Theme) -> UIViewController? { switch detailType { case .page: guard let articleURL = previewArticleURLForItemAtIndex(index) else { return nil } return WMFArticleViewController(articleURL: articleURL, dataStore: dataStore, theme: theme) case .pageWithRandomButton: guard let articleURL = previewArticleURLForItemAtIndex(index) else { return nil } return WMFRandomArticleViewController(articleURL: articleURL, dataStore: dataStore, theme: theme) case .gallery: guard let date = self.date else { return nil } return WMFPOTDImageGalleryViewController(dates: [date], theme: theme, overlayViewTopBarHidden: false) case .story, .event: return detailViewControllerWithDataStore(dataStore, theme: theme) default: return nil } } @objc(detailViewControllerWithDataStore:theme:) public func detailViewControllerWithDataStore(_ dataStore: MWKDataStore, theme: Theme) -> UIViewController? { switch moreType { case .pageList: guard let articleURLs = contentURLs else { return nil } let vc = ArticleURLListViewController(articleURLs: articleURLs, dataStore: dataStore, contentGroup: self, theme: theme) vc.title = moreTitle return vc case .pageListWithLocation: guard let articleURLs = contentURLs else { return nil } return ArticleLocationCollectionViewController(articleURLs: articleURLs, dataStore: dataStore, theme: theme) case .news: guard let stories = fullContent?.object as? [WMFFeedNewsStory] else { return nil } return NewsViewController(stories: stories, dataStore: dataStore, theme: theme) case .onThisDay: guard let date = midnightUTCDate, let events = fullContent?.object as? [WMFFeedOnThisDayEvent] else { return nil } return OnThisDayViewController(events: events, dataStore: dataStore, midnightUTCDate: date, theme: theme) case .pageWithRandomButton: guard let siteURL = siteURL else { return nil } return WMFFirstRandomViewController(siteURL: siteURL, dataStore: dataStore, theme: theme) default: return nil } } }
mit
92a95bade1b842a4f608f5c4258fdcf0
42.290323
133
0.622951
5.615063
false
false
false
false
KoheiKanagu/hogehoge
AddUUIDtoXcodePluginsInfoPlist/AddUUIDtoXcodePluginsInfoPlist/main.swift
1
1309
// // main.swift // AddUUIDtoXcodePluginsInfoPlist // // Created by Kohei on 2015/03/11. // Copyright (c) 2015年 KoheiKanagu. All rights reserved. // import Foundation println("Hello, World!") let xcodeUUID: NSString = "A16FF353-8441-459E-A50C-B071F53F51B7" let pluginsPath: NSString = NSHomeDirectory() + "/Library/Application Support/Developer/Shared/Xcode/Plug-ins/" let fileList: NSArray = NSFileManager.defaultManager().contentsOfDirectoryAtPath(pluginsPath, error: nil)! for value in fileList { let pluginFullPath: NSString = pluginsPath + (value as NSString) + "/Contents/Info.plist" if NSFileManager.defaultManager().fileExistsAtPath(pluginFullPath) { let dic: NSMutableDictionary = NSMutableDictionary(contentsOfFile: pluginFullPath)! let array: NSMutableArray = NSMutableArray(array: (dic.objectForKey("DVTPlugInCompatibilityUUIDs")) as NSArray) if (array.indexOfObject(xcodeUUID) == NSNotFound) { array.addObject(xcodeUUID) println("\(value) にXcode6.2のUUIDを追加") dic.setObject(array, forKey: "DVTPlugInCompatibilityUUIDs") dic.writeToFile(pluginFullPath, atomically: true) }else{ println("\(value) はXcode6.2のUUIDは追加済み") } } }
mit
f7bd222f98af14d65856e256b8926ff5
34.666667
119
0.696804
4.047319
false
false
false
false
ip3r/Cart
CartTests/Products/Model/InMemoryProductSpec.swift
1
2597
// // InMemoryProductSpec.swift // CartTests // // Created by Jens Meder on 12.06.17. // Copyright © 2017 Jens Meder. All rights reserved. // import XCTest @testable import Cart class InMemoryProductSpec: XCTestCase { func test_GIVEN_InMemoryProduct_WHEN_name_THEN_shouldReturnName() { // Given let uuid = UUID() let store = Memory<[UUID: Memory<[String:String]>]>( value: [ uuid : Memory( value: [ "name": "Peas", "unit": "bag", "amount": "0.95" ] ), UUID() : Memory( value: [ "name": "Eggs", "unit": "dozen", "amount": "2.10" ]), UUID() : Memory( value: [ "name": "Milk", "unit": "bottle", "amount": "1.30" ]), UUID() : Memory( value: [ "name": "Beans", "unit": "can", "amount": "0.73" ]) ] ) let product = InMemoryProduct(uuid:uuid, products: store) // When let result = product.name // Then XCTAssertTrue(result.stringValue == "Peas") } func test_GIVEN_InMemoryProduct_WHEN_price_THEN_shouldReturnAmountInUSD() { // Given let uuid = UUID() let store = Memory<[UUID: Memory<[String:String]>]>( value: [ uuid : Memory( value: [ "name": "Peas", "unit": "bag", "amount": "0.95" ] ), UUID() : Memory( value: [ "name": "Eggs", "unit": "dozen", "amount": "2.10" ]), UUID() : Memory( value: [ "name": "Milk", "unit": "bottle", "amount": "1.30" ]), UUID() : Memory( value: [ "name": "Beans", "unit": "can", "amount": "0.73" ]) ] ) let product = InMemoryProduct(uuid:uuid, products: store) // When let result = product.price // Then XCTAssertTrue(result.value - 0.95 < 1e-6) } func test_GIVEN_InMemoryProduct_WHEN_uuid_THEN_shouldReturnItsIdentifier() { // Given let uuid = UUID() let store = Memory<[UUID: Memory<[String:String]>]>( value: [ uuid : Memory( value: [ "name": "Peas", "unit": "bag", "amount": "0.95" ] ), UUID() : Memory( value: [ "name": "Eggs", "unit": "dozen", "amount": "2.10" ]), UUID() : Memory( value: [ "name": "Milk", "unit": "bottle", "amount": "1.30" ]), UUID() : Memory( value: [ "name": "Beans", "unit": "can", "amount": "0.73" ]) ] ) let product = InMemoryProduct(uuid:uuid, products: store) // When let result = product.uuid // Then XCTAssertTrue(result == uuid) } }
mit
1c8238e51e21e5733893ec737de730ce
18.088235
77
0.506163
2.910314
false
true
false
false
JGiola/swift-corelibs-foundation
Foundation/Bundle.swift
1
13022
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation open class Bundle: NSObject { private var _bundle : CFBundle! private static var _mainBundle : Bundle = { return Bundle(cfBundle: CFBundleGetMainBundle()) }() open class var main: Bundle { get { return _mainBundle } } open class var allBundles: [Bundle] { NSUnimplemented() } internal init(cfBundle: CFBundle) { super.init() _bundle = cfBundle } public init?(path: String) { super.init() // TODO: We do not yet resolve symlinks, but we must for compatibility // let resolvedPath = path._nsObject.stringByResolvingSymlinksInPath let resolvedPath = path guard resolvedPath.length > 0 else { return nil } let url = URL(fileURLWithPath: resolvedPath) _bundle = CFBundleCreate(kCFAllocatorSystemDefault, unsafeBitCast(url, to: CFURL.self)) if (_bundle == nil) { return nil } } public convenience init?(url: URL) { self.init(path: url.path) } public init(for aClass: AnyClass) { NSUnimplemented() } public init?(identifier: String) { super.init() guard let result = CFBundleGetBundleWithIdentifier(identifier._cfObject) else { return nil } _bundle = result } override open var description: String { return "\(String(describing: Bundle.self)) <\(bundleURL.path)> (\(isLoaded ? "loaded" : "not yet loaded"))" } /* Methods for loading and unloading bundles. */ open func load() -> Bool { return CFBundleLoadExecutable(_bundle) } open var isLoaded: Bool { return CFBundleIsExecutableLoaded(_bundle) } @available(*,deprecated,message:"Not available on non-Darwin platforms") open func unload() -> Bool { NSUnsupported() } open func preflight() throws { var unmanagedError:Unmanaged<CFError>? = nil try withUnsafeMutablePointer(to: &unmanagedError) { (unmanagedCFError: UnsafeMutablePointer<Unmanaged<CFError>?>) in CFBundlePreflightExecutable(_bundle, unmanagedCFError) if let error = unmanagedCFError.pointee { throw error.takeRetainedValue()._nsObject } } } open func loadAndReturnError() throws { var unmanagedError:Unmanaged<CFError>? = nil try withUnsafeMutablePointer(to: &unmanagedError) { (unmanagedCFError: UnsafeMutablePointer<Unmanaged<CFError>?>) in CFBundleLoadExecutableAndReturnError(_bundle, unmanagedCFError) if let error = unmanagedCFError.pointee { let retainedValue = error.takeRetainedValue() throw retainedValue._nsObject } } } /* Methods for locating various components of a bundle. */ open var bundleURL: URL { return CFBundleCopyBundleURL(_bundle)._swiftObject } open var resourceURL: URL? { return CFBundleCopyResourcesDirectoryURL(_bundle)?._swiftObject } open var executableURL: URL? { return CFBundleCopyExecutableURL(_bundle)?._swiftObject } open func url(forAuxiliaryExecutable executableName: String) -> URL? { return CFBundleCopyAuxiliaryExecutableURL(_bundle, executableName._cfObject)?._swiftObject } open var privateFrameworksURL: URL? { return CFBundleCopyPrivateFrameworksURL(_bundle)?._swiftObject } open var sharedFrameworksURL: URL? { return CFBundleCopySharedFrameworksURL(_bundle)?._swiftObject } open var sharedSupportURL: URL? { return CFBundleCopySharedSupportURL(_bundle)?._swiftObject } open var builtInPlugInsURL: URL? { return CFBundleCopyBuiltInPlugInsURL(_bundle)?._swiftObject } open var appStoreReceiptURL: URL? { // Always nil on this platform return nil } open var bundlePath: String { return bundleURL.path } open var resourcePath: String? { return resourceURL?.path } open var executablePath: String? { return executableURL?.path } open func path(forAuxiliaryExecutable executableName: String) -> String? { return url(forAuxiliaryExecutable: executableName)?.path } open var privateFrameworksPath: String? { return privateFrameworksURL?.path } open var sharedFrameworksPath: String? { return sharedFrameworksURL?.path } open var sharedSupportPath: String? { return sharedSupportURL?.path } open var builtInPlugInsPath: String? { return builtInPlugInsURL?.path } // ----------------------------------------------------------------------------------- // MARK: - URL Resource Lookup - Class open class func url(forResource name: String?, withExtension ext: String?, subdirectory subpath: String?, in bundleURL: URL) -> URL? { // If both name and ext are nil/zero-length, return nil if (name == nil || name!.isEmpty) && (ext == nil || ext!.isEmpty) { return nil } return CFBundleCopyResourceURLInDirectory(bundleURL._cfObject, name?._cfObject, ext?._cfObject, subpath?._cfObject)._swiftObject } open class func urls(forResourcesWithExtension ext: String?, subdirectory subpath: String?, in bundleURL: NSURL) -> [NSURL]? { return CFBundleCopyResourceURLsOfTypeInDirectory(bundleURL._cfObject, ext?._cfObject, subpath?._cfObject)?._unsafeTypedBridge() } // ----------------------------------------------------------------------------------- // MARK: - URL Resource Lookup - Instance open func url(forResource name: String?, withExtension ext: String?) -> URL? { return self.url(forResource: name, withExtension: ext, subdirectory: nil) } open func url(forResource name: String?, withExtension ext: String?, subdirectory subpath: String?) -> URL? { // If both name and ext are nil/zero-length, return nil if (name == nil || name!.isEmpty) && (ext == nil || ext!.isEmpty) { return nil } return CFBundleCopyResourceURL(_bundle, name?._cfObject, ext?._cfObject, subpath?._cfObject)?._swiftObject } open func url(forResource name: String?, withExtension ext: String?, subdirectory subpath: String?, localization localizationName: String?) -> URL? { // If both name and ext are nil/zero-length, return nil if (name == nil || name!.isEmpty) && (ext == nil || ext!.isEmpty) { return nil } return CFBundleCopyResourceURLForLocalization(_bundle, name?._cfObject, ext?._cfObject, subpath?._cfObject, localizationName?._cfObject)?._swiftObject } open func urls(forResourcesWithExtension ext: String?, subdirectory subpath: String?) -> [NSURL]? { return CFBundleCopyResourceURLsOfType(_bundle, ext?._cfObject, subpath?._cfObject)?._unsafeTypedBridge() } open func urls(forResourcesWithExtension ext: String?, subdirectory subpath: String?, localization localizationName: String?) -> [NSURL]? { return CFBundleCopyResourceURLsOfTypeForLocalization(_bundle, ext?._cfObject, subpath?._cfObject, localizationName?._cfObject)?._unsafeTypedBridge() } // ----------------------------------------------------------------------------------- // MARK: - Path Resource Lookup - Class open class func path(forResource name: String?, ofType ext: String?, inDirectory bundlePath: String) -> String? { return Bundle.url(forResource: name, withExtension: ext, subdirectory: bundlePath, in: URL(fileURLWithPath: bundlePath))?.path } open class func paths(forResourcesOfType ext: String?, inDirectory bundlePath: String) -> [String] { // Force-unwrap path, beacuse if the URL can't be turned into a path then something is wrong anyway return urls(forResourcesWithExtension: ext, subdirectory: bundlePath, in: NSURL(fileURLWithPath: bundlePath))?.map { $0.path! } ?? [] } // ----------------------------------------------------------------------------------- // MARK: - Path Resource Lookup - Instance open func path(forResource name: String?, ofType ext: String?) -> String? { return self.url(forResource: name, withExtension: ext, subdirectory: nil)?.path } open func path(forResource name: String?, ofType ext: String?, inDirectory subpath: String?) -> String? { return self.url(forResource: name, withExtension: ext, subdirectory: subpath)?.path } open func path(forResource name: String?, ofType ext: String?, inDirectory subpath: String?, forLocalization localizationName: String?) -> String? { return self.url(forResource: name, withExtension: ext, subdirectory: subpath, localization: localizationName)?.path } open func paths(forResourcesOfType ext: String?, inDirectory subpath: String?) -> [String] { // Force-unwrap path, beacuse if the URL can't be turned into a path then something is wrong anyway return self.urls(forResourcesWithExtension: ext, subdirectory: subpath)?.map { $0.path! } ?? [] } open func paths(forResourcesOfType ext: String?, inDirectory subpath: String?, forLocalization localizationName: String?) -> [String] { // Force-unwrap path, beacuse if the URL can't be turned into a path then something is wrong anyway return self.urls(forResourcesWithExtension: ext, subdirectory: subpath, localization: localizationName)?.map { $0.path! } ?? [] } // ----------------------------------------------------------------------------------- // MARK: - Localized Strings open func localizedString(forKey key: String, value: String?, table tableName: String?) -> String { let localizedString = CFBundleCopyLocalizedString(_bundle, key._cfObject, value?._cfObject, tableName?._cfObject)! return localizedString._swiftObject } // ----------------------------------------------------------------------------------- // MARK: - Other open var bundleIdentifier: String? { return CFBundleGetIdentifier(_bundle)?._swiftObject } open var infoDictionary: [String : Any]? { let cfDict: CFDictionary? = CFBundleGetInfoDictionary(_bundle) return __SwiftValue.fetch(cfDict) as? [String : Any] } open var localizedInfoDictionary: [String : Any]? { let cfDict: CFDictionary? = CFBundleGetLocalInfoDictionary(_bundle) return __SwiftValue.fetch(cfDict) as? [String : Any] } open func object(forInfoDictionaryKey key: String) -> Any? { if let localizedInfoDictionary = localizedInfoDictionary { return localizedInfoDictionary[key] } else { return infoDictionary?[key] } } open func classNamed(_ className: String) -> AnyClass? { NSUnimplemented() } open var principalClass: AnyClass? { NSUnimplemented() } open var preferredLocalizations: [String] { return Bundle.preferredLocalizations(from: localizations) } open var localizations: [String] { let cfLocalizations: CFArray? = CFBundleCopyBundleLocalizations(_bundle) let nsLocalizations = __SwiftValue.fetch(cfLocalizations) as? [Any] return nsLocalizations?.map { $0 as! String } ?? [] } open var developmentLocalization: String? { let region = CFBundleGetDevelopmentRegion(_bundle)! return region._swiftObject } open class func preferredLocalizations(from localizationsArray: [String]) -> [String] { let cfLocalizations: CFArray? = CFBundleCopyPreferredLocalizationsFromArray(localizationsArray._cfObject) let nsLocalizations = __SwiftValue.fetch(cfLocalizations) as? [Any] return nsLocalizations?.map { $0 as! String } ?? [] } open class func preferredLocalizations(from localizationsArray: [String], forPreferences preferencesArray: [String]?) -> [String] { let localizations = CFBundleCopyLocalizationsForPreferences(localizationsArray._cfObject, preferencesArray?._cfObject)! return localizations._swiftObject.map { return ($0 as! NSString)._swiftObject } } open var executableArchitectures: [NSNumber]? { let architectures = CFBundleCopyExecutableArchitectures(_bundle)! return architectures._swiftObject.map() { $0 as! NSNumber } } }
apache-2.0
eeb514fd7925d8728f1d4ac396b5918f
38.82263
158
0.630088
5.062986
false
false
false
false
pablosproject/Panda-Mac-app
Panda/Controller/Preferences/NSPreferencePanelWindowController.swift
1
2267
// // NSPreferencePanelWindowController.swift // devMod // // Created by Paolo Tagliani on 10/25/14. // Copyright (c) 2014 Paolo Tagliani. All rights reserved. // import Cocoa import Quartz class NSPreferencePanelWindowController: NSWindowController { @IBOutlet weak var launchAtStartupButton: NSButton! @IBOutlet weak var darkModeDatePicker: NSDatePicker! @IBOutlet weak var lightModeDatePicker: NSDatePicker! override func windowDidLoad() { super.windowDidLoad() self.window?.appearance = NSAppearance(named: NSAppearanceNameVibrantDark) self.window?.titleVisibility = NSWindowTitleVisibility.Hidden; //Set login item state launchAtStartupButton.state = PALoginItemUtility.isCurrentApplicatonInLoginItems() ? NSOnState : NSOffState //Set darkDate if let darkDate = NSUserDefaults.standardUserDefaults().objectForKey("DarkTime") as? NSDate { darkModeDatePicker.dateValue = darkDate } //Set light date if let lightDate = NSUserDefaults.standardUserDefaults().objectForKey("LightTime") as? NSDate{ lightModeDatePicker.dateValue = lightDate } } @IBAction func launchLoginPressed(sender: NSButton) { if sender.state == NSOnState{ PALoginItemUtility.addCurrentApplicatonToLoginItems() } else{ PALoginItemUtility.removeCurrentApplicatonToLoginItems() } } @IBAction func darkTimeChange(sender: NSDatePicker) { let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate appDelegate.darkTime = sender.dateValue let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setValue(sender.dateValue, forKey: "DarkTime") userDefaults.synchronize() } @IBAction func lightTimeChange(sender: NSDatePicker) { let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate appDelegate.lightTime = sender.dateValue let userDefaults = NSUserDefaults.standardUserDefaults() NSUserDefaults.standardUserDefaults().setValue(sender.dateValue, forKey: "LightTime") userDefaults.synchronize() } }
apache-2.0
4637761684cf6e18ea02cabf576931fd
34.421875
115
0.695633
5.309133
false
false
false
false
zhangliangzhi/RollCall
RollCall/MemberPage/MultAddViewController.swift
1
4890
// // MultAddViewController.swift // RollCall // // Created by ZhangLiangZhi on 2017/1/8. // Copyright © 2017年 xigk. All rights reserved. // import UIKit import Toaster class MultAddViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var mTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() mTextView.delegate = self self.title = "名字间用逗号隔开" mTextView.text = UIPasteboard.general.string } override func viewWillAppear(_ animated: Bool) { // mTextView.text = "" } // 导入 @IBAction func mumInAction(_ sender: Any) { let allname:String = mTextView.text if allname == "" { TipsSwift.showTopWithText("没有内容") return } // id let strMembers:String = arrClassData[gIndexClass].member! let membersJsonData = strMembers.data(using: .utf8) let arrMembers = JSON(data:membersJsonData!) let lastId = arrMembers[arrMembers.count-1]["id"] var iLastID:Int32 = 1 if lastId != JSON.null { iLastID = Int32(lastId.description)! + 1 } let arrn = allname.components(separatedBy: ",") for i in 0..<arrn.count { let name:String = arrn[i] // print(name) // 去除头尾空格 var getMemName:String = name getMemName = getMemName.trimmingCharacters(in: .whitespaces) // 名字不为空 if getMemName == "" { TipsSwift.showCenterWithText("名字不能为空") return } // 学号为是数字 let num = iLastID let strMembers:String = arrClassData[gIndexClass].member! let membersJsonData = strMembers.data(using: .utf8) var arrMembers = JSON(data:membersJsonData!) // 学号不能重复 for i in 0..<arrMembers.count { if num == arrMembers[i]["id"].int32Value { TipsSwift.showCenterWithText("学号不能重复") return } } // 加一个成员 var arrCMember:[CMember] = [] for i in 0..<arrMembers.count { arrCMember.append(CMember(name: arrMembers[i]["name"].stringValue, id: arrMembers[i]["id"].int32Value)) } arrCMember.append(CMember(name: getMemName, id: num)) var strMemberJson:String = "[" for i in 0..<arrCMember.count { let onem = arrCMember[i] if i == arrCMember.count - 1 { strMemberJson = strMemberJson + onem.toJSON()! }else { strMemberJson = strMemberJson + onem.toJSON()! + "," } } strMemberJson += "]" // 修改数据 arrClassData[gIndexClass].member = strMemberJson iLastID = iLastID + 1 // umeng统计观 MobClick.event("UMADDMEMBER") } // 数据保存 appDelegate.saveContext() self.navigationController?.popViewController(animated: true) TipsSwift.showTopWithText("导入成功") // umeng统计观 MobClick.event("ONEKEYADDIN") } // 导出 @IBAction func memOutAction(_ sender: Any) { // umeng统计观 MobClick.event("ONEKEYADDOUT") var getNames = "" let strMembers:String = arrClassData[gIndexClass].member! let membersJsonData = strMembers.data(using: .utf8) let arrMembers = JSON(data:membersJsonData!) if arrMembers.count == 0 { TipsSwift.showTopWithText("没有成员导出失败") return } for i in 0..<arrMembers.count { let name:String = arrMembers[i]["name"].stringValue getNames = getNames + name if i != arrMembers.count - 1 { getNames = getNames + "," } } mTextView.text = getNames UIPasteboard.general.string = getNames TipsSwift.showTopWithText("成功复杂到剪切板") Toast(text: "把成员列表,粘贴发送给其他人吧!").show() self.navigationController?.popViewController(animated: true) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(false) } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { mTextView.resignFirstResponder() } return true } }
mit
86ceaceda5e562029938aacd1ffbca2d
30.126667
119
0.534161
4.33519
false
false
false
false
WCByrne/CBToolkit
CBToolkit/CBToolkit/CBImageEditor.swift
1
31288
// // ImageCropController.swift // Punned // // Created by Wes Byrne on 9/26/14. // Copyright (c) 2014 WCBmedia. All rights reserved. // import Foundation import UIKit public protocol CBImageEditorDelegate { func imageEditor(_ editor: CBImageEditor, didFinishEditingImage original: UIImage, editedImage: UIImage) func imageEditorDidCancel(_ editor: CBImageEditor) } class FilterData { let key: String var previewImage: UIImage let name : String var params: [NSObject:AnyObject]! var image: UIImage? init(key: String, previewImage: UIImage, name: String, params: [NSObject:AnyObject]? = nil) { self.key = key self.previewImage = previewImage self.name = name self.params = params ?? [:] } } /// A simple photo editor allowing the user to crop, zoom and add filters to an image. public class CBImageEditor: UIViewController, UIScrollViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private var scrollView: UIScrollView! private var blurView: UIVisualEffectView! private var layerMask : CAShapeLayer? private var imageView: UIImageView! private var cropRect: CGRect! = CGRect.zero private var originalImage: UIImage! private var editingImage: UIImage! private var filters: [FilterData]! = [] private var imageContext: CIContext = CIContext(options: nil) public var delegate: CBImageEditorDelegate! public var cropRatio: CGSize! = CGSize(width: 1, height: 1) public var circleCrop: Bool = false { didSet { if circleCrop { self.setSquareCrop() } else { self.view.setNeedsLayout() } } } private var ratioConstraint: NSLayoutConstraint? public var horizontalRatio : CGSize! = CGSize(width: 3, height: 2) public var verticalRatio : CGSize! = CGSize(width: 2, height: 3) public var finalSize: CGSize? public var headerView: UIView! public var titleLabel: UILabel! public var saveButton: CBButton! public var cancelButton: CBButton! public var squareButton: CBButton! public var horizontalButton: CBButton! public var verticalButton: CBButton! public var filterCV : UICollectionView! private var headerHeight: NSLayoutConstraint! private var filterHeightConstraint: NSLayoutConstraint! public init(image: UIImage!, style: UIBlurEffectStyle, delegate: CBImageEditorDelegate) { super.init(nibName: nil, bundle: nil) self.delegate = delegate self.originalImage = image if image.size.width > 3000 || image.size.height > 3000 { self.originalImage = image.resize(CGSize(width: 3000, height: 3000), contentMode: CBImageContentMode.aspectFit) } self.view.backgroundColor = style == UIBlurEffectStyle.dark ? UIColor(white: 0.2, alpha: 1) : UIColor(white: 0.9, alpha: 1) self.view.clipsToBounds = true scrollView = UIScrollView(frame: cropRect) scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.center = self.view.center scrollView.alwaysBounceHorizontal = true scrollView.alwaysBounceVertical = true scrollView.clipsToBounds = false scrollView.delegate = self scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.bouncesZoom = true scrollView.maximumZoomScale = 2 scrollView.backgroundColor = UIColor.clear self.view.addSubview(scrollView) let isPad = UI_USER_INTERFACE_IDIOM() == .pad self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: scrollView, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 10)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.lessThanOrEqual, toItem: scrollView, attribute: NSLayoutAttribute.left, multiplier: 1, constant: -10)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.lessThanOrEqual, toItem: scrollView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: isPad ? -70 : -62)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: scrollView, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: isPad ? 70 : 62)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: scrollView, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: scrollView, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)) let widthConstraint = NSLayoutConstraint(item: scrollView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.width, multiplier: 1, constant: 0) widthConstraint.priority = UILayoutPriority(rawValue: 250) self.view.addConstraint(widthConstraint) editingImage = originalImage imageView = UIImageView(frame: CGRect.zero) imageView.image = editingImage imageView.contentMode = UIViewContentMode.scaleToFill scrollView.addSubview(imageView) let effect = UIBlurEffect(style: style) blurView = UIVisualEffectView(effect: effect) blurView.translatesAutoresizingMaskIntoConstraints = false blurView.frame = self.view.frame blurView.isUserInteractionEnabled = false blurView.alpha = 0.95 self.view.addSubview(blurView) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: blurView, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: blurView, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: blurView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: blurView, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)) // Title, Save, & Cancel headerView = UIView(frame: CGRect.zero) headerView.translatesAutoresizingMaskIntoConstraints = false headerView.backgroundColor = UIColor(white: 0.5, alpha: 0.1) self.view.addSubview(headerView) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: headerView, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: headerView, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: headerView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)) headerHeight = NSLayoutConstraint(item: headerView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 60) headerView.addConstraint(headerHeight) titleLabel = UILabel(frame: CGRect.zero) titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.font = UIFont(name: "Avenir-Medium", size: 22) titleLabel.textColor = style == UIBlurEffectStyle.dark ? UIColor.white : UIColor.black titleLabel.textAlignment = NSTextAlignment.center titleLabel.text = "Adjust your Photo" headerView.addSubview(titleLabel) titleLabel.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 44)) headerView.addConstraint(NSLayoutConstraint(item: headerView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: titleLabel, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)) headerView.addConstraint(NSLayoutConstraint(item: headerView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: titleLabel, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)) titleLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 250), for: UILayoutConstraintAxis.horizontal) cancelButton = CBButton(type: UIButtonType.system) cancelButton.translatesAutoresizingMaskIntoConstraints = false cancelButton.setTitle("Cancel", for: UIControlState.normal) cancelButton.titleLabel?.font = UIFont(name: "Avenir-Book", size: 18) cancelButton.tintColor = UIColor(white: style == UIBlurEffectStyle.dark ? 0.9 : 0.1, alpha: 1) cancelButton.addTarget(self, action: #selector(CBImageEditor.cancel), for: UIControlEvents.touchUpInside) headerView.addSubview(cancelButton) cancelButton.addConstraint(NSLayoutConstraint(item: cancelButton, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 44)) headerView.addConstraint(NSLayoutConstraint(item: cancelButton, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.lessThanOrEqual, toItem: titleLabel, attribute: NSLayoutAttribute.left, multiplier: 1, constant: -8)) headerView.addConstraint(NSLayoutConstraint(item: cancelButton, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: headerView, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 8)) headerView.addConstraint(NSLayoutConstraint(item: headerView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: cancelButton, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)) saveButton = CBButton(type: UIButtonType.system) saveButton.translatesAutoresizingMaskIntoConstraints = false saveButton.setTitle("Save", for: UIControlState.normal) saveButton.titleLabel?.font = UIFont(name: "Avenir-Medium", size: 18) saveButton.tintColor = UIColor(white: style == UIBlurEffectStyle.dark ? 0.9 : 0.1, alpha: 1) saveButton.addTarget(self, action: #selector(CBImageEditor.finish), for: UIControlEvents.touchUpInside) headerView.addSubview(saveButton) saveButton.addConstraint(NSLayoutConstraint(item: saveButton, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 44)) headerView.addConstraint(NSLayoutConstraint(item: saveButton, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: headerView, attribute: NSLayoutAttribute.right, multiplier: 1, constant: -8)) headerView.addConstraint(NSLayoutConstraint(item: saveButton, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: titleLabel, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 8)) headerView.addConstraint(NSLayoutConstraint(item: headerView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: saveButton, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)) let cvLayout = UICollectionViewFlowLayout() cvLayout.scrollDirection = UICollectionViewScrollDirection.horizontal cvLayout.minimumInteritemSpacing = 4 cvLayout.minimumLineSpacing = 4 filterCV = UICollectionView(frame: CGRect.zero, collectionViewLayout: cvLayout) filterCV.register(CropperFilterCell.self, forCellWithReuseIdentifier: "CropperFilterCell") filterCV.backgroundColor = UIColor(white: 0.5, alpha: 0.1) filterCV.translatesAutoresizingMaskIntoConstraints = false print(filterCV.collectionViewLayout, terminator: "") filterCV.delegate = self filterCV.dataSource = self self.view.addSubview(filterCV) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: filterCV, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: filterCV, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: filterCV, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 0)) filterHeightConstraint = NSLayoutConstraint(item: filterCV, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 60 ) filterCV.addConstraint(filterHeightConstraint) verticalButton = CBButton(type: UIButtonType.system) verticalButton.translatesAutoresizingMaskIntoConstraints = false verticalButton.addTarget(self, action: #selector(CBImageEditor.setVerticalCrop), for: UIControlEvents.touchUpInside) self.view.addSubview(verticalButton) verticalButton.layer.borderColor = UIColor(white: style == UIBlurEffectStyle.dark ? 1 : 0, alpha: 0.6).cgColor verticalButton.layer.borderWidth = 2 self.view.addConstraint(NSLayoutConstraint(item: verticalButton, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 8)) self.view.addConstraint(NSLayoutConstraint(item: filterCV, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: verticalButton, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 8)) verticalButton.addConstraint(NSLayoutConstraint(item: verticalButton, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 18)) verticalButton.addConstraint(NSLayoutConstraint(item: verticalButton, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 26)) horizontalButton = CBButton(type: UIButtonType.system) horizontalButton.translatesAutoresizingMaskIntoConstraints = false horizontalButton.addTarget(self, action: #selector(CBImageEditor.setHorizontalCrop), for: UIControlEvents.touchUpInside) self.view.addSubview(horizontalButton) horizontalButton.layer.borderColor = UIColor(white: style == UIBlurEffectStyle.dark ? 1 : 0, alpha: 0.6).cgColor horizontalButton.layer.borderWidth = 2 self.view.addConstraint(NSLayoutConstraint(item: horizontalButton, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: verticalButton, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 8)) horizontalButton.addConstraint(NSLayoutConstraint(item: horizontalButton, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 26)) horizontalButton.addConstraint(NSLayoutConstraint(item: horizontalButton, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 18)) self.view.addConstraint(NSLayoutConstraint(item: horizontalButton, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: verticalButton, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)) squareButton = CBButton(type: UIButtonType.system) squareButton.translatesAutoresizingMaskIntoConstraints = false squareButton.addTarget(self, action: #selector(CBImageEditor.setSquareCrop), for: UIControlEvents.touchUpInside) self.view.addSubview(squareButton) squareButton.layer.borderColor = UIColor(white: style == UIBlurEffectStyle.dark ? 1 : 0, alpha: 0.6).cgColor squareButton.layer.borderWidth = 2 self.view.addConstraint(NSLayoutConstraint(item: squareButton, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: horizontalButton, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 8)) squareButton.addConstraint(NSLayoutConstraint(item: squareButton, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 20)) squareButton.addConstraint(NSLayoutConstraint(item: squareButton, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 20)) self.view.addConstraint(NSLayoutConstraint(item: squareButton, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: verticalButton, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)) self.enableFilters(true, animated: false) if (originalImage.size.width > originalImage.size.height) { setHorizontalCrop() } else if (originalImage.size.width < originalImage.size.height) { setVerticalCrop() } else { setSquareCrop() } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public func enableAspectRatios(_ enable: Bool, animated: Bool) { if animated { UIView.animate(withDuration: 0.2, animations: { () -> Void in self.squareButton.alpha = enable ? 1 : 0 self.verticalButton.alpha = enable ? 1 : 0 self.horizontalButton.alpha = enable ? 1 : 0 }) } else { self.squareButton.alpha = enable ? 1 : 0 self.verticalButton.alpha = enable ? 1 : 0 self.horizontalButton.alpha = enable ? 1 : 0 } } public func enableFilters(_ enable: Bool, animated: Bool) { if enable { self.processFilters() self.filterCV.reloadData() self.filterHeightConstraint.constant = 60 } else { self.editingImage = self.originalImage self.imageView.image = editingImage self.filterHeightConstraint.constant = 0 } if animated { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: { () -> Void in self.view.layoutIfNeeded() }, completion: nil) } else { self.view.layoutIfNeeded() } } private func processFilters() { // Filters let thumb = originalImage.thumbnail(in: 200) filters = [ FilterData(key: "CIVignette", previewImage: thumb, name: "Vignette", params: [kCIInputIntensityKey as NSString : NSNumber(value: 1)]), FilterData(key: "CIPhotoEffectChrome", previewImage: thumb, name: "Chrome"), FilterData(key: "CIPhotoEffectTransfer", previewImage: thumb, name: "Transfer"), FilterData(key: "CIPhotoEffectInstant", previewImage: thumb, name: "Instant"), FilterData(key: "CIPhotoEffectProcess", previewImage: thumb, name: "Process"), FilterData(key: "CISepiaTone", previewImage: thumb, name: "Sepia", params: [kCIInputIntensityKey as NSString : NSNumber(value: 0.8)]), FilterData(key: "CIPhotoEffectTonal", previewImage: thumb, name: "B&W"), FilterData(key: "CIPhotoEffectNoir", previewImage: thumb, name: "Noir"), ] OperationQueue().addOperation({ () -> Void in var i = 0 for filter in self.filters { let image = CIImage(cgImage: filter.previewImage.cgImage!) var params = filter.params as! [String:AnyObject] params[kCIInputImageKey] = image let ciFilter = CIFilter(name: filter.key, withInputParameters: params) let outImage = ciFilter!.outputImage let cgImage = self.imageContext.createCGImage(outImage!, from: outImage!.extent) let img = UIImage(cgImage: cgImage!) filter.previewImage = img OperationQueue.main.addOperation({ self.filterCV.reloadItems(at: [IndexPath(item: i, section: 0)]) }) i += 1 } }) } // Hides the status bar and shrinks the custom navBar on landscape for iPhone override public func willAnimateRotation(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) { if UI_USER_INTERFACE_IDIOM() != .pad { let h : CGFloat = toInterfaceOrientation != UIInterfaceOrientation.portrait ? 44 : 64 headerHeight.constant = h UIApplication.shared.setStatusBarHidden(h == 44, with: UIStatusBarAnimation.fade) } } override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // var shortSide = self.view.frame.size.width > self.view.frame.size.height ? self.view.frame.size.height : self.view.frame.size.width scrollView.setZoomScale(1.0, animated: true) cropRect = scrollView.frame var imageRect = cropRect imageRect?.origin.x = 0 imageRect?.origin.y = 0 // horizontal image let yDif = originalImage.size.height/cropRect.size.height let xDif = originalImage.size.width/cropRect.size.width if (yDif < xDif) { imageRect?.size.width = originalImage.size.width * (cropRect.size.height/originalImage.size.height) } // Vertical image else { imageRect?.size.height = originalImage.size.height * (cropRect.size.width/originalImage.size.width) } imageView.frame = imageRect! scrollView.setZoomScale(1.0, animated: true) scrollView.contentSize = (imageRect?.size)! if scrollView.contentSize.height > scrollView.frame.size.height { scrollView.contentOffset.y = (scrollView.contentSize.height - scrollView.frame.size.height)/2 } if scrollView.contentSize.width > scrollView.frame.size.width { scrollView.contentOffset.x = (scrollView.contentSize.width - scrollView.frame.size.width)/2 } blurView.layer.frame = blurView.bounds let path = UIBezierPath(rect: self.view.bounds) let innerPath = UIBezierPath(roundedRect: cropRect, cornerRadius: circleCrop ? cropRect.size.width/2 : 0) path.append(innerPath) path.usesEvenOddFillRule = true if layerMask == nil { let fillLayer = CAShapeLayer() fillLayer.path = path.cgPath fillLayer.fillRule = kCAFillRuleEvenOdd blurView.layer.mask = fillLayer } else { let anim = CABasicAnimation(keyPath: "path") anim.duration = 1 anim.fromValue = layerMask!.path anim.toValue = path.cgPath layerMask!.path = path.cgPath layerMask!.add(anim, forKey: "maskAnimation") } } @objc func cancel() { self.delegate.imageEditorDidCancel(self) } @objc public func finish() { var rect = self.view.convert(cropRect, to: imageView) let scale = (originalImage.size.width/imageView.frame.size.width) rect.origin.x = (rect.origin.x * scale) * scrollView.zoomScale rect.origin.y = (rect.origin.y * scale) * scrollView.zoomScale rect.size.width = (rect.size.width * scale) * scrollView.zoomScale rect.size.height = (rect.size.height * scale) * scrollView.zoomScale var croppedImage = editingImage.crop(to: rect) if finalSize != nil { croppedImage = croppedImage.resize(finalSize!, contentMode: CBImageContentMode.aspectFit) } self.delegate.imageEditor(self, didFinishEditingImage: self.originalImage, editedImage: croppedImage) } @objc public func setSquareCrop() { if ratioConstraint != nil { self.view.removeConstraint(ratioConstraint!) } ratioConstraint = NSLayoutConstraint(item: scrollView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: scrollView, attribute: NSLayoutAttribute.height, multiplier: 1, constant: 0) self.view.addConstraint(ratioConstraint!) UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [UIViewAnimationOptions.curveEaseInOut, UIViewAnimationOptions.allowUserInteraction], animations: { () -> Void in self.view.layoutIfNeeded() }, completion: nil) squareButton.backgroundColor = squareButton.borderColor verticalButton.backgroundColor = UIColor.clear horizontalButton.backgroundColor = UIColor.clear } @objc public func setHorizontalCrop() { circleCrop = false if ratioConstraint != nil { self.view.removeConstraint(ratioConstraint!) } ratioConstraint = NSLayoutConstraint(item: scrollView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: scrollView, attribute: NSLayoutAttribute.height, multiplier: horizontalRatio.width/horizontalRatio.height, constant: 0) self.view.addConstraint(ratioConstraint!) UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [UIViewAnimationOptions.curveEaseInOut, UIViewAnimationOptions.allowUserInteraction], animations: { () -> Void in self.view.layoutIfNeeded() }, completion: nil) squareButton.backgroundColor = UIColor.clear verticalButton.backgroundColor = UIColor.clear horizontalButton.backgroundColor = horizontalButton.borderColor } @objc public func setVerticalCrop() { circleCrop = false if ratioConstraint != nil { self.view.removeConstraint(ratioConstraint!) } ratioConstraint = NSLayoutConstraint(item: scrollView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: scrollView, attribute: NSLayoutAttribute.height, multiplier: verticalRatio.width/verticalRatio.height, constant: 0) self.view.addConstraint(ratioConstraint!) UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [UIViewAnimationOptions.curveEaseInOut, UIViewAnimationOptions.allowUserInteraction], animations: { () -> Void in self.view.layoutIfNeeded() }, completion: nil) squareButton.backgroundColor = UIColor.clear verticalButton.backgroundColor = verticalButton.borderColor horizontalButton.backgroundColor = UIColor.clear } public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return filters.count + 1 } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 54, height: 54) } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CropperFilterCell", for: indexPath as IndexPath) as! CropperFilterCell if indexPath.row == 0 { cell.imageView.image = originalImage } else { cell.imageView.image = filters[indexPath.row-1].previewImage } return cell } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.row == 0 { editingImage = originalImage } else { let filter = filters[indexPath.row - 1] if filter.image != nil { editingImage = filter.image } else { let image = CIImage(cgImage: originalImage.cgImage!) var params = filter.params as! [String:AnyObject] params[kCIInputImageKey] = image let ciFilter = CIFilter(name: filter.key, withInputParameters: params) let outImage = ciFilter!.outputImage let cgImage = imageContext.createCGImage(outImage!, from: outImage!.extent) let img = UIImage(cgImage: cgImage!) filter.image = img editingImage = img } } imageView.image = editingImage } } class CropperFilterCell : UICollectionViewCell { var imageView: CBImageView! override init(frame: CGRect) { super.init(frame: frame) self.layer.cornerRadius = 2 self.clipsToBounds = true imageView = CBImageView() imageView.contentMode = UIViewContentMode.scaleAspectFill self.addSubview(imageView) _ = imageView.addConstraintsToMatchParent() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
bed1c26f6be5eab2f96adbbae2aeca10
54.475177
261
0.700077
5.224244
false
false
false
false
shuhrat/sicp-swift
ch3.playground/section-1.swift
3
43094
// CODE FROM CHAPTER 3 OF STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS // Examples from the book are commented out with ;: so that they // are easy to find and so that they will be omitted if you evaluate a // chunk of the file (programs with intervening examples) in Scheme. // BEWARE: Although the whole file can be loaded into Scheme, // you won't want to do so. For example, you generally do // not want to use the procedural representation of pairs // (cons, car, cdr as defined in section 3.3.1) instead of // Scheme's primitive pairs. // Some things require code that is not in the book -- see ch3support.scm // SECTION 3.1 // SECTION 3.1.1 // $> (withdraw 25) // $> (withdraw 25) // $> (withdraw 60) // $> (withdraw 15) (define balance 100) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define new-withdraw (let ((balance 100)) (lambda (amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")))) (define (make-withdraw balance) (lambda (amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds"))) // $> (define W1 (make-withdraw 100)) // $> (define W2 (make-withdraw 100)) // $> (W1 50) // $> (W2 70) // $> (W2 40) // $> (W1 40) (define (make-account balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (dispatch m) (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch) // $> (define acc (make-account 100)) // $> ((acc 'withdraw) 50) // $> ((acc 'withdraw) 60) // $> ((acc 'deposit) 40) // $> ((acc 'withdraw) 60) // $> (define acc2 (make-account 100)) // EXERCISE 3.1 // $> (define A (make-accumulator 5)) // $> (A 10) // $> (A 10) // EXERCISE 3.2 // $> (define s (make-monitored sqrt)) // $> (s 100) // $> (s 'how-many-calls?) // EXERCISE 3.3 // $> (define acc (make-account 100 'secret-password)) // $> ((acc 'secret-password 'withdraw) 40) // $> ((acc 'some-other-password 'deposit) 50) // SECTION 3.1.2 // *following uses rand-update -- see ch3support.scm // *also must set random-init to some value (define random-init 7) ;**not in book** (define rand (let ((x random-init)) (lambda () (set! x (rand-update x)) x))) (define (estimate-pi trials) (sqrt (/ 6 (monte-carlo trials cesaro-test)))) (define (cesaro-test) (= (gcd (rand) (rand)) 1)) (define (monte-carlo trials experiment) (define (iter trials-remaining trials-passed) (cond ((= trials-remaining 0) (/ trials-passed trials)) ((experiment) (iter (- trials-remaining 1) (+ trials-passed 1))) (else (iter (- trials-remaining 1) trials-passed)))) (iter trials 0)) // second version (no assignment) (define (estimate-pi trials) (sqrt (/ 6 (random-gcd-test trials random-init)))) (define (random-gcd-test trials initial-x) (define (iter trials-remaining trials-passed x) (let ((x1 (rand-update x))) (let ((x2 (rand-update x1))) (cond ((= trials-remaining 0) (/ trials-passed trials)) ((= (gcd x1 x2) 1) (iter (- trials-remaining 1) (+ trials-passed 1) x2)) (else (iter (- trials-remaining 1) trials-passed x2)))))) (iter trials 0 initial-x)) // EXERCISE 3.5 (define (random-in-range low high) (let ((range (- high low))) (+ low (random range)))) // SECTION 3.1.3 (define (make-simplified-withdraw balance) (lambda (amount) (set! balance (- balance amount)) balance)) // $> (define W (make-simplified-withdraw 25)) // $> (W 20) // $> (W 10) (define (make-decrementer balance) (lambda (amount) (- balance amount))) // $> (define D (make-decrementer 25)) // $> (D 20) // $> (D 10) // $> ((make-decrementer 25) 20) // $> ((lambda (amount) (- 25 amount)) 20) // $> (- 25 20) // $> ((make-simplified-withdraw 25) 20) // $> ((lambda (amount) (set! balance (- 25 amount)) 25) 20) // $> (set! balance (- 25 20)) 25 // Sameness and change // $> (define D1 (make-decrementer 25)) // $> (define D2 (make-decrementer 25)) // $> // $> (define W1 (make-simplified-withdraw 25)) // $> (define W2 (make-simplified-withdraw 25)) // $> // $> (W1 20) // $> (W1 20) // $> (W2 20) // $> (define peter-acc (make-account 100)) // $> (define paul-acc (make-account 100)) // $> // $> (define peter-acc (make-account 100)) // $> (define paul-acc peter-acc) // Pitfalls of imperative programming (define (factorial n) (define (iter product counter) (if (> counter n) product (iter (* counter product) (+ counter 1)))) (iter 1 1)) (define (factorial n) (let ((product 1) (counter 1)) (define (iter) (if (> counter n) product (begin (set! product (* counter product)) (set! counter (+ counter 1)) (iter)))) (iter))) // EXERCISE 3.7 // $> (define paul-acc // $> (make-joint peter-acc 'open-sesame 'rosebud)) // SECTION 3.2 // SECTION 3.2.1 (define (square x) (* x x)) (define square (lambda (x) (* x x))) // SECTION 3.2.2 (define (square x) (* x x)) (define (sum-of-squares x y) (+ (square x) (square y))) (define (f a) (sum-of-squares (+ a 1) (* a 2))) // $> (sum-of-squares (+ a 1) (* a 2)) // EXERCISE 3.9 (define (factorial n) (if (= n 1) 1 (* n (factorial (- n 1))))) (define (factorial n) (fact-iter 1 1 n)) (define (fact-iter product counter max-count) (if (> counter max-count) product (fact-iter (* counter product) (+ counter 1) max-count))) // SECTION 3.2.3 (define (make-withdraw balance) (lambda (amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds"))) // $> (define W1 (make-withdraw 100)) // $> (W1 50) // $> (define W2 (make-withdraw 100)) // EXERCISE 3.10 (define (make-withdraw initial-amount) (let ((balance initial-amount)) (lambda (amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")))) // $> (define W1 (make-withdraw 100)) // $> (W1 50) // $> (define W2 (make-withdraw 100)) // SECTION 3.2.4 // same as in section 1.1.8 (define (sqrt x) (define (good-enough? guess) (< (abs (- (square guess) x)) 0.001)) (define (improve guess) (average guess (/ x guess))) (define (sqrt-iter guess) (if (good-enough? guess) guess (sqrt-iter (improve guess)))) (sqrt-iter 1.0)) // EXERCISE 3.11 (define (make-account balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (dispatch m) (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch) // $> (define acc (make-account 50)) // $> // $> ((acc 'deposit) 40) // $> ((acc 'withdraw) 60) // $> // $> (define acc2 (make-account 100)) // SECTION 3.3 // SECTION 3.3.1 (define (cons x y) (let ((new (get-new-pair))) (set-car! new x) (set-cdr! new y) new)) // EXERCISE 3.12 (define (append x y) (if (null? x) y (cons (car x) (append (cdr x) y)))) (define (append! x y) (set-cdr! (last-pair x) y) x) (define (last-pair x) (if (null? (cdr x)) x (last-pair (cdr x)))) // $> (define x (list 'a 'b)) // $> (define y (list 'c 'd)) // $> (define z (append x y)) // $> z // $> (cdr x) // $> // $> (define w (append! x y)) // $> w // $> (cdr x) // EXERCISE 3.13 (define (make-cycle x) (set-cdr! (last-pair x) x) x) // $> (define z (make-cycle (list 'a 'b 'c))) // EXERCISE 3.14 (define (mystery x) (define (loop x y) (if (null? x) y (let ((temp (cdr x))) (set-cdr! x y) (loop temp x)))) (loop x '())) // Sharing and identity // $> (define x (list 'a 'b)) // $> (define z1 (cons x x)) // $> (define z2 (cons (list 'a 'b) (list 'a 'b))) (define (set-to-wow! x) (set-car! (car x) 'wow) x) // $> z1 // $> (set-to-wow! z1) // $> z2 // $> (set-to-wow! z2) // EXERCISE 3.16 (define (count-pairs x) (if (not (pair? x)) 0 (+ (count-pairs (car x)) (count-pairs (cdr x)) 1))) // Mutation as assignment (define (cons x y) (define (dispatch m) (cond ((eq? m 'car) x) ((eq? m 'cdr) y) (else (error "Undefined operation -- CONS" m)))) dispatch) (define (car z) (z 'car)) (define (cdr z) (z 'cdr)) (define (cons x y) (define (set-x! v) (set! x v)) (define (set-y! v) (set! y v)) (define (dispatch m) (cond ((eq? m 'car) x) ((eq? m 'cdr) y) ((eq? m 'set-car!) set-x!) ((eq? m 'set-cdr!) set-y!) (else (error "Undefined operation -- CONS" m)))) dispatch) (define (car z) (z 'car)) (define (cdr z) (z 'cdr)) (define (set-car! z new-value) ((z 'set-car!) new-value) z) (define (set-cdr! z new-value) ((z 'set-cdr!) new-value) z) // EXERCISE 3.20 // $> (define x (cons 1 2)) // $> (define z (cons x x)) // $> (set-car! (cdr z) 17) // $> (car x) // SECTION 3.3.2 (define (front-ptr queue) (car queue)) (define (rear-ptr queue) (cdr queue)) (define (set-front-ptr! queue item) (set-car! queue item)) (define (set-rear-ptr! queue item) (set-cdr! queue item)) (define (empty-queue? queue) (null? (front-ptr queue))) (define (make-queue) (cons '() '())) (define (front-queue queue) (if (empty-queue? queue) (error "FRONT called with an empty queue" queue) (car (front-ptr queue)))) (define (insert-queue! queue item) (let ((new-pair (cons item '()))) (cond ((empty-queue? queue) (set-front-ptr! queue new-pair) (set-rear-ptr! queue new-pair) queue) (else (set-cdr! (rear-ptr queue) new-pair) (set-rear-ptr! queue new-pair) queue)))) (define (delete-queue! queue) (cond ((empty-queue? queue) (error "DELETE! called with an empty queue" queue)) (else (set-front-ptr! queue (cdr (front-ptr queue))) queue))) // EXERCISE 3.21 // $> (define q1 (make-queue)) // $> (insert-queue! q1 'a) // $> (insert-queue! q1 'b) // $> (delete-queue! q1) // $> (delete-queue! q1) // SECTION 3.3.3 (define (lookup key table) (let ((record (assoc key (cdr table)))) (if record (cdr record) false))) (define (assoc key records) (cond ((null? records) false) ((equal? key (caar records)) (car records)) (else (assoc key (cdr records))))) (define (insert! key value table) (let ((record (assoc key (cdr table)))) (if record (set-cdr! record value) (set-cdr! table (cons (cons key value) (cdr table))))) 'ok) (define (make-table) (list '*table*)) // two-dimensional (define (lookup key-1 key-2 table) (let ((subtable (assoc key-1 (cdr table)))) (if subtable (let ((record (assoc key-2 (cdr subtable)))) (if record (cdr record) false)) false))) (define (insert! key-1 key-2 value table) (let ((subtable (assoc key-1 (cdr table)))) (if subtable (let ((record (assoc key-2 (cdr subtable)))) (if record (set-cdr! record value) (set-cdr! subtable (cons (cons key-2 value) (cdr subtable))))) (set-cdr! table (cons (list key-1 (cons key-2 value)) (cdr table))))) 'ok) // local tables (define (make-table) (let ((local-table (list '*table*))) (define (lookup key-1 key-2) (let ((subtable (assoc key-1 (cdr local-table)))) (if subtable (let ((record (assoc key-2 (cdr subtable)))) (if record (cdr record) false)) false))) (define (insert! key-1 key-2 value) (let ((subtable (assoc key-1 (cdr local-table)))) (if subtable (let ((record (assoc key-2 (cdr subtable)))) (if record (set-cdr! record value) (set-cdr! subtable (cons (cons key-2 value) (cdr subtable))))) (set-cdr! local-table (cons (list key-1 (cons key-2 value)) (cdr local-table))))) 'ok) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) (else (error "Unknown operation -- TABLE" m)))) dispatch)) (define operation-table (make-table)) (define get (operation-table 'lookup-proc)) (define put (operation-table 'insert-proc!)) // EXERCISE 3.27 (define (fib n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (fib (- n 1)) (fib (- n 2)))))) (define (memoize f) (let ((table (make-table))) (lambda (x) (let ((previously-computed-result (lookup x table))) (or previously-computed-result (let ((result (f x))) (insert! x result table) result)))))) (define memo-fib (memoize (lambda (n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (memo-fib (- n 1)) (memo-fib (- n 2)))))))) // SECTION 3.3.4 // $> (define a (make-wire)) // $> (define b (make-wire)) // $> (define c (make-wire)) // $> (define d (make-wire)) // $> (define e (make-wire)) // $> (define s (make-wire)) // $> // $> (or-gate a b d) // $> (and-gate a b c) // $> (inverter c e) // $> (and-gate d e s) // NB. To use half-adder, need or-gate from exercise 3.28 (define (half-adder a b s c) (let ((d (make-wire)) (e (make-wire))) (or-gate a b d) (and-gate a b c) (inverter c e) (and-gate d e s) 'ok)) (define (full-adder a b c-in sum c-out) (let ((s (make-wire)) (c1 (make-wire)) (c2 (make-wire))) (half-adder b c-in s c1) (half-adder a s sum c2) (or-gate c1 c2 c-out) 'ok)) (define (inverter input output) (define (invert-input) (let ((new-value (logical-not (get-signal input)))) (after-delay inverter-delay (lambda () (set-signal! output new-value))))) (add-action! input invert-input) 'ok) (define (logical-not s) (cond ((= s 0) 1) ((= s 1) 0) (else (error "Invalid signal" s)))) // *following uses logical-and -- see ch3support.scm (define (and-gate a1 a2 output) (define (and-action-procedure) (let ((new-value (logical-and (get-signal a1) (get-signal a2)))) (after-delay and-gate-delay (lambda () (set-signal! output new-value))))) (add-action! a1 and-action-procedure) (add-action! a2 and-action-procedure) 'ok) (define (make-wire) (let ((signal-value 0) (action-procedures '())) (define (set-my-signal! new-value) (if (not (= signal-value new-value)) (begin (set! signal-value new-value) (call-each action-procedures)) 'done)) (define (accept-action-procedure! proc) (set! action-procedures (cons proc action-procedures)) (proc)) (define (dispatch m) (cond ((eq? m 'get-signal) signal-value) ((eq? m 'set-signal!) set-my-signal!) ((eq? m 'add-action!) accept-action-procedure!) (else (error "Unknown operation -- WIRE" m)))) dispatch)) (define (call-each procedures) (if (null? procedures) 'done (begin ((car procedures)) (call-each (cdr procedures))))) (define (get-signal wire) (wire 'get-signal)) (define (set-signal! wire new-value) ((wire 'set-signal!) new-value)) (define (add-action! wire action-procedure) ((wire 'add-action!) action-procedure)) (define (after-delay delay action) (add-to-agenda! (+ delay (current-time the-agenda)) action the-agenda)) (define (propagate) (if (empty-agenda? the-agenda) 'done (let ((first-item (first-agenda-item the-agenda))) (first-item) (remove-first-agenda-item! the-agenda) (propagate)))) (define (probe name wire) (add-action! wire (lambda () (newline) (display name) (display " ") (display (current-time the-agenda)) (display " New-value = ") (display (get-signal wire))))) // Sample simulation // $> (define the-agenda (make-agenda)) // $> (define inverter-delay 2) // $> (define and-gate-delay 3) // $> (define or-gate-delay 5) // $> // $> (define input-1 (make-wire)) // $> (define input-2 (make-wire)) // $> (define sum (make-wire)) // $> (define carry (make-wire)) // $> // $> (probe 'sum sum) // $> (probe 'carry carry) // $> // $> (half-adder input-1 input-2 sum carry) // $> (set-signal! input-1 1) // $> (propagate) // $> // $> (set-signal! input-2 1) // $> (propagate) // EXERCISE 3.31 // $> (define (accept-action-procedure! proc) // $> (set! action-procedures (cons proc action-procedures))) // Implementing agenda (define (make-time-segment time queue) (cons time queue)) (define (segment-time s) (car s)) (define (segment-queue s) (cdr s)) (define (make-agenda) (list 0)) (define (current-time agenda) (car agenda)) (define (set-current-time! agenda time) (set-car! agenda time)) (define (segments agenda) (cdr agenda)) (define (set-segments! agenda segments) (set-cdr! agenda segments)) (define (first-segment agenda) (car (segments agenda))) (define (rest-segments agenda) (cdr (segments agenda))) (define (empty-agenda? agenda) (null? (segments agenda))) (define (add-to-agenda! time action agenda) (define (belongs-before? segments) (or (null? segments) (< time (segment-time (car segments))))) (define (make-new-time-segment time action) (let ((q (make-queue))) (insert-queue! q action) (make-time-segment time q))) (define (add-to-segments! segments) (if (= (segment-time (car segments)) time) (insert-queue! (segment-queue (car segments)) action) (let ((rest (cdr segments))) (if (belongs-before? rest) (set-cdr! segments (cons (make-new-time-segment time action) (cdr segments))) (add-to-segments! rest))))) (let ((segments (segments agenda))) (if (belongs-before? segments) (set-segments! agenda (cons (make-new-time-segment time action) segments)) (add-to-segments! segments)))) (define (remove-first-agenda-item! agenda) (let ((q (segment-queue (first-segment agenda)))) (delete-queue! q) (if (empty-queue? q) (set-segments! agenda (rest-segments agenda))))) (define (first-agenda-item agenda) (if (empty-agenda? agenda) (error "Agenda is empty -- FIRST-AGENDA-ITEM") (let ((first-seg (first-segment agenda))) (set-current-time! agenda (segment-time first-seg)) (front-queue (segment-queue first-seg))))) // SECTION 3.3.5 // $> (define C (make-connector)) // $> (define F (make-connector)) // $> (celsius-fahrenheit-converter C F) (define (celsius-fahrenheit-converter c f) (let ((u (make-connector)) (v (make-connector)) (w (make-connector)) (x (make-connector)) (y (make-connector))) (multiplier c w u) (multiplier v x u) (adder v y f) (constant 9 w) (constant 5 x) (constant 32 y) 'ok)) // $> (probe "Celsius temp" C) // $> (probe "Fahrenheit temp" F) // $> (set-value! C 25 'user) // $> (set-value! F 212 'user) // $> (forget-value! C 'user) // $> (set-value! F 212 'user) (define (adder a1 a2 sum) (define (process-new-value) (cond ((and (has-value? a1) (has-value? a2)) (set-value! sum (+ (get-value a1) (get-value a2)) me)) ((and (has-value? a1) (has-value? sum)) (set-value! a2 (- (get-value sum) (get-value a1)) me)) ((and (has-value? a2) (has-value? sum)) (set-value! a1 (- (get-value sum) (get-value a2)) me)))) (define (process-forget-value) (forget-value! sum me) (forget-value! a1 me) (forget-value! a2 me) (process-new-value)) (define (me request) (cond ((eq? request 'I-have-a-value) (process-new-value)) ((eq? request 'I-lost-my-value) (process-forget-value)) (else (error "Unknown request -- ADDER" request)))) (connect a1 me) (connect a2 me) (connect sum me) me) (define (inform-about-value constraint) (constraint 'I-have-a-value)) (define (inform-about-no-value constraint) (constraint 'I-lost-my-value)) (define (multiplier m1 m2 product) (define (process-new-value) (cond ((or (and (has-value? m1) (= (get-value m1) 0)) (and (has-value? m2) (= (get-value m2) 0))) (set-value! product 0 me)) ((and (has-value? m1) (has-value? m2)) (set-value! product (* (get-value m1) (get-value m2)) me)) ((and (has-value? product) (has-value? m1)) (set-value! m2 (/ (get-value product) (get-value m1)) me)) ((and (has-value? product) (has-value? m2)) (set-value! m1 (/ (get-value product) (get-value m2)) me)))) (define (process-forget-value) (forget-value! product me) (forget-value! m1 me) (forget-value! m2 me) (process-new-value)) (define (me request) (cond ((eq? request 'I-have-a-value) (process-new-value)) ((eq? request 'I-lost-my-value) (process-forget-value)) (else (error "Unknown request -- MULTIPLIER" request)))) (connect m1 me) (connect m2 me) (connect product me) me) (define (constant value connector) (define (me request) (error "Unknown request -- CONSTANT" request)) (connect connector me) (set-value! connector value me) me) (define (probe name connector) (define (print-probe value) (newline) (display "Probe: ") (display name) (display " = ") (display value)) (define (process-new-value) (print-probe (get-value connector))) (define (process-forget-value) (print-probe "?")) (define (me request) (cond ((eq? request 'I-have-a-value) (process-new-value)) ((eq? request 'I-lost-my-value) (process-forget-value)) (else (error "Unknown request -- PROBE" request)))) (connect connector me) me) (define (make-connector) (let ((value false) (informant false) (constraints '())) (define (set-my-value newval setter) (cond ((not (has-value? me)) (set! value newval) (set! informant setter) (for-each-except setter inform-about-value constraints)) ((not (= value newval)) (error "Contradiction" (list value newval))) (else 'ignored))) (define (forget-my-value retractor) (if (eq? retractor informant) (begin (set! informant false) (for-each-except retractor inform-about-no-value constraints)) 'ignored)) (define (connect new-constraint) (if (not (memq new-constraint constraints)) (set! constraints (cons new-constraint constraints))) (if (has-value? me) (inform-about-value new-constraint)) 'done) (define (me request) (cond ((eq? request 'has-value?) (if informant true false)) ((eq? request 'value) value) ((eq? request 'set-value!) set-my-value) ((eq? request 'forget) forget-my-value) ((eq? request 'connect) connect) (else (error "Unknown operation -- CONNECTOR" request)))) me)) (define (for-each-except exception procedure list) (define (loop items) (cond ((null? items) 'done) ((eq? (car items) exception) (loop (cdr items))) (else (procedure (car items)) (loop (cdr items))))) (loop list)) (define (has-value? connector) (connector 'has-value?)) (define (get-value connector) (connector 'value)) (define (set-value! connector new-value informant) ((connector 'set-value!) new-value informant)) (define (forget-value! connector retractor) ((connector 'forget) retractor)) (define (connect connector new-constraint) ((connector 'connect) new-constraint)) // EXERCISE 3.34 (define (squarer a b) (multiplier a a b)) // EXERCISE 3.36 // $> (define a (make-connector)) // $> (define b (make-connector)) // $> (set-value! a 10 'user) // EXERCISE 3.37 (define (celsius-fahrenheit-converter x) (c+ (c* (c/ (cv 9) (cv 5)) x) (cv 32))) // $> (define C (make-connector)) // $> (define F (celsius-fahrenheit-converter C)) (define (c+ x y) (let ((z (make-connector))) (adder x y z) z)) // SECTION 3.4 // **Need parallel-execute, available for MIT Scheme // SECTION 3.4.1 (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) // EXERCISE 3.38 // $> (set! balance (+ balance 10)) // $> (set! balance (- balance 20)) // $> (set! balance (- balance (/ balance 2))) // SECTION 3.4.2 // $> (define x 10) // $> (parallel-execute (lambda () (set! x (* x x))) // $> (lambda () (set! x (+ x 1)))) // $> (define x 10) // $> (define s (make-serializer)) // $> (parallel-execute (s (lambda () (set! x (* x x)))) // $> (s (lambda () (set! x (+ x 1))))) (define (make-account balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (let ((protected (make-serializer))) (define (dispatch m) (cond ((eq? m 'withdraw) (protected withdraw)) ((eq? m 'deposit) (protected deposit)) ((eq? m 'balance) balance) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch)) // EXERCISE 3.39 // $> (define x 10) // $> (define s (make-serializer)) // $> (parallel-execute (lambda () (set! x ((s (lambda () (* x x)))))) // $> (s (lambda () (set! x (+ x 1))))) // EXERCISE 3.40 // $> (define x 10) // $> (parallel-execute (lambda () (set! x (* x x))) // $> (lambda () (set! x (* x x x)))) // $> // $> // $> (define x 10) // $> (define s (make-serializer)) // $> (parallel-execute (s (lambda () (set! x (* x x)))) // $> (s (lambda () (set! x (* x x x))))) // EXERCISE 3.41 (define (make-account balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (let ((protected (make-serializer))) (define (dispatch m) (cond ((eq? m 'withdraw) (protected withdraw)) ((eq? m 'deposit) (protected deposit)) ((eq? m 'balance) ((protected (lambda () balance)))) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch)) // EXERCISE 3.42 (define (make-account balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (let ((protected (make-serializer))) (let ((protected-withdraw (protected withdraw)) (protected-deposit (protected deposit))) (define (dispatch m) (cond ((eq? m 'withdraw) protected-withdraw) ((eq? m 'deposit) protected-deposit) ((eq? m 'balance) balance) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch))) // Multiple shared resources (define (exchange account1 account2) (let ((difference (- (account1 'balance) (account2 'balance)))) ((account1 'withdraw) difference) ((account2 'deposit) difference))) (define (make-account-and-serializer balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (let ((balance-serializer (make-serializer))) (define (dispatch m) (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) ((eq? m 'balance) balance) ((eq? m 'serializer) balance-serializer) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch)) (define (deposit account amount) (let ((s (account 'serializer)) (d (account 'deposit))) ((s d) amount))) (define (serialized-exchange account1 account2) (let ((serializer1 (account1 'serializer)) (serializer2 (account2 'serializer))) ((serializer1 (serializer2 exchange)) account1 account2))) // EXERCISE 3.44 (define (transfer from-account to-account amount) ((from-account 'withdraw) amount) ((to-account 'deposit) amount)) // EXERCISE 3.45 (define (make-account-and-serializer balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (let ((balance-serializer (make-serializer))) (define (dispatch m) (cond ((eq? m 'withdraw) (balance-serializer withdraw)) ((eq? m 'deposit) (balance-serializer deposit)) ((eq? m 'balance) balance) ((eq? m 'serializer) balance-serializer) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch)) (define (deposit account amount) ((account 'deposit) amount)) // Implementing serializers (define (make-serializer) (let ((mutex (make-mutex))) (lambda (p) (define (serialized-p . args) (mutex 'acquire) (let ((val (apply p args))) (mutex 'release) val)) serialized-p))) (define (make-mutex) (let ((cell (list false))) (define (the-mutex m) (cond ((eq? m 'acquire) (if (test-and-set! cell) (the-mutex 'acquire))) ((eq? m 'release) (clear! cell)))) the-mutex)) (define (clear! cell) (set-car! cell false)) (define (test-and-set! cell) (if (car cell) true (begin (set-car! cell true) false))) // from footnote -- MIT Scheme (define (test-and-set! cell) (without-interrupts (lambda () (if (car cell) true (begin (set-car! cell true) false))))) // SECTION 3.5 // SECTION 3.5.1 (define (sum-primes a b) (define (iter count accum) (cond ((> count b) accum) ((prime? count) (iter (+ count 1) (+ count accum))) (else (iter (+ count 1) accum)))) (iter a 0)) (define (sum-primes a b) (accumulate + 0 (filter prime? (enumerate-interval a b)))) // $> (car (cdr (filter prime? // $> (enumerate-interval 10000 1000000)))) (define (stream-ref s n) (if (= n 0) (stream-car s) (stream-ref (stream-cdr s) (- n 1)))) (define (stream-map proc s) (if (stream-null? s) the-empty-stream (cons-stream (proc (stream-car s)) (stream-map proc (stream-cdr s))))) (define (stream-for-each proc s) (if (stream-null? s) 'done (begin (proc (stream-car s)) (stream-for-each proc (stream-cdr s))))) (define (display-stream s) (stream-for-each display-line s)) (define (display-line x) (newline) (display x)) // stream-car and stream-cdr would normally be built into // the stream implementation // $> (define (stream-car stream) (car stream)) // $> (define (stream-cdr stream) (force (cdr stream))) // $> (stream-car // $> (stream-cdr // $> (stream-filter prime? // $> (stream-enumerate-interval 10000 1000000)))) (define (stream-enumerate-interval low high) (if (> low high) the-empty-stream (cons-stream low (stream-enumerate-interval (+ low 1) high)))) (define (stream-filter pred stream) (cond ((stream-null? stream) the-empty-stream) ((pred (stream-car stream)) (cons-stream (stream-car stream) (stream-filter pred (stream-cdr stream)))) (else (stream-filter pred (stream-cdr stream))))) // force would normally be built into // the stream implementation // $> (define (force delayed-object) // $> (delayed-object)) (define (memo-proc proc) (let ((already-run? false) (result false)) (lambda () (if (not already-run?) (begin (set! result (proc)) (set! already-run? true) result) result)))) // EXERCISE 3.51 (define (show x) (display-line x) x) // $> (define x (stream-map show (stream-enumerate-interval 0 10))) // $> (stream-ref x 5) // $> (stream-ref x 7) // EXERCISE 3.52 (define sum 0) (define (accum x) (set! sum (+ x sum)) sum) // $> (define seq (stream-map accum (stream-enumerate-interval 1 20))) // $> (define y (stream-filter even? seq)) // $> (define z (stream-filter (lambda (x) (= (remainder x 5) 0)) // $> seq)) // $> (stream-ref y 7) // $> (display-stream z) // SECTION 3.5.2 (define (integers-starting-from n) (cons-stream n (integers-starting-from (+ n 1)))) (define integers (integers-starting-from 1)) (define (divisible? x y) (= (remainder x y) 0)) (define no-sevens (stream-filter (lambda (x) (not (divisible? x 7))) integers)) // $> (stream-ref no-sevens 100) (define (fibgen a b) (cons-stream a (fibgen b (+ a b)))) (define fibs (fibgen 0 1)) (define (sieve stream) (cons-stream (stream-car stream) (sieve (stream-filter (lambda (x) (not (divisible? x (stream-car stream)))) (stream-cdr stream))))) (define primes (sieve (integers-starting-from 2))) // $> (stream-ref primes 50) // Defining streams implicitly;;;Defining streams implicitly (define ones (cons-stream 1 ones)) (define (add-streams s1 s2) (stream-map + s1 s2)) (define integers (cons-stream 1 (add-streams ones integers))) (define fibs (cons-stream 0 (cons-stream 1 (add-streams (stream-cdr fibs) fibs)))) (define (scale-stream stream factor) (stream-map (lambda (x) (* x factor)) stream)) (define double (cons-stream 1 (scale-stream double 2))) (define primes (cons-stream 2 (stream-filter prime? (integers-starting-from 3)))) (define (prime? n) (define (iter ps) (cond ((> (square (stream-car ps)) n) true) ((divisible? n (stream-car ps)) false) (else (iter (stream-cdr ps))))) (iter primes)) // EXERCISE 3.53 // $> (define s (cons-stream 1 (add-streams s s))) // EXERCISE 3.56 (define (merge s1 s2) (cond ((stream-null? s1) s2) ((stream-null? s2) s1) (else (let ((s1car (stream-car s1)) (s2car (stream-car s2))) (cond ((< s1car s2car) (cons-stream s1car (merge (stream-cdr s1) s2))) ((> s1car s2car) (cons-stream s2car (merge s1 (stream-cdr s2)))) (else (cons-stream s1car (merge (stream-cdr s1) (stream-cdr s2))))))))) // EXERCISE 3.58 (define (expand num den radix) (cons-stream (quotient (* num radix) den) (expand (remainder (* num radix) den) den radix))) // EXERCISE 3.59 // $> (define exp-series // $> (cons-stream 1 (integrate-series exp-series))) // SECTION 3.5.3 (define (sqrt-improve guess x) (average guess (/ x guess))) (define (sqrt-stream x) (define guesses (cons-stream 1.0 (stream-map (lambda (guess) (sqrt-improve guess x)) guesses))) guesses) // $> (display-stream (sqrt-stream 2)) (define (pi-summands n) (cons-stream (/ 1.0 n) (stream-map - (pi-summands (+ n 2))))) // $> (define pi-stream // $> (scale-stream (partial-sums (pi-summands 1)) 4)) // $> (display-stream pi-stream) (define (euler-transform s) (let ((s0 (stream-ref s 0)) (s1 (stream-ref s 1)) (s2 (stream-ref s 2))) (cons-stream (- s2 (/ (square (- s2 s1)) (+ s0 (* -2 s1) s2))) (euler-transform (stream-cdr s))))) // $> (display-stream (euler-transform pi-stream)) (define (make-tableau transform s) (cons-stream s (make-tableau transform (transform s)))) (define (accelerated-sequence transform s) (stream-map stream-car (make-tableau transform s))) // $> (display-stream (accelerated-sequence euler-transform // $> pi-stream)) // EXERCISE 3.63 (define (sqrt-stream x) (cons-stream 1.0 (stream-map (lambda (guess) (sqrt-improve guess x)) (sqrt-stream x)))) // EXERCISE 3.64 (define (sqrt x tolerance) (stream-limit (sqrt-stream x) tolerance)) // Infinite streams of pairs // $> (stream-filter (lambda (pair) // $> (prime? (+ (car pair) (cadr pair)))) // $> int-pairs) (define (stream-append s1 s2) (if (stream-null? s1) s2 (cons-stream (stream-car s1) (stream-append (stream-cdr s1) s2)))) // $> (pairs integers integers) (define (interleave s1 s2) (if (stream-null? s1) s2 (cons-stream (stream-car s1) (interleave s2 (stream-cdr s1))))) (define (pairs s t) (cons-stream (list (stream-car s) (stream-car t)) (interleave (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (pairs (stream-cdr s) (stream-cdr t))))) // EXERCISE 3.68 (define (pairs s t) (interleave (stream-map (lambda (x) (list (stream-car s) x)) t) (pairs (stream-cdr s) (stream-cdr t)))) // Streams as signals (define (integral integrand initial-value dt) (define int (cons-stream initial-value (add-streams (scale-stream integrand dt) int))) int) // EXERCISE 3.74 (define (make-zero-crossings input-stream last-value) (cons-stream (sign-change-detector (stream-car input-stream) last-value) (make-zero-crossings (stream-cdr input-stream) (stream-car input-stream)))) // $> (define zero-crossings (make-zero-crossings sense-data 0)) // EXERCISE 3.75 (define (make-zero-crossings input-stream last-value) (let ((avpt (/ (+ (stream-car input-stream) last-value) 2))) (cons-stream (sign-change-detector avpt last-value) (make-zero-crossings (stream-cdr input-stream) avpt)))) // SECTION 3.5.4 (define (solve f y0 dt) (define y (integral dy y0 dt)) (define dy (stream-map f y)) y) (define (integral delayed-integrand initial-value dt) (define int (cons-stream initial-value (let ((integrand (force delayed-integrand))) (add-streams (scale-stream integrand dt) int)))) int) (define (solve f y0 dt) (define y (integral (delay dy) y0 dt)) (define dy (stream-map f y)) y) // $> (stream-ref (solve (lambda (y) y) 1 0.001) 1000) // EXERCISE 3.77 (define (integral integrand initial-value dt) (cons-stream initial-value (if (stream-null? integrand) the-empty-stream (integral (stream-cdr integrand) (+ (* dt (stream-car integrand)) initial-value) dt)))) // SECTION 3.5.5 // same as in section 3.1.2 (define rand (let ((x random-init)) (lambda () (set! x (rand-update x)) x))) (define random-numbers (cons-stream random-init (stream-map rand-update random-numbers))) // $> (define cesaro-stream // $> (map-successive-pairs (lambda (r1 r2) (= (gcd r1 r2) 1)) // $> random-numbers)) (define (map-successive-pairs f s) (cons-stream (f (stream-car s) (stream-car (stream-cdr s))) (map-successive-pairs f (stream-cdr (stream-cdr s))))) (define (monte-carlo experiment-stream passed failed) (define (next passed failed) (cons-stream (/ passed (+ passed failed)) (monte-carlo (stream-cdr experiment-stream) passed failed))) (if (stream-car experiment-stream) (next (+ passed 1) failed) (next passed (+ failed 1)))) // $> (define pi // $> (stream-map (lambda (p) (sqrt (/ 6 p))) // $> (monte-carlo cesaro-stream 0 0))) // same as in section 3.1.3 (define (make-simplified-withdraw balance) (lambda (amount) (set! balance (- balance amount)) balance)) (define (stream-withdraw balance amount-stream) (cons-stream balance (stream-withdraw (- balance (stream-car amount-stream)) (stream-cdr amount-stream))))
cc0-1.0
a46b41a9a506150864d0fd70dff3dd61
24.186441
75
0.541885
3.291126
false
false
false
false
jacobwhite/firefox-ios
Client/Utils/FaviconFetcher.swift
1
12431
/* 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 Storage import Shared import Alamofire import XCGLogger import Deferred import SDWebImage import Fuzi import SwiftyJSON private let log = Logger.browserLogger private let queue = DispatchQueue(label: "FaviconFetcher", attributes: DispatchQueue.Attributes.concurrent) class FaviconFetcherErrorType: MaybeErrorType { let description: String init(description: String) { self.description = description } } /* A helper class to find the favicon associated with a URL. * This will load the page and parse any icons it finds out of it. * If that fails, it will attempt to find a favicon.ico in the root host domain. */ open class FaviconFetcher: NSObject, XMLParserDelegate { open static var userAgent: String = "" static let ExpirationTime = TimeInterval(60*60*24*7) // Only check for icons once a week fileprivate static var characterToFaviconCache = [String: UIImage]() static var defaultFavicon: UIImage = { return UIImage(named: "defaultFavicon")! }() static var colors: [String: UIColor] = [:] //An in-Memory data store that stores background colors domains. Stored using url.baseDomain. // Sites can be accessed via their baseDomain. static var defaultIcons: [String: (color: UIColor, url: String)] = { return FaviconFetcher.getDefaultIcons() }() static let multiRegionDomains = ["craigslist", "google", "amazon"] class func getDefaultIconForURL(url: URL) -> (color: UIColor, url: String)? { // Problem: Sites like amazon exist with .ca/.de and many other tlds. // Solution: They are stored in the default icons list as "amazon" instead of "amazon.com" this allows us to have favicons for every tld." // Here, If the site is in the multiRegionDomain array look it up via its second level domain (amazon) instead of its baseDomain (amazon.com) let hostName = url.hostSLD if multiRegionDomains.contains(hostName), let icon = defaultIcons[hostName] { return icon } if let name = url.baseDomain, let icon = defaultIcons[name] { return icon } return nil } class func getForURL(_ url: URL, profile: Profile) -> Deferred<Maybe<[Favicon]>> { let f = FaviconFetcher() return f.loadFavicons(url, profile: profile) } fileprivate func loadFavicons(_ url: URL, profile: Profile, oldIcons: [Favicon] = [Favicon]()) -> Deferred<Maybe<[Favicon]>> { if isIgnoredURL(url) { return deferMaybe(FaviconFetcherErrorType(description: "Not fetching ignored URL to find favicons.")) } let deferred = Deferred<Maybe<[Favicon]>>() var oldIcons: [Favicon] = oldIcons queue.async { self.parseHTMLForFavicons(url).bind({ (result: Maybe<[Favicon]>) -> Deferred<[Maybe<Favicon>]> in var deferreds = [Deferred<Maybe<Favicon>>]() if let icons = result.successValue { deferreds = icons.map { self.getFavicon(url, icon: $0, profile: profile) } } return all(deferreds) }).bind({ (results: [Maybe<Favicon>]) -> Deferred<Maybe<[Favicon]>> in for result in results { if let icon = result.successValue { oldIcons.append(icon) } } oldIcons = oldIcons.sorted { return $0.width! > $1.width! } return deferMaybe(oldIcons) }).upon({ (result: Maybe<[Favicon]>) in deferred.fill(result) return }) } return deferred } lazy fileprivate var alamofire: SessionManager = { let configuration = URLSessionConfiguration.default var defaultHeaders = SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:] defaultHeaders["User-Agent"] = FaviconFetcher.userAgent configuration.httpAdditionalHeaders = defaultHeaders configuration.timeoutIntervalForRequest = 5 return SessionManager(configuration: configuration) }() fileprivate func fetchDataForURL(_ url: URL) -> Deferred<Maybe<Data>> { let deferred = Deferred<Maybe<Data>>() alamofire.request(url).response { response in // Don't cancel requests just because our Manager is deallocated. withExtendedLifetime(self.alamofire) { if response.error == nil { if let data = response.data { deferred.fill(Maybe(success: data)) return } } let errorDescription = (response.error as NSError?)?.description ?? "No content." deferred.fill(Maybe(failure: FaviconFetcherErrorType(description: errorDescription))) } } return deferred } // Loads and parses an html document and tries to find any known favicon-type tags for the page fileprivate func parseHTMLForFavicons(_ url: URL) -> Deferred<Maybe<[Favicon]>> { return fetchDataForURL(url).bind({ result -> Deferred<Maybe<[Favicon]>> in var icons = [Favicon]() guard let data = result.successValue, result.isSuccess, let root = try? HTMLDocument(data: data as Data) else { return deferMaybe([]) } var reloadUrl: URL? = nil for meta in root.xpath("//head/meta") { if let refresh = meta["http-equiv"], refresh == "Refresh", let content = meta["content"], let index = content.range(of: "URL="), let url = NSURL(string: content.substring(from: index.upperBound)) { reloadUrl = url as URL } } if let url = reloadUrl { return self.parseHTMLForFavicons(url) } for link in root.xpath("//head//link[contains(@rel, 'icon')]") { guard let href = link["href"] else { continue //Skip the rest of the loop. But don't stop the loop } if let iconUrl = NSURL(string: href, relativeTo: url as URL), let absoluteString = iconUrl.absoluteString { let icon = Favicon(url: absoluteString) icons = [icon] } // If we haven't got any options icons, then use the default at the root of the domain. if let url = NSURL(string: "/favicon.ico", relativeTo: url as URL), icons.isEmpty, let absoluteString = url.absoluteString { let icon = Favicon(url: absoluteString) icons = [icon] } } return deferMaybe(icons) }) } func getFavicon(_ siteUrl: URL, icon: Favicon, profile: Profile) -> Deferred<Maybe<Favicon>> { let deferred = Deferred<Maybe<Favicon>>() let url = icon.url let manager = SDWebImageManager.shared() let site = Site(url: siteUrl.absoluteString, title: "") var fav = Favicon(url: url) if let url = url.asURL { var fetch: SDWebImageOperation? fetch = manager.loadImage(with: url, options: .lowPriority, progress: { (receivedSize, expectedSize, _) in if receivedSize > FaviconHandler.MaximumFaviconSize || expectedSize > FaviconHandler.MaximumFaviconSize { fetch?.cancel() } }, completed: { (img, _, _, _, _, url) in guard let url = url else { deferred.fill(Maybe(failure: FaviconError())) return } fav = Favicon(url: url.absoluteString) if let img = img { fav.width = Int(img.size.width) fav.height = Int(img.size.height) profile.favicons.addFavicon(fav, forSite: site) } else { fav.width = 0 fav.height = 0 } deferred.fill(Maybe(success: fav)) }) } else { return deferMaybe(FaviconFetcherErrorType(description: "Invalid URL \(url)")) } return deferred } // Returns a single Favicon UIImage for a given URL class func fetchFavImageForURL(forURL url: URL, profile: Profile) -> Deferred<Maybe<UIImage>> { let deferred = Deferred<Maybe<UIImage>>() FaviconFetcher.getForURL(url.domainURL, profile: profile).uponQueue(.main) { result in var iconURL: URL? if let favicons = result.successValue, favicons.count > 0, let faviconImageURL = favicons.first?.url.asURL { iconURL = faviconImageURL } else { return deferred.fill(Maybe(failure: FaviconError())) } SDWebImageManager.shared().loadImage(with: iconURL, options: .continueInBackground, progress: nil) { (image, _, _, _, _, _) in if let image = image { deferred.fill(Maybe(success: image)) } else { deferred.fill(Maybe(failure: FaviconError())) } } } return deferred } // Returns the default favicon for a site based on the first letter of the site's domain class func getDefaultFavicon(_ url: URL) -> UIImage { guard let character = url.baseDomain?.first else { return defaultFavicon } let faviconLetter = String(character).uppercased() if let cachedFavicon = characterToFaviconCache[faviconLetter] { return cachedFavicon } var faviconImage = UIImage() let faviconLabel = UILabel(frame: CGRect(x: 0, y: 0, width: TwoLineCellUX.ImageSize, height: TwoLineCellUX.ImageSize)) faviconLabel.text = faviconLetter faviconLabel.textAlignment = .center faviconLabel.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium) faviconLabel.textColor = UIColor.white UIGraphicsBeginImageContextWithOptions(faviconLabel.bounds.size, false, 0.0) faviconLabel.layer.render(in: UIGraphicsGetCurrentContext()!) faviconImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() characterToFaviconCache[faviconLetter] = faviconImage return faviconImage } // Returns a color based on the url's hash class func getDefaultColor(_ url: URL) -> UIColor { guard let hash = url.baseDomain?.hashValue else { return UIColor.gray } let index = abs(hash) % (UIConstants.DefaultColorStrings.count - 1) let colorHex = UIConstants.DefaultColorStrings[index] return UIColor(colorString: colorHex) } // Default favicons and background colors provided via mozilla/tippy-top-sites class func getDefaultIcons() -> [String: (color: UIColor, url: String)] { let filePath = Bundle.main.path(forResource: "top_sites", ofType: "json") let file = try! Data(contentsOf: URL(fileURLWithPath: filePath!)) let json = JSON(file) var icons: [String: (color: UIColor, url: String)] = [:] json.forEach({ guard let url = $0.1["domain"].string, let color = $0.1["background_color"].string, var path = $0.1["image_url"].string else { return } path = path.replacingOccurrences(of: ".png", with: "") let filePath = Bundle.main.path(forResource: "TopSites/" + path, ofType: "png") if let filePath = filePath { if color == "#fff" || color == "#FFF" { icons[url] = (UIColor.clear, filePath) } else { icons[url] = (UIColor(colorString: color.replacingOccurrences(of: "#", with: "")), filePath) } } }) return icons } }
mpl-2.0
e1efec42ee4fa7095db9f7e638268e44
41.426621
149
0.583219
5.004428
false
false
false
false
JustForFunOrg/2-TapOrHoldCounter
TapOrHoldCounter/MainViewController.swift
1
1369
// // MainVC.swift // TapOrHoldCounter // // Created by vmalikov on 1/28/16. // Copyright © 2016 justForFun. All rights reserved. // import UIKit class MainViewController: UIViewController { @IBOutlet weak var counterLabel: UILabel! @IBOutlet weak var tapOrHoldButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // reset counter resetButtonTapped(self) addGestureRecognizers() } func addGestureRecognizers() { let tapGesture = UITapGestureRecognizer(target: self, action: "tapOrHoldButtonTapped") let holdGesture = UILongPressGestureRecognizer(target: self, action: "tapOrHoldButtonHolded") tapGesture.numberOfTapsRequired = 1 tapOrHoldButton.addGestureRecognizer(tapGesture) tapOrHoldButton.addGestureRecognizer(holdGesture) } func tapOrHoldButtonTapped() { increaseCounter() } func tapOrHoldButtonHolded() { increaseCounter() } @IBAction func resetButtonTapped(sender: AnyObject) { counterLabel.text = "0"; } func increaseCounter() { guard let counterText = counterLabel.text else { return } if let currentNumber = Int(counterText) { counterLabel.text = String(currentNumber + 1) } } }
mit
b8bdedaedaa1fa411920850dd267ef01
24.811321
101
0.641082
4.868327
false
false
false
false
pyngit/RealmSample
RealmSample/service/UserService.swift
1
2610
// // UserService.swift // RealmSample // // Created by pyngit on 2015/10/29. // // import Foundation class UserService{ /** ユーザ情報の取得 - parameter UserDomain: 取得するユーザのIDをセットしたUserDomain */ func getUserInfo(userDomain:UserDomain) throws -> UserInfoVO{ print("getUserInfo user id:\(userDomain.id)"); let vo = UserInfoVO(); let userRealm = CommonRealm.createRealm(); //ユーザ情報の取得 let userResult:UserDomain? = userRealm.objectForPrimaryKey(UserDomain.self, key: userDomain.id); //誕生日から星座を取得 if(userResult != nil){ //検索結果をセット vo.userDomain = userResult!; //ユーザ情報から星座を取得 let birthday = userResult!.birthday; let masterRealm = CommonRealm.createRealm("master"); let singsZodiacList = masterRealm.objects(SingsZodiacDomain).filter("mindate <= \(birthday) AND maxdate >= \(birthday)") print("singsZodiacList count:\(singsZodiacList.count)"); if(singsZodiacList.count > 0){ vo.signsZodiacDomain = singsZodiacList[0]; } } return vo; } /* ユーザ登録 - parameter UserDomain: 登録するUserDomain */ func add(userDomain:UserDomain) throws ->UserInfoVO{ let vo = UserInfoVO(); vo.userDomain = userDomain; let realm = CommonRealm.createRealm(); //IDのセット let userId:Int? = realm.objects(UserDomain).max("id"); print("UserService add userId:\(userId)"); if(userId != nil){ //ID に一つ加算 userDomain.id = userId! + 1; }else{ userDomain.id = 0; } realm.beginWrite() //追記 realm.add(userDomain); try realm.commitWrite(); print("UserService add:\(userDomain.id) - \(userDomain.name) - \(userDomain.birthday))"); return vo; } /** 全件削除 */ func deleteAll()throws{ let realm = CommonRealm.createRealm(); //全件取得 let allObject = realm.objects(UserDomain); print("deleteAll count:\(allObject.count)"); if(allObject.count > 0){ realm.beginWrite() //検索結果を削除 realm.delete(allObject); try realm.commitWrite(); } } }
mit
1c87dbab21aaff43dac501f3fd293d80
25.315217
132
0.539256
4.158076
false
false
false
false
wackosix/WSNetEaseNews
NetEaseNews/Classes/External/PhotoBrowser/Frameworks/Haneke/Cache.swift
2
12292
// // Cache.swift // Haneke // // Created by Luis Ascorbe on 23/07/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit // Used to add T to NSCache class ObjectWrapper : NSObject { let value: Any init(value: Any) { self.value = value } } extension HanekeGlobals { // It'd be better to define this in the Cache class but Swift doesn't allow statics in a generic type public struct Cache { public static let OriginalFormatName = "original" public enum ErrorCode : Int { case ObjectNotFound = -100 case FormatNotFound = -101 } } } public class Cache<T: DataConvertible where T.Result == T, T : DataRepresentable> { let name: String var memoryWarningObserver : NSObjectProtocol! public init(name: String) { self.name = name let notifications = NSNotificationCenter.defaultCenter() // Using block-based observer to avoid subclassing NSObject memoryWarningObserver = notifications.addObserverForName(UIApplicationDidReceiveMemoryWarningNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: { [unowned self] (notification : NSNotification!) -> Void in self.onMemoryWarning() } ) let originalFormat = Format<T>(name: HanekeGlobals.Cache.OriginalFormatName) self.addFormat(originalFormat) } deinit { let notifications = NSNotificationCenter.defaultCenter() notifications.removeObserver(memoryWarningObserver, name: UIApplicationDidReceiveMemoryWarningNotification, object: nil) } public func set(value value: T, key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, success succeed: ((T) -> ())? = nil) { if let (format, memoryCache, diskCache) = self.formats[formatName] { self.format(value: value, format: format) { formattedValue in let wrapper = ObjectWrapper(value: formattedValue) memoryCache.setObject(wrapper, forKey: key) // Value data is sent as @autoclosure to be executed in the disk cache queue. diskCache.setData(self.dataFromValue(formattedValue, format: format), key: key) succeed?(formattedValue) } } else { assertionFailure("Can't set value before adding format") } } public func fetch(key key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> { let fetch = Cache.buildFetch(failure: fail, success: succeed) if let (format, memoryCache, diskCache) = self.formats[formatName] { if let wrapper = memoryCache.objectForKey(key) as? ObjectWrapper, let result = wrapper.value as? T { fetch.succeed(result) diskCache.updateAccessDate(self.dataFromValue(result, format: format), key: key) return fetch } self.fetchFromDiskCache(diskCache, key: key, memoryCache: memoryCache, failure: { error in fetch.fail(error) }) { value in fetch.succeed(value) } } else { let localizedFormat = NSLocalizedString("Format %@ not found", comment: "Error description") let description = String(format:localizedFormat, formatName) let error = errorWithCode(HanekeGlobals.Cache.ErrorCode.FormatNotFound.rawValue, description: description) fetch.fail(error) } return fetch } public func fetch(fetcher fetcher : Fetcher<T>, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> { let key = fetcher.key let fetch = Cache.buildFetch(failure: fail, success: succeed) self.fetch(key: key, formatName: formatName, failure: { error in if error?.code == HanekeGlobals.Cache.ErrorCode.FormatNotFound.rawValue { fetch.fail(error) } if let (format, _, _) = self.formats[formatName] { self.fetchAndSet(fetcher, format: format, failure: {error in fetch.fail(error) }) {value in fetch.succeed(value) } } // Unreachable code. Formats can't be removed from Cache. }) { value in fetch.succeed(value) } return fetch } public func remove(key key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName) { if let (_, memoryCache, diskCache) = self.formats[formatName] { memoryCache.removeObjectForKey(key) diskCache.removeData(key) } } public func removeAll(completion: (() -> ())? = nil) { let group = dispatch_group_create(); for (_, (_, memoryCache, diskCache)) in self.formats { memoryCache.removeAllObjects() dispatch_group_enter(group) diskCache.removeAllData { dispatch_group_leave(group) } } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let timeout = dispatch_time(DISPATCH_TIME_NOW, Int64(60 * NSEC_PER_SEC)) if dispatch_group_wait(group, timeout) != 0 { Log.error("removeAll timed out waiting for disk caches") } let path = self.cachePath do { try NSFileManager.defaultManager().removeItemAtPath(path) } catch { Log.error("Failed to remove path \(path)", error as NSError) } if let completion = completion { dispatch_async(dispatch_get_main_queue()) { completion() } } } } // MARK: Notifications func onMemoryWarning() { for (_, (_, memoryCache, _)) in self.formats { memoryCache.removeAllObjects() } } // MARK: Formats var formats : [String : (Format<T>, NSCache, DiskCache)] = [:] public func addFormat(format : Format<T>) { let name = format.name let formatPath = self.formatPath(formatName: name) let memoryCache = NSCache() let diskCache = DiskCache(path: formatPath, capacity : format.diskCapacity) self.formats[name] = (format, memoryCache, diskCache) } // MARK: Internal lazy var cachePath: String = { let basePath = DiskCache.basePath() let cachePath = (basePath as NSString).stringByAppendingPathComponent(self.name) return cachePath }() func formatPath(formatName formatName: String) -> String { let formatPath = (self.cachePath as NSString).stringByAppendingPathComponent(formatName) do { try NSFileManager.defaultManager().createDirectoryAtPath(formatPath, withIntermediateDirectories: true, attributes: nil) } catch { Log.error("Failed to create directory \(formatPath)", error as NSError) } return formatPath } // MARK: Private func dataFromValue(value : T, format : Format<T>) -> NSData? { if let data = format.convertToData?(value) { return data } return value.asData() } private func fetchFromDiskCache(diskCache : DiskCache, key: String, memoryCache : NSCache, failure fail : ((NSError?) -> ())?, success succeed : (T) -> ()) { diskCache.fetchData(key: key, failure: { error in if let block = fail { if (error?.code == NSFileReadNoSuchFileError) { let localizedFormat = NSLocalizedString("Object not found for key %@", comment: "Error description") let description = String(format:localizedFormat, key) let error = errorWithCode(HanekeGlobals.Cache.ErrorCode.ObjectNotFound.rawValue, description: description) block(error) } else { block(error) } } }) { data in dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { let value = T.convertFromData(data) if let value = value { let descompressedValue = self.decompressedImageIfNeeded(value) dispatch_async(dispatch_get_main_queue(), { succeed(descompressedValue) let wrapper = ObjectWrapper(value: descompressedValue) memoryCache.setObject(wrapper, forKey: key) }) } }) } } private func fetchAndSet(fetcher : Fetcher<T>, format : Format<T>, failure fail : ((NSError?) -> ())?, success succeed : (T) -> ()) { fetcher.fetch(failure: { error in let _ = fail?(error) }) { value in self.set(value: value, key: fetcher.key, formatName: format.name, success: succeed) } } private func format(value value : T, format : Format<T>, success succeed : (T) -> ()) { // HACK: Ideally Cache shouldn't treat images differently but I can't think of any other way of doing this that doesn't complicate the API for other types. if format.isIdentity && !(value is UIImage) { succeed(value) } else { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { var formatted = format.apply(value) if let formattedImage = formatted as? UIImage { let originalImage = value as? UIImage if formattedImage === originalImage { formatted = self.decompressedImageIfNeeded(formatted) } } dispatch_async(dispatch_get_main_queue()) { succeed(formatted) } } } } private func decompressedImageIfNeeded(value : T) -> T { if let image = value as? UIImage { let decompressedImage = image.hnk_decompressedImage() as? T return decompressedImage! } return value } private class func buildFetch(failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> { let fetch = Fetch<T>() if let succeed = succeed { fetch.onSuccess(succeed) } if let fail = fail { fetch.onFailure(fail) } return fetch } // MARK: Convenience fetch // Ideally we would put each of these in the respective fetcher file as a Cache extension. Unfortunately, this fails to link when using the framework in a project as of Xcode 6.1. public func fetch(key key: String, @autoclosure(escaping) value getValue : () -> T.Result, formatName: String = HanekeGlobals.Cache.OriginalFormatName, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> { let fetcher = SimpleFetcher<T>(key: key, value: getValue) return self.fetch(fetcher: fetcher, formatName: formatName, success: succeed) } public func fetch(path path: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> { let fetcher = DiskFetcher<T>(path: path) return self.fetch(fetcher: fetcher, formatName: formatName, failure: fail, success: succeed) } public func fetch(URL URL : NSURL, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> { let fetcher = NetworkFetcher<T>(URL: URL) return self.fetch(fetcher: fetcher, formatName: formatName, failure: fail, success: succeed) } }
mit
7e46c77c344594e5fa38298d736a6c64
39.837209
214
0.590465
4.82607
false
false
false
false
iadmir/Signal-iOS
Signal/src/UserInterface/Notifications/UserNotificationsAdaptee.swift
2
7763
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // /** * TODO This is currently unused code. I started implenting new notifications as UserNotifications rather than the deprecated * LocalNotifications before I realized we can't mix and match. Registering notifications for one clobbers the other. * So, for now iOS10 continues to use LocalNotifications until we can port all the NotificationsManager stuff here. */ import Foundation import UserNotifications @available(iOS 10.0, *) struct AppNotifications { enum Category { case missedCall, missedCallFromNoLongerVerifiedIdentity // Don't forget to update this! We use it to register categories. static let allValues = [ missedCall, missedCallFromNoLongerVerifiedIdentity ] } enum Action { case callBack, showThread } static var allCategories: Set<UNNotificationCategory> { let categories = Category.allValues.map { category($0) } return Set(categories) } static func category(_ type: Category) -> UNNotificationCategory { switch type { case .missedCall: return UNNotificationCategory(identifier: "org.whispersystems.signal.AppNotifications.Category.missedCall", actions: [ action(.callBack) ], intentIdentifiers: [], options: []) case .missedCallFromNoLongerVerifiedIdentity: return UNNotificationCategory(identifier: "org.whispersystems.signal.AppNotifications.Category.missedCallFromNoLongerVerifiedIdentity", actions: [ action(.showThread) ], intentIdentifiers: [], options: []) } } static func action(_ type: Action) -> UNNotificationAction { switch type { case .callBack: return UNNotificationAction(identifier: "org.whispersystems.signal.AppNotifications.Action.callBack", title: CallStrings.callBackButtonTitle, options: .authenticationRequired) case .showThread: return UNNotificationAction(identifier: "org.whispersystems.signal.AppNotifications.Action.showThread", title: CallStrings.showThreadButtonTitle, options: .authenticationRequired) } } } @available(iOS 10.0, *) class UserNotificationsAdaptee: NSObject, OWSCallNotificationsAdaptee, UNUserNotificationCenterDelegate { let TAG = "[UserNotificationsAdaptee]" private let center: UNUserNotificationCenter var previewType: NotificationType { return Environment.getCurrent().preferences.notificationPreviewType() } override init() { self.center = UNUserNotificationCenter.current() super.init() center.delegate = self // FIXME TODO only do this after user has registered. // maybe the PushManager needs a reference to the NotificationsAdapter. requestAuthorization() center.setNotificationCategories(AppNotifications.allCategories) } func requestAuthorization() { center.requestAuthorization(options: [.badge, .sound, .alert]) { (granted, error) in if granted { Logger.debug("\(self.TAG) \(#function) succeeded.") } else if error != nil { Logger.error("\(self.TAG) \(#function) failed with error: \(error!)") } else { Logger.error("\(self.TAG) \(#function) failed without error.") } } } // MARK: - OWSCallNotificationsAdaptee public func presentIncomingCall(_ call: SignalCall, callerName: String) { Logger.debug("\(TAG) \(#function) is no-op, because it's handled with callkit.") // TODO since CallKit doesn't currently work on the simulator, // we could implement UNNotifications for simulator testing, or if people have opted out of callkit. } public func presentMissedCall(_ call: SignalCall, callerName: String) { Logger.debug("\(TAG) \(#function)") let content = UNMutableNotificationContent() // TODO group by thread identifier // content.threadIdentifier = threadId let notificationBody = { () -> String in switch previewType { case .noNameNoPreview: return CallStrings.missedCallNotificationBodyWithoutCallerName case .nameNoPreview, .namePreview: return (Environment.getCurrent().preferences.isCallKitPrivacyEnabled() ? CallStrings.missedCallNotificationBodyWithoutCallerName : String(format: CallStrings.missedCallNotificationBodyWithCallerName, callerName)) }}() content.body = notificationBody content.sound = UNNotificationSound.default() content.categoryIdentifier = AppNotifications.category(.missedCall).identifier let request = UNNotificationRequest.init(identifier: call.localId.uuidString, content: content, trigger: nil) center.add(request) } public func presentMissedCallBecauseOfNoLongerVerifiedIdentity(call: SignalCall, callerName: String) { Logger.debug("\(TAG) \(#function)") let content = UNMutableNotificationContent() // TODO group by thread identifier // content.threadIdentifier = threadId let notificationBody = { () -> String in switch previewType { case .noNameNoPreview: return CallStrings.missedCallWithIdentityChangeNotificationBodyWithoutCallerName case .nameNoPreview, .namePreview: return (Environment.getCurrent().preferences.isCallKitPrivacyEnabled() ? CallStrings.missedCallWithIdentityChangeNotificationBodyWithoutCallerName : String(format: CallStrings.missedCallWithIdentityChangeNotificationBodyWithCallerName, callerName)) }}() content.body = notificationBody content.sound = UNNotificationSound.default() content.categoryIdentifier = AppNotifications.category(.missedCallFromNoLongerVerifiedIdentity).identifier let request = UNNotificationRequest.init(identifier: call.localId.uuidString, content: content, trigger: nil) center.add(request) } public func presentMissedCallBecauseOfNewIdentity(call: SignalCall, callerName: String) { Logger.debug("\(TAG) \(#function)") let content = UNMutableNotificationContent() // TODO group by thread identifier // content.threadIdentifier = threadId let notificationBody = { () -> String in switch previewType { case .noNameNoPreview: return CallStrings.missedCallWithIdentityChangeNotificationBodyWithoutCallerName case .nameNoPreview, .namePreview: return (Environment.getCurrent().preferences.isCallKitPrivacyEnabled() ? CallStrings.missedCallWithIdentityChangeNotificationBodyWithoutCallerName : String(format: CallStrings.missedCallWithIdentityChangeNotificationBodyWithCallerName, callerName)) }}() content.body = notificationBody content.sound = UNNotificationSound.default() content.categoryIdentifier = AppNotifications.category(.missedCall).identifier let request = UNNotificationRequest.init(identifier: call.localId.uuidString, content: content, trigger: nil) center.add(request) } }
gpl-3.0
df86165a32923393212b194dab1c42bb
41.420765
147
0.651295
5.836842
false
false
false
false
Za1006/TIY-Assignments
VenueMenu/VenueMenu/FavoritesTableViewController.swift
1
4565
// // FavoritesTableViewController.swift // VenueMenu // // Created by Elizabeth Yeh on 11/29/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import CoreData protocol VenueSearchDelegate { func venueWasChoosen(venue: NSManagedObject) } class FavoritesTableViewController: UITableViewController,VenueSearchDelegate { let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext var venues = Array<NSManagedObject>() override func viewDidLoad() { super.viewDidLoad() title = "Favorite Venues" navigationItem.leftBarButtonItem = self.editButtonItem() let fetchRequest = NSFetchRequest(entityName: "Venue") do { let fetchResults = try managedObjectContext.executeFetchRequest(fetchRequest) as? [Venue] venues = fetchResults! } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return venues.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("FavoritesVenueCell", forIndexPath: indexPath) as! FavoritesVenueCell let aVenue = venues[indexPath.row] cell.favoritesLabel.text = aVenue.valueForKey("name") as? String cell.ratingLable.text = aVenue.valueForKey("rating")as? String return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let aVenue = venues[indexPath.row] venues.removeAtIndex(indexPath.row) managedObjectContext.deletedObjects(aVenue) saveContext() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowVenueSearchSegue" { let destVC = segue.destinationViewController as! UINavigationController let modalVC = destVC.viewControllers[0] as! VenueSearchViewController modalVC.delegate = self } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let venueDetailVC = storyboard?.instantiateViewControllerWithIdentifier("VenueDetailViewController") as! VenueDetailViewController venueDetailVC.indexRow = indexPath.row venueDetailVC.venuesForDetailView = venues navigationController?.pushViewController(venueDetailVC, animated: true) } func venueWasChoosen(venue: NSManagedObject) { } func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
cc0-1.0
3e8e21044201164a8846762f96a21fb5
30.694444
194
0.657975
5.799238
false
false
false
false
steveholt55/Gear8-Demo
Gear8Demo/Scenes/GameScene.swift
1
1267
// // Copyright (c) 2015 Brandon Jenniges. All rights reserved. // import SpriteKit class GameScene: SKScene { let playButton: SKSpriteNode override init(size: CGSize) { playButton = SKSpriteNode(imageNamed: "play") super.init(size: size) backgroundColor = SKColor(red: 1, green: 1, blue: 1, alpha: 1) let background = SKSpriteNode(imageNamed: "title") background.position = CGPointMake(size.width / 2, size.height / 2) addChild(background) playButton.position = CGPointMake(size.width / 2, size.height / 2 - 150) addChild(playButton) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { let location = touch.locationInNode(self) if self.playButton.containsPoint(location) { let scene = DragDropScene(size: self.size) let sceneTransition = SKTransition.fadeWithColor(UIColor.lightGrayColor(), duration: 2) self.view?.presentScene(scene, transition: sceneTransition) } } } }
mit
30b656afc05a7dd3336cf09e5ad61a01
31.487179
103
0.617206
4.675277
false
false
false
false
SwiftGen/SwiftGen
Sources/SwiftGenKit/Parsers/CoreData/Entity.swift
1
3317
// // SwiftGenKit // Copyright © 2022 SwiftGen // MIT Licence // import Foundation import Kanna extension CoreData { public struct Entity { public let name: String public let className: String public let isAbstract: Bool public let userInfo: [String: Any] public let superEntity: String? public let attributes: [Attribute] public let relationships: [Relationship] public let fetchedProperties: [FetchedProperty] public let uniquenessConstraints: [[String]] public let shouldGenerateCode: Bool } } private enum XML { fileprivate enum Attributes { static let name = "name" static let representedClassName = "representedClassName" static let isAbstract = "isAbstract" static let superEntity = "parentEntity" static let codeGenerationType = "codeGenerationType" } fileprivate enum Values { static let categoryCodeGeneration = "category" static let classCodeGeneration = "class" } static let attributesPath = "attribute" static let relationshipsPath = "relationship" static let fetchedPropertiesPath = "fetchedProperty" static let userInfoPath = "userInfo" static let uniquenessConstraintsPath = "uniquenessConstraints" } extension CoreData.Entity { init(with object: Kanna.XMLElement) throws { guard let name = object[XML.Attributes.name] else { throw CoreData.ParserError.invalidFormat(reason: "Missing required entity name.") } // The module and the class name are stored in the same field, separated by a '.'. If the user chooses // "current product module", the field is prefixed with a '.'. We actually do not want the module part of the type, // so we need to remove it. let classComponents = (object[XML.Attributes.representedClassName] ?? "").components(separatedBy: ".") let className: String if classComponents.count > 1 { className = classComponents.dropFirst().joined(separator: ".") } else { className = classComponents.joined(separator: ".") } let isAbstract = object[XML.Attributes.isAbstract].flatMap(Bool.init(from:)) ?? false let superEntity = object[XML.Attributes.superEntity] let shouldGenerateCode = object[XML.Attributes.codeGenerationType].map { value in value != XML.Values.categoryCodeGeneration && value != XML.Values.classCodeGeneration } ?? true let attributes = try object.xpath(XML.attributesPath).map(CoreData.Attribute.init(with:)) let relationships = try object.xpath(XML.relationshipsPath).map(CoreData.Relationship.init(with:)) let fetchedProperties = try object.xpath(XML.fetchedPropertiesPath).map(CoreData.FetchedProperty.init(with:)) let userInfo = try object.at_xpath(XML.userInfoPath).map { try CoreData.UserInfo.parse(from: $0) } ?? [:] let uniquenessConstraints = try object.at_xpath(XML.uniquenessConstraintsPath).map { element in try CoreData.UniquenessConstraints.parse(from: element) } ?? [] self.init( name: name, className: className, isAbstract: isAbstract, userInfo: userInfo, superEntity: superEntity, attributes: attributes, relationships: relationships, fetchedProperties: fetchedProperties, uniquenessConstraints: uniquenessConstraints, shouldGenerateCode: shouldGenerateCode ) } }
mit
3b974cb32b0290819b524f9b99a76fcb
35.844444
119
0.722256
4.481081
false
false
false
false
AutomationStation/BouncerBuddy
BouncerBuddy(version1.2)/BouncerBuddy/RegisterViewController.swift
2
9336
// // RegisterViewController.swift // BouncerBuddy // // Created by Sha Wu on 16/3/2. // Copyright © 2016年 Sheryl Hong. All rights reserved. // import UIKit class RegisterViewController: UIViewController { @IBOutlet weak var userEmailtextfield: UITextField! @IBOutlet weak var usernameTextfield: UITextField! @IBOutlet weak var userPasswordTextfield: UITextField! @IBOutlet weak var reenterpassword: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let background = CAGradientLayer().turquoiseColor() background.frame = self.view.bounds self.view.layer.insertSublayer(background, atIndex: 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func Registertapped(sender: AnyObject) { let userEmail = userEmailtextfield.text; let userName = usernameTextfield.text; let userPassword = userPasswordTextfield.text; let repeatPassword = reenterpassword.text; //Check empty fields& check if password match // Check for empty fields if(userEmail!.isEmpty || userPassword!.isEmpty || repeatPassword!.isEmpty) { // Display alert message displayMyAlertMessage("All fields are required"); return; } //Check if passwords match if(userPassword != repeatPassword) { // Display an alert message displayMyAlertMessage("Passwords do not match"); return; } //store data to mysql let post:NSString = "user_email=\(userEmail!)&user_name=\(userName!)&user_password=\(userPassword!)&c_password=\(repeatPassword)" NSLog("PostData: %@",post); let url:NSURL = NSURL(string: "https://cgi.soic.indiana.edu/~hong43/connect.php")! let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)! let postLength:NSString = String( postData.length ) let request:NSMutableURLRequest = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.HTTPBody = postData request.setValue(postLength as String, forHTTPHeaderField: "Content-Length") request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") var reponseError: NSError? var response: NSURLResponse? var urlData: NSData? do { urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response) } catch let error as NSError { reponseError = error urlData = nil } if ( urlData != nil ) { let res = response as! NSHTTPURLResponse!; NSLog("Response code: %ld", res.statusCode); if (res.statusCode >= 200 && res.statusCode < 300) { let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)! NSLog("Response ==> %@", responseData); var error: NSError? let jsonData:NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers )) as! NSDictionary let success:NSInteger = jsonData.valueForKey("success") as! NSInteger //[jsonData[@"success"] integerValue]; NSLog("Success: %ld", success); if(success == 1) { NSLog("Sign Up SUCCESS"); self.dismissViewControllerAnimated(true, completion: nil) } else { var error_msg:NSString if jsonData["error_message"] as? NSString != nil { error_msg = jsonData["error_message"] as! NSString } else { error_msg = "Unknown Error" } let alertView:UIAlertView = UIAlertView() alertView.title = "Sign Up Failed!" alertView.message = error_msg as String alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } } else { let alertView:UIAlertView = UIAlertView() alertView.title = "Sign Up Failed!" alertView.message = "Connection Failed" alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } } else { let alertView:UIAlertView = UIAlertView() alertView.title = "Sign in Failed!" alertView.message = "Connection Failure" if let error = reponseError { alertView.message = (error.localizedDescription) } alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } /** let myUrl = NSURL(string: "https://cgi.soic.indiana.edu/~hong43/userRegister.php"); let request = NSMutableURLRequest(URL:myUrl!); request.HTTPMethod = "POST"; let postString = "email=\(userEmail!)&name=\(userName!)&password=\(userPassword!)"; request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding); NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in dispatch_async(dispatch_get_main_queue()) { //spinningActivity.hide(true) if error != nil { self.displayMyAlertMessage(error!.localizedDescription) return } do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary if let parseJSON = json { let resultValue = parseJSON["status"] as? String var isUserRegistered:Bool = false; if( resultValue == "Success"){ isUserRegistered = true; } var messageToDisplay:String = parseJSON["message"] as! String!; if(!isUserRegistered) { messageToDisplay = parseJSON["message"] as! String!; } let myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default){(action) in self.dismissViewControllerAnimated(true, completion: nil) } myAlert.addAction(okAction); self.presentViewController(myAlert, animated: true, completion: nil); } } catch{ print(error) } } }).resume() */ } // alert function func displayMyAlertMessage(userMessage:String) { let myAlert = UIAlertController(title:"Alert", message:userMessage, preferredStyle: UIAlertControllerStyle.Alert); let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.Default, handler:nil); myAlert.addAction(okAction); self.presentViewController(myAlert, animated:true, completion:nil); } //back to sign in @IBAction func backtosignin(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } /* // 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. } */ }
apache-2.0
26d8efae47e425222eb600bf53a72e46
35.889328
165
0.519769
6.267965
false
false
false
false
iNoles/NolesFootball
NolesFootball.iOS/Noles Football/ScheduleViewController.swift
1
3322
// // ScheduleTableViewController.swift // Noles Football // // Created by Jonathan Steele on 8/3/14. // Copyright (c) 2014 Jonathan Steele. All rights reserved. // import UIKit class ScheduleViewController: UITableViewController { private var list = [[Events](), [Events]()] @IBOutlet weak var segmentedControl: UISegmentedControl! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() /*let format = DateUtils(format: "yyyy-MM-dd'T'HH:mm:ssZ") let dateFormatter = DateUtils(format: "MMM dd 'at' hh:mma") parseData(withURL: "http://www.seminoles.com/XML/services/v2/schedules.v2.dbml?DB_OEM_ID=32900&spid=157113", query: "//schedule_score", callback: { [unowned self] childNode in var events = Events() childNode.forEach { nodes in if nodes.tagName == "opponent_name" { events.opponentName = nodes.firstChild?.content } if nodes.tagName == "opponent_score" { events.opponentScore = nodes.firstChild?.content } if nodes.tagName == "home_score" { events.homeScore = nodes.firstChild?.content } if nodes.tagName == "game_date_time_gmt" { let date = format.dateFromString(string: nodes.firstChild?.content) events.date = dateFormatter.stringFromDate(date: date!) } } if events.homeScore != nil { self.list[0].append(events) } else { self.list[1].append(events) } }, deferCallback: tableView.reloadData)*/ // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func indexChanged(sender _: UISegmentedControl) { tableView.reloadData() } // MARK: - Table view data source override func numberOfSections(in _: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { // Return the number of rows in the section. return list[segmentedControl.selectedSegmentIndex].count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SchedulesCell", for: indexPath) as! ScheduleTableCell // Configure the cell... cell.events = list[segmentedControl.selectedSegmentIndex][indexPath.row] as Events return cell } /* // 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
a6d35d1e9fab30e90d1a4f3150195760
35.108696
183
0.624022
4.914201
false
false
false
false
modocache/swift
test/stdlib/TestUUID.swift
4
6180
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation #if FOUNDATION_XCTEST import XCTest class TestUUIDSuper : XCTestCase { } #else import StdlibUnittest class TestUUIDSuper { } #endif class TestUUID : TestUUIDSuper { func test_NS_Equality() { let uuidA = NSUUID(uuidString: "E621E1F8-C36C-495A-93FC-0C247A3E6E5F") let uuidB = NSUUID(uuidString: "e621e1f8-c36c-495a-93fc-0c247a3e6e5f") let uuidC = NSUUID(uuidBytes: [0xe6,0x21,0xe1,0xf8,0xc3,0x6c,0x49,0x5a,0x93,0xfc,0x0c,0x24,0x7a,0x3e,0x6e,0x5f]) let uuidD = NSUUID() expectEqual(uuidA, uuidB, "String case must not matter.") expectEqual(uuidA, uuidC, "A UUID initialized with a string must be equal to the same UUID initialized with its UnsafePointer<UInt8> equivalent representation.") expectNotEqual(uuidC, uuidD, "Two different UUIDs must not be equal.") } func test_Equality() { let uuidA = UUID(uuidString: "E621E1F8-C36C-495A-93FC-0C247A3E6E5F") let uuidB = UUID(uuidString: "e621e1f8-c36c-495a-93fc-0c247a3e6e5f") let uuidC = UUID(uuid: uuid_t(0xe6,0x21,0xe1,0xf8,0xc3,0x6c,0x49,0x5a,0x93,0xfc,0x0c,0x24,0x7a,0x3e,0x6e,0x5f)) let uuidD = UUID() expectEqual(uuidA, uuidB, "String case must not matter.") expectEqual(uuidA, uuidC, "A UUID initialized with a string must be equal to the same UUID initialized with its UnsafePointer<UInt8> equivalent representation.") expectNotEqual(uuidC, uuidD, "Two different UUIDs must not be equal.") } func test_NS_InvalidUUID() { let uuid = NSUUID(uuidString: "Invalid UUID") expectNil(uuid, "The convenience initializer `init?(uuidString string:)` must return nil for an invalid UUID string.") } func test_InvalidUUID() { let uuid = UUID(uuidString: "Invalid UUID") expectNil(uuid, "The convenience initializer `init?(uuidString string:)` must return nil for an invalid UUID string.") } func test_NS_uuidString() { let uuid = NSUUID(uuidBytes: [0xe6,0x21,0xe1,0xf8,0xc3,0x6c,0x49,0x5a,0x93,0xfc,0x0c,0x24,0x7a,0x3e,0x6e,0x5f]) expectEqual(uuid.uuidString, "E621E1F8-C36C-495A-93FC-0C247A3E6E5F") } func test_uuidString() { let uuid = UUID(uuid: uuid_t(0xe6,0x21,0xe1,0xf8,0xc3,0x6c,0x49,0x5a,0x93,0xfc,0x0c,0x24,0x7a,0x3e,0x6e,0x5f)) expectEqual(uuid.uuidString, "E621E1F8-C36C-495A-93FC-0C247A3E6E5F") } func test_description() { let uuid = UUID() expectEqual(uuid.description, uuid.uuidString, "The description must be the same as the uuidString.") } func test_roundTrips() { let ref = NSUUID() let valFromRef = ref as UUID var bytes: [UInt8] = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] let valFromBytes = bytes.withUnsafeMutableBufferPointer { buffer -> UUID in ref.getBytes(buffer.baseAddress) return UUID(uuid: UnsafeRawPointer(buffer.baseAddress!).load(as: uuid_t.self)) } let valFromStr = UUID(uuidString: ref.uuidString) expectEqual(ref.uuidString, valFromRef.uuidString) expectEqual(ref.uuidString, valFromBytes.uuidString) expectNotNil(valFromStr) expectEqual(ref.uuidString, valFromStr!.uuidString) } func test_hash() { let ref = NSUUID() let val = UUID(uuidString: ref.uuidString)! expectEqual(ref.hashValue, val.hashValue, "Hashes of references and values should be identical") } func test_AnyHashableContainingUUID() { let values: [UUID] = [ UUID(uuidString: "e621e1f8-c36c-495a-93fc-0c247a3e6e5f")!, UUID(uuidString: "f81d4fae-7dec-11d0-a765-00a0c91e6bf6")!, UUID(uuidString: "f81d4fae-7dec-11d0-a765-00a0c91e6bf6")!, ] let anyHashables = values.map(AnyHashable.init) expectEqual(UUID.self, type(of: anyHashables[0].base)) expectEqual(UUID.self, type(of: anyHashables[1].base)) expectEqual(UUID.self, type(of: anyHashables[2].base)) expectNotEqual(anyHashables[0], anyHashables[1]) expectEqual(anyHashables[1], anyHashables[2]) } func test_AnyHashableCreatedFromNSUUID() { let values: [NSUUID] = [ NSUUID(uuidString: "e621e1f8-c36c-495a-93fc-0c247a3e6e5f")!, NSUUID(uuidString: "f81d4fae-7dec-11d0-a765-00a0c91e6bf6")!, NSUUID(uuidString: "f81d4fae-7dec-11d0-a765-00a0c91e6bf6")!, ] let anyHashables = values.map(AnyHashable.init) expectEqual(UUID.self, type(of: anyHashables[0].base)) expectEqual(UUID.self, type(of: anyHashables[1].base)) expectEqual(UUID.self, type(of: anyHashables[2].base)) expectNotEqual(anyHashables[0], anyHashables[1]) expectEqual(anyHashables[1], anyHashables[2]) } } #if !FOUNDATION_XCTEST var UUIDTests = TestSuite("TestUUID") UUIDTests.test("test_NS_Equality") { TestUUID().test_NS_Equality() } UUIDTests.test("test_Equality") { TestUUID().test_Equality() } UUIDTests.test("test_NS_InvalidUUID") { TestUUID().test_NS_InvalidUUID() } UUIDTests.test("test_InvalidUUID") { TestUUID().test_InvalidUUID() } UUIDTests.test("test_NS_uuidString") { TestUUID().test_NS_uuidString() } UUIDTests.test("test_uuidString") { TestUUID().test_uuidString() } UUIDTests.test("test_description") { TestUUID().test_description() } UUIDTests.test("test_roundTrips") { TestUUID().test_roundTrips() } UUIDTests.test("test_hash") { TestUUID().test_hash() } UUIDTests.test("test_AnyHashableContainingUUID") { TestUUID().test_AnyHashableContainingUUID() } UUIDTests.test("test_AnyHashableCreatedFromNSUUID") { TestUUID().test_AnyHashableCreatedFromNSUUID() } runAllTests() #endif
apache-2.0
6540ae75af4a627d1934578caeabe551
44.109489
169
0.672977
3.244094
false
true
false
false
rafalwojcik/WRUserSettings
WRUserSettingsExample/WRUserSettingsExample/ViewController.swift
1
2262
// // Copyright (c) 2019 Chilli Coder - Rafał Wójcik // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import WRUserSettings class ViewController: UIViewController { @IBOutlet weak var tutorialSwitch: UISwitch! @IBOutlet weak var temperatureTextField: UITextField! @IBOutlet weak var notificationSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() populateData() } func populateData() { tutorialSwitch.isOn = MyUserSettings.shared.shouldShowTutorial temperatureTextField.text = MyUserSettings.shared.temperatureUnit notificationSwitch.isOn = MyUserSettings.shared.notificationOn } @IBAction func temperatureChanged(_ sender: UITextField) { MyUserSettings.shared.temperatureUnit = sender.text ?? "" } @IBAction func switchChanged(_ sender: UISwitch) { switch sender { case tutorialSwitch: MyUserSettings.shared.shouldShowTutorial = sender.isOn case notificationSwitch: MyUserSettings.shared.notificationOn = sender.isOn default: break } } @IBAction func resetTapped(_ sender: Any) { MyUserSettings.shared.reset() populateData() } }
mit
6de06a5f400b921ba694c7ffbe98c43e
38.649123
87
0.728319
4.860215
false
false
false
false
mattiasjahnke/arduino-projects
matrix-painter/iOS/PixelDrawer/Carthage/Checkouts/flow/Flow/Signal+Listeners.swift
1
6072
// // Signal+Listeners.swift // Flow // // Created by Måns Bernhardt on 2015-09-17. // Copyright © 2015 iZettle. All rights reserved. // import Foundation public extension SignalProvider { /// Start listening on values via the provided `callback`. /// - Returns: A disposable that will stop listening on values when being disposed. func onValue(on scheduler: Scheduler = .current, _ callback: @escaping (Value) -> Void) -> Disposable { return providedSignal.onEventType(on: scheduler) { eventType in guard case .event(.value(let val)) = eventType else { return } callback(val) } } /// Start listening on values via the provided `callback` and dispose the disposable previously returned from the `callback` when a new value is signaled. /// - Returns: A disposable that will stop listening on values when being disposed. func onValueDisposePrevious(on scheduler: Scheduler = .current, _ callback: @escaping (Value) -> Disposable?) -> Disposable { let bag = DisposeBag() let subBag = bag.innerBag() bag += onValue(on: scheduler) { value in subBag.dispose() subBag += callback(value) } return bag } } public extension SignalProvider where Kind == Finite { /// Start listening on events via the provided `callback`. /// - Returns: A disposable that will stop listening on values when being disposed. func onEvent(on scheduler: Scheduler = .current, _ callback: @escaping (Event<Value>) -> Void) -> Disposable { return providedSignal.onEventType(on: scheduler) { eventType in guard case .event(let event) = eventType else { return } callback(event) } } /// Wait for an end event and call `callback`. /// - Returns: A disposable that will stop listening on values when being disposed. func onEnd(on scheduler: Scheduler = .current, _ callback: @escaping () -> Void) -> Disposable { return onEvent(on: scheduler) { $0.isEnd ? callback() : () } } /// Wait for an error event and call `callback` with that error. /// - Returns: A disposable that will stop listening on values when being disposed. func onError(on scheduler: Scheduler = .current, _ callback: @escaping (Error) -> Void) -> Disposable { return onEvent(on: scheduler) { $0.error.map(callback) } } } public extension SignalProvider { /// Wait for the first value and call `callback` with that value. /// - Returns: A disposable that will stop listening on values when being disposed. /// - Note: equivalent to `take(first: 1).onValue(callback)` func onFirstValue(on scheduler: Scheduler = .current, _ callback: @escaping (Value) -> Void) -> Disposable { return take(first: 1).onValue(on: scheduler, callback) } } public extension SignalProvider { /// Start listening on values via the provided `setValue`. /// - Returns: A disposable that will stop listening on values when being disposed. /// - Note: equivalent to `onValue(setValue)` func bindTo(on scheduler: Scheduler = .current, _ setValue: @escaping (Value) -> ()) -> Disposable { return onValue(on: scheduler, setValue) } /// Start listening on values and update `signal`'s value with the latest signaled value. /// - Returns: A disposable that will stop listening on values when being disposed. func bindTo<WriteSignal: SignalProvider>(_ signal: WriteSignal) -> Disposable where WriteSignal.Value == Value, WriteSignal.Kind == ReadWrite { return onValue { signal.providedSignal.value = $0 } } /// Start listening on values and update the value at the `keyPath` of `value`. /// /// bindTo(button, \.isEnabled) /// /// - Returns: A disposable that will stop listening on values when being disposed. func bindTo<T>(on scheduler: Scheduler = .current, _ value: T, _ keyPath: ReferenceWritableKeyPath<T, Value>) -> Disposable { return onValue(on: scheduler) { value[keyPath: keyPath] = $0 } } } public extension SignalProvider where Kind == ReadWrite { /// Start listening on values for both `self` and `signal` and update each other's value with the latest signaled value. /// - Parameter isSame: Are two values the same. Used to avoid infinite recursion. /// - Returns: A disposable that will stop listening on values when being disposed. func bidirectionallyBindTo<WriteSignal: SignalProvider>(_ signal: WriteSignal, isSame: @escaping (Value, Value) -> Bool) -> Disposable where WriteSignal.Value == Value, WriteSignal.Kind == ReadWrite { let bag = DisposeBag() // Use `distinct()` to avoid infinite recursion /// Make `self` and `signal` plain to allow `distinct()` to not filter out intitial values, such as `atOnce()`. bag += Signal(self).distinct(isSame).bindTo(signal) bag += Signal(signal).distinct(isSame).bindTo(self) return bag } } public extension SignalProvider where Kind == ReadWrite, Value: Equatable { /// Start listening on values for both `self` and `signal` and update each other's value with the latest signaled value. /// - Returns: A disposable that will stop listening on values when being disposed. /// - Note: Infinite recursion is avoided by comparing equality with the previous value. func bidirectionallyBindTo<P: SignalProvider>(_ property: P) -> Disposable where P.Value == Value, P.Kind == ReadWrite { return bidirectionallyBindTo(property, isSame: ==) } } public extension SignalProvider where Value == () { /// Start listening on values and toggle `signal`'s value for every recieved event. /// - Returns: A disposable that will stop listening on values when being disposed. func toggle<P: SignalProvider>(_ signal: P) -> Disposable where P.Value == Bool, P.Kind == ReadWrite { let signal = signal.providedSignal return onValue { signal.value = !signal.value } } }
mit
37ec821c20d5e41c5d0730ac52078647
47.56
204
0.668863
4.437135
false
false
false
false
Dougly/2For1
2for1/ScoreView.swift
1
1060
// // ScoreView.swift // 2for1 // // Created by Douglas Galante on 1/28/17. // Copyright © 2017 Flatiron. All rights reserved. // import UIKit class ScoreView: UIView { @IBOutlet var contentView: UIView! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var drinksLabel: UILabel! @IBOutlet weak var drinksTextLabel: UILabel! override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { Bundle.main.loadNibNamed("ScoreView", owner: self, options: nil) self.addSubview(contentView) self.constrain(contentView) } func updateLabels(score: Int, drinks: Int) { if drinks == 1 { drinksTextLabel.text = "drink" } else { drinksTextLabel.text = "drinks" } scoreLabel.text = "\(score)" drinksLabel.text = "\(drinks)" } }
mit
401f26974d215b38570045bc3c2368f8
20.612245
72
0.577904
4.322449
false
false
false
false
honghaoz/ZHSwiftLogger
Source/Color.swift
2
6249
// // Color.swift // Loggerithm // // Created by Honghao Zhang on 2015-08-13. // Copyright (c) 2015 Honghao Zhang (张宏昊) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #if os(iOS) || os(watchOS) || os(tvOS) import UIKit public typealias Color = UIColor #elseif os(OSX) import Cocoa public typealias Color = NSColor #endif /** * Color logging support for Loggerithm logger. */ struct LoggerColor { static fileprivate let ESCAPE = "\u{001b}[" static fileprivate let RESET_FG = ESCAPE + "fg;" // Clear any foreground color static fileprivate let RESET_BG = ESCAPE + "bg;" // Clear any background color static fileprivate let RESET = ESCAPE + ";" // Clear any foreground or background color /// RGB Color components. typealias ColorTuple = (r: Int, g: Int, b: Int) /// Color for verbose log strings. static var verboseColor: Color? { didSet { if let verboseColor = verboseColor { verboseColorTuple = colorTupleForColor(verboseColor) } else { verboseColorTuple = defaultVerboseColorTuple } } } /// Color for debug log strings. static var debugColor: Color? { didSet { if let debugColor = debugColor { debugColorTuple = colorTupleForColor(debugColor) } else { debugColorTuple = defaultDebugColorTuple } } } /// Color for info log strings. static var infoColor: Color? { didSet { if let infoColor = infoColor { infoColorTuple = colorTupleForColor(infoColor) } else { infoColorTuple = defaultInfoColorTuple } } } /// Color for warning log strings. static var warningColor: Color? { didSet { if let warningColor = warningColor { warningColorTuple = colorTupleForColor(warningColor) } else { warningColorTuple = defaultWarningColorTuple } } } /// Color for error log strings. static var errorColor: Color? { didSet { if let errorColor = errorColor { errorColorTuple = colorTupleForColor(errorColor) } else { errorColorTuple = defaultErrorColorTuple } } } /// Default color rgb components for verbose string. static fileprivate var defaultVerboseColorTuple = ColorTuple(r: 190, g: 190, b: 190) /// Default color rgb components for debug string. static fileprivate var defaultDebugColorTuple = ColorTuple(r: 60, g: 161, b: 202) /// Default color rgb components for info string. static fileprivate var defaultInfoColorTuple = ColorTuple(r: 253, g: 190, b: 10) /// Default color rgb components for warning string. static fileprivate var defaultWarningColorTuple = ColorTuple(r: 251, g: 127, b: 8) /// Default color rgb components for error string. static fileprivate var defaultErrorColorTuple = ColorTuple(r: 247, g: 13, b: 23) /// Color rgb components for verbose string. static fileprivate var verboseColorTuple = defaultVerboseColorTuple /// Color rgb components for debug string. static fileprivate var debugColorTuple = defaultDebugColorTuple /// Color rgb components for info string. static fileprivate var infoColorTuple = defaultInfoColorTuple /// Color rgb components for warning string. static fileprivate var warningColorTuple = defaultWarningColorTuple /// Color rgb components for error string. static fileprivate var errorColorTuple = defaultErrorColorTuple /** Add color setting code for a string. - parameter logString: A string - parameter level: A log level - returns: A string with color setting code inserted. */ static func applyColorForLogString(_ logString: String, withLevel level: LogLevel) -> String { let (red, green, blue) = rgbForLogLevel(level) return "\(ESCAPE)fg\(red),\(green),\(blue);\(logString)\(RESET)" } /** Get corresponding color tuple for log level. - parameter level: A log level - returns: ColorTuple instance. */ static fileprivate func rgbForLogLevel(_ level: LogLevel) -> ColorTuple { switch level { case .verbose: return verboseColorTuple case .debug: return debugColorTuple case .info: return infoColorTuple case .warning: return warningColorTuple case .error: return errorColorTuple default: return verboseColorTuple } } /** Get corresponding color tuple for an UIColor/NSColor. - parameter color: UIColor for iOS, NSColor for OSX - returns: ColorTuple instance. */ static fileprivate func colorTupleForColor(_ color: Color) -> ColorTuple { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 color.getRed(&red, green: &green, blue: &blue, alpha: nil) return ColorTuple(r: Int(red * 255), g: Int(green * 255), b: Int(blue * 255)) } }
mit
e9c5b0a5bf49cf5e52ffdcb85bb0cf10
35.940828
98
0.649367
4.655481
false
false
false
false
wangCanHui/weiboSwift
weiboSwift/Classes/Lib/PhotoBrowser/Animation/CZPhotoBrowserModalAnimation.swift
1
1953
// // CZPhotoBrowserModalAnimation.swift // weiboSwift // // Created by 王灿辉 on 15/11/11. // Copyright © 2015年 王灿辉. All rights reserved. // import UIKit class CZPhotoBrowserModalAnimation: NSObject , UIViewControllerAnimatedTransitioning { // 返回动画的时间 func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } // 自定义动画 func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // 获取modal出来的控制器的view let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! toView.alpha = 0 // 添加到容器视图 transitionContext.containerView()?.addSubview(toView) // 获取Modal出来的控制器 let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! CZPhotoBrowserViewController // 获取过渡的视图 let tempImageView = toVC.modalTempImageView() // TODO: 测试,添加到window上面 // UIApplication.sharedApplication().keyWindow?.addSubview(tempImageView) transitionContext.containerView()?.addSubview(tempImageView) // 隐藏collectionView toVC.collectionView.hidden = true // 动画 UIView.animateWithDuration(transitionDuration(nil), animations: { () -> Void in // 设置透明 toView.alpha = 1.0 // 设置过渡视图最终动画放大完成的frame tempImageView.frame = toVC.modalTargetFrame() }) { (_) -> Void in // 移除过渡视图 tempImageView.removeFromSuperview() // 显示collectioView toVC.collectionView.hidden = false // 转场完成 transitionContext.completeTransition(true) } } }
apache-2.0
639d533703d658700940fc657df62ff2
34.36
130
0.640271
5.559748
false
false
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/NotificationsV2/NotificationsPermissionView.swift
1
4224
/** * Copyright © 2019 Aga Khan Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ import Foundation import UIKit protocol NotificationPermissionCellDelegate: AnyObject { func turnOnNotifictions() func close() } struct NotificationPermissionCellContext: CellContext { let identifier: String = NotificationPermissionCell.identifier let title: String let description: String let disclosureText: String } class NotificationPermissionCell: ConfigurableTableViewCell { static var identifier: String = "NotificationPermissionCell" private let cardView = CardViewV2() private let disclosureView = CellDisclosureView() weak var delegate: NotificationPermissionCellDelegate? let headerLabel = UILabel(typography: .title) let descriptionLabel = UILabel(typography: .smallRegular, color: Style.Colors.FoundationGrey.withAlphaComponent(0.5)) let closeButton: UIImageView = { let imageView = UIImageView() imageView.image = Assets.close.image imageView.contentMode = .scaleAspectFit return imageView }() override func commonInit() { super.commonInit() backgroundColor = .clear disclosureView.delegate = self contentView.addSubview(cardView) { $0.leading.trailing.equalToSuperview().inset(Style.Padding.p24) $0.top.bottom.equalToSuperview().inset(Style.Padding.p12) } cardView.addSubview(headerLabel) { $0.leading.trailing.equalToSuperview().inset(Style.Padding.p16) $0.top.equalToSuperview().offset(Style.Padding.p20) } cardView.addSubview(descriptionLabel) { $0.leading.trailing.equalToSuperview().inset(Style.Padding.p16) $0.top.equalTo(headerLabel.snp.bottom).offset(Style.Padding.p8) } cardView.addSubview(disclosureView) { $0.top.equalTo(descriptionLabel.snp.bottom).offset(Style.Padding.p20) $0.leading.trailing.bottom.equalToSuperview() } cardView.addSubview(closeButton) { $0.trailing.equalToSuperview().inset(Style.Padding.p16) $0.top.equalToSuperview().offset(Style.Padding.p16) $0.height.width.equalTo(Style.Size.s12) } closeButton.isUserInteractionEnabled = true closeButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(closeButtonTapped))) } func configure(context: CellContext) { guard let context = context as? NotificationPermissionCellContext else { return } headerLabel.text = context.title descriptionLabel.text = context.description disclosureView.configure(context: CellDisclosureContext(label: context.disclosureText)) } @objc func closeButtonTapped() { delegate?.close() } } extension NotificationPermissionCell: CellDisclosureViewDelegate { func cellDisclosureTapped() { delegate?.turnOnNotifictions() } }
bsd-3-clause
d4e956a1cd13ab16a6dfd87d852aa096
35.094017
119
0.745915
4.630482
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/WelcomePanelLabelContentViewController.swift
3
1269
import UIKit class WelcomePanelLabelContentViewController: UIViewController { @IBOutlet private weak var label: UILabel! private let text: String private var theme = Theme.standard init(text: String) { self.text = text super.init(nibName: "WelcomePanelLabelContentViewController", bundle: Bundle.main) } override func viewDidLoad() { super.viewDidLoad() label.text = text updateFonts() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateFonts() } private func updateFonts() { label.font = UIFont.wmf_font(.subheadline, compatibleWithTraitCollection: traitCollection) } } extension WelcomePanelLabelContentViewController: Themeable { func apply(theme: Theme) { guard viewIfLoaded != nil else { self.theme = theme return } view.backgroundColor = theme.colors.midBackground label.textColor = theme.colors.primaryText label.backgroundColor = theme.colors.midBackground } }
mit
64e8da25b5c094b567d736792d0dd4ce
28.511628
98
0.680063
5.35443
false
false
false
false
mpclarkson/StravaSwift
Sources/StravaSwift/AthleteStats.swift
1
2169
// // AthleteStats.swift // StravaSwift // // Created by Andy on 01/22/2017 // Copyright © 2017 Andy Gonzalez. All rights reserved. // import Foundation import SwiftyJSON /** Stats are aggregated data for an athlete **/ public final class AthleteStats: Strava { public final class Totals { public let count: Int? public let distance: Double? public let movingTime: TimeInterval? public let elapsedTime: TimeInterval? public let elevationGain: Double? public let achievementCount: Int? required public init(_ json: JSON) { count = json["count"].int distance = json["distance"].double movingTime = json["moving_time"].double elapsedTime = json["elapsed_time"].double elevationGain = json["elevation_gain"].double achievementCount = json["achievement_count"].int } } public let biggestRideDistance: Double? public let biggestClimbElevationGain: Double? public let recentRideTotals: Totals? public let recentRunTotals: Totals? public let recentSwimTotals: Totals? public let ytdRideTotals: Totals? public let ytdRunTotals: Totals? public let ytdSwimTotals: Totals? public let allRideTotals: Totals? public let allRunTotals: Totals? public let allSwimTotals: Totals? /** Initializer - Parameter json: SwiftyJSON object - Internal **/ required public init(_ json: JSON) { biggestRideDistance = json["biggest_ride_distance"].double biggestClimbElevationGain = json["biggest_climb_elevation_gain"].double recentRideTotals = Totals(json["recent_ride_totals"]) recentRunTotals = Totals(json["recent_run_totals"]) recentSwimTotals = Totals(json["recent_swim_totals"]) ytdRideTotals = Totals(json["ytd_ride_totals"]) ytdRunTotals = Totals(json["ytd_run_totals"]) ytdSwimTotals = Totals(json["ytd_swim_totals"]) allRideTotals = Totals(json["all_ride_totals"]) allRunTotals = Totals(json["all_run_totals"]) allSwimTotals = Totals(json["all_swim_totals"]) } }
mit
740bb50882d4aaa0111237ce5a712776
30.882353
79
0.659594
4.02974
false
false
false
false