repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
yosan/AwsChat
AwsChat/ChatMessagesService.swift
1
3829
// // ChatMessagesService.swift // AwsChat // // Created by Takahashi Yosuke on 2016/08/14. // Copyright © 2016年 Yosan. All rights reserved. // import Foundation import AWSDynamoDB /// Service of chat messages class ChatMessagesService { /// Object Mapper fileprivate lazy var dynamoDBObjectMapper = AWSDynamoDBObjectMapper.default() /** Send message - parameter text: message text - parameter user: user who wants to send the message - parameter room: room to post message - parameter completion: callback */ func sendMessage(text: String, user: AWSChatUser, room: AWSChatRoom, completion: ((Error?) -> Void)?) { let dynamoMessage = AWSChatMessage() let date = Date() let messageId = Int(date.timeIntervalSince1970 * 1000) dynamoMessage?.MessageId = "\(messageId)" as NSString dynamoMessage?.RoomId = room.RoomId dynamoMessage?.UserId = user.UserId dynamoMessage?.Text = text as NSString dynamoMessage?.Time = NSNumber(value: date.timeIntervalSince1970) dynamoDBObjectMapper.save(dynamoMessage!) .continue(with: AWSExecutor.mainThread(), with: {(task) -> AnyObject? in if let error = task.error { print(error) completion?(error) } if let exception = task.exception { print(exception) } if let _ = task.result { print("succeeded!") } completion?(nil) return nil }) } /** Get message - parameter room: room in which message exits - parameter lastMessageId: last message ID which the app already known. If it's nil, latest 10 messages are fetched. - parameter completion: callback */ func getMessages(room: AWSChatRoom, lastMessageId: String?, completion: (([AWSChatMessage]?, Error?) -> Void)?) { let query = AWSDynamoDBQueryExpression() query.keyConditionExpression = "RoomId = :roomId and MessageId > :messageId" let lastMessageId: String = lastMessageId ?? "0" query.expressionAttributeValues = [":roomId" : room.RoomId, ":messageId" : lastMessageId] query.limit = 10 query.scanIndexForward = false dynamoDBObjectMapper.query(AWSChatMessage.self, expression: query) .continue(with: AWSExecutor.mainThread(), with: { task -> AnyObject! in if let error = task.error { completion?(nil, error) return nil } guard let messages = task.result?.items as? [AWSChatMessage] else { fatalError() } // Reverse messages completion?(messages.reversed(), nil) return nil }) } /** Get user data - parameter userIds: user IDs to get data - parameter completion: callback */ func getUsers(_ userIds: [String], completion: (([AWSChatUser]?, Error?) -> Void)?) { let tasks = userIds.map { userId -> AWSTask<AnyObject> in return dynamoDBObjectMapper.load(AWSChatUser.self, hashKey: userId, rangeKey: nil) } AWSTask<NSArray>(forCompletionOfAllTasksWithResults: tasks).continue(with: AWSExecutor.mainThread(), with: { (task) -> Any? in if let error = task.error { completion?(nil, error) return nil } guard let users = task.result as? [AWSChatUser] else { fatalError() } completion?(users, nil) return nil }) } }
mit
27634a4d228ad0a40f60f1efce03d221
35.09434
134
0.567695
4.988266
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/Chart/TimeAxisController.swift
1
8701
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit protocol TimeAxisControllerDelegate: class { /// Tells the delegate the pinned-to-now state changed. /// /// - Parameters: /// - timeAxisController: A time axis controller. /// - isPinnedToNow: The current pinned-to-now state. func timeAxisController(_ timeAxisController: TimeAxisController, didChangePinnedToNow isPinnedToNow: Bool) } /// Controls the display of a TimeAxisView. class TimeAxisController: UIViewController { var timeAxisView: TimeAxisView { // swiftlint:disable force_cast return view as! TimeAxisView // swiftlint:enable force_cast } weak var delegate: TimeAxisControllerDelegate? // The visible axis of the chart views. The time axis view may show a different visible axis if // the time axis view is wider than the chart views. private(set) var visibleXAxis: ChartAxis<Int64> = .zero // The total range of values represented by a chart view's scroll view. var dataXAxis: ChartAxis<Int64> = .zero { didSet { timeAxisView.dataAxis = dataXAxis } } let defaultVisibleRange: Int64 = 20000 // 20 seconds in milliseconds var listener: ((ChartAxis<Int64>, ChartAxis<Int64>, ChartController?) -> Void)? /// The insets relative var chartTimeAxisInsets = UIEdgeInsets.zero let liveTimeInterval = 0.02 // 20 milliseconds /// A timer that updates the view when there is an incoming stream of data. var liveTimer: Timer? var isLive: Bool var isPinnedToNow: Bool { didSet { guard isPinnedToNow != oldValue else { return } delegate?.timeAxisController(self, didChangePinnedToNow: isPinnedToNow) } } /// The amount of time in milliseconds before the current time the view can be scrolled to enable /// pinning the scroll to the current time. let pinnedToNowThreshold: Int64 = 100 /// The percent of the chart's visible time added after the now timestamp. let nowPaddingPercent = 0.05 // 5% /// True if the time axis is moving because of a user interaction, otherwise false. var isUserScrolling = false { didSet { guard oldValue != isUserScrolling else { return } if isUserScrolling { // Started dragging. Disabled pinned to now in case the user drags away from the // current point. isPinnedToNow = false } else { // Stopped dragging. If movement ended at the max data value or within a threshold, enable // pinned to now. if visibleXAxis.max >= (dataXAxis.max - pinnedToNowThreshold) { isPinnedToNow = true } } } } /// The starting time of a recording. When in observe mode the time axis will display a red dot /// and line to mark the time range that is being recorded. Setting this on a review style axis /// has no effect. var recordingStartTime: Int64? { get { return timeAxisView.recordingStartTime } set { timeAxisView.recordingStartTime = newValue } } private let style: TimeAxisView.Style init(style: TimeAxisView.Style, xAxis: ChartAxis<Int64>? = nil) { self.style = style isLive = style == .observe isPinnedToNow = style == .observe super.init(nibName: nil, bundle: nil) if let xAxis = xAxis { visibleXAxis = xAxis dataXAxis = xAxis } else { // If no axis was set use the default range. resetAxisToDefault() } updateForVisibleAxis() } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not supported") } // MARK: - UIViewController override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) startLiveTimer() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) stopLiveTimer() } override func loadView() { view = TimeAxisView(style: style, visibleAxis: visibleXAxis, dataAxis: dataXAxis) } // MARK: - Public // Reset visible and data axes from the current time through the default visible range. func resetAxisToDefault() { let nowTimestamp = Date().millisecondsSince1970 visibleXAxis = ChartAxis(min: nowTimestamp - defaultVisibleRange, max: nowTimestamp) dataXAxis = visibleXAxis } /// Adds a note dote at a timestamp. func addNoteDotAtTimestamp(_ timestamp: Int64) { guard style == .observe else { return } timeAxisView.noteTimestamps.append(timestamp) } /// Removes all note dots. func removeAllNoteDots() { guard style == .observe else { return } timeAxisView.noteTimestamps.removeAll() } // MARK: - Private // Starts the live timer which causes the time axis to scroll along with the current time. func startLiveTimer() { let timer = Timer.scheduledTimer(timeInterval: liveTimeInterval, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true) // Allows the timer to fire while scroll views are tracking. RunLoop.main.add(timer, forMode: .common) liveTimer = timer } // Stops the live timer, removing it from the main run loop. func stopLiveTimer() { liveTimer?.invalidate() } @objc func timerFired() { // Only change axes if live and the user is not dragging. guard isLive, !isUserScrolling else { return } let nowTimestamp = Date().millisecondsSince1970 // Expand the data axis if the current time is beyond the bounds, minus a padding threshold. let currentVisibleLength = visibleXAxis.length let horizontalPadding = Int64(Double(currentVisibleLength) * nowPaddingPercent) let maxTimeThreshold = dataXAxis.max - horizontalPadding if nowTimestamp > maxTimeThreshold { let visibleMax = nowTimestamp + horizontalPadding dataXAxis.max = visibleMax timeAxisView.dataAxis.max = visibleMax // Pin visible area to latest timestamp if pinned to now. if isPinnedToNow { visibleXAxis = ChartAxis(min: visibleMax - currentVisibleLength, max: visibleMax) } // When recording, label time is relative to the recording start time, otherwise it's // relative to the current time. if let recordingStartTime = recordingStartTime { timeAxisView.zeroTime = recordingStartTime } else { timeAxisView.zeroTime = nowTimestamp } } updateForVisibleAxis() } func visibleAxisChanged(_ visibleXAxis: ChartAxis<Int64>, by chartController: ChartController? = nil) { guard visibleXAxis.max > visibleXAxis.min else { return } self.visibleXAxis = visibleXAxis updateForVisibleAxis(sourceChartController: chartController) } func updateForVisibleAxis(sourceChartController chartController: ChartController? = nil) { // Update listener. if let listener = listener { listener(visibleXAxis, dataXAxis, chartController) } // Update timeAxisView. The visible and data axis must be adjusted if the size of the chart is // different than the size of the time axis. Typically the charts have left and right margins, // but the time axis can sometimes be full screen width. var timeAxisVisibleAxis = visibleXAxis var timeAxisDataAxis = dataXAxis if chartTimeAxisInsets != .zero { let chartWidth = timeAxisView.bounds.size.width - chartTimeAxisInsets.left - chartTimeAxisInsets.right let xScale = CGFloat(visibleXAxis.length) / chartWidth let leftDiff = Int64(chartTimeAxisInsets.left * xScale) let rightDiff = Int64(chartTimeAxisInsets.right * xScale) timeAxisVisibleAxis = ChartAxis(min: timeAxisVisibleAxis.min - leftDiff, max: timeAxisVisibleAxis.max + rightDiff) timeAxisDataAxis = ChartAxis(min: timeAxisDataAxis.min - leftDiff, max: timeAxisDataAxis.max + rightDiff) } timeAxisView.dataAxis = timeAxisDataAxis timeAxisView.visibleAxis = timeAxisVisibleAxis } }
apache-2.0
2cbe6f908c537c00b8cd4fd62869f85e
33.391304
99
0.685553
4.423488
false
false
false
false
PekanMmd/Pokemon-XD-Code
enums/XGMoves.swift
1
4998
// // XGMoves.swift // XG Tool // // Created by StarsMmd on 01/06/2015. // Copyright (c) 2015 StarsMmd. All rights reserved. // import Foundation let kFirstShadowMoveIndex = game == .XD ? 0x164 : 0x164 let kLastShadowMoveIndex = game == .XD ? 0x176 : 0x164 let shadowMovesUseHMFlag = XGMove(index: kFirstShadowMoveIndex).HMFlag enum XGMoves : CustomStringConvertible { case index(Int) var index : Int { get { switch self { case .index(let i): if i > CommonIndexes.NumberOfMoves.value || i < 0 { return 0 } return i } } } var hex : String { get { return String(format: "0x%x",self.index) } } var startOffset : Int { get { let safeIndex = index < kNumberOfMoves ? index : 0 return CommonIndexes.Moves.startOffset + (safeIndex * kSizeOfMoveData) } } var nameID : Int { get { return Int(XGFiles.common_rel.data!.getWordAtOffset(startOffset + kMoveNameIDOffset)) } } var name : XGString { get { return XGFiles.common_rel.stringTable.stringSafelyWithID(nameID) } } var descriptionID : Int { get { return Int(XGFiles.common_rel.data!.getWordAtOffset(startOffset + kMoveDescriptionIDOffset)) } } var description : String { get { return self.name.string } } var mdescription : XGString { get { return XGFiles.dol.stringTable.stringSafelyWithID(descriptionID) } } var type : XGMoveTypes { get { let index = XGFiles.common_rel.data!.getByteAtOffset(startOffset + kMoveTypeOffset) return XGMoveTypes.index(index) } } var category : XGMoveCategories { get { let index = XGFiles.common_rel.data!.getByteAtOffset(startOffset + kMoveCategoryOffset) return XGMoveCategories(rawValue: index) ?? .none } } var isShadowMove : Bool { get { return shadowMovesUseHMFlag ? self.data.HMFlag : (self.index >= kFirstShadowMoveIndex) && (self.index <= kLastShadowMoveIndex) } } var data : XGMove { get { return XGMove(index: self.index) } } static func allMoves() -> [XGMoves] { var moves = [XGMoves]() for i in 0 ..< kNumberOfMoves { moves.append(.index(i)) } return moves } static func random() -> XGMoves { var rand = 0 let discludedMoves = [0, 355, game == .Colosseum ? 357 : 374] while (XGMoves.index(rand).isShadowMove) || (XGMoves.index(rand).descriptionID == 0) || discludedMoves.contains(rand) { rand = Int.random(in: 1 ..< kNumberOfMoves) } return XGMoves.index(rand) } static func randomShadow() -> XGMoves { var rand = 0 let discludedMoves = [0, 355, game == .Colosseum ? 357 : 374] while (!XGMoves.index(rand).isShadowMove) || (XGMoves.index(rand).descriptionID == 0) || discludedMoves.contains(rand) { rand = Int.random(in: 1 ..< kNumberOfMoves) } return XGMoves.index(rand) } static func randomDamaging() -> XGMoves { var rand = XGMoves.random() while (rand.data.basePower == 0) || (rand.descriptionID == 0) { rand = XGMoves.random() } return rand } static func randomMoveset(count: Int = 4) -> [XGMoves] { var set = [Int]() while set.count < count { if set.count == 0 { set.addUnique(XGMoves.randomDamaging().index) } else { set.addUnique(XGMoves.random().index) } } while set.count < 4 { set.append(0) } return set.map({ (i) -> XGMoves in return .index(i) }) } static func randomShadowMoveset(count: Int = 4) -> [XGMoves] { var set = [Int]() while set.count < count { set.addUnique(XGMoves.randomShadow().index) } while set.count < 4 { set.append(0) } return set.map({ (i) -> XGMoves in return .index(i) }) } } func allMoves() -> [String : XGMoves] { var dic = [String : XGMoves]() for i in 0 ..< kNumberOfMoves { let a = XGMoves.index(i) dic[a.name.string.simplified] = a } return dic } let moves = allMoves() func move(_ name: String) -> XGMoves { if XGSettings.current.verbose && (moves[name.simplified] == nil) { printg("couldn't find: " + name) } return moves[name.simplified] ?? .index(0) } func allMovesArray() -> [XGMoves] { var moves: [XGMoves] = [] for i in 0 ..< kNumberOfMoves { moves.append(XGMoves.index(i)) } return moves } extension XGMoves: Codable { enum CodingKeys: String, CodingKey { case index, name } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let index = try container.decode(Int.self, forKey: .index) self = .index(index) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.index, forKey: .index) try container.encode(self.name.string, forKey: .name) } } extension XGMoves: XGEnumerable { var enumerableName: String { return name.string.spaceToLength(20) } var enumerableValue: String? { return index.string } static var className: String { return "Moves" } static var allValues: [XGMoves] { return XGMoves.allMoves() } }
gpl-2.0
11be4bf3cb169e2ef3f60ba114623c00
18.223077
129
0.655662
3.036452
false
false
false
false
proxyco/RxBluetoothKit
Source/Unimplemented.swift
1
1619
// The MIT License (MIT) // // Copyright (c) 2016 Polidea // // 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 RxSwift func unimplementedFunction(file: String = #file, function: String = #function, line: Int = #line) { fatalError("Unimplemented function \(function) in \(file):\(line)") } extension Observable { static func unimplemented(file: String = #file, function: String = #function, line: Int = #line) -> Observable<Element> { unimplementedFunction(file, function: function, line: line) return Observable<Element>.empty() } }
mit
a3b4c8b84535afa43d95983614d6656b
43.972222
100
0.738728
4.460055
false
false
false
false
rob-brown/Atoms
Atoms/WordCell.swift
1
2116
// ~MMMMMMMM,. .,MMMMMMM .. // DNMMDMMMMMMMM,. ..MMMMNMMMNMMM, // MMM.. ...NMMM MMNMM ,MMM // NMM, , MMND MMMM .MM // MMN MMMMM MMM // .MM , MMMMMM , MMM // .MM MMM. MMMM MMM // .MM~ .MMM. NMMN. MMM // MMM MMMM: .M ..MMM .MM, // MMM.NNMMMMMMMMMMMMMMMMMMMMMMMMMM:MMM, // ,,MMMMMMMMMMMMMMM NMMDNMMMMMMMMN~, // MMMMMMMMM,, OMMM NMM . ,MMNMMMMN. // ,MMMND .,MM= NMM~ MMMMMM+. MMM. NMM. .:MMMMM. // MMMM NMM,MMMD MMM$ZZZMMM: .NMN.MMM NMMM // MMNM MMMMMM MMZO~:ZZZZMM~ MMNMMN .MMM // MMM MMMMM MMNZ~~:ZZZZZNM, MMMM MMN. // MM. .MMM. MMZZOZZZZZZZMM. MMMM MMM. // MMN MMMMN MMMZZZZZZZZZNM. MMMM MMM. // NMMM .MMMNMN .MM$ZZZZZZZMMN ..NMMMMM MMM // MMMMM MMM.MMM~ .MNMZZZZMMMD MMM MMM . . NMMN, // NMMMM: ..MM8 MMM, . MNMMMM: .MMM: NMM ..MMMMM // ...MMMMMMNMM MMM .. MMM. MNDMMMMM. // .: MMMMMMMMMMDMMND MMMMMMMMNMMMMM // NMM8MNNMMMMMMMMMMMMMMMMMMMMMMMMMMNMM // ,MMM NMMMDMMMMM NMM.,. ,MM // MMO ..MMM NMMM MMD // .MM. ,,MMM+.MMMM= ,MMM // .MM. MMMMMM~. MMM // MM= MMMMM.. .MMN // MMM MMM8 MMMN. MM, // +MMO MMMN, MMMMM, MMM // ,MMMMMMM8MMMMM, . MMNMMMMMMMMM. // .NMMMMNMM DMDMMMMMM import UIKit class WordCell: SmartTableViewCell { @IBOutlet weak var wordLabel: UILabel! class func cell(_ tableView: UITableView, word: String) -> Self { let cell = self.cell(tableView) cell.wordLabel.text = word return cell } }
mit
296a794588c587bc0eb584558c7385c5
45
69
0.410681
3.44065
false
false
false
false
younata/RSSClient
TethysAppSpecs/Helpers/Factories.swift
1
6369
@testable import Tethys import TethysKit import AuthenticationServices func splitViewControllerFactory() -> SplitViewController { return SplitViewController() } func findFeedViewControllerFactory( importUseCase: ImportUseCase = FakeImportUseCase(), analytics: Analytics = FakeAnalytics(), notificationCenter: NotificationCenter = NotificationCenter() ) -> FindFeedViewController { return FindFeedViewController( importUseCase: importUseCase, analytics: analytics, notificationCenter: notificationCenter ) } func feedViewControllerFactory( feed: Feed = feedFactory(), feedService: FeedService = FakeFeedService(), tagEditorViewController: @escaping () -> TagEditorViewController = { tagEditorViewControllerFactory() } ) -> FeedViewController { return FeedViewController( feed: feed, feedService: feedService, tagEditorViewController: tagEditorViewController ) } func tagEditorViewControllerFactory( feedService: FeedService = FakeFeedService() ) -> TagEditorViewController { return TagEditorViewController( feedService: feedService ) } func feedListControllerFactory( feedCoordinator: FeedCoordinator = FakeFeedCoordinator(), settingsRepository: SettingsRepository = settingsRepositoryFactory(), messenger: Messenger = FakeMessenger(), mainQueue: FakeOperationQueue = FakeOperationQueue(), notificationCenter: NotificationCenter = NotificationCenter(), findFeedViewController: @escaping () -> FindFeedViewController = { findFeedViewControllerFactory() }, feedViewController: @escaping (Feed) -> FeedViewController = { feed in feedViewControllerFactory(feed: feed) }, settingsViewController: @escaping () -> SettingsViewController = { settingsViewControllerFactory() }, articleListController: @escaping (Feed) -> ArticleListController = { feed in articleListControllerFactory(feed: feed) } ) -> FeedListController { return FeedListController( feedCoordinator: feedCoordinator, settingsRepository: SettingsRepository(userDefaults: nil), messenger: messenger, mainQueue: mainQueue, notificationCenter: notificationCenter, findFeedViewController: findFeedViewController, feedViewController: feedViewController, settingsViewController: settingsViewController, articleListController: articleListController ) } func articleViewControllerFactory( article: Article = articleFactory(), articleUseCase: ArticleUseCase = FakeArticleUseCase(), htmlViewController: @escaping () -> HTMLViewController = { htmlViewControllerFactory() } ) -> ArticleViewController { return ArticleViewController( article: article, articleUseCase: articleUseCase, htmlViewController: htmlViewController ) } func htmlViewControllerFactory() -> HTMLViewController { return HTMLViewController() } func articleListControllerFactory( feed: Feed = feedFactory(), mainQueue: OperationQueue = FakeOperationQueue(), messenger: Messenger = FakeMessenger(), feedCoordinator: FeedCoordinator = FakeFeedCoordinator(), articleCoordinator: ArticleCoordinator = FakeArticleCoordinator(), notificationCenter: NotificationCenter = NotificationCenter(), articleCellController: ArticleCellController = FakeArticleCellController(), articleViewController: @escaping (Article) -> ArticleViewController = { article in articleViewControllerFactory(article: article) } ) -> ArticleListController { return ArticleListController( feed: feed, mainQueue: mainQueue, messenger: messenger, feedCoordinator: feedCoordinator, articleCoordinator: articleCoordinator, notificationCenter: notificationCenter, articleCellController: articleCellController, articleViewController: articleViewController ) } func breakout3DEasterEggViewControllerFactory( mainQueue: FakeOperationQueue = FakeOperationQueue() ) -> Breakout3DEasterEggViewController { return Breakout3DEasterEggViewController( mainQueue: mainQueue ) } func settingsViewControllerFactory( settingsRepository: SettingsRepository = settingsRepositoryFactory(), opmlService: OPMLService = FakeOPMLService(), mainQueue: FakeOperationQueue = FakeOperationQueue(), accountService: AccountService = FakeAccountService(), messenger: Messenger = FakeMessenger(), appIconChanger: AppIconChanger = FakeAppIconChanger(), loginController: LoginController = FakeLoginController(), documentationViewController: @escaping (Documentation) -> DocumentationViewController = { docs in documentationViewControllerFactory(documentation: docs) }, appIconChangeController: @escaping () -> UIViewController = { UIViewController() }, easterEggViewController: @escaping () -> UIViewController = { UIViewController() } ) -> SettingsViewController { return SettingsViewController( settingsRepository: settingsRepository, opmlService: opmlService, mainQueue: mainQueue, accountService: accountService, messenger: messenger, appIconChanger: appIconChanger, loginController: loginController, documentationViewController: documentationViewController, appIconChangeController: appIconChangeController, easterEggViewController: easterEggViewController ) } func documentationViewControllerFactory( documentation: Documentation = .libraries, htmlViewController: HTMLViewController = htmlViewControllerFactory() ) -> DocumentationViewController { return DocumentationViewController( documentation: documentation, htmlViewController: htmlViewController ) } func augmentedRealityViewControllerFactory( mainQueue: OperationQueue = FakeOperationQueue(), feedListController: @escaping () -> FeedListController = { return feedListControllerFactory() } ) -> AugmentedRealityEasterEggViewController { return AugmentedRealityEasterEggViewController( mainQueue: mainQueue, feedListControllerFactory: feedListController ) } // Repositories func settingsRepositoryFactory(userDefaults: UserDefaults? = nil) -> SettingsRepository { return SettingsRepository(userDefaults: userDefaults) }
mit
4e091ef4c81a2eae5913aa5e166d0601
38.559006
160
0.753179
5.952336
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/CommonCrypto/Sources/CommonCryptoKit/JSCrypto/PBKDF2.swift
1
2932
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import CommonCrypto import Foundation public enum PBKDF2Error: Error { case keyDerivationError } public class PBKDF2 { public enum PBKDFAlgorithm { case sha1 case sha512 fileprivate var commonCryptoAlgorithm: CCPBKDFAlgorithm { switch self { case .sha1: return CCPBKDFAlgorithm(kCCPRFHmacAlgSHA1) case .sha512: return CCPBKDFAlgorithm(kCCPRFHmacAlgSHA512) } } } public class func deriveSHA1Result(password: String, salt: Data, iterations: UInt32, keySizeBytes: UInt) -> Result<Data, PBKDF2Error> { deriveResult( password: password, salt: salt, iterations: iterations, keySizeBytes: keySizeBytes, algorithm: .sha1 ) } public class func derive(password: String, salt: Data, iterations: UInt32, keySizeBytes: UInt, algorithm: PBKDFAlgorithm) -> Data? { let derivation = PBKDF2.deriveResult( password: password, salt: salt, iterations: iterations, keySizeBytes: keySizeBytes, algorithm: algorithm ) guard case .success(let key) = derivation else { return nil } return key } private class func deriveResult( password: String, salt: Data, iterations: UInt32, keySizeBytes: UInt, algorithm: PBKDFAlgorithm ) -> Result<Data, PBKDF2Error> { func derive(with password: String, salt: Data, iterations: UInt32, keySizeBytes: UInt, algorithm: CCPBKDFAlgorithm) throws -> Data { var derivedKeyData = Data(repeating: 0, count: Int(keySizeBytes)) let derivedKeyDataCount = derivedKeyData.count try derivedKeyData.withUnsafeMutableBytes { (outputBytes: UnsafeMutableRawBufferPointer) in let status = CCKeyDerivationPBKDF( CCPBKDFAlgorithm(kCCPBKDF2), password, password.utf8.count, salt.bytes, salt.bytes.count, algorithm, iterations, outputBytes.baseAddress?.assumingMemoryBound(to: UInt8.self), derivedKeyDataCount ) guard status == kCCSuccess else { throw PBKDF2Error.keyDerivationError } } return derivedKeyData } return Result { try derive( with: password, salt: salt, iterations: iterations, keySizeBytes: keySizeBytes, algorithm: algorithm.commonCryptoAlgorithm ) } .mapError { _ in PBKDF2Error.keyDerivationError } } }
lgpl-3.0
6a70327abfe6d07c7b48581477b81c08
31.208791
140
0.564995
5.027444
false
false
false
false
mischa-hildebrand/AlignedCollectionViewFlowLayout
Example/AlignedCollectionViewFlowLayout/CollectionViewController.swift
1
1977
// // CollectionViewController.swift // AlignedCollectionViewFlowLayout // // Created by Mischa Hildebrand on 04/15/2017. // Copyright (c) 2017 Mischa Hildebrand. All rights reserved. // import UIKit import AlignedCollectionViewFlowLayout private let reuseIdentifier = "blueCell" class CollectionViewController: UICollectionViewController { let tags1 = ["When you", "eliminate", "the impossible,", "whatever remains,", "however improbable,", "must be", "the truth."] let tags2 = ["Of all the souls", "I have", "encountered", "in my travels,", "his", "was the most…", "human."] let tags3 = ["Computers", "make", "excellent", "and", "efficient", "servants", "but", "I", "have", "no", "wish", "to", "serve", "under", "them."] var dataSource: [[String]] = [[]] override func viewDidLoad() { super.viewDidLoad() dataSource = [tags1, tags2, tags3] // Set up the flow layout's cell alignment: let flowLayout = collectionView?.collectionViewLayout as? AlignedCollectionViewFlowLayout flowLayout?.horizontalAlignment = .trailing // Enable automatic cell-sizing with Auto Layout: flowLayout?.estimatedItemSize = .init(width: 100, height: 40) } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return dataSource.count } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource[section].count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell cell.label.text = dataSource[indexPath.section][indexPath.item] return cell } }
mit
e08625fed5167dbe37338cdf93892401
34.909091
149
0.674937
4.840686
false
false
false
false
joeblau/SensorVisualizer
Example/SensorVisualizer/OptionsTableViewController.swift
1
1028
// // OptionsTableViewController.swift // // // Created by Joseph Blau on 3/22/16. // // import UIKit let resuseIdentifer = "Option Cell" class OptionsTableViewController: UITableViewController { let options = ["Touches", "Map", "Panning", "Web", "Shake"] // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: resuseIdentifer, for: indexPath) cell.textLabel?.text = options[(indexPath as NSIndexPath).row] return cell } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let option = options[(indexPath as NSIndexPath).row] self.performSegue(withIdentifier: "Show \(option)", sender: self) } }
mit
c97481a4c8623c5aa64178727b54919d
28.371429
109
0.689689
4.872038
false
false
false
false
noahemmet/FingerPaint
FingerPaint/PaintGestureRecognizer.swift
1
1889
// // PaintGestureRecognizer.swift // FingerPaint // // Created by Noah Emmet on 4/24/16. // Copyright © 2016 Sticks. All rights reserved. // import UIKit import UIKit.UIGestureRecognizerSubclass public protocol PaintGestureDelegate { // func paintGestureRecognizer(paintGestureRecognizer: PaintGestureRecognizer, didUpdateTouchPath: TouchPath) } public class PaintGestureRecognizer: UIGestureRecognizer { public var paintDelegate: PaintGestureDelegate? // public var stroke: Stroke = Stroke(points: []) // private var touchPath: TouchPath! public var touchManager = TouchManager() public var touchPath = TouchPath() public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent) { super.touchesBegan(touches, withEvent: event) if touchPath.frames.last?.touches.isEmpty == true { touchPath = TouchPath() } touchPath.addTouches(touches) self.state = touchPath.gestureState print("began: ", touchPath.frames.last?.touches.count) } override public func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent) { super.touchesMoved(touches, withEvent: event) touchPath.moveTouches(touches) self.state = touchPath.gestureState } override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent) { super.touchesEnded(touches, withEvent: event) touchPath.removeTouches(touches) print("ended: ", touchManager.touchFrames.last?.touches.count) self.state = touchPath.gestureState } public override func touchesCancelled(touches: Set<UITouch>, withEvent event: UIEvent) { super.touchesCancelled(touches, withEvent: event) touchPath.removeTouches(touches) self.state = .Cancelled } public override func shouldRequireFailureOfGestureRecognizer(otherGestureRecognizer: UIGestureRecognizer) -> Bool { if otherGestureRecognizer is UITapGestureRecognizer { return true } return false } }
apache-2.0
b5340eeddc86e1b947e61d2fcbd5d4a5
31.016949
116
0.774894
4.008493
false
false
false
false
heyogrady/SpaceEvaders
SpaceEvaders/Pause.swift
2
804
import SpriteKit class Pause { var pause: SKSpriteNode init(size: CGSize, x: CGFloat, y: CGFloat) { pause = SKSpriteNode(color: UIColor.clearColor(), size: CGSizeMake(size.width / 3, size.height / 6)) pause.position = CGPoint(x: x, y: y); pause.zPosition = 10 pause.name = "pause" addPause() } func addPause() { let text = SKLabelNode(text: "=") text.fontName = "timeburner" text.name = "pause" text.fontSize = 100 text.zRotation = CGFloat(M_PI_2) text.horizontalAlignmentMode = .Right pause.addChild(text) } func addTo(parentNode: GameScene) -> Pause { parentNode.addChild(pause) return self } func removeThis() { pause.removeFromParent() } }
mit
bc8d9a3c6176faf341796ad658fe085e
24.15625
108
0.583333
4.102041
false
false
false
false
hanjoes/drift-doc
Drift/Sources/DriftRuntime/DriftConverter.swift
1
2446
import Foundation import Antlr4 public struct DriftConverter { /// Prevent from using initializer. private init() { } public static func rewrite(content: String) throws -> String { let input = ANTLRInputStream(Preprocess.convertComment(in: content)) let lexer = JavadocLexer(input) let tokens = CommonTokenStream(lexer) try tokens.fill() let rewriter = TokenStreamRewriter(tokens) let javadocs = emitJavaDocs(from: tokens) try javadocs.forEach { let range = $0.range let markupDesc = $0.markup.description let markupLines = markupDesc.split(separator: "\n", maxSplits: Int.max, omittingEmptySubsequences: false) var indent = "" if let hiddenTokens = try tokens.getHiddenTokensToLeft(range.lowerBound) { if hiddenTokens.count > 0 { let hidden = hiddenTokens.first!.getText()! let lines = hidden.split(separator: "\n", maxSplits: Int.max, omittingEmptySubsequences: false) indent = String(lines.last!) } } var index = 0 var replacementLines = [String]() while index < markupLines.count { if index == 0 { replacementLines.append("/// \(markupLines[index])") } else { replacementLines.append("\(indent)/// \(markupLines[index])") } index += 1 } let replacement = replacementLines.joined(separator: "\n") try rewriter.replace(range.lowerBound, range.upperBound, replacement) } return try rewriter.getText() } } private extension DriftConverter { static func makeANTLRTokenStream(from content: String) -> TokenStream { let input = ANTLRInputStream(content) let lexer = JavadocLexer(input) return CommonTokenStream(lexer) } static func emitJavaDocs(from tokens: TokenStream) -> [Javadoc] { if let parser = try? JavadocParser(tokens) { let scanner = JavadocScanner() let walker = ParseTreeWalker() guard let _ = try? walker.walk(scanner, parser.file()) else { return [Javadoc]() } return scanner.docs } return [Javadoc]() } }
mit
230643361b758131feb29c3ddb88fbe4
34.970588
117
0.563369
4.786693
false
false
false
false
vector-im/vector-ios
Riot/Modules/Room/ParticipantsInviteModal/OptionList/OptionListCoordinator.swift
1
2933
// File created from ScreenTemplate // $ createScreen.sh Room/ParticipantsInviteModal/OptionList OptionList /* Copyright 2021 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit final class OptionListCoordinator: OptionListCoordinatorProtocol { // MARK: - Properties // MARK: Private private let parameters: OptionListCoordinatorParameters private var optionListViewModel: OptionListViewModelProtocol private let optionListViewController: OptionListViewController private lazy var slidingModalPresenter: SlidingModalPresenter = SlidingModalPresenter() // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] weak var delegate: OptionListCoordinatorDelegate? // MARK: - Setup init(parameters: OptionListCoordinatorParameters) { self.parameters = parameters let optionListViewModel = OptionListViewModel(title: self.parameters.title, options: self.parameters.options) let optionListViewController = OptionListViewController.instantiate(with: optionListViewModel) self.optionListViewModel = optionListViewModel self.optionListViewController = optionListViewController } // MARK: - Public func start() { self.optionListViewModel.coordinatorDelegate = self if let rootViewController = self.parameters.navigationRouter?.toPresentable() { slidingModalPresenter.present(optionListViewController, from: rootViewController, animated: true, completion: nil) } } func dismiss(animated: Bool, completion: (() -> Void)?) { slidingModalPresenter.dismiss(animated: animated, completion: completion) } func toPresentable() -> UIViewController { return self.optionListViewController } } // MARK: - OptionListViewModelCoordinatorDelegate extension OptionListCoordinator: OptionListViewModelCoordinatorDelegate { func optionListViewModel(_ viewModel: OptionListViewModelProtocol, didSelectOptionAt index: Int) { dismiss(animated: false) { self.delegate?.optionListCoordinator(self, didSelectOptionAt: index) } } func optionListViewModelDidCancel(_ viewModel: OptionListViewModelProtocol) { dismiss(animated: true) { self.delegate?.optionListCoordinatorDidCancel(self) } } }
apache-2.0
9b7846610424eefbcd7aa4f511fa0df6
34.768293
126
0.732356
5.451673
false
false
false
false
danlozano/Requestr
TinyApiClient/Request.swift
1
1960
// // Request.swift // Analytics // // Created by Daniel Lozano Valdés on 2/13/18. // import Foundation public protocol Request { var method: HTTPMethod { get } var address: Address { get } var parameters: URLParameters? { get } var body: JSONSerializable? { get } } public enum Address { case absolute(String) case relative(host: String, path: String) } public struct BasicRequest: Request { public let method: HTTPMethod public let address: Address public let parameters: URLParameters? public let body: JSONSerializable? } public extension Request { var fullAddress: String { switch address { case let .absolute(fullAddress): return fullAddress case let .relative(host, path): var fullAddress = host if fullAddress.last != "/" { fullAddress += "/" } var tempPath = path if tempPath.first == "/" { tempPath.removeFirst() } fullAddress += tempPath return fullAddress } } var url: URL? { guard let escaped = fullAddress.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return nil } guard let parameters = parameters else { return URL(string: escaped) } guard let url = URL(string: escaped), var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil } let queryItems: [URLQueryItem] = parameters.map { (key, value) -> URLQueryItem in return URLQueryItem(name: key, value: value) } components.queryItems = queryItems return components.url } var urlRequest: URLRequest? { guard let url = url else { return nil } guard method != .GET else { return URLRequest(url: url) } do { var request = URLRequest(url: url) request.httpMethod = method.rawValue if let body = body { let json = body.json let bodyData = try JSONSerialization.data(withJSONObject: json, options: []) request.httpBody = bodyData } return request } catch { return nil } } }
mit
c84f5002b87c570433dbc2e3659be076
17.836538
119
0.683002
3.607735
false
false
false
false
AboutObjects/Modelmatic
Example/Modelmatic/HttpSessionProtocol.swift
1
5415
// // Copyright (C) 2016 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this example's licensing information. // import Foundation private let handled = "ModelmaticRequestHandled" private let handledKey = handled + "Key" private let resourceKey = "resource" as NSString // MARK: - NSInputStream extension InputStream { func data() -> Data? { let data = NSMutableData() var buf = [UInt8](repeating: 0, count: 4096) while hasBytesAvailable { let length = read(&buf, maxLength: buf.count) if length > 0 { data.append(buf, length: length) } } return data as Data } } // MARK: NSURLProtocol class HttpSessionProtocol: URLProtocol, URLSessionTaskDelegate, URLSessionDataDelegate { var session: Foundation.URLSession! var data: NSMutableData? lazy var serialQueue: OperationQueue = { let queue = OperationQueue() queue.maxConcurrentOperationCount = 1 return queue }() override init(request: URLRequest, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) { let mutableRequest = (request as NSURLRequest).mutableCopy() (mutableRequest as AnyObject).setValue(handled, forHTTPHeaderField: handledKey) super.init(request: mutableRequest as! URLRequest, cachedResponse: cachedResponse, client: client) } override class func canInit(with request: URLRequest) -> Bool { let isHttpRequest = request.url?.scheme?.caseInsensitiveCompare("http") == .orderedSame guard let handledField: String = request.value(forHTTPHeaderField: handledKey) else { return true } return isHttpRequest && handledField != handled } override class func canonicalRequest(for request: URLRequest) -> URLRequest { return request } } extension HttpSessionProtocol { func loadData(_ url: URL) { if let data = NSMutableData(contentsOf: url) { self.data = data return } guard let fileName = request.url?.parameterValue(resourceKey), let bundleUrl = URL.bundleDirectoryURL(forFileName: fileName, type: "json") else { return } data = NSMutableData(contentsOf: bundleUrl) } func loadFile(_ url: URL) { serialQueue.isSuspended = true serialQueue.addOperation { [weak self] in self?.loadData(url) } serialQueue.addOperation { [weak self] in self?.finishLoading() } serialQueue.isSuspended = false } func save(_ data: Data?, url: URL) { guard let data = data else { print("WARNING: data was nil"); return } try? data.write(to: url, options: [.atomic]) } override func startLoading() { guard let fileName = request.url?.parameterValue(resourceKey) else { print("WARNING: resource (filename) is nil"); return } var fileUrl: URL? = URL.libraryDirectoryURL(forFileName: fileName, type: "json") if fileUrl == nil { fileUrl = URL.bundleDirectoryURL(forFileName: fileName, type: "json") if fileUrl == nil { print("WARNING: Unable to find file \(fileName)") let task = session.dataTask(with: request) { data, response, error in if let d = data { self.notifyClient(data: d, response: response!, error: error) } } task.resume(); return } } if let httpMethod: String = request.httpMethod, httpMethod == "POST" || httpMethod == "PUT" { guard let stream = request.httpBodyStream else { print("WARNING: Stream is empty"); return } stream.open() save(stream.data(), url: fileUrl!) } loadFile(fileUrl!) } func notifyClient(data: Data, response: URLResponse, error: Error?) { guard error == nil else { client?.urlProtocol(self, didFailWithError: error!); return } client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .allowed) client?.urlProtocol(self, didLoad: data) client?.urlProtocolDidFinishLoading(self) } func finishLoading() { guard let data = data, let url = request.url, let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil) else { client?.urlProtocol(self, didFailWithError: NSError(domain: "ModelmaticNetworkDomain", code: 42, userInfo: nil)) return } client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .allowed) client?.urlProtocol(self, didLoad: data as Data) client?.urlProtocolDidFinishLoading(self) } override func stopLoading() { serialQueue.cancelAllOperations() data = nil } } // MARK: - NSURLSessionTaskDelegate extension HttpSessionProtocol { func urlSession(session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { data = nil } } // MARK: - NSURLSessionDataDelegate extension HttpSessionProtocol { func URLSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: NSData) { data.enumerateBytes { bytes, byteRange, stop in self.data?.append(bytes, length: byteRange.length) } } }
mit
28d1d14a53be3f52f5de7d2bb589b2a2
34.860927
131
0.631025
4.904891
false
false
false
false
IngmarStein/swift
test/Generics/associated_type_typo.swift
1
2633
// RUN: %target-parse-verify-swift // RUN: not %target-swift-frontend -parse -debug-generic-signatures %s > %t.dump 2>&1 // RUN: %FileCheck -check-prefix CHECK-GENERIC %s < %t.dump protocol P1 { associatedtype Assoc } protocol P2 { associatedtype AssocP2 : P1 } protocol P3 { } protocol P4 { } // expected-error@+1{{'T' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{30-35=Assoc}} func typoAssoc1<T : P1>(x: T.assoc) { } // expected-error@+2{{'T' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{43-48=Assoc}} // expected-error@+1{{'U' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{54-59=Assoc}} func typoAssoc2<T : P1, U : P1>() where T.assoc == U.assoc {} // CHECK-GENERIC-LABEL: .typoAssoc2 // CHECK-GENERIC: Generic signature: <T, U where T : P1, U : P1, T.Assoc == U.Assoc> // expected-error@+3{{'T.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{42-47=Assoc}} // expected-error@+2{{'U.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{19-24=Assoc}} func typoAssoc3<T : P2, U : P2>() where U.AssocP2.assoc : P3, T.AssocP2.assoc : P4, T.AssocP2 == U.AssocP2 {} // expected-error@+2{{'T' does not have a member type named 'Assocp2'; did you mean 'AssocP2'?}}{{39-46=AssocP2}} // expected-error@+1{{'T.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{47-52=Assoc}} func typoAssoc4<T : P2>(_: T) where T.Assocp2.assoc : P3 {} // CHECK-GENERIC-LABEL: .typoAssoc4@ // CHECK-GENERIC-NEXT: Requirements: // CHECK-GENERIC-NEXT: T witness marker // CHECK-GENERIC-NEXT: T : P2 [explicit // CHECK-GENERIC-NEXT: T[.P2].AssocP2 witness marker // CHECK-GENERIC-NEXT: T[.P2].AssocP2 : P1 [protocol // CHECK-GENERIC-NEXT: T[.P2].AssocP2 == T.AssocP2 [redundant] // CHECK-GENERIC-NEXT: T[.P2].AssocP2[.P1].Assoc witness marker // CHECK-GENERIC-NEXT: T[.P2].AssocP2[.P1].Assoc : P3 [explicit // CHECK-GENERIC-NEXT: T[.P2].AssocP2[.P1].Assoc == T[.P2].AssocP2.Assoc [redundant] // CHECK-GENERIC-NEXT: Generic signature // <rdar://problem/19620340> func typoFunc1<T : P1>(x: TypoType) { // expected-error{{use of undeclared type 'TypoType'}} let _: T.Assoc -> () = { let _ = $0 } // expected-error{{'Assoc' is not a member type of 'T'}} } func typoFunc2<T : P1>(x: TypoType, y: T) { // expected-error{{use of undeclared type 'TypoType'}} let _: T.Assoc -> () = { let _ = $0 } // expected-error{{'Assoc' is not a member type of 'T'}} } func typoFunc3<T : P1>(x: TypoType, y: (T.Assoc) -> ()) { // expected-error{{use of undeclared type 'TypoType'}} }
apache-2.0
5ceff42a93e837d55b06bb9d491c6268
41.467742
115
0.650589
2.880744
false
false
false
false
iOSDevLog/iOSDevLog
Checklists/Checklists/Checklist.swift
1
1274
// // Checklist.swift // Checklists // // Created by iosdevlog on 16/1/3. // Copyright © 2016年 iosdevlog. All rights reserved. // import UIKit class Checklist: NSObject, NSCoding { var name = "" var iconName = "No Icon" var items = [ChecklistItem]() convenience init(name: String) { self.init(name: name, iconName: "No Icon") } init(name: String, iconName: String) { self.name = name self.iconName = iconName super.init() } // MARK: - protocol NSCoding func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: "Name") aCoder.encodeObject(iconName, forKey: "IconName") aCoder.encodeObject(items, forKey: "Items") } required init?(coder aDecoder: NSCoder) { name = aDecoder.decodeObjectForKey("Name") as! String iconName = aDecoder.decodeObjectForKey("IconName") as! String items = aDecoder.decodeObjectForKey("Items") as! [ChecklistItem] super.init() } // MARK: - Helper func countUncheckedItems() -> Int { var count = 0 for item in items where !item.checked { count += 1 } return count } }
mit
ea90c100f3541711471aa39436fa1557
22.981132
72
0.575924
4.397924
false
false
false
false
AfricanSwift/TUIKit
TUIKit/Source/Ansi/Ansi+Color2.swift
1
17221
// // File: Ansi+Color2.swift // Created by: African Swift import Darwin public extension Ansi { public class Color2 { private var rgb: RGB private var alpha: Double public var red: Double { return self.rgb.red } public var green: Double { return self.rgb.green } public var blue: Double { return self.rgb.blue } public var hsl: HSL { return self.toHSL() } public var lab: LAB { return self.toLAB() } public var cmyb: CMYB { return self.toCMYB() } private static func clip(value: Double, min: Double, max: Double) -> Double { return value > max ? max : value < min ? min : value } private init(rgb: RGB, alpha: Double) { self.rgb = rgb self.alpha = Ansi.Color2.clip(value: alpha, min: 0, max: 1) } public convenience init(red: Double, green: Double, blue: Double, alpha: Double) { let rgb = RGB(red: red, green: green, blue: blue) self.init(rgb: rgb, alpha: alpha) } public convenience init(cyan: Double, yellow: Double, magenta: Double, black: Double, alpha: Double) { let cmyb = CMYB(cyan: cyan, magenta: magenta, yellow: yellow, black: black) self.init(rgb: cmyb.toRGB(), alpha: alpha) } public convenience init(l: Double, a: Double, b: Double, alpha: Double) { let lab = LAB(l: l, a: a, b: b) self.init(rgb: lab.toRGB(), alpha: alpha) } public convenience init(hue: Double, saturation: Double, lightness: Double, alpha: Double) { let h = hue.truncatingRemainder(dividingBy: 360) let hsl = HSL(hue: h, saturation: saturation, lightness: lightness) self.init(rgb: hsl.toRGB(), alpha: alpha) } } } public extension Ansi.Color2 { public func toAnsiColor() -> Ansi.Color { return Ansi.Color(red: self.red, green: self.green, blue: self.blue, alpha: self.alpha) } /// Returns a color with the hue rotated along the color wheel by the given amount. /// /// - Parameters: /// - amount: A double representing the number of degrees as ratio (between -360.0 degree and 360.0 degree). public func alterHue(by amount: Double) -> Ansi.Color2 { let hsl = self.hsl return Ansi.Color2(hue: hsl.hue + amount, saturation: hsl.saturation, lightness: hsl.lightness, alpha: self.alpha) } /// Creates and returns the complement of the color object. /// This is identical to adjustedHue(180). public func complementary() -> Ansi.Color2 { return alterHue(by: 180) } /// Returns a color with the lightness increased by the given amount. /// /// - Parameters: /// - amount: Double between 0.0 and 1.0. public func lighten(by amount: Double = 0.2) -> Ansi.Color2 { let hsl = self.hsl return Ansi.Color2(hue: hsl.hue, saturation: hsl.saturation, lightness: hsl.lightness + amount, alpha: self.alpha) } /// Returns a color with the lightness decreased by the given amount. /// /// - Parameters: /// - amount: Double between 0.0 and 1.0. public func darken(by amount: Double = 0.2) -> Ansi.Color2 { return lighten(by: amount * -1) } /// Returns a color with the saturation increased by the given amount. /// /// - Parameters: /// - amount: Double between 0.0 and 1.0. public func saturate(by amount: Double = 0.2) -> Ansi.Color2 { let hsl = self.hsl return Ansi.Color2(hue: hsl.hue, saturation: hsl.saturation + amount, lightness: hsl.lightness, alpha: self.alpha) } /// Returns a color with the saturation decreased by the given amount. /// /// - Parameters: /// - amount: Double between 0.0 and 1.0. public func desaturate(by amount: Double = 0.2) -> Ansi.Color2 { return saturate(by: amount * -1) } /// Creates and returns a color object converted to grayscale. /// This is identical to desaturateColor(1). public func grayscale() -> Ansi.Color2 { return Ansi.Color2(red: self.red, green: self.red, blue: self.red, alpha: self.alpha) } /// Creates and return a color object where the red, green, and blue values are inverted, /// while the alpha channel is left alone. public func invert() -> Ansi.Color2 { return Ansi.Color2(red: 1 - self.red, green: 1 - self.green, blue: 1 - self.blue, alpha: self.alpha) } /// Mixes the given color object with the receiver. /// Specifically, takes the average of each of the RGB components, optionally weighted by the given percentage. /// The opacity of the colors object is also considered when weighting the components. /// /// - Parameters: /// - color: A color object to mix with the receiver. /// - weight: The weight specifies the amount of the given color object (between 0 and 1). The default /// value is 0.5, which means that half the given color and half the receiver color object /// should be used. 0.25 means that a quarter of the given color object and three quarters /// of the receiver color object should be used. public func mix(with: Ansi.Color2, by weight: Double = 0.5) -> Ansi.Color2 { let clippedWeight = Ansi.Color2.clip(value: weight, min: 0, max: 1) let red = self.red + clippedWeight * (with.red - self.red) let green = self.green + clippedWeight * (with.green - self.green) let blue = self.blue + clippedWeight * (with.blue - self.blue) let alpha = self.alpha + clippedWeight * (with.alpha - self.alpha) return Ansi.Color2(red: red, green: green, blue: blue, alpha: alpha) } /// Creates and returns a color object corresponding to the mix of the receiver and an amount /// of white color, which increases lightness. /// /// - Parameters: /// - amount: Double between 0.0 and 1.0. The default amount is equal to 0.2. public func tint(by weight: Double = 0.2) -> Ansi.Color2 { let white = Ansi.Color2(red: 1, green: 1, blue: 1, alpha: 1) return mix(with: white, by: weight) } /// Creates and returns a color object corresponding to the mix of the receiver and an amount /// of black color, which reduces lightness. /// /// - Parameters: /// - amount: Double between 0.0 and 1.0. The default amount is equal to 0.2. public func shade(by weight: Double = 0.2) -> Ansi.Color2 { let black = Ansi.Color2(red: 0, green: 0, blue: 0, alpha: 1) return mix(with: black, by: weight) } /// Creates and returns a color object with the alpha increased by the given amount. /// /// - Parameters: /// - amount: Double between 0.0 and 1.0. public func adjustAlpha(by amount: Double) -> Ansi.Color2 { let alpha = Ansi.Color2.clip(value: self.alpha + amount, min: 0, max: 1) return Ansi.Color2(red: self.red, green: self.green, blue: self.blue, alpha: alpha) } } private extension Ansi.Color2 { /// Convert RGB to LAB /// /// - returns: Ansi.Color2.LAB private func toLAB() -> LAB { let XYZ = convertRGBToXYZ() return Ansi.Color2.convertXYZToLAB(xyz: XYZ) } /// Convert RGB to XYZ /// /// - returns: Ansi.Color2.XYZ private func convertRGBToXYZ() -> XYZ { func adjustPrimary(_ c: Double) -> Double { return (c > 0.04045 ? pow((c + 0.055) / 1.055, 2.4) : c / 12.92) * 100 } //Observer = 2°, Illuminant = D65 func toXYZ() -> XYZ { let red = adjustPrimary(self.rgb.red) let green = adjustPrimary(self.rgb.green) let blue = adjustPrimary(self.rgb.blue) return XYZ( x: red * 0.4124 + green * 0.3576 + blue * 0.1805, y: red * 0.2126 + green * 0.7152 + blue * 0.0722, z: red * 0.0193 + green * 0.1192 + blue * 0.9505) } return toXYZ() } /// Convert XYZ to LAB /// /// - parameters: /// - xyz: Ansi.Color2.XYZ /// - returns: Ansi.Color2.LAB private static func convertXYZToLAB(xyz value: XYZ) -> LAB { // CIE XYZ tristimulus values of the reference white point, // Observer = 2°, Illuminant = D65 let wpRefX: Double = 95.047 let wpRefY: Double = 100.000 let wpRefZ: Double = 108.883 enum XYZComponents { case x, y, z } func convertXYZ(_ v: Double, _ c: XYZComponents) -> Double { let adjComp = c == .x ? v / wpRefX : c == .y ? v / wpRefY : v / wpRefZ return adjComp > 0.008856 ? pow(adjComp, 1 / 3) : (7.787 * adjComp) + (16 / 116) } func toCieLAB(vx: Double, vy: Double, vz: Double) -> LAB { return LAB(l: (116 * vy) - 16, a: 500 * (vx - vy), b: 200 * (vy - vz)) } return toCieLAB(vx: convertXYZ(value.x, .x), vy: convertXYZ(value.y, .y), vz: convertXYZ(value.z, .z)) } } private extension Ansi.Color2 { /// Convert RGB to HSL /// /// - returns: Ansi.Color2.HSL private func toHSL() -> HSL { var component = (h: 0.0, s: 0.0, l: 0.0) let maximum = max(max(self.red, self.blue), self.green) let minimum = min(min(self.red, self.blue), self.green) let delta = maximum - minimum component.l = maximum if delta != 0 { if maximum == self.red { component.h = fmod(((self.green - self.blue) / delta), 6.0) } else if maximum == self.green { component.h = (self.blue - self.red) / delta + 2.0 } else // if maximum == self.blue { component.h = (self.red - self.green) / delta + 4.0 } component.h *= 60.0 component.s = delta / component.l } return HSL(hue: component.h * 360, saturation: component.s, lightness: component.l) } } private extension Ansi.Color2 { /// Convert RGB to CMYB /// /// - returns: Ansi.Color2.CMYB private func toCMYB() -> CMYB { // CMY Conversion var cyan = (1 - self.red) var magenta = (1 - self.green) var yellow = (1 - self.blue) var black = 1.0 if cyan < black { black = cyan } if magenta < black { black = magenta } if yellow < black { black = yellow } // Black if black == 1.0 { cyan = 0 magenta = 0 yellow = 0 } else { cyan = ( cyan - black ) / ( 1 - black ) magenta = ( magenta - black ) / ( 1 - black ) yellow = ( yellow - black ) / ( 1 - black ) } return CMYB(cyan: cyan, magenta: magenta, yellow: yellow, black: black) } } public extension Ansi.Color2 { internal struct XYZ { let x: Double let y: Double let z: Double } /// CIE XYZ color space component values with an observer at 2° and a D65 illuminant. /// /// - Parameters: /// - l: The lightness, specified as a value from 0 to 1.0 /// - a: The red-green axis, specified as a value from -0.5 to 0.5 /// - b: The yellow-blue axis, specified as a value from -0.5 to 0.5 public struct LAB { let l: Double let a: Double let b: Double internal init(l: Double, a: Double, b: Double) { self.l = Ansi.Color2.clip(value: l, min: 0, max: 1) self.a = Ansi.Color2.clip(value: a, min: -0.5, max: 0.5) self.b = Ansi.Color2.clip(value: b, min: -0.5, max: 0.5) } /// Convert LAB to RGB /// /// - returns: Ansi.Color2.RGB internal func toRGB() -> RGB { let xyz = convertLABToXYZ() return LAB.convertXYZToRGB(xyz: xyz) } /// Convert LAB to XYZ /// /// - returns: Ansi.Color2.XYZ private func convertLABToXYZ() -> XYZ { // CIE XYZ tristimulus values of the reference white point, let wpRefX: Double = 95.047 let wpRefY: Double = 100.000 let wpRefZ: Double = 108.883 enum XYZComponents { case x, y, z } // Observer = 2°, Illuminant = D65 func toXYZ(_ v: Double, _ c: XYZComponents) -> Double { let comp3 = pow(v, 3) let adjComp = comp3 > 0.008856 ? comp3 : (v - (16 / 116)) / 7.787 return c == .x ? adjComp * wpRefX : c == .y ? adjComp * wpRefY : adjComp * wpRefZ //.Z } let y = (self.l + 16) / 116 let x = (self.a / 500) + y let z = y - (self.b / 200) return XYZ(x: toXYZ(x, .x), y: toXYZ(y, .y), z: toXYZ(z, .z)) } /// Convert XYZ to RGB /// /// - parameters: /// - xyz: Ansi.Color2.XYZ /// - returns: Ansi.Color2.RGB private static func convertXYZToRGB(xyz value: XYZ) -> RGB { // Observer = 2°, Illuminant = D65 let vx = value.x / 100 let vy = value.y / 100 let vz = value.z / 100 func convertPrimary(_ v: Double) -> Double { return v > 0.0031308 ? 1.055 * (pow(v, 1 / 2.4)) - 0.055 : 12.92 * v } return RGB(red: convertPrimary(vx * 3.2406 + vy * -1.5372 + vz * -0.4986), green: convertPrimary(vx * -0.9689 + vy * 1.8758 + vz * 0.0415), blue: convertPrimary(vx * 0.0557 + vy * -0.2040 + vz * 1.0570)) } } } public extension Ansi.Color2 { /// CMYB color model is a subtractive color model, used in color printing. /// /// - Parameters: /// - cyan: cyan ink, specified as a value from 0.0 to 1.0 /// - magenta: magenta ink, specified as a value from 0.0 to 1.0 /// - yellow: yellow ink, specified as a value from 0.0 to 1.0 /// - black: black ink, specified as a value from 0.0 to 1.0 public struct CMYB { public let cyan: Double public let magenta: Double public let yellow: Double public let black: Double init(cyan: Double, magenta: Double, yellow: Double, black: Double) { self.cyan = Ansi.Color2.clip(value: cyan, min: 0, max: 1) self.magenta = Ansi.Color2.clip(value: magenta, min: 0, max: 1) self.yellow = Ansi.Color2.clip(value: yellow, min: 0, max: 1) self.black = Ansi.Color2.clip(value: black, min: 0, max: 1) } /// Convert CMYB to RGB /// /// - returns: Ansi.Color2.RGB internal func toRGB() -> RGB { // CMYB to CMY let cyan = (self.cyan * (1 - self.black) + self.black) let magenta = (self.magenta * (1 - self.black) + self.black) let yellow = (self.yellow * (1 - self.black) + self.black) // CMY to RGB return RGB(red: 1 - cyan, green: 1 - magenta, blue: 1 - yellow) } } } public extension Ansi.Color2 { /// RGB color model is an additive color model in which red, green and blue light are added together /// in various ways to reproduce a broad array of colors /// /// - Parameters: /// - red: The red component, specified as a value from 0.0 to 1.0 /// - green: The green component, specified as a value from 0.0 to 1.0 /// - blue: The blue component, specified as a value from 0.0 to 1.0 internal struct RGB { internal let red: Double internal let green: Double internal let blue: Double init(red: Double, green: Double, blue: Double) { self.red = Ansi.Color2.clip(value: red, min: 0, max: 1) self.green = Ansi.Color2.clip(value: green, min: 0, max: 1) self.blue = Ansi.Color2.clip(value: blue, min: 0, max: 1) } } } public extension Ansi.Color2 { /// HSL color from the hue, saturation, lightness components. /// /// - Parameters: /// - hue: The hue component of the color object, specified as a value between 0.0 and 360.0 degree. /// - saturation: The saturation component of the color object, specified as a value between 0.0 and 1.0. /// - lightness: The lightness component of the color object, specified as a value between 0.0 and 1.0. public struct HSL { public let hue: Double public let saturation: Double public let lightness: Double internal init(hue: Double, saturation: Double, lightness: Double) { self.hue = hue / 360 self.saturation = Ansi.Color2.clip(value: saturation, min: 0, max: 1) self.lightness = Ansi.Color2.clip(value: lightness, min: 0, max: 1) } /// Convert HSL to RGB /// /// - returns: Ansi.Color2.RGB internal func toRGB() -> RGB { let h = self.hue * 360 let chroma = self.lightness * self.saturation let x = chroma * (1.0 - fabs(fmod(h / 60.0, 2.0) - 1.0)) let m = self.lightness - chroma if h >= 0.0 && h < 60.0 { return RGB(red: chroma + m, green: x + m, blue: m) } else if h >= 60.0 && h < 120.0 { return RGB(red: x + m, green: chroma + m, blue: m) } else if h >= 120.0 && h < 180.0 { return RGB(red: m, green: chroma + m, blue: x + m) } else if h >= 180.0 && h < 240.0 { return RGB(red: m, green: x + m, blue: chroma + m) } else if h >= 240.0 && h < 300.0 { return RGB(red: x + m, green: m, blue: chroma + m) } else if h >= 300.0 && h < 360.0 { return RGB(red: chroma + m, green: m, blue: x + m) } else { return RGB(red: m, green: m, blue: m) } } } }
mit
b01ba03a4090e6b45167ca1870d7e07a
29.416961
114
0.581145
3.437013
false
false
false
false
PGSSoft/AutoMate
AutoMate/Models/SystemLanguage.swift
1
28235
// swiftlint:disable identifier_name file_length type_body_length /// Enumeration describing available languages in the system. public enum SystemLanguage: String, LaunchArgumentValue { /// Automatically generated value for language Cheyenne. case Cheyenne = "chy" /// Automatically generated value for language EnglishIndia. case EnglishIndia = "en-IN" /// Automatically generated value for language EnglishUnitedStates. case EnglishUnitedStates = "en-US" /// Automatically generated value for language Malagasy. case Malagasy = "mg" /// Automatically generated value for language Tasawaq. case Tasawaq = "twq" /// Automatically generated value for language Nuer. case Nuer = "nus" /// Automatically generated value for language ChineseSimplified. case ChineseSimplified = "zh-Hans" /// Automatically generated value for language KashmiriArabic. case KashmiriArabic = "ks-Arab" /// Automatically generated value for language FrenchFrance. case FrenchFrance = "fr-FR" /// Automatically generated value for language Bengali. case Bengali = "bn" /// Automatically generated value for language TatarLatin. case TatarLatin = "tt-Latn" /// Automatically generated value for language SouthernSotho. case SouthernSotho = "st" /// Automatically generated value for language Neapolitan. case Neapolitan = "nap" /// Automatically generated value for language Fulah. case Fulah = "ff" /// Automatically generated value for language CentralKurdish. case CentralKurdish = "ckb" /// Automatically generated value for language Slovak. case Slovak = "sk" /// Automatically generated value for language Adangme. case Adangme = "ada" /// Automatically generated value for language Luo. case Luo = "luo" /// Automatically generated value for language Tumbuka. case Tumbuka = "tum" /// Automatically generated value for language Javanese. case Javanese = "jv" /// Automatically generated value for language Meru. case Meru = "mer" /// Automatically generated value for language Ido. case Ido = "io" /// Automatically generated value for language Angika. case Angika = "anp" /// Automatically generated value for language Tsonga. case Tsonga = "ts" /// Automatically generated value for language FrenchCanada. case FrenchCanada = "fr-CA" /// Automatically generated value for language Rarotongan. case Rarotongan = "rar" /// Automatically generated value for language Sango. case Sango = "sg" /// Automatically generated value for language Arapaho. case Arapaho = "arp" /// Automatically generated value for language Bemba. case Bemba = "bem" /// Automatically generated value for language GermanSwitzerland. case GermanSwitzerland = "de-CH" /// Automatically generated value for language Kpelle. case Kpelle = "kpe" /// Automatically generated value for language Tajik. case Tajik = "tg" /// Automatically generated value for language Marshallese. case Marshallese = "mh" /// Automatically generated value for language Akan. case Akan = "ak" /// Automatically generated value for language Kimbundu. case Kimbundu = "kmb" /// Automatically generated value for language Telugu. case Telugu = "te" /// Automatically generated value for language Soga. case Soga = "xog" /// Automatically generated value for language Aragonese. case Aragonese = "an" /// Automatically generated value for language Manx. case Manx = "gv" /// Automatically generated value for language Palauan. case Palauan = "pau" /// Automatically generated value for language Pashto. case Pashto = "ps" /// Automatically generated value for language Nepali. case Nepali = "ne" /// Automatically generated value for language Ainu. case Ainu = "ain" /// Automatically generated value for language Albanian. case Albanian = "sq" /// Automatically generated value for language Ndonga. case Ndonga = "ng" /// Automatically generated value for language Estonian. case Estonian = "et" /// Automatically generated value for language Newari. case Newari = "new" /// Automatically generated value for language Welsh. case Welsh = "cy" /// Automatically generated value for language Quechua. case Quechua = "qu" /// Automatically generated value for language Colognian. case Colognian = "ksh" /// Automatically generated value for language Malay. case Malay = "ms" /// Automatically generated value for language Bambara. case Bambara = "bm" /// Automatically generated value for language Swahili. case Swahili = "sw" /// Automatically generated value for language Tibetan. case Tibetan = "bo" /// Automatically generated value for language Metaʼ. case Metaʼ = "mgo" /// Automatically generated value for language Lingala. case Lingala = "ln" /// Automatically generated value for language Filipino. case Filipino = "fil" /// Automatically generated value for language Sakha. case Sakha = "sah" /// Automatically generated value for language Finnish. case Finnish = "fi" /// Automatically generated value for language Tahitian. case Tahitian = "ty" /// Automatically generated value for language Kuanyama. case Kuanyama = "kj" /// Automatically generated value for language Ngomba. case Ngomba = "jgo" /// Automatically generated value for language English. case English = "en" /// Automatically generated value for language Maori. case Maori = "mi" /// Automatically generated value for language Nyankole. case Nyankole = "nyn" /// Automatically generated value for language Pampanga. case Pampanga = "pam" /// Automatically generated value for language Nias. case Nias = "nia" /// Automatically generated value for language Slovenian. case Slovenian = "sl" /// Automatically generated value for language ChineseTaiwan. case ChineseTaiwan = "zh-TW" /// Automatically generated value for language Khmer. case Khmer = "km" /// Automatically generated value for language Kurukh. case Kurukh = "kru" /// Automatically generated value for language Mapuche. case Mapuche = "arn" /// Automatically generated value for language Micmac. case Micmac = "mic" /// Automatically generated value for language Jju. case Jju = "kaj" /// Automatically generated value for language Sukuma. case Sukuma = "suk" /// Automatically generated value for language Japanese. case Japanese = "ja" /// Automatically generated value for language Sindhi. case Sindhi = "sd" /// Automatically generated value for language Khasi. case Khasi = "kha" /// Automatically generated value for language Lozi. case Lozi = "loz" /// Automatically generated value for language Awadhi. case Awadhi = "awa" /// Automatically generated value for language Ngiemboon. case Ngiemboon = "nnh" /// Automatically generated value for language Umbundu. case Umbundu = "umb" /// Automatically generated value for language Sicilian. case Sicilian = "scn" /// Automatically generated value for language Karelian. case Karelian = "krl" /// Automatically generated value for language SerbianLatin. case SerbianLatin = "sr-Latn" /// Automatically generated value for language Chamorro. case Chamorro = "ch" /// Automatically generated value for language Makasar. case Makasar = "mak" /// Automatically generated value for language German. case German = "de" /// Automatically generated value for language Korean. case Korean = "ko" /// Automatically generated value for language Morisyen. case Morisyen = "mfe" /// Automatically generated value for language Tongan. case Tongan = "to" /// Automatically generated value for language Kyrgyz. case Kyrgyz = "ky" /// Automatically generated value for language Moksha. case Moksha = "mdf" /// Automatically generated value for language Mundang. case Mundang = "mua" /// Automatically generated value for language Twi. case Twi = "tw" /// Automatically generated value for language UzbekCyrillic. case UzbekCyrillic = "uz-Cyrl" /// Automatically generated value for language GermanGermany. case GermanGermany = "de-DE" /// Automatically generated value for language Ukrainian. case Ukrainian = "uk" /// Automatically generated value for language Vietnamese. case Vietnamese = "vi" /// Automatically generated value for language Greek. case Greek = "el" /// Automatically generated value for language Limburgish. case Limburgish = "li" /// Automatically generated value for language Tigre. case Tigre = "tig" /// Automatically generated value for language Malayalam. case Malayalam = "ml" /// Automatically generated value for language LubaKatanga. case LubaKatanga = "lu" /// Automatically generated value for language Erzya. case Erzya = "myv" /// Automatically generated value for language TatarCyrillic. case TatarCyrillic = "tt-Cyrl" /// Automatically generated value for language Italian. case Italian = "it" /// Automatically generated value for language Zuni. case Zuni = "zun" /// Automatically generated value for language Walloon. case Walloon = "wa" /// Automatically generated value for language Somali. case Somali = "so" /// Automatically generated value for language Vai. case Vai = "vai" /// Automatically generated value for language TokPisin. case TokPisin = "tpi" /// Automatically generated value for language Croatian. case Croatian = "hr" /// Automatically generated value for language Kamba. case Kamba = "kam" /// Automatically generated value for language SrananTongo. case SrananTongo = "srn" /// Automatically generated value for language SundaneseLatin. case SundaneseLatin = "su-Latn" /// Automatically generated value for language Mohawk. case Mohawk = "moh" /// Automatically generated value for language Serbian. case Serbian = "sr" /// Automatically generated value for language Czech. case Czech = "cs" /// Automatically generated value for language Venda. case Venda = "ve" /// Automatically generated value for language TachelhitLatin. case TachelhitLatin = "shi-Latn" /// Automatically generated value for language Abkhazian. case Abkhazian = "ab" /// Automatically generated value for language Romansh. case Romansh = "rm" /// Automatically generated value for language SundaneseSundanese. case SundaneseSundanese = "su-Sund" /// Automatically generated value for language Amharic. case Amharic = "am" /// Automatically generated value for language TurkmenCyrillic. case TurkmenCyrillic = "tk-Cyrl" /// Automatically generated value for language Kabuverdianu. case Kabuverdianu = "kea" /// Automatically generated value for language Breton. case Breton = "br" /// Automatically generated value for language Comorian. case Comorian = "swb" /// Automatically generated value for language Luxembourgish. case Luxembourgish = "lb" /// Automatically generated value for language Russian. case Russian = "ru" /// Automatically generated value for language Rundi. case Rundi = "rn" /// Automatically generated value for language KoyraChiini. case KoyraChiini = "khq" /// Automatically generated value for language Marathi. case Marathi = "mr" /// Automatically generated value for language ItalianItaly. case ItalianItaly = "it-IT" /// Automatically generated value for language Swedish. case Swedish = "sv" /// Automatically generated value for language Klingon. case Klingon = "tlh" /// Automatically generated value for language Armenian. case Armenian = "hy" /// Automatically generated value for language Luyia. case Luyia = "luy" /// Automatically generated value for language Tuvinian. case Tuvinian = "tyv" /// Automatically generated value for language Georgian. case Georgian = "ka" /// Automatically generated value for language Macedonian. case Macedonian = "mk" /// Automatically generated value for language Asturian. case Asturian = "ast" /// Automatically generated value for language KoyraboroSenni. case KoyraboroSenni = "ses" /// Automatically generated value for language Yoruba. case Yoruba = "yo" /// Automatically generated value for language Creek. case Creek = "mus" /// Automatically generated value for language Santali. case Santali = "sat" /// Automatically generated value for language TurkmenLatin. case TurkmenLatin = "tk-Latn" /// Automatically generated value for language Magahi. case Magahi = "mag" /// Automatically generated value for language Kinyarwanda. case Kinyarwanda = "rw" /// Automatically generated value for language Oromo. case Oromo = "om" /// Automatically generated value for language Adyghe. case Adyghe = "ady" /// Automatically generated value for language Tswana. case Tswana = "tn" /// Automatically generated value for language SpanishLatinAmerica. case SpanishLatinAmerica = "es-419" /// Automatically generated value for language SichuanYi. case SichuanYi = "ii" /// Automatically generated value for language SpanishSpain. case SpanishSpain = "es-ES" /// Automatically generated value for language Hindi. case Hindi = "hi" /// Automatically generated value for language Aromanian. case Aromanian = "rup" /// Automatically generated value for language Komi. case Komi = "kv" /// Automatically generated value for language French. case French = "fr" /// Automatically generated value for language SindhiDevanagari. case SindhiDevanagari = "sd-Deva" /// Automatically generated value for language Occitan. case Occitan = "oc" /// Automatically generated value for language NorthernSami. case NorthernSami = "se" /// Automatically generated value for language AzerbaijaniLatin. case AzerbaijaniLatin = "az-Latn" /// Automatically generated value for language Persian. case Persian = "fa" /// Automatically generated value for language Kalmyk. case Kalmyk = "xal" /// Automatically generated value for language Mossi. case Mossi = "mos" /// Automatically generated value for language Niuean. case Niuean = "niu" /// Automatically generated value for language Faroese. case Faroese = "fo" /// Automatically generated value for language Igbo. case Igbo = "ig" /// Automatically generated value for language Hebrew. case Hebrew = "he" /// Automatically generated value for language Polish. case Polish = "pl" /// Automatically generated value for language Romanian. case Romanian = "ro" /// Automatically generated value for language DutchBelgium. case DutchBelgium = "nl-BE" /// Automatically generated value for language Tagalog. case Tagalog = "tl" /// Automatically generated value for language Nauru. case Nauru = "na" /// Automatically generated value for language Masai. case Masai = "mas" /// Automatically generated value for language Indonesian. case Indonesian = "id" /// Automatically generated value for language Latin. case Latin = "la" /// Automatically generated value for language PunjabiArabic. case PunjabiArabic = "pa-Arab" /// Automatically generated value for language SouthNdebele. case SouthNdebele = "nr" /// Automatically generated value for language Xhosa. case Xhosa = "xh" /// Automatically generated value for language Uyghur. case Uyghur = "ug" /// Automatically generated value for language StandardMoroccanTamazight. case StandardMoroccanTamazight = "zgh" /// Automatically generated value for language Danish. case Danish = "da" /// Automatically generated value for language KarachayBalkar. case KarachayBalkar = "krc" /// Automatically generated value for language Lao. case Lao = "lo" /// Automatically generated value for language NorwegianNynorsk. case NorwegianNynorsk = "nn" /// Automatically generated value for language GermanAustria. case GermanAustria = "de-AT" /// Automatically generated value for language Sinhala. case Sinhala = "si" /// Automatically generated value for language Portuguese. case Portuguese = "pt" /// Automatically generated value for language LubaLulua. case LubaLulua = "lua" /// Automatically generated value for language Kalaallisut. case Kalaallisut = "kl" /// Automatically generated value for language EnglishAustralia. case EnglishAustralia = "en-AU" /// Automatically generated value for language Udmurt. case Udmurt = "udm" /// Automatically generated value for language Ossetic. case Ossetic = "os" /// Automatically generated value for language Bulgarian. case Bulgarian = "bg" /// Automatically generated value for language ItalianSwitzerland. case ItalianSwitzerland = "it-CH" /// Automatically generated value for language SoninkeArabic. case SoninkeArabic = "snk-Arab" /// Automatically generated value for language ScottishGaelic. case ScottishGaelic = "gd" /// Automatically generated value for language NorthNdebele. case NorthNdebele = "nd" /// Automatically generated value for language Sandawe. case Sandawe = "sad" /// Automatically generated value for language Lojban. case Lojban = "jbo" /// Automatically generated value for language Punjabi. case Punjabi = "pa" /// Automatically generated value for language AzerbaijaniCyrillic. case AzerbaijaniCyrillic = "az-Cyrl" /// Automatically generated value for language Fanti. case Fanti = "fat" /// Automatically generated value for language Kumyk. case Kumyk = "kum" /// Automatically generated value for language Nama. case Nama = "naq" /// Automatically generated value for language Gusii. case Gusii = "guz" /// Automatically generated value for language FrenchSwitzerland. case FrenchSwitzerland = "fr-CH" /// Automatically generated value for language ChineseHongKongSARChina. case ChineseHongKongSARChina = "zh-HK" /// Automatically generated value for language SoninkeLatin. case SoninkeLatin = "snk-Latn" /// Automatically generated value for language Manipuri. case Manipuri = "mni" /// Automatically generated value for language Ngambay. case Ngambay = "sba" /// Automatically generated value for language Lakota. case Lakota = "lkt" /// Automatically generated value for language Konkani. case Konkani = "kok" /// Automatically generated value for language EnglishUnitedKingdom. case EnglishUnitedKingdom = "en-GB" /// Automatically generated value for language Cantonese. case Cantonese = "yue" /// Automatically generated value for language Bosnian. case Bosnian = "bs" /// Automatically generated value for language Sanskrit. case Sanskrit = "sa" /// Automatically generated value for language Minangkabau. case Minangkabau = "min" /// Automatically generated value for language Kachin. case Kachin = "kac" /// Automatically generated value for language Icelandic. case Icelandic = "is" /// Automatically generated value for language Kabyle. case Kabyle = "kab" /// Automatically generated value for language Waray. case Waray = "war" /// Automatically generated value for language Esperanto. case Esperanto = "eo" /// Automatically generated value for language Kanuri. case Kanuri = "kr" /// Automatically generated value for language Tigrinya. case Tigrinya = "ti" /// Automatically generated value for language SouthernAltai. case SouthernAltai = "alt" /// Automatically generated value for language Inuktitut. case Inuktitut = "iu" /// Automatically generated value for language Bislama. case Bislama = "bi" /// Automatically generated value for language Ewe. case Ewe = "ee" /// Automatically generated value for language Spanish. case Spanish = "es" /// Automatically generated value for language Nyanja. case Nyanja = "ny" /// Automatically generated value for language Madurese. case Madurese = "mad" /// Automatically generated value for language Mizo. case Mizo = "lus" /// Automatically generated value for language UzbekArabic. case UzbekArabic = "uz-Arab" /// Automatically generated value for language Avaric. case Avaric = "av" /// Automatically generated value for language Turkish. case Turkish = "tr" /// Automatically generated value for language Kannada. case Kannada = "kn" /// Automatically generated value for language Sardinian. case Sardinian = "sc" /// Automatically generated value for language Guarani. case Guarani = "gn" /// Automatically generated value for language Kazakh. case Kazakh = "kk" /// Automatically generated value for language Yemba. case Yemba = "ybb" /// Automatically generated value for language Taroko. case Taroko = "trv" /// Automatically generated value for language DutchNetherlands. case DutchNetherlands = "nl-NL" /// Automatically generated value for language Achinese. case Achinese = "ace" /// Automatically generated value for language Ganda. case Ganda = "lg" /// Automatically generated value for language Timne. case Timne = "tem" /// Automatically generated value for language Lithuanian. case Lithuanian = "lt" /// Automatically generated value for language Kabardian. case Kabardian = "kbd" /// Automatically generated value for language Samoan. case Samoan = "sm" /// Automatically generated value for language Ladino. case Ladino = "lad" /// Automatically generated value for language Oriya. case Oriya = "or" /// Automatically generated value for language ChineseTraditional. case ChineseTraditional = "zh-Hant" /// Automatically generated value for language Belarusian. case Belarusian = "be" /// Automatically generated value for language Mongolian. case Mongolian = "mn" /// Automatically generated value for language MalayArabic. case MalayArabic = "ms-Arab" /// Automatically generated value for language Tamil. case Tamil = "ta" /// Automatically generated value for language Basque. case Basque = "eu" /// Automatically generated value for language Teso. case Teso = "teo" /// Automatically generated value for language Kikuyu. case Kikuyu = "ki" /// Automatically generated value for language Gujarati. case Gujarati = "gu" /// Automatically generated value for language Zaza. case Zaza = "zza" /// Automatically generated value for language Galician. case Galician = "gl" /// Automatically generated value for language Lezghian. case Lezghian = "lez" /// Automatically generated value for language PortugueseBrazil. case PortugueseBrazil = "pt-BR" /// Automatically generated value for language Maltese. case Maltese = "mt" /// Automatically generated value for language SwissGerman. case SwissGerman = "gsw" /// Automatically generated value for language Zarma. case Zarma = "dje" /// Automatically generated value for language Navajo. case Navajo = "nv" /// Automatically generated value for language Pangasinan. case Pangasinan = "pag" /// Automatically generated value for language PortuguesePortugal. case PortuguesePortugal = "pt-PT" /// Automatically generated value for language Assamese. case Assamese = "as" /// Automatically generated value for language VaiLatin. case VaiLatin = "vai-Latn" /// Automatically generated value for language NʼKo. case NʼKo = "nqo" /// Automatically generated value for language Latvian. case Latvian = "lv" /// Automatically generated value for language Maithili. case Maithili = "mai" /// Automatically generated value for language Nogai. case Nogai = "nog" /// Automatically generated value for language Mirandese. case Mirandese = "mwl" /// Automatically generated value for language Aleut. case Aleut = "ale" /// Automatically generated value for language Haitian. case Haitian = "ht" /// Automatically generated value for language Kako. case Kako = "kkj" /// Automatically generated value for language Scots. case Scots = "sco" /// Automatically generated value for language Urdu. case Urdu = "ur" /// Automatically generated value for language Catalan. case Catalan = "ca" /// Automatically generated value for language NorwegianBokmål. case NorwegianBokmål = "nb" /// Automatically generated value for language Burmese. case Burmese = "my" /// Automatically generated value for language BosnianCyrillic. case BosnianCyrillic = "bs-Cyrl" /// Automatically generated value for language Swati. case Swati = "ss" /// Automatically generated value for language Tuvalu. case Tuvalu = "tvl" /// Automatically generated value for language Afrikaans. case Afrikaans = "af" /// Automatically generated value for language Hungarian. case Hungarian = "hu" /// Automatically generated value for language SpanishMexico. case SpanishMexico = "es-MX" /// Automatically generated value for language Mende. case Mende = "men" /// Automatically generated value for language Corsican. case Corsican = "co" /// Automatically generated value for language Rapanui. case Rapanui = "rap" /// Automatically generated value for language Zulu. case Zulu = "zu" /// Automatically generated value for language Irish. case Irish = "ga" /// Automatically generated value for language Thai. case Thai = "th" /// Automatically generated value for language Shona. case Shona = "sn" /// Automatically generated value for language EnglishCanada. case EnglishCanada = "en-CA" /// Automatically generated value for language Lunda. case Lunda = "lun" /// Automatically generated value for language Hawaiian. case Hawaiian = "haw" /// Automatically generated value for language Aymara. case Aymara = "ay" /// Automatically generated value for language Tetum. case Tetum = "tet" /// Automatically generated value for language UzbekLatin. case UzbekLatin = "uz-Latn" /// Automatically generated value for language Dzongkha. case Dzongkha = "dz" /// Automatically generated value for language MakhuwaMeetto. case MakhuwaMeetto = "mgh" /// Automatically generated value for language Shan. case Shan = "shn" /// Automatically generated value for language NorthernSotho. case NorthernSotho = "nso" /// Automatically generated value for language Dutch. case Dutch = "nl" /// Automatically generated value for language Yiddish. case Yiddish = "yi" /// Automatically generated value for language Arabic. case Arabic = "ar" /// Automatically generated value for language Wolof. case Wolof = "wo" /// Automatically generated value for language Kalenjin. case Kalenjin = "kln" /// Automatically generated value for language Cornish. case Cornish = "kw" /// Automatically generated value for language Cherokee. case Cherokee = "chr" }
mit
e38180eb24cac1bb088cb1da3afeedd7
28.435871
77
0.692975
4.334255
false
false
false
false
ps2/rileylink_ios
MinimedKit/Messages/DataFrameMessageBody.swift
1
2050
// // DataFrameMessageBody.swift // RileyLink // // Created by Pete Schwamb on 5/6/17. // Copyright © 2017 Pete Schwamb. All rights reserved. // import Foundation public class DataFrameMessageBody: CarelinkLongMessageBody { public let isLastFrame: Bool public let frameNumber: Int public let contents: Data public required init?(rxData: Data) { guard rxData.count == type(of: self).length else { return nil } self.isLastFrame = rxData[0] & 0b1000_0000 != 0 self.frameNumber = Int(rxData[0] & 0b0111_1111) self.contents = rxData.subdata(in: (1..<rxData.count)) super.init(rxData: rxData) } init(frameNumber: Int, isLastFrame: Bool, contents: Data) { self.frameNumber = frameNumber self.isLastFrame = isLastFrame self.contents = contents super.init(rxData: Data())! } public override var txData: Data { var byte0 = UInt8(frameNumber) if isLastFrame { byte0 |= 0b1000_0000 } var data = Data([byte0]) data.append(contents) return data } } extension DataFrameMessageBody { public static func dataFramesFromContents(_ contents: Data) -> [DataFrameMessageBody] { var frames = [DataFrameMessageBody]() let frameContentsSize = DataFrameMessageBody.length - 1 for frameNumber in sequence(first: 0, next: { $0 + 1 }) { let startIndex = frameNumber * frameContentsSize var endIndex = startIndex + frameContentsSize var isLastFrame = false if endIndex >= contents.count { isLastFrame = true endIndex = contents.count } frames.append(DataFrameMessageBody( frameNumber: frameNumber + 1, isLastFrame: isLastFrame, contents: contents[startIndex..<endIndex] )) if isLastFrame { break } } return frames } }
mit
f7e078665c23a757900477cf3f177c49
25.269231
91
0.589556
4.678082
false
false
false
false
gerardogrisolini/Webretail
Sources/Webretail/Repositories/BrandRepository.swift
1
1746
// // BrandRepository.swift // PerfectTurnstilePostgreSQLDemo // // Created by Gerardo Grisolini on 16/02/17. // // import StORM struct BrandRepository : BrandProtocol { func getAll() throws -> [Brand] { let items = Brand() try items.query(orderby: ["brandId"]) return items.rows() } func get(id: Int) throws -> Brand? { let item = Brand() try item.query(id: id) return item } func add(item: Brand) throws { if (item.brandSeo.permalink.isEmpty) { item.brandSeo.permalink = item.brandName.permalink() } item.brandSeo.description = item.brandSeo.description.filter({ !$0.value.isEmpty }) item.brandDescription = item.brandDescription.filter({ !$0.value.isEmpty }) item.brandCreated = Int.now() item.brandUpdated = Int.now() try item.save { id in item.brandId = id as! Int } } func update(id: Int, item: Brand) throws { guard let current = try get(id: id) else { throw StORMError.noRecordFound } current.brandName = item.brandName if (item.brandSeo.permalink.isEmpty) { item.brandSeo.permalink = item.brandName.permalink() } current.brandSeo.description = item.brandSeo.description.filter({ !$0.value.isEmpty }) current.brandDescription = item.brandDescription.filter({ !$0.value.isEmpty }) current.brandMedia = item.brandMedia current.brandSeo = item.brandSeo current.brandUpdated = Int.now() try current.save() } func delete(id: Int) throws { let item = Brand() item.brandId = id try item.delete() } }
apache-2.0
945640ba2b208e03833209c062f145bb
27.16129
94
0.593356
3.90604
false
false
false
false
809848367/CHTCollectionViewWaterfallLayout
SwiftDemo/CHTWaterfallSwiftDemo/CHTWaterfallSwiftDemo/ViewController.swift
8
3286
// // ViewController.swift // CHTWaterfallSwift // // Created by Sophie Fader on 3/21/15. // Copyright (c) 2015 Sophie Fader. All rights reserved. // import UIKit class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, CHTCollectionViewDelegateWaterfallLayout { @IBOutlet weak var collectionView: UICollectionView! let model = Model() //MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() model.buildDataSource() // Attach datasource and delegate self.collectionView.dataSource = self self.collectionView.delegate = self //Layout setup setupCollectionView() //Register nibs registerNibs() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - CollectionView UI Setup func setupCollectionView(){ // Create a waterfall layout var layout = CHTCollectionViewWaterfallLayout() // Change individual layout attributes for the spacing between cells layout.minimumColumnSpacing = 1.0 layout.minimumInteritemSpacing = 1.0 // Collection view attributes self.collectionView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth self.collectionView.alwaysBounceVertical = true // Add the waterfall layout to your collection view self.collectionView.collectionViewLayout = layout } // Register CollectionView Nibs func registerNibs(){ // attach the UI nib file for the ImageUICollectionViewCell to the collectionview var viewNib = UINib(nibName: "ImageUICollectionViewCell", bundle: nil) collectionView.registerNib(viewNib, forCellWithReuseIdentifier: "cell") } //MARK: - CollectionView Delegate Methods //** Number of Cells in the CollectionView */ func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return model.images.count } //** Create a basic CollectionView Cell */ func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // Create the cell and return the cell var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! ImageUICollectionViewCell // Add image to cell cell.image.image = model.images[indexPath.row] return cell } //MARK: - CollectionView Waterfall Layout Delegate Methods (Required) //** Size for the cells in the Waterfall Layout */ func collectionView(collectionView: UICollectionView!, layout collectionViewLayout: UICollectionViewLayout!, sizeForItemAtIndexPath indexPath: NSIndexPath!) -> CGSize { // create a cell size from the image size, and return the size let imageSize = model.images[indexPath.row].size return imageSize } }
mit
3f1b7b4b401b7a5fdf72205f2b6ece5c
30.902913
172
0.663421
6.018315
false
false
false
false
russbishop/swift
stdlib/public/core/ArrayCast.swift
1
7142
//===--- ArrayCast.swift - Casts and conversions for Array ----------------===// // // 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 // //===----------------------------------------------------------------------===// // // Because NSArray is effectively an [AnyObject], casting [T] -> [U] // is an integral part of the bridging process and these two issues // are handled together. // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) // FIXME: These need to be implemented even for non-objc: // rdar://problem/18881196 internal enum _ValueOrReference { case reference, value internal init<T>(_: T.Type) { self = _isClassOrObjCExistential(T.self) ? .reference : .value } } internal enum _BridgeStyle { case verbatim, explicit internal init<T>(_: T.Type) { self = _isBridgedVerbatimToObjectiveC(T.self) ? .verbatim : .explicit } } //===--- Forced casts: [T] as! [U] ----------------------------------------===// /// Implements `source as! [TargetElement]`. /// /// - Precondition: At least one of `SourceElement` and `TargetElement` is a /// class type or ObjC existential. May trap for other "valid" inputs when /// `TargetElement` is not bridged verbatim, if an element can't be converted. public func _arrayForceCast<SourceElement, TargetElement>( _ source: Array<SourceElement> ) -> Array<TargetElement> { switch ( _ValueOrReference(SourceElement.self), _BridgeStyle(TargetElement.self) ) { case (.reference, .verbatim): let native = source._buffer.requestNativeBuffer() if _fastPath(native != nil) { if _fastPath(native!.storesOnlyElementsOfType(TargetElement.self)) { // A native buffer that is known to store only elements of the // TargetElement can be used directly return Array(_buffer: source._buffer.cast(toBufferOf: TargetElement.self)) } // Other native buffers must use deferred element type checking return Array(_buffer: source._buffer.downcast( toBufferWithDeferredTypeCheckOf: TargetElement.self)) } // All non-native buffers use deferred element typechecking return Array(_immutableCocoaArray: source._buffer._asCocoaArray()) case (.reference, .explicit): let result: [TargetElement]? = _arrayConditionalBridgeElements(source) _precondition(result != nil, "array cannot be bridged from Objective-C") return result! case (.value, .verbatim): if source.isEmpty { return Array() } var buf = _ContiguousArrayBuffer<TargetElement>( uninitializedCount: source.count, minimumCapacity: 0) let _: Void = buf.withUnsafeMutableBufferPointer { var p = $0.baseAddress! for value in source { let bridged: AnyObject? = _bridgeToObjectiveC(value) _precondition( bridged != nil, "array element cannot be bridged to Objective-C") // FIXME: should be an unsafeDowncast. p.initialize(with: unsafeBitCast(bridged!, to: TargetElement.self)) p += 1 } } return Array(_buffer: _ArrayBuffer(buf, shiftedToStartIndex: 0)) case (.value, .explicit): _sanityCheckFailure( "Force-casting between Arrays of value types not prevented at compile-time" ) } } //===--- Conditional casts: [T] as? [U] -----------------------------------===// /// Implements the semantics of `x as? [TargetElement]` where `x` has type /// `[SourceElement]` and `TargetElement` is a verbatim-bridged trivial subtype of /// `SourceElement`. /// /// Returns an Array<TargetElement> containing the same elements as a /// /// O(1) if a's buffer elements are dynamically known to have type /// TargetElement or a type derived from TargetElement. O(N) /// otherwise. internal func _arrayConditionalDownCastElements<SourceElement, TargetElement>( _ a: Array<SourceElement> ) -> [TargetElement]? { _sanityCheck(_isBridgedVerbatimToObjectiveC(SourceElement.self)) _sanityCheck(_isBridgedVerbatimToObjectiveC(TargetElement.self)) if _fastPath(!a.isEmpty) { let native = a._buffer.requestNativeBuffer() if _fastPath(native != nil) { if native!.storesOnlyElementsOfType(TargetElement.self) { return Array(_buffer: a._buffer.cast(toBufferOf: TargetElement.self)) } return nil } // slow path: we store an NSArray // We can skip the check if TargetElement happens to be AnyObject if !(AnyObject.self is TargetElement.Type) { for element in a { if !(element is TargetElement) { return nil } } } return Array(_buffer: a._buffer.cast(toBufferOf: TargetElement.self)) } return [] } /// Try to convert the source array of objects to an array of values /// produced by bridging the objects from Objective-C to `TargetElement`. /// /// - Precondition: SourceElement is a class type. /// - Precondition: TargetElement is bridged non-verbatim to Objective-C. /// O(n), because each element must be bridged separately. internal func _arrayConditionalBridgeElements<SourceElement, TargetElement>( _ source: Array<SourceElement> ) -> Array<TargetElement>? { _sanityCheck(_isBridgedVerbatimToObjectiveC(SourceElement.self)) _sanityCheck(!_isBridgedVerbatimToObjectiveC(TargetElement.self)) let buf = _ContiguousArrayBuffer<TargetElement>( uninitializedCount: source.count, minimumCapacity: 0) var p = buf.firstElementAddress ElementwiseBridging: repeat { for object: SourceElement in source { let value = Swift._conditionallyBridgeFromObjectiveC( unsafeBitCast(object, to: AnyObject.self), TargetElement.self) if _slowPath(value == nil) { break ElementwiseBridging } p.initialize(with: value!) p += 1 } return Array(_buffer: _ArrayBuffer(buf, shiftedToStartIndex: 0)) } while false // Don't destroy anything we never created. buf.count = p - buf.firstElementAddress // Report failure return nil } /// Implements `source as? [TargetElement]`: convert each element of /// `source` to a `TargetElement` and return the resulting array, or /// return `nil` if any element fails to convert. /// /// - Precondition: `SourceElement` is a class or ObjC existential type. /// O(n), because each element must be checked. public func _arrayConditionalCast<SourceElement, TargetElement>( _ source: [SourceElement] ) -> [TargetElement]? { switch (_ValueOrReference(SourceElement.self), _BridgeStyle(TargetElement.self)) { case (.value, _): _sanityCheckFailure( "Conditional cast from array of value types not prevented at compile-time") case (.reference, .verbatim): return _arrayConditionalDownCastElements(source) case (.reference, .explicit): return _arrayConditionalBridgeElements(source) } } #endif
apache-2.0
9350ffbb4022eeb2a04800d8f70ee33a
34.356436
84
0.66732
4.411365
false
false
false
false
lucianomarisi/LoadIt
Sources/LoadIt/Convenience Types/Services/NetworkJSONResourceService.swift
1
3002
// // NetworkJSONResourceService.swift // LoadIt // // Created by Luciano Marisi on 25/06/2016. // Copyright © 2016 Luciano Marisi. All rights reserved. // import Foundation /** Enum representing an error from a network service - CouldNotCreateURLRequest: The URL request could be formed - StatusCodeError: A status code error between 400 and 600 (not including 600) was returned - NetworkingError: Any other networking error - NoData: No data was returned */ public enum NetworkServiceError: ErrorType { case CouldNotCreateURLRequest case StatusCodeError(statusCode: Int) case NetworkingError(error: NSError) case NoData } public class NetworkJSONResourceService<Resource: NetworkJSONResourceType>: ResourceServiceType { /** Method designed to be implemented on subclasses, these fields will be overriden by any HTTP header field key that is defined in the resource (in case of conflicts) - returns: Return any additional header fields that need to be added to the url request */ public func additionalHeaderFields() -> [String: String] { return [:] } let session: URLSessionType public required init() { self.session = NSURLSession.sharedSession() } init(session: URLSessionType) { self.session = session } public final func fetch(resource resource: Resource, completion: (Result<Resource.Model>) -> Void) { guard let urlRequest = resource.urlRequest() as? NSMutableURLRequest else { completion(.Failure(NetworkServiceError.CouldNotCreateURLRequest)) return } urlRequest.allHTTPHeaderFields = allHTTPHeaderFields(resourceHTTPHeaderFields: urlRequest.allHTTPHeaderFields) session.perform(request: urlRequest) { (data, URLResponse, error) in completion(self.resultFrom(resource: resource, data: data, URLResponse: URLResponse, error: error)) } } private func allHTTPHeaderFields(resourceHTTPHeaderFields resourceHTTPHeaderFields: [String: String]?) -> [String: String]? { var generalHTTPHeaderFields = additionalHeaderFields() if let resourceHTTPHeaderFields = resourceHTTPHeaderFields { for (key, value) in resourceHTTPHeaderFields { generalHTTPHeaderFields[key] = value } } return generalHTTPHeaderFields } private func resultFrom(resource resource: Resource, data: NSData?, URLResponse: NSURLResponse?, error: NSError?) -> Result<Resource.Model> { if let HTTPURLResponse = URLResponse as? NSHTTPURLResponse { switch HTTPURLResponse.statusCode { case 400..<600: return .Failure(NetworkServiceError.StatusCodeError(statusCode: HTTPURLResponse.statusCode)) default: break } } if let error = error { return .Failure(NetworkServiceError.NetworkingError(error: error)) } guard let data = data else { return .Failure(NetworkServiceError.NoData) } return resource.resultFrom(data: data) } }
mit
127431f0b668be6ef1566d3ab512ab42
31.619565
143
0.716095
4.952145
false
false
false
false
mownier/photostream
Photostream/UI/Comments/CommentFeedViewController.swift
1
5282
// // CommentFeedViewController.swift // Photostream // // Created by Mounir Ybanez on 23/08/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // import UIKit @objc protocol CommentFeedViewControllerAction: class { func back() func triggerRefresh() } class CommentFeedViewController: UITableViewController, CommentFeedViewControllerAction { var presenter: CommentFeedModuleInterface! var indicatorView: UIActivityIndicatorView! var emptyView: CommentFeedEmptyView! var refreshView: UIRefreshControl! var shouldShowInitialLoadView: Bool = false { didSet { guard oldValue != shouldShowInitialLoadView else { return } if shouldShowInitialLoadView { tableView.backgroundView = indicatorView indicatorView.startAnimating() } else { indicatorView.stopAnimating() tableView.backgroundView = nil } } } var shouldShowEmptyView: Bool = false { didSet { guard oldValue != shouldShowEmptyView else { return } if shouldShowEmptyView { emptyView.frame.size = tableView.bounds.size tableView.backgroundView = emptyView } else { tableView.backgroundView = nil } } } var shouldShowRefreshView: Bool = false { didSet { if refreshView.superview == nil { tableView.addSubview(refreshView) } guard oldValue != shouldShowRefreshView else { return } if shouldShowRefreshView { refreshView.beginRefreshing() } else { refreshView.endRefreshing() } } } var prototype = CommentListCell() override func loadView() { super.loadView() refreshView = UIRefreshControl() refreshView.addTarget(self, action: #selector(self.triggerRefresh), for: .valueChanged) indicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray) indicatorView.hidesWhenStopped = true emptyView = CommentFeedEmptyView() emptyView.messageLabel.text = "No comments" tableView.tableHeaderView = UIView() tableView.tableFooterView = UIView() tableView.allowsSelection = false tableView.separatorStyle = .none CommentListCell.register(in: tableView) title = "Comments" let barItem = UIBarButtonItem(image: #imageLiteral(resourceName: "back_nav_icon"), style: .plain, target: self, action: #selector(self.back)) navigationItem.leftBarButtonItem = barItem } override func viewDidLoad() { super.viewDidLoad() presenter.refreshComments() } func back() { presenter.exit() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return presenter.commentCount } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = CommentListCell.dequeue(from: tableView)! let comment = presenter.comment(at: indexPath.row) as? CommentListCellItem cell.configure(with: comment) cell.delegate = self return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let comment = presenter.comment(at: indexPath.row) as? CommentListCellItem prototype.configure(with: comment, isPrototype: true) return prototype.dynamicHeight } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath.row == presenter.commentCount - 10 { presenter.loadMoreComments() } } func triggerRefresh() { presenter.refreshComments() } } extension CommentFeedViewController: CommentFeedScene { var controller: UIViewController? { return self } func reload() { tableView.reloadData() } func showEmptyView() { shouldShowEmptyView = true } func showInitialLoadView() { shouldShowInitialLoadView = true } func showRefreshView() { shouldShowRefreshView = true } func hideEmptyView() { shouldShowEmptyView = false } func hideInitialLoadView() { shouldShowInitialLoadView = false } func hideRefreshView() { shouldShowRefreshView = false } func didRefreshComments(with error: String?) { } func didLoadMoreComments(with error: String?) { } } extension CommentFeedViewController: CommentListCellDelegate { func didTapAuthor(cell: CommentListCell) { guard let index = tableView.indexPath(for: cell)?.row else { return } presenter.presentUserTimeline(at: index) } }
mit
c88eb97eb0807b6b32745c87bd30acac
26.505208
149
0.602348
5.79057
false
false
false
false
mark-breen/Tennis-Refactoring-Kata
swift/Tennis/TennisGame1.swift
3
1917
import Foundation class TennisGame1: TennisGame { private let player1: String private let player2: String private var score1: Int private var score2: Int required init(player1: String, player2: String) { self.player1 = player1 self.player2 = player2 self.score1 = 0 self.score2 = 0 } func wonPoint(_ playerName: String) { if playerName == "player1" { score1 += 1 } else { score2 += 1 } } var score: String? { var score = "" var tempScore = 0 if score1 == score2 { switch score1 { case 0: score = "Love-All" case 1: score = "Fifteen-All" case 2: score = "Thirty-All" default: score = "Deuce" } } else if score1>=4 || score2>=4 { let minusResult = score1-score2 if minusResult==1 { score = "Advantage player1" } else if minusResult == -1 { score = "Advantage player2" } else if minusResult>=2 { score = "Win for player1" } else { score = "Win for player2" } } else { for i in 1..<3 { if i==1 { tempScore = score1 } else { score = "\(score)-"; tempScore = score2 } switch tempScore { case 0: score = "\(score)Love" case 1: score = "\(score)Fifteen" case 2: score = "\(score)Thirty" case 3: score = "\(score)Forty" default: break } } } return score } }
mit
b8332839af4e98a7b3715017f479b21c
22.096386
70
0.406364
4.608173
false
false
false
false
kouky/MavlinkPrimaryFlightDisplay
Sources/iOS/HomeViewController.swift
1
4724
// // HomeViewController.swift // MavlinkPrimaryFlightDisplay-iOS // // Created by Michael Koukoullis on 26/03/2016. // Copyright © 2016 Michael Koukoullis. All rights reserved. // import UIKit import ReactiveMavlink import ReactiveCocoa import PrimaryFlightDisplay import CoreBluetooth import SpriteKit typealias BLEScanner = () -> () typealias BLEConnector = CBPeripheral -> () class HomeViewController: UIViewController { @IBOutlet weak var containerView: UIView! @IBOutlet weak var scanButton: UIButton! private let ble = BLE() private let reactiveMavlink = ReactiveMavlink() private let peripherals = MutableProperty([CBPeripheral]()) private var bleScanner: BLEScanner { return { [weak self] in guard let `self` = self else { return } if case .PoweredOn = self.ble.state { self.ble.startScanning(10) } } } private var bleConnector: BLEConnector { return { [weak self] peripheral in guard let `self` = self else { return } if case .PoweredOn = self.ble.state { self.ble.connectToPeripheral(peripheral) } } } override func viewDidLoad() { super.viewDidLoad() var settings = iPadSettings() if case .Phone = UIDevice.currentDevice().userInterfaceIdiom { settings = iPhoneSettings() } let flightView = PrimaryFlightDisplayView(frame: containerView.frame, settings: settings) flightView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] containerView.addSubview(flightView) ble.delegate = self scanButton.layer.cornerRadius = 4 reactiveMavlink.headUpDisplay.observeNext { [weak flightView] hud in flightView?.setHeadingDegree(Double(hud.heading)) flightView?.setAirSpeed(Double(hud.airSpeed)) flightView?.setAltitude(Double(hud.altitude)) } reactiveMavlink.attitude.observeNext { [weak flightView] attitude in flightView?.setAttitude(rollRadians: Double(attitude.roll), pitchRadians: Double(attitude.pitch)) } } override func prefersStatusBarHidden() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return [.Landscape] } @IBAction func scanButtonTapped(sender: UIButton) { let scanViewController = ScanViewController(producer: peripherals.producer, scanner: bleScanner, connector: bleConnector) let navViewConroller = UINavigationController(rootViewController: scanViewController) presentViewController(navViewConroller, animated: true, completion: nil) } deinit { ble.delegate = nil ble.disconnectActivePeripheral() } } extension HomeViewController: BLEDelegate { func bleDidDiscoverPeripherals() { self.peripherals.value = ble.peripherals } func bleDidConnectToPeripheral() { // Noop } func bleDidReceiveData(data: NSData?) { if let data = data { reactiveMavlink.receiveData(data) } } func bleDidDisconenctFromPeripheral() { // Noop } func bleDidDicoverCharacateristics() { ble.setBaudRate(.Bps57600) } } private func iPhoneSettings() -> SettingsType { var settings = DefaultSmallScreenSettings() let pinkColor = SKColor(red:1.00, green:0.11, blue:0.56, alpha:1.0) settings.horizon.groundColor = SKColor.brownColor() settings.attitudeReferenceIndex.fillColor = pinkColor settings.bankIndicator.skyPointerFillColor = pinkColor settings.bankIndicator.arcMaximumDisplayDegree = 75 return settings } private func iPadSettings() -> SettingsType { var settings = DefaultSettings() let pinkColor = SKColor(red:1.00, green:0.11, blue:0.56, alpha:1.0) settings.horizon.groundColor = SKColor.brownColor() settings.bankIndicator.skyPointerFillColor = pinkColor settings.bankIndicator.arcMaximumDisplayDegree = 75 settings.bankIndicator.arcRadius = 160 settings.attitudeReferenceIndex.fillColor = pinkColor settings.attitudeReferenceIndex.sideBarWidth = 80 settings.attitudeReferenceIndex.sideBarHeight = 15 settings.headingIndicator.pointsPerUnitValue = 10 settings.headingIndicator.size.width = 1060 settings.headingIndicator.size.height = 40 settings.headingIndicator.markerTextOffset = 15 settings.headingIndicator.minorMarkerFrequency = 1 settings.headingIndicator.majorMarkerFrequency = 10 return settings }
mit
9a1e0f5aed145e8e83f9e4857d0c16c5
31.129252
129
0.677535
4.751509
false
false
false
false
sarvex/SwiftRecepies
FileManagement/Writing to and Reading from Files/Writing to and Reading from Files/AppDelegate.swift
1
4153
// // AppDelegate.swift // Writing to and Reading from Files // // Created by Vandad Nahavandipoor on 6/20/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func example1(){ let someText = NSString(string: "Put some string here") let destinationPath = NSTemporaryDirectory() + "MyFile.txt" var error:NSError? let written = someText.writeToFile(destinationPath, atomically: true, encoding: NSUTF8StringEncoding, error: &error) if written{ println("Successfully stored the file at path \(destinationPath)") } else { if let errorValue = error{ println("An error occurred: \(errorValue)") } } } func example2(){ var error:NSError? let path = NSTemporaryDirectory() + "MyFile.txt" let succeeded = "Hello, World!".writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: &error) if (succeeded){ /* Now read from the same file */ let readString = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as! String println("The read string is: \(readString)") } else { if let theError = error{ println("Could not write. Error = \(theError)") } } } func example3(){ let path = NSTemporaryDirectory() + "MyFile.txt" let arrayOfNames:NSArray = ["Steve", "John", "Edward"] if arrayOfNames.writeToFile(path, atomically: true){ let readArray:NSArray? = NSArray(contentsOfFile: path) if let array = readArray{ println("Could read the array back = \(array)") } else { println("Failed to read the array back") } } } func example4(){ let path = NSTemporaryDirectory() + "MyFile.txt" let dict:NSDictionary = [ "first name" : "Steven", "middle name" : "Paul", "last name" : "Jobs", ] if dict.writeToFile(path, atomically: true){ let readDict:NSDictionary? = NSDictionary(contentsOfFile: path) if let dict = readDict{ println("Read the dictionary back from disk = \(dict)") } else { println("Failed to read the dictionary back from disk") } } else { println("Failed to write the dictionary to disk") } } func example5(){ let path = NSTemporaryDirectory() + "MyFile.txt" let chars = [CUnsignedChar(ascii: "a"), CUnsignedChar(ascii: "b")] let data = NSData(bytes: chars, length: 2) if data.writeToFile(path, atomically: true){ println("Wrote the data") let readData = NSData(contentsOfFile: path) if readData!.isEqualToData(data){ println("Read the same data") } else { println("Not the same data") } } else { println("Could not write the data") } } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { example5() self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // Override point for customization after application launch. self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() return true } }
isc
1340224674edb8e3f767323a523127be
28.453901
126
0.644835
4.357817
false
false
false
false
mbeloded/beaconDemo
PassKitApp/PassKitApp/Classes/UI/MainMenu/MainMenuView.swift
1
2721
// // MainMenuView.swift // PassKitApp // // Created by Alexandr Chernyy on 10/3/14. // Copyright (c) 2014 Alexandr Chernyy. All rights reserved. // import UIKit let cellIdent = "MainCellID" class MainMenuView: UIView, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! var selectedIndex:Int = 0 var items:Array<AnyObject> = [] var owner:UIViewController! var category_id:String! func setupView() { items = CoreDataManager.sharedManager.loadData(RequestType.CATEGORY) collectionView.reloadData() } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdent, forIndexPath: indexPath) as MainCollectionViewCell cell.backgroundColor = UIColor.clearColor() var category = items[indexPath.row] as CategoryModel cell.category = category cell.nameLabel.text = (items[indexPath.row] as CategoryModel).name return cell } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 1.0 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return 1.0 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(0, 0, 0, 0) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSizeMake(self.frame.size.width/3 - 3 , self.frame.size.width/3 - 3) } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { selectedIndex = indexPath.row var category = items[indexPath.row] as CategoryModel category_id = category.id owner?.performSegueWithIdentifier("showCategory", sender: owner) } }
gpl-2.0
95f6261d279a1e3f929063a779aa023a
33.443038
134
0.711136
5.656965
false
false
false
false
jasl/MoyaX
Sources/Response.swift
2
1615
import Foundation /// Used to store all response data returned from a completed request. public struct Response: CustomDebugStringConvertible { public let response: NSURLResponse? public let statusCode: Int public let data: NSData public lazy var responseClass: ResponseStatus = { return ResponseStatus(statusCode: self.statusCode) }() public init(statusCode: Int, data: NSData, response: NSURLResponse? = nil) { self.statusCode = statusCode self.data = data self.response = response } public var description: String { return "Status Code: \(statusCode), Data Length: \(data.length)" } public var debugDescription: String { return description } } /** The category for response status code - informational: status code in 100 to 199 - success: status code in 200 to 299 - redirection: status code in 300 to 399 - clientError: status code in 400 to 499 - serverError: status code in 500 to 599 - undefined: other status code */ public enum ResponseStatus { case informational case success case redirection case clientError case serverError case undefined public init(statusCode: Int) { switch statusCode { case 100 ..< 200: self = .informational case 200 ..< 300: self = .success case 300 ..< 400: self = .redirection case 400 ..< 500: self = .clientError case 500 ..< 600: self = .serverError default: self = .undefined } } }
mit
97f431267a7d045b7dcfe208efe0d84f
24.634921
80
0.624149
5.031153
false
false
false
false
kadarandras/KAAuthenticationManager
KAAuthenticationManager.swift
1
12197
// // AuthenticationManager.swift // cfo // // Created by Andras Kadar on 2015. 10. 28.. // Copyright (c) 2015. Inceptech. All rights reserved. // import UIKit public protocol KAAuthenticationManagerDelegate: class { func showLogin() func showLicence() func serverLogin(email: String, password: String, loginCompletionHandler: (KAAuthenticationManager.LoginResult -> Void)) func forgotPassword(email: String, forgotCompletionHandler: (() -> Void)) } public extension KAAuthenticationManagerDelegate where Self: UIViewController { func showLogin() { KAAuthenticationManager.sharedInstance.showLogin(fromViewController: self) } } public extension KAAuthenticationManagerDelegate { func showLicence() { } func forgotPassword(email: String, forgotCompletionHandler: (() -> Void)) { } } public class KAAuthenticationManager: NSObject { public enum LoginResult { case IncorrectFormatNoPassword case IncorrectFormatTooShortPassword case IncorrectFormatWrongEmailFormat case NoInternetConnection case ServerNotReachable case WrongCredentials case UnknownError(errorMessage: String?) case SuccessfulLogin static var formatErrorTypes: [LoginResult] { return [.IncorrectFormatNoPassword, .IncorrectFormatTooShortPassword, .IncorrectFormatWrongEmailFormat] } var key: String { switch self { case IncorrectFormatNoPassword: return "login.result.error.incorrectformat.nopassword" case IncorrectFormatTooShortPassword: return "login.result.error.incorrectformat.tooshortpassword" case IncorrectFormatWrongEmailFormat: return "login.result.error.incorrectformat.wrongemailformat" case NoInternetConnection: return "login.result.error.nointernetconnection" case ServerNotReachable: return "login.result.error.servernotreachable" case WrongCredentials: return "login.result.error.wrongcredentials" case SuccessfulLogin: return "login.result.success" case UnknownError(_): return "" } } var title: String { if case .UnknownError(_) = self { return "login.result.error.unknown.title".localizedString } return "\(key).title".localizedString } var message: String { if case .UnknownError(let message) = self { return message ?? "login.result.error.unknown.message".localizedString } return "\(key).message".localizedString } var buttons: [String] { switch self { case .WrongCredentials: return [ "login.result.button.forgotpassword".localizedString ] default: return [] } } var success: Bool { if case LoginResult.SuccessfulLogin = self { return true } return false } } public static let sharedInstance : KAAuthenticationManager = KAAuthenticationManager() override init() { super.init() NSUserDefaults.standardUserDefaults().registerDefaults([ firstLoginKey: false ]) } public weak var delegate: KAAuthenticationManagerDelegate? public var supportForgetPassword: Bool = true public var minimumPasswordLength: Int = 6 private var visibleResult: LoginResult? { didSet { if visibleResult == nil { visibleEmail = nil } } } private var visibleEmail: String? private var dismissCallback: (() -> Void)? private let firstLoginKey: String = "ka.authenticationmanager.firstlogin" private var firstLogin: Bool { get { return NSUserDefaults.standardUserDefaults().boolForKey(firstLoginKey) } set { NSUserDefaults.standardUserDefaults().setBool(newValue, forKey: firstLoginKey) NSUserDefaults.standardUserDefaults().synchronize() } } public func show() { } public func checkLoginInput( email: String, password: String, serverLoginBlock: ((loginCompletionHandler: (LoginResult -> Void)) -> Void)? = nil, resultBlock: ((LoginResult) -> Bool)) -> Bool { if visibleEmail != nil { return false } visibleEmail = email let handleLoginResult = { (result: LoginResult) -> Void in if resultBlock(result) { // If returned true, show alert self.showError(forResultType: result) self.visibleResult = result } else { self.visibleResult = nil } } // Check format for formatErrorType in LoginResult.formatErrorTypes { if hasFormatError(inEmail: email, password: password, forResultType: formatErrorType) { handleLoginResult(formatErrorType) return false } } if !Reachability.isConnectedToNetwork() { // No internet connection handleLoginResult(LoginResult.NoInternetConnection) return false } // Try to log in let loginCompletion = { (result: LoginResult) -> Void in handleLoginResult(result) // Check success & first login if result.success && self.firstLogin { self.delegate?.showLicence() self.firstLogin = false } } if let serverLoginBlock = serverLoginBlock { serverLoginBlock(loginCompletionHandler: loginCompletion) } else { delegate?.serverLogin( email, password: password, loginCompletionHandler: loginCompletion ) } return true } private func hasFormatError(inEmail email: String, password: String, forResultType result: LoginResult) -> Bool { switch result { case .IncorrectFormatNoPassword: return password.characters.count == 0 case .IncorrectFormatTooShortPassword: return password.characters.count < minimumPasswordLength case .IncorrectFormatWrongEmailFormat: return !email.isValidEmail default: return false } } private func showError(forResultType result: LoginResult) { let alertView = UIAlertView( title: result.title, message: result.message, delegate: self, cancelButtonTitle: "login.result.button.ok".localizedString) for button in result.buttons { alertView.addButtonWithTitle(button) } alertView.show() } public func showLogin(fromViewController viewController: UIViewController) { let loginController = UIAlertController( title: "login.title".localizedString, message: "login.message".localizedString, preferredStyle: UIAlertControllerStyle.Alert) var emailTextField: UITextField! var passwordTextField: UITextField! loginController.addTextFieldWithConfigurationHandler { (textField) -> Void in textField.placeholder = "login.email.placeholder".localizedString emailTextField = textField } loginController.addTextFieldWithConfigurationHandler { (textField) -> Void in textField.placeholder = "login.password.placeholder".localizedString textField.secureTextEntry = true passwordTextField = textField } loginController.addAction( UIAlertAction( title: "login.button.login".localizedString, style: UIAlertActionStyle.Default, handler: { (action) -> Void in self.checkLoginInput(emailTextField.text!, password: passwordTextField.text!, resultBlock: { (loginResult) -> Bool in if !loginResult.success { self.dismissCallback = { viewController.presentViewController(loginController, animated: true, completion: nil) } return true } return false }) return }) ) if supportForgetPassword { loginController.addAction(UIAlertAction( title: "login.button.forgetpassword".localizedString, style: UIAlertActionStyle.Destructive, handler: { (action) -> Void in if self.hasFormatError(inEmail: emailTextField.text ?? "", password: passwordTextField.text ?? "", forResultType: .IncorrectFormatWrongEmailFormat) { self.dismissCallback = { viewController.presentViewController(loginController, animated: true, completion: nil) } self.showError(forResultType: .IncorrectFormatWrongEmailFormat) } else { self.delegate?.forgotPassword(emailTextField.text!, forgotCompletionHandler: { () -> Void in }) } return })) } viewController.presentViewController(loginController, animated: true, completion: nil) } } extension KAAuthenticationManager: UIAlertViewDelegate { public func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) { if let result = visibleResult where buttonIndex != alertView.cancelButtonIndex { if case .WrongCredentials = result { } } else { self.dismissCallback?() self.dismissCallback = nil } visibleResult = nil } } private extension String { var isValidEmail: Bool { let emailRegEx = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluateWithObject(self) } } public var PodBundle: NSBundle = { if let path = NSBundle(forClass: KAAuthenticationManager.self) .pathForResource("KAAuthenticationManager", ofType: "bundle"), let bundle = NSBundle(path: path) { return bundle } return NSBundle.mainBundle() }() private extension String { var localizedString: String { return NSLocalizedString(self, tableName: "Localizable", bundle: PodBundle, value: "", comment: "") } } import SystemConfiguration public class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) } var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) { return false } let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) } }
mit
a69da037bcbb5b33189782c9231225a6
34.768328
169
0.582356
5.794299
false
false
false
false
ttlock/iOS_TTLock_Demo
Pods/iOSDFULibrary/iOSDFULibrary/Classes/Utilities/DFUPackage/Manifest/Manifest.swift
2
2300
// // Manifest.swift // Pods // // Created by Mostafa Berg on 28/07/16. // // import Foundation class Manifest: NSObject { var application: ManifestFirmwareInfo? var softdevice: ManifestFirmwareInfo? var bootloader: ManifestFirmwareInfo? var softdeviceBootloader: SoftdeviceBootloaderInfo? var valid: Bool { // The manifest.json file may specify only: // 1. a softdevice, a bootloader, or both combined (with, or without an app) // 2. only the app let hasApplication = application != nil var count = 0 count += softdevice != nil ? 1 : 0 count += bootloader != nil ? 1 : 0 count += softdeviceBootloader != nil ? 1 : 0 return count == 1 || (count == 0 && hasApplication) } init(withJsonString aString : String) { do { let data = aString.data(using: String.Encoding.utf8) let aDictionary = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! Dictionary<String, AnyObject> let mainObject = aDictionary["manifest"] as! Dictionary<String, AnyObject> if mainObject.keys.contains("application") { let dictionary = mainObject["application"] as? Dictionary<String, AnyObject> self.application = ManifestFirmwareInfo(withDictionary: dictionary!) } if mainObject.keys.contains("softdevice_bootloader") { let dictionary = mainObject["softdevice_bootloader"] as? Dictionary<String, AnyObject> self.softdeviceBootloader = SoftdeviceBootloaderInfo(withDictionary: dictionary!) } if mainObject.keys.contains("softdevice"){ let dictionary = mainObject["softdevice"] as? Dictionary<String, AnyObject> self.softdevice = ManifestFirmwareInfo(withDictionary: dictionary!) } if mainObject.keys.contains("bootloader"){ let dictionary = mainObject["bootloader"] as? Dictionary<String, AnyObject> self.bootloader = ManifestFirmwareInfo(withDictionary: dictionary!) } } catch { print("an error occured while parsing manifest.json \(error)") } } }
mit
87ef7a0d8f047772de5e0b402b45a4a1
39.350877
135
0.614348
4.883227
false
false
false
false
tsolomko/SWCompression
Sources/Common/Container/Permissions.swift
1
1505
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation /// Represents file access permissions in UNIX format. public struct Permissions: OptionSet { /// Raw bit flags value (in decimal). public let rawValue: UInt32 /// Initializes permissions with bit flags in decimal. public init(rawValue: UInt32) { self.rawValue = rawValue } /// Set UID. public static let setuid = Permissions(rawValue: 0o4000) /// Set GID. public static let setgid = Permissions(rawValue: 0o2000) /// Sticky bit. public static let sticky = Permissions(rawValue: 0o1000) /// Owner can read. public static let readOwner = Permissions(rawValue: 0o0400) /// Owner can write. public static let writeOwner = Permissions(rawValue: 0o0200) /// Owner can execute. public static let executeOwner = Permissions(rawValue: 0o0100) /// Group can read. public static let readGroup = Permissions(rawValue: 0o0040) /// Group can write. public static let writeGroup = Permissions(rawValue: 0o0020) /// Group can execute. public static let executeGroup = Permissions(rawValue: 0o0010) /// Others can read. public static let readOther = Permissions(rawValue: 0o0004) /// Others can write. public static let writeOther = Permissions(rawValue: 0o0002) /// Others can execute. public static let executeOther = Permissions(rawValue: 0o0001) }
mit
013384f501673ae82cc390cf56cfa3a6
26.363636
66
0.693023
4.400585
false
false
false
false
Lordxen/MagistralSwift
Pods/SwiftMQTT/SwiftMQTT/SwiftMQTT/Models/MQTTSubPacket.swift
1
945
// // MQTTSubPacket.swift // SwiftMQTT // // Created by Ankit Aggarwal on 12/11/15. // Copyright © 2015 Ankit. All rights reserved. // import Foundation class MQTTSubPacket: MQTTPacket { let topics: [String: MQTTQoS] let messageID: UInt16 init(topics: [String: MQTTQoS], messageID: UInt16) { self.topics = topics self.messageID = messageID super.init(header: MQTTPacketFixedHeader(packetType: .subscribe, flags: 0x02)) } override func networkPacket() -> Data { // Variable Header var variableHeader = Data() variableHeader.mqtt_append(messageID) // Payload var payload = Data() for (key, value) in topics { payload.mqtt_append(key) let qos = value.rawValue & 0x03 payload.mqtt_append(qos) } return finalPacket(variableHeader, payload: payload) } }
mit
a84b172630dfcf6a8efceca60a67c9c8
23.842105
86
0.59428
4.104348
false
false
false
false
akabekobeko/examples-ios-fmdb
UsingFMDB-Swift/UsingFMDB-Swift/BookCache.swift
1
3661
// // BookCache.swift // UsingFMDB-Swift // // Created by akabeko on 2016/12/22. // Copyright © 2016年 akabeko. All rights reserved. // import UIKit /// Manager fot the book data. class BookCache: NSObject { /// A collection of author names. var authors = Array<String>() /// Dictionary of book collection classified by author name. var booksByAuthor = Dictionary<String, Array<Book>>() /// Initialize the instance. override init() { super.init() } /// Initialize the instance. /// /// - Parameter books: Collection of the book data. init(books: Array<Book>) { super.init() books.forEach({ (book) in if !self.add(book: book) { print("Faild to add book: " + book.author + " - " + book.title ) } }) } /// Add the new book. /// /// - Parameter book: Book data. /// - Returns: "true" if successful. func add(book: Book) -> Bool { if book.bookId == Book.BookIdNone { return false } if var existBooks = self.booksByAuthor[book.author] { existBooks.append(book) self.booksByAuthor.updateValue(existBooks, forKey: book.author) } else { var newBooks = Array<Book>() newBooks.append(book) self.booksByAuthor[book.author] = newBooks self.authors.append(book.author) } return true } /// Remove the book. /// /// - Parameter book: Book data. /// - Returns: "true" if successful. func remove(book: Book) -> Bool { guard var books = self.booksByAuthor[book.author] else { return false } for i in 0..<books.count { let existBook = books[i] if existBook.bookId == book.bookId { books.remove(at: i) self.booksByAuthor.updateValue(books, forKey: book.author) break } } if books.count == 0 { return self.removeAuthor(author: book.author) } return true } /// Update the book. /// /// - Parameter oldBook: New book data. /// - Parameter newBook: Old book data. /// - Returns: "true" if successful. func update(oldBook: Book, newBook: Book) -> Bool { if oldBook.author == newBook.author { return self.replaceBook(newBook: newBook) } else if self.remove(book: oldBook) { return self.add(book: newBook) } return false } /// Remove the author at the inner collection. /// /// - Parameter author: Name of the author. /// - Returns: "true" if successful. private func removeAuthor(author: String) -> Bool { self.booksByAuthor.removeValue(forKey: author) for i in 0..<self.authors.count { let existAuthor = self.authors[i] if existAuthor == author { self.authors.remove(at: i) return true } } return false } /// Replace the book. /// /// - Parameter newBook: New book data. /// - Returns: "true" if successful. private func replaceBook(newBook: Book) -> Bool { guard var books = self.booksByAuthor[newBook.author] else { return false } for i in 0..<books.count { let book = books[i] if book.bookId == newBook.bookId { books[i] = newBook self.booksByAuthor.updateValue(books, forKey: newBook.author) return true } } return false } }
mit
13560bf7e57c90bf3beda811ea012b63
25.897059
80
0.539913
4.166287
false
false
false
false
netease-app/NIMSwift
Example/Pods/CFWebView/CFWebView/Classes/CFWebViewController.swift
1
9638
// // CFWebViewController.swift // // // Created by 衡成飞 on 10/25/16. // Copyright © 2016 qianwang. All rights reserved. // import UIKit import WebKit open class CFWebViewController: UIViewController,WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler { /** 初始化一个Web Controller - 注意导航栏的titile是否居中,和左右侧的barbuttonitem有关系,如果存在,但是隐藏,也会占位置 - parameter url: url地址 - parameter swiped: 是否可以滑动返回(true:可以手势左滑动,false:h5内可以滑动,但是不能手势返回到前一个页面) - parameter callbackHandlerName: JavaScript调用App时,定义的名字 - parameter callbackHandler: App收到Javascript时的回调方法 - returns: controller实例 */ public init(url:String?,swiped:Bool? = false,callbackHandlerName:[String]? = nil,callbackHandler:((_ handlerName:String,_ sendData:String,_ vc:UIViewController) -> Void)? = nil){ self.url = url self.swiped = swiped self.callbackHandlerName = callbackHandlerName self.callbackHandler = callbackHandler super.init(nibName: nil, bundle: nil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open var backImage : UIImage! open var isCloseShow:Bool = true open var closeButtonColor:UIColor = UIColor.black open var progressColor:UIColor = UIColor.black fileprivate var url : String? fileprivate var shareURL:String? fileprivate var swiped:Bool? fileprivate var callbackHandlerName:[String]? fileprivate var callbackHandler:((_ handlerName:String,_ sendData:String,_ vc:UIViewController) -> Void)? fileprivate var webView:WKWebView! fileprivate var progressView:UIProgressView! fileprivate var request:URLRequest! var shareEnable = false var shareTitle:String? var shareContent:String? fileprivate var backButton:UIButton! fileprivate var closeButton:UIButton! open override func viewDidLoad() { super.viewDidLoad() backButton = UIButton() backButton.frame = CGRect(x: 0, y: 0, width: 48, height: 20) backButton.setImage(self.backImage, for: .normal) closeButton = UIButton() closeButton.frame = CGRect(x: 0, y: 0, width: 45, height: 30) closeButton.setTitle("关闭", for: UIControlState()) closeButton.setTitleColor(closeButtonColor, for: .normal) closeButton.titleLabel?.font = UIFont.systemFont(ofSize: 16.0) closeButton.contentHorizontalAlignment = .left self.automaticallyAdjustsScrollViewInsets = false progressView = UIProgressView(progressViewStyle: UIProgressViewStyle.bar) progressView.frame = CGRect(x: 0, y: 64, width: UIScreen.main.bounds.size.width, height: 1) progressView.tintColor = progressColor view.addSubview(progressView) let conf = WKWebViewConfiguration() //JavaScript回调APP if let handler = self.callbackHandlerName , handler.count > 0 { for j in handler { conf.userContentController.add(self, name: j) } } webView = WKWebView(frame: self.view.frame, configuration: conf) webView.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(webView, belowSubview: progressView) let vfl_h = "H:|-0-[webview]-0-|" let vfl_v = "V:|-0-[webview]-0-|" let views:[String:UIView] = ["webview":webView] view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: vfl_h, options: NSLayoutFormatOptions.alignAllLastBaseline, metrics: nil, views: views)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: vfl_v, options: .alignAllLastBaseline, metrics: nil, views: views)) webView.addObserver(self, forKeyPath: "title", options: .new, context: nil) webView.addObserver(self, forKeyPath: "loading", options: .new, context: nil) webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) webView.navigationDelegate = self webView.uiDelegate = self webView.scrollView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0) //不可左滑时,添加关闭 if swiped == nil || swiped! == false { backButton.addTarget(self, action: #selector(back), for: UIControlEvents.touchUpInside) closeButton.addTarget(self, action: #selector(close), for: UIControlEvents.touchUpInside) self.navigationItem.leftBarButtonItems = [UIBarButtonItem(customView: backButton)] self.navigationItem.hidesBackButton = true webView.allowsBackForwardNavigationGestures = true // 支持滑动返回 } //调用本地的html5 //let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("h5", ofType:"html")!) if let ur = url, let uu = URL(string: ur){ var request = URLRequest(url: uu, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 20) let cookie = UserDefaults.standard.object(forKey: "Cookie") as? String if let cook = cookie { request.addValue(cook, forHTTPHeaderField: "Cookie") } self.webView.load(request) } } func back(){ if webView.canGoBack { webView.goBack() }else{ if let nav = navigationController { _ = nav.popViewController(animated: true) nav.presentingViewController?.dismiss(animated: true, completion: nil) }else{ self.dismiss(animated: true, completion: nil) } } } func close(){ if let nav = navigationController { _ = nav.popViewController(animated: true) nav.presentingViewController?.dismiss(animated: true, completion: nil) }else{ self.dismiss(animated: true, completion: nil) } } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "title" { self.title = webView.title } if keyPath == "loading" { } if keyPath == "estimatedProgress" { progressView.isHidden = webView.estimatedProgress == 1 progressView.setProgress(Float(webView.estimatedProgress), animated: true) } if webView.canGoBack { self.navigationItem.leftBarButtonItems = [UIBarButtonItem(customView: backButton),UIBarButtonItem(customView: closeButton)] }else{ self.navigationItem.leftBarButtonItems = [UIBarButtonItem(customView: backButton)] } } open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { //this is a 'new window action' (aka target="_blank") > open this URL externally. If we´re doing nothing here, WKWebView will also just do nothing. Maybe this will change in a later stage of the iOS 8 Beta if navigationAction.targetFrame != nil { let url = navigationAction.request.url! if url.absoluteString.hasPrefix("https://itunes.apple.com") { let app = UIApplication.shared if app.canOpenURL(url){ if #available(iOS 10.0, *) { app.open(url, options: [:], completionHandler: nil) } else { app.openURL(url) } } }else if url.absoluteString.hasPrefix("http"){ //新的URL(删除所有的参数) self.shareURL = url.absoluteString + "?share=1" let newQuerys = url.query?.components(separatedBy: "&") if let qs = newQuerys { var ss:[String] = [] for q in qs { if !q.hasPrefix("uid=") && !q.hasPrefix("pkey=") && !q.hasPrefix("tok"){ ss.append(q) } } if ss.count > 0 { self.shareURL = self.shareURL! + "&" + ss.joined(separator: "&") } } } } decisionHandler(WKNavigationActionPolicy.allow) } open func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { progressView.setProgress(0.0, animated: false) } deinit{ webView.removeObserver(self, forKeyPath: "title") webView.removeObserver(self, forKeyPath: "loading") webView.removeObserver(self, forKeyPath: "estimatedProgress") webView.navigationDelegate = nil webView.uiDelegate = nil } // MARK: - WKScriptMessageHandler open func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if callbackHandler != nil { callbackHandler!(message.name,message.body as! String,self) } } }
mit
70ba509b74089d3f3109f0a1c52665aa
38.812766
213
0.611479
5.022008
false
false
false
false
Egibide-DAM/swift
02_ejemplos/05_funciones_clausuras/02_tipos_funciones/07_tuplas_opcionales.playground/Contents.swift
1
496
func minMax(array: [Int]) -> (min: Int, max: Int)? { if array.isEmpty { return nil } var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin { currentMin = value } else if value > currentMax { currentMax = value } } return (currentMin, currentMax) } if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) { print("min is \(bounds.min) and max is \(bounds.max)") }
apache-2.0
0a67e9f019b22847a692dc4f061292ad
28.176471
58
0.560484
3.594203
false
false
false
false
innominds-mobility/swift-location
swift-location/swift-location/GoogleLocationViewController.swift
1
2614
// // GoogleLocationViewController.swift // swift-location // // Created by Harika Annam on 6/23/17. // Copyright © 2017 Innominds Mobility. All rights reserved. // import UIKit import CoreLocation import GoogleMaps import GooglePlaces /// The purpose of this view controller is to provide a user interface for displaying user location in Google map. /// The `GoogleLocationViewController` class is a subclass of the `UIViewController`. class GoogleLocationViewController: UIViewController { var userLocation = CLLocation() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Google Map" /// It holds latitude,longitude values let coordinations = CLLocationCoordinate2D(latitude: (self.userLocation.coordinate.latitude), longitude: (self.userLocation.coordinate.longitude)) let camera = GMSCameraPosition.camera(withLatitude: coordinations.latitude, longitude:coordinations.longitude, zoom: 10) /// Declaration of GMSMapView let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) mapView.isMyLocationEnabled = true //mapView.delegate = self self.view = mapView let marker = GMSMarker() marker.position = CLLocationCoordinate2DMake(coordinations.latitude, coordinations.longitude) marker.map = mapView /// Reverse geocoding by using latitude and longitude values to display location let geocoder = GMSGeocoder() geocoder.reverseGeocodeCoordinate( CLLocationCoordinate2DMake(coordinations.latitude, coordinations.longitude)) { response, error in if error == nil { if let address = response?.firstResult() { print("Address from google \(address)") marker.title = address.locality marker.snippet = address.administrativeArea } } } } 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. } */ }
gpl-3.0
dfcb39df360ff21c55297bb03ad62b7b
40.47619
114
0.657099
5.432432
false
false
false
false
vgorloff/AUHost
Vendor/mc/mcxUIExtensions/Sources/AppKit/NSViewController.swift
1
1408
// // NSViewController.swift // MCA-OSS-AUH // // Created by Vlad Gorlov on 06.06.2020. // Copyright © 2020 Vlad Gorlov. All rights reserved. // #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit import mcxUI extension NSViewController { public func loadViewIfNeeded() { if !isViewLoaded { loadView() } } public func embedChildViewController(_ vc: NSViewController, container: NSView? = nil) { addChild(vc) let targetView = container ?? view // Fix for possible layout issues. Origin: https://stackoverflow.com/a/49255958/1418981 var frame = CGRect(x: 0, y: 0, width: targetView.frame.width, height: targetView.frame.height) if frame.size.width == 0 { frame.size.width = CGFloat.leastNormalMagnitude } if frame.size.height == 0 { frame.size.height = CGFloat.leastNormalMagnitude } vc.view.frame = frame vc.view.translatesAutoresizingMaskIntoConstraints = true vc.view.autoresizingMask = [.height, .width] targetView.addSubview(vc.view) } public func unembedChildViewController(_ vc: NSViewController) { vc.view.removeFromSuperview() vc.removeFromParent() } public var systemAppearance: SystemAppearance { return view.systemAppearance } public var anchor: LayoutConstraint { return LayoutConstraint() } } #endif
mit
bb05591392293bc3370780b60d57c62a
26.588235
100
0.675906
4.356037
false
false
false
false
jlecomte/EarthquakeTracker
EarthquakeTracker/ListViewController.swift
1
2847
// // ListViewController.swift // EarthquakeTracker // // Created by Julien Lecomte on 10/11/14. // Copyright (c) 2014 Julien Lecomte. All rights reserved. // import UIKit class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView! var earthquakes: [Earthquake] = [] var dateFormatter: NSDateFormatter! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd 'at' h:mm a" } override func viewDidAppear(animated: Bool) { // In case you just changed your settings... refreshList() } func refreshList() { let client = USGSClient.sharedInstance client.getEarthquakeList() { (earthquakes: [Earthquake]!, error: NSError!) -> Void in if error != nil { var alert = UIAlertController(title: "Error", message: error.description, preferredStyle: UIAlertControllerStyle.Alert) self.presentViewController(alert, animated: false, completion: nil) } else { self.earthquakes = earthquakes let sortListBy = EarthquakeTrackerSettings.sharedInstance.sortListBy if sortListBy == sortEventListBy.TIME { self.earthquakes.sort { $0.timems!.longLongValue > $1.timems!.longLongValue } } else if sortListBy == sortEventListBy.MAGNITUDE { self.earthquakes.sort { $0.magnitude > $1.magnitude } } self.tableView.reloadData() self.tableView.scrollRectToVisible(CGRectMake(0, 0, 1, 1), animated: false) } } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return earthquakes.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("EarthquakeTableViewCell") as EarthquakeTableViewCell var earthquake = earthquakes[indexPath.row] cell.timeLabel.text = dateFormatter.stringFromDate(earthquake.time!) cell.placeLabel.text = earthquake.place cell.magnitudeLabel.text = NSString(format: "%.2f", earthquake.magnitude!) cell.depthLabel.text = NSString(format: "%.2f miles", earthquake.depth! * 0.621371) var magnitude = earthquake.magnitude! var hue = 0.3 - magnitude / 20 cell.backgroundColor = UIColor(hue: CGFloat(hue), saturation: 1.0, brightness: 1.0, alpha: 1.0) return cell } }
mit
abfef27dd34cedfd4b19225a3415e8af
34.148148
135
0.627327
4.942708
false
false
false
false
colemancda/Pedido
Pedido Admin/Pedido Admin/MenuItemsViewController.swift
1
3044
// // MenuItemsViewController.swift // Pedido Admin // // Created by Alsey Coleman Miller on 12/7/14. // Copyright (c) 2014 ColemanCDA. All rights reserved. // import Foundation import UIKit import CoreData import CorePedido import CorePedidoClient class MenuItemsViewController: FetchedResultsViewController { // MARK: - Properties let numberFormatter: NSNumberFormatter = { let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle return numberFormatter }() // MARK: - Initialization override func viewDidLoad() { super.viewDidLoad() // set fetch request let fetchRequest = NSFetchRequest(entityName: "MenuItem") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)] self.fetchRequest = fetchRequest } // MARK: - Methods override func dequeueReusableCellForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { return self.tableView.dequeueReusableCellWithIdentifier(CellIdentifier.MenuItemCell.rawValue, forIndexPath: indexPath) as UITableViewCell } override func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath, withError error: NSError?) { if error != nil { // TODO: Configure cell for error } // get model object let menuItem = self.fetchedResultsController!.objectAtIndexPath(indexPath) as MenuItem let dateCached = menuItem.valueForKey(Store.sharedStore.dateCachedAttributeName!) as? NSDate // not cached if dateCached == nil { // configure empty cell... cell.textLabel!.text = NSLocalizedString("Loading...", comment: "Loading...") cell.detailTextLabel!.text = "" cell.userInteractionEnabled = false return } // configure cell... cell.userInteractionEnabled = true cell.textLabel!.text = menuItem.name // build price text self.numberFormatter.locale = NSLocale(localeIdentifier: menuItem.currencyLocaleIdentifier) cell.detailTextLabel!.text = self.numberFormatter.stringFromNumber(menuItem.price) // fix detail text label not showing cell.layoutIfNeeded() } // MARK: - UITableViewDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.showMainStoryboardDetailController(.MenuItemDetail, forManagedObjectAtIndexPath: indexPath) tableView.deselectRowAtIndexPath(indexPath, animated: true) } } // MARK: - Private Enumerations private enum CellIdentifier: String { case MenuItemCell = "MenuItemCell" }
mit
cf008df1a94a8088f7a7c6f7469a1b1f
27.716981
145
0.626478
6.250513
false
false
false
false
rtoal/polyglot
swift/animals.swift
2
772
// Rather than abstract classes, Swift uses protocols to compose behavior protocol Animal { var name: String {get} var sound: String {get} func speak() -> String } // Protocol extensions allow adaptees to get default implementations extension Animal { func speak() -> String { return "\(name) says \(sound)" } } struct Cow: Animal { let name: String let sound = "moooo" } struct Horse: Animal { let name: String let sound = "neigh" } struct Sheep: Animal { let name: String let sound = "baaaa" } let h: Animal = Horse(name: "CJ") assert(h.speak() == "CJ says neigh") let c: Animal = Cow(name: "Bessie") assert(c.speak() == "Bessie says moooo") assert(Sheep(name: "Little Lamb").speak() == "Little Lamb says baaaa")
mit
0922c8f2aed725e44054a5e539f1b955
21.705882
73
0.646373
3.461883
false
false
false
false
Bunn/FCBCurrencyService
Library/FCBQuote.swift
1
2221
/* The MIT License (MIT) Copyright (c) 2016 Fernando Bunn 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 struct FCBQuote { var name: String var yearHigh: String var yearLow: String var rate: String } enum SerializationError: Error { case missing(String) } extension FCBQuote { init(json: [String: Any]) throws { guard let name = json["Name"] as? String else { throw SerializationError.missing("Name") } guard let rate = json["Bid"] as? String else { throw SerializationError.missing("Bid") } guard let yearHigh = json["YearHigh"] as? String else { throw SerializationError.missing("YearHigh") } guard let yearLow = json["YearLow"] as? String else { throw SerializationError.missing("YearLow") } self.name = name self.rate = rate self.yearLow = yearLow self.yearHigh = yearHigh } } /* ASK AND BID The Ask price is what sellers are willing to take for it. If you are selling a stock, you are going to get the Bid price, if you are buying a stock you are going to get the ask price. */
mit
1b05aa26a3e12625ed62277f8c2cf444
31.661765
125
0.69113
4.532653
false
false
false
false
qkrqjadn/SoonChat
source/Data/FirebaseAPI.swift
1
1907
// // InfoCellNetApi.swift // soonchat // // Created by 박범우 on 2017. 1. 10.. // Copyright © 2017년 bumwoo. All rights reserved. // import Foundation import Firebase class FirebaseAPI : NSObject { static let sharedInstance = FirebaseAPI() let dateString : String = { let today = Date() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter.string(from: today) }() lazy var dataBaseForInfo : FIRDatabaseReference = { let db = FIRDatabase.database().reference(fromURL: "https://soonchat-840b5.firebaseio.com/").child("infomation") return db }() let dataBaseRef : FIRDatabaseReference = { let db = FIRDatabase.database().reference(fromURL: "https://soonchat-840b5.firebaseio.com/") return db }() let dataStorageRef : FIRStorageReference = { let ds = FIRStorage.storage().reference(forURL: "gs://soonchat-840b5.appspot.com") return ds }() func addChild(_ PathString : String...) -> FIRDatabaseReference { var database = dataBaseRef for path in PathString { database = database.child(path) } return database } let cache = NSCache<AnyObject, AnyObject>() func getUserProfileImageUrlForUID(FIRUser:String) -> String? { if let cache = cache.object(forKey: FIRUser as AnyObject) { return cache as? String ?? "" } var imgurl:String? dataBaseRef.child("users").child(FIRUser).child("profileImage").observeSingleEvent(of: .value, with: {[weak self](snapshot) in if let `self` = self?.cache.setObject(snapshot.value as AnyObject, forKey: FIRUser as AnyObject){ imgurl = snapshot.value as? String } }) return imgurl } }
mit
e911f6a085c172ce37602ccaebbd0038
27.328358
134
0.608535
4.363218
false
false
false
false
capstone411/SHAF
Capstone/IOS_app/SHAF/SHAF/FirstViewController.swift
1
3994
// // FirstViewController.swift // SHAF // // Created by Ahmed Abdulkareem on 4/12/16. // Copyright © 2016 Ahmed Abdulkareem. All rights reserved. // import UIKit class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var buttonActivityIndicator: UIActivityIndicatorView! @IBOutlet weak var bluetoothTable: UITableView! @IBOutlet weak var connectButton: UIButton! var selected_device = 0; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //self.bluetoothTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "BLCell") // to update table view notification NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FirstViewController.loadList(_:)),name:"discoveredPeriph", object: nil) // notify when connected NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FirstViewController.periphConnected(_:)),name:"periphConnected", object: nil) self.connectButton.enabled = false // activity view in the connect button self.buttonActivityIndicator.hidden = true BLEDiscovery // start bluetooth } // load bluetooth table func loadList(notification: NSNotification) { dispatch_sync(dispatch_get_main_queue()) { //load data of table self.bluetoothTable.reloadData() } } // executes when peripheral is connected func periphConnected(notification: NSNotification) { dispatch_sync(dispatch_get_main_queue()) { self.performSegueWithIdentifier("selectGoalIdentifier", sender: nil) // stop activity indicator let cells = self.bluetoothTable.visibleCells as! [BluetoothTableCellTableViewCell] let cell = cells[self.selected_device] cell.indicator.stopAnimating() self.buttonActivityIndicator.hidden = true self.buttonActivityIndicator.stopAnimating() } } @IBAction func connectButton(sender: AnyObject) { // connect to peripheral BLEDiscovery.connect(self.selected_device) // start activitiy indicator let cells = self.bluetoothTable.visibleCells as! [BluetoothTableCellTableViewCell] let currCell = cells[self.selected_device] currCell.indicator.startAnimating() self.buttonActivityIndicator.hidden = false self.buttonActivityIndicator.startAnimating() // for connect button // disable connect button self.connectButton.enabled = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return BLEDiscovery.devicesDiscovered.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell : BluetoothTableCellTableViewCell = self.bluetoothTable.dequeueReusableCellWithIdentifier("BLCell")! as! BluetoothTableCellTableViewCell let cellName = BLEDiscovery.devicesDiscovered[indexPath.row] cell.textLabel?.text = cellName // check if this is the bluetooth device and add // check mark next to it if cellName == "SHAF Bluetooth" { cell.checkMarkImage.hidden = false } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.connectButton.enabled = true // enable connect button if not already self.selected_device = indexPath.row // this is the index of selected device } }
mit
0a9b4dc7614874a45a4059cb86c84497
35.633028
160
0.670924
5.41791
false
false
false
false
lieonCX/Hospital
Hospital/Hospital/View/News/GithubSignupVC.swift
1
2778
// // GithubSignupVC.swift // Hospital // // Created by lieon on 2017/5/9. // Copyright © 2017年 ChangHongCloudTechService. All rights reserved. // import UIKit import RxSwift import RxCocoa class GithubSignupVC: BaseViewController { @IBOutlet weak var usernameOutlet: UITextField! @IBOutlet weak var usernameValidationOutlet: UILabel! @IBOutlet weak var passwordOutlet: UITextField! @IBOutlet weak var passwordValidationOutlet: UILabel! @IBOutlet weak var repeatedPasswordOutlet: UITextField! @IBOutlet weak var repeatedPasswordValidationOutlet: UILabel! @IBOutlet weak var signupOutlet: UIButton! @IBOutlet weak var signingUpOulet: UIActivityIndicatorView! private let usernameminLength: Int = 5 private let passwordminLength: Int = 6 override func viewDidLoad() { super.viewDidLoad() setupUI() } fileprivate func setupUI() { let signupVM = GithubSignupViewModel( input: ( username: usernameOutlet.rx.text.orEmpty.asObservable(), password: passwordOutlet.rx.text.orEmpty.asObservable(), repeatPassword: repeatedPasswordOutlet.rx.text.orEmpty.asObservable(), signupTaps: signupOutlet.rx.tap.asObservable()), dependency: ( API: GithubDefaultAPI.sahred, service: GitHubDefaultValidationService.shared) ) signupVM.validatedUsername .bind(to: usernameValidationOutlet.rx.validationResult) .disposed(by: disposeBag) signupVM.validatedPassword .bind(to: passwordValidationOutlet.rx.validationResult) .disposed(by: disposeBag) signupVM.validatedRepeatPassword .bind(to: repeatedPasswordValidationOutlet.rx.validationResult) .disposed(by: disposeBag) signupVM.signingin .bind(to: signingUpOulet.rx.isAnimating) .disposed(by: disposeBag) signupVM.signedin .subscribe(onNext: { signedIn in print("User signed in \(signedIn)") }) .disposed(by: disposeBag) signupVM.signupEnable .subscribe(onNext: { signed in self.signupOutlet.isEnabled = signed self.signupOutlet.alpha = signed ? 1.0 : 0.5 }) .disposed(by: disposeBag) let tap = UITapGestureRecognizer() tap.rx.event.subscribe(onNext: { [weak self] _ in self?.view.endEditing(true) }).disposed(by: disposeBag) view.addGestureRecognizer(tap) } }
mit
2db8d9ed81bef877b1be52db7ef716ad
33.6875
106
0.607207
5.119926
false
false
false
false
dshahidehpour/IGListKit
Examples/Examples-iOS/IGListKitExamples/Models/FeedItem.swift
4
1336
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import IGListKit final class FeedItem: IGListDiffable { let pk: Int let user: User let comments: [String] init(pk: Int, user: User, comments: [String]) { self.pk = pk self.user = user self.comments = comments } //MARK: IGListDiffable func diffIdentifier() -> NSObjectProtocol { return pk as NSObjectProtocol } func isEqual(toDiffableObject object: IGListDiffable?) -> Bool { guard self !== object else { return true } guard let object = object as? FeedItem else { return false } return user.isEqual(toDiffableObject: object.user) && comments == object.comments } }
bsd-3-clause
da22aa5448b5cc285600f1b37a840212
31.585366
89
0.708832
4.704225
false
false
false
false
lenglengiOS/BuDeJie
百思不得姐/Pods/Charts/Charts/Classes/Renderers/ChartLegendRenderer.swift
19
15560
// // ChartLegendRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class ChartLegendRenderer: ChartRendererBase { /// the legend object this renderer renders internal var _legend: ChartLegend! public init(viewPortHandler: ChartViewPortHandler, legend: ChartLegend?) { super.init(viewPortHandler: viewPortHandler) _legend = legend } /// Prepares the legend and calculates all needed forms, labels and colors. public func computeLegend(data: ChartData) { if (!_legend.isLegendCustom) { var labels = [String?]() var colors = [UIColor?]() // loop for building up the colors and labels used in the legend for (var i = 0, count = data.dataSetCount; i < count; i++) { let dataSet = data.getDataSetByIndex(i)! var clrs: [UIColor] = dataSet.colors let entryCount = dataSet.entryCount // if we have a barchart with stacked bars if (dataSet.isKindOfClass(BarChartDataSet) && (dataSet as! BarChartDataSet).isStacked) { let bds = dataSet as! BarChartDataSet var sLabels = bds.stackLabels for (var j = 0; j < clrs.count && j < bds.stackSize; j++) { labels.append(sLabels[j % sLabels.count]) colors.append(clrs[j]) } if (bds.label != nil) { // add the legend description label colors.append(nil) labels.append(bds.label) } } else if (dataSet.isKindOfClass(PieChartDataSet)) { var xVals = data.xVals let pds = dataSet as! PieChartDataSet for (var j = 0; j < clrs.count && j < entryCount && j < xVals.count; j++) { labels.append(xVals[j]) colors.append(clrs[j]) } if (pds.label != nil) { // add the legend description label colors.append(nil) labels.append(pds.label) } } else { // all others for (var j = 0; j < clrs.count && j < entryCount; j++) { // if multiple colors are set for a DataSet, group them if (j < clrs.count - 1 && j < entryCount - 1) { labels.append(nil) } else { // add label to the last entry labels.append(dataSet.label) } colors.append(clrs[j]) } } } _legend.colors = colors + _legend._extraColors _legend.labels = labels + _legend._extraLabels } // calculate all dimensions of the legend _legend.calculateDimensions(labelFont: _legend.font, viewPortHandler: viewPortHandler) } public func renderLegend(context context: CGContext) { if (_legend === nil || !_legend.enabled) { return } let labelFont = _legend.font let labelTextColor = _legend.textColor let labelLineHeight = labelFont.lineHeight let formYOffset = labelLineHeight / 2.0 var labels = _legend.labels var colors = _legend.colors let formSize = _legend.formSize let formToTextSpace = _legend.formToTextSpace let xEntrySpace = _legend.xEntrySpace let direction = _legend.direction // space between the entries let stackSpace = _legend.stackSpace let yoffset = _legend.yOffset let xoffset = _legend.xOffset let legendPosition = _legend.position switch (legendPosition) { case .BelowChartLeft: fallthrough case .BelowChartRight: fallthrough case .BelowChartCenter: fallthrough case .AboveChartLeft: fallthrough case .AboveChartRight: fallthrough case .AboveChartCenter: let contentWidth: CGFloat = viewPortHandler.contentWidth var originPosX: CGFloat if (legendPosition == .BelowChartLeft || legendPosition == .AboveChartLeft) { originPosX = viewPortHandler.contentLeft + xoffset if (direction == .RightToLeft) { originPosX += _legend.neededWidth } } else if (legendPosition == .BelowChartRight || legendPosition == .AboveChartRight) { originPosX = viewPortHandler.contentRight - xoffset if (direction == .LeftToRight) { originPosX -= _legend.neededWidth } } else // .BelowChartCenter || .AboveChartCenter { originPosX = viewPortHandler.contentLeft + contentWidth / 2.0 } var calculatedLineSizes = _legend.calculatedLineSizes var calculatedLabelSizes = _legend.calculatedLabelSizes var calculatedLabelBreakPoints = _legend.calculatedLabelBreakPoints var posX: CGFloat = originPosX var posY: CGFloat if (legendPosition == .AboveChartLeft || legendPosition == .AboveChartRight || legendPosition == .AboveChartCenter) { posY = 0 } else { posY = viewPortHandler.chartHeight - yoffset - _legend.neededHeight } var lineIndex: Int = 0 for (var i = 0, count = labels.count; i < count; i++) { if (i < calculatedLabelBreakPoints.count && calculatedLabelBreakPoints[i]) { posX = originPosX posY += labelLineHeight } if (posX == originPosX && legendPosition == .BelowChartCenter && lineIndex < calculatedLineSizes.count) { posX += (direction == .RightToLeft ? calculatedLineSizes[lineIndex].width : -calculatedLineSizes[lineIndex].width) / 2.0 lineIndex++ } let drawingForm = colors[i] != nil let isStacked = labels[i] == nil; // grouped forms have null labels if (drawingForm) { if (direction == .RightToLeft) { posX -= formSize } drawForm(context: context, x: posX, y: posY + formYOffset, colorIndex: i, legend: _legend) if (direction == .LeftToRight) { posX += formSize } } if (!isStacked) { if (drawingForm) { posX += direction == .RightToLeft ? -formToTextSpace : formToTextSpace } if (direction == .RightToLeft) { posX -= calculatedLabelSizes[i].width } drawLabel(context: context, x: posX, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor) if (direction == .LeftToRight) { posX += calculatedLabelSizes[i].width } posX += direction == .RightToLeft ? -xEntrySpace : xEntrySpace } else { posX += direction == .RightToLeft ? -stackSpace : stackSpace } } break case .PiechartCenter: fallthrough case .RightOfChart: fallthrough case .RightOfChartCenter: fallthrough case .RightOfChartInside: fallthrough case .LeftOfChart: fallthrough case .LeftOfChartCenter: fallthrough case .LeftOfChartInside: // contains the stacked legend size in pixels var stack = CGFloat(0.0) var wasStacked = false var posX: CGFloat = 0.0, posY: CGFloat = 0.0 if (legendPosition == .PiechartCenter) { posX = viewPortHandler.chartWidth / 2.0 + (direction == .LeftToRight ? -_legend.textWidthMax / 2.0 : _legend.textWidthMax / 2.0) posY = viewPortHandler.chartHeight / 2.0 - _legend.neededHeight / 2.0 + _legend.yOffset } else { let isRightAligned = legendPosition == .RightOfChart || legendPosition == .RightOfChartCenter || legendPosition == .RightOfChartInside if (isRightAligned) { posX = viewPortHandler.chartWidth - xoffset if (direction == .LeftToRight) { posX -= _legend.textWidthMax } } else { posX = xoffset if (direction == .RightToLeft) { posX += _legend.textWidthMax } } if (legendPosition == .RightOfChart || legendPosition == .LeftOfChart) { posY = viewPortHandler.contentTop + yoffset } else if (legendPosition == .RightOfChartCenter || legendPosition == .LeftOfChartCenter) { posY = viewPortHandler.chartHeight / 2.0 - _legend.neededHeight / 2.0 } else /*if (legend.position == .RightOfChartInside || legend.position == .LeftOfChartInside)*/ { posY = viewPortHandler.contentTop + yoffset } } for (var i = 0; i < labels.count; i++) { let drawingForm = colors[i] != nil var x = posX if (drawingForm) { if (direction == .LeftToRight) { x += stack } else { x -= formSize - stack } drawForm(context: context, x: x, y: posY + formYOffset, colorIndex: i, legend: _legend) if (direction == .LeftToRight) { x += formSize } } if (labels[i] != nil) { if (drawingForm && !wasStacked) { x += direction == .LeftToRight ? formToTextSpace : -formToTextSpace } else if (wasStacked) { x = posX } if (direction == .RightToLeft) { x -= (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont]).width } if (!wasStacked) { drawLabel(context: context, x: x, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor) } else { posY += labelLineHeight drawLabel(context: context, x: x, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor) } // make a step down posY += labelLineHeight stack = 0.0 } else { stack += formSize + stackSpace wasStacked = true } } break } } private var _formLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) /// Draws the Legend-form at the given position with the color at the given index. internal func drawForm(context context: CGContext, x: CGFloat, y: CGFloat, colorIndex: Int, legend: ChartLegend) { let formColor = legend.colors[colorIndex] if (formColor === nil || formColor == UIColor.clearColor()) { return } let formsize = legend.formSize CGContextSaveGState(context) switch (legend.form) { case .Circle: CGContextSetFillColorWithColor(context, formColor!.CGColor) CGContextFillEllipseInRect(context, CGRect(x: x, y: y - formsize / 2.0, width: formsize, height: formsize)) break case .Square: CGContextSetFillColorWithColor(context, formColor!.CGColor) CGContextFillRect(context, CGRect(x: x, y: y - formsize / 2.0, width: formsize, height: formsize)) break case .Line: CGContextSetLineWidth(context, legend.formLineWidth) CGContextSetStrokeColorWithColor(context, formColor!.CGColor) _formLineSegmentsBuffer[0].x = x _formLineSegmentsBuffer[0].y = y _formLineSegmentsBuffer[1].x = x + formsize _formLineSegmentsBuffer[1].y = y CGContextStrokeLineSegments(context, _formLineSegmentsBuffer, 2) break } CGContextRestoreGState(context) } /// Draws the provided label at the given position. internal func drawLabel(context context: CGContext, x: CGFloat, y: CGFloat, label: String, font: UIFont, textColor: UIColor) { ChartUtils.drawText(context: context, text: label, point: CGPoint(x: x, y: y), align: .Left, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: textColor]) } }
apache-2.0
058af195d1b4b49de9b76b1fd8cf9c0d
35.528169
184
0.454756
6.377049
false
false
false
false
aijaz/icw1502
playgrounds/Week03.playground/Pages/Types.xcplaygroundpage/Contents.swift
1
1935
//: [Previous](@previous) // Value Types // Reference Types // EVERYTHING IN SWIFT IS A VALUE TYPE // except classes // ALMOST EVERYTHING IN SWIFT IS **NOT** A CLASS var x = 7 var y = x x y // +---+ // x-> | 7 | // y-> +---+ // x = 5 // +---+ // x-> | 5 | // +---+ // // +---+ // | 7 | // y-> +---+ // x y var name1 = "kljsldkjflskdjflksdjflksjd flksjdf lksjdf ls" var name2 = name1 name1 name2 name1 = "Aijaz" name1 name2 class Person { var name:String init() { name = "" } } var firstSon = Person() firstSon.name = "Aijaz" var secondSon = Person() secondSon.name = "Adel" var brother = secondSon // // +-------------+ // f-> | Aijaz | // +-------------+ // // +-------------+ // s-> | Adel | // b-> +-------------+ // firstSon secondSon brother brother.name = "Doofus" // // +-------------+ // f-> | Aijaz | // +-------------+ // // +-------------+ // s-> | Doofus | // b-> +-------------+ // // // .--------------------------- brother secondSon // IN SWIFT ARRAYS ARE VALUE TYPES var xNums = [0, 1, 2] var yNums = xNums xNums yNums xNums[0] = 100 xNums yNums var kids = [firstSon, secondSon] var students = kids // // +-------------+ // f-> | Aijaz | // +-------------+ // // +-------------+ // s-> | Doofus | // +-------------+ // // kids = [f, s] // students = [f, s] // var graduate = Person() graduate.name = "Shahed" students[0] = graduate kids students var second = kids[1] second.name = "Adel" // // +-------------+ // f-> | Aijaz | // +-------------+ // // +-------------+ // s-> | Adel | // +-------------+ // // +-------------+ // s2-> | Shahed | // +-------------+ // kids = [f, s] // students = [s2, s] // kids students //: [Next](@next)
mit
e6da5fb36643969d52c1d239cffb73a7
11.730263
58
0.376744
2.717697
false
false
false
false
yoonhg84/CPAdManager-iOS
Source/Banner/CPFacebookBannerAD.swift
1
1347
// // Created by Chope on 2016. 7. 3.. // Copyright (c) 2016 Chope. All rights reserved. // import Foundation import FBAudienceNetwork open class CPFacebookBannerAd: CPBannerAd { public override var identifier: String { return "Facebook" } fileprivate weak var delegate: CPBannerAdDelegate? private var adView: FBAdView? private let placementId: String public init(placementId: String) { self.placementId = placementId } override func request(in viewController: UIViewController) { if adView == nil { let adSize = (UIDevice.current.userInterfaceIdiom == .pad) ? kFBAdSizeHeight90Banner : kFBAdSizeHeight50Banner adView = FBAdView(placementID: placementId, adSize: adSize, rootViewController: viewController) adView?.delegate = self } adView?.loadAd() } override func set(delegate: CPBannerAdDelegate) { self.delegate = delegate } public override func bannerView() -> UIView? { return adView } } extension CPFacebookBannerAd: FBAdViewDelegate { public func adViewDidLoad(_ adView: FBAdView) { delegate?.onLoaded(bannerAd: self) } public func adView(_ adView: FBAdView, didFailWithError error: Error) { delegate?.onFailedToLoad(bannerAd: self, error: error) } }
mit
7c3310ef3bf1301ff990fe29dc483884
25.94
122
0.673348
4.401961
false
false
false
false
iostalks/SFBlogDemo
UICollectionViewBug/BugTest/CollectionViewCell.swift
1
1010
// // CollectionViewCell.swift // BugTest // // Created by bong on 2017/10/23. // Copyright © 2017年 Smallfly. All rights reserved. // import UIKit class CollectionViewCell: UICollectionViewCell { private let downloadQueue = DispatchQueue(label: "ImageQueue") @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! func configure(_ model: MusicModel, for indexPath: IndexPath) { if indexPath.row == 0 { imageView.image = UIImage.init(named: "local") titleLabel.text = "本地图片" } else { titleLabel.text = model.title downloadQueue.async { let imageData = NSData(contentsOf: model.URL) guard let imgData = imageData else { return } DispatchQueue.main.async { self.imageView.image = UIImage(data: imgData as Data) } } } } }
mit
bbab9b904b6d0b6c64293f7bc6f67ff9
27.542857
73
0.561562
4.802885
false
false
false
false
jyhong836/Vivi
ViviInterface/Core Data Objects/VIAccountMO.swift
1
5158
// // Account.swift // Vivi // // Created by Junyuan Hong on 8/11/15. // Copyright © 2015 Junyuan Hong. All rights reserved. // import Foundation import CoreData import ViviSwiften //@objc(Account) public class VIAccountMO: NSManagedObject { public override func awakeFromInsert() { groups = NSSet() resources = NSSet() } public var accountString: String { get { return "\(node!)@\(domain!)" } } // MARK: - Account accessors(static) public var swaccount: SWAccount? { get { return SWAccount(accountName: accountString) } set { self.node = newValue?.getNodeString() self.domain = newValue?.getDomainString() } } /// Get existed group. public static func getAccount(node: String, domain: String, managedObjectContext moc: NSManagedObjectContext) -> VIAccountMO? { let fetchRequest = NSFetchRequest(entityName: "Account") fetchRequest.predicate = NSPredicate(format: "(node == %@) AND (domain == %@)", node, domain) do { let fetchedAccounts = try moc.executeFetchRequest(fetchRequest) as! [VIAccountMO] guard fetchedAccounts.count <= 1 else { fatalError("More than one account with the same node and domain.") } if fetchedAccounts.count == 1 { return fetchedAccounts[0] } else { return nil } } catch { fatalError("Fail to fetch account, error: \(error)") } } /// Add new account or get existed account. Entity will be /// validated immediately, throw relevant error when failed /// and delete the entity from managedObjectContext. /// - Parameter node: Account node string. /// - Parameter domain: Account domain string. /// - Parameter managedObjectContext: NSManagedObjectContext /// for core data. /// - Throws: addAccount will call account.validateForInsert(), /// and throw relevant NSError after delete invalidate account. public static func addAccount(node: String, domain: String, managedObjectContext moc: NSManagedObjectContext) throws -> VIAccountMO { if let existedAccount = getAccount(node, domain: domain, managedObjectContext: moc) { return existedAccount } else { let account = NSEntityDescription.insertNewObjectForEntityForName("Account", inManagedObjectContext: moc) as! VIAccountMO account.node = node account.domain = domain do { try account.validateForInsert() } catch { moc.deleteObject(account) throw error } return account } } /// Add new account or get existed account. Entity will be /// validated immediately, throw relevant error when failed /// and delete the entity from managedObjectContext. /// - Parameter swaccount: SWAccount stored relevant messages. /// - Parameter managedObjectContext: NSManagedObjectContext /// for core data. /// - Throws: addAccount will call account.validateForInsert(), /// and throw relevant NSError after delete invalidate account. public static func addAccount(swaccount: SWAccount, managedObjectContext moc: NSManagedObjectContext) throws -> VIAccountMO { return try addAccount(swaccount.getNodeString(), domain: swaccount.getDomainString(), managedObjectContext: moc) } /// Try to remove account. If account does not exist in core /// data, return without do anything. public static func removeAccount(node: String, domain: String, managedObjectContext moc: NSManagedObjectContext) { if let account = getAccount(node, domain: domain, managedObjectContext: moc) { moc.deleteObject(account) } } /// Try to remove account. If account does not exist in core /// data, return without do anything. public static func removeAccount(swaccount: SWAccount, managedObjectContext moc: NSManagedObjectContext) { removeAccount(swaccount.getNodeString(), domain: swaccount.getDomainString(), managedObjectContext: moc) } // MARK: - Group accessors /// Return true if exist group. func existGroup(newGroup: VIGroupMO) -> Bool { for element in self.groups! { let group = element as! VIGroupMO if (group.name == newGroup.name) { return true } } return false } /// Return true, if add new group to account. func addGroup(newGroup: VIGroupMO) -> Bool { if existGroup(newGroup) { return false } else { let groups = self.mutableSetValueForKey("groups") groups.addObject(newGroup) return true } } // MARK: Account presence public var presence: SWPresenceType = SWPresenceType.Unavailable public var presenceshow: SWPresenceShowType = SWPresenceShowType.None public var status: String = "" }
gpl-2.0
82c8fed92793df2bf409b688797f6d53
35.835714
137
0.629436
5.111001
false
false
false
false
digice/ioscxn
Swift/Connection/ConnectionManager.swift
1
3182
// // ConnectionManager.swift // iOSCxn // // Created by Roderic Linguri. // Copyright © 2017 Digices LLC. All rights reserved. // import UIKit // MARK: - Protocol protocol ConnectionManagerDelegate { func connectionDidComplete(response: Response) } // MARK: - Class class ConnectionManager { // MARK: - Properties // let connectionManager: ConnectionManager = ConnectionManager.shared static let shared: ConnectionManager = ConnectionManager() var object: Connection var delegate: ConnectionManagerDelegate? var request: Request? var response: Response? var message: String = "" // MARK: - Methods // Init private init() { if let storedData = UserDefaults.standard.object(forKey: "connection") as? Data { if let storedConnection = NSKeyedUnarchiver.unarchiveObject(with: storedData) as? Connection { self.object = storedConnection } else { self.object = Connection() self.saveDefault() } } else { self.object = Connection() self.saveDefault() } } // ./init // Save Default func saveDefault() { let defaults = UserDefaults.standard let dataToSave = NSKeyedArchiver.archivedData(withRootObject: self.object) defaults.set(dataToSave, forKey: "connection") defaults.synchronize() } // ./saveDefault // Completion Handler func completionHandler(data: Data?, response: URLResponse?, error: Error?) { if let e = error { self.response = Response(error: e) } if let receivedData = data { do { if let json = try JSONSerialization.jsonObject(with: receivedData, options: .allowFragments) as? [String:Any] { // DEBUG dump(json) if let metadata = json["meta"] as? [String:Any] { var responseData: [Any]? = nil if let result = json["data"] as? [Any] { responseData = result } // ./data in json self.response = Response(metadata: metadata, data: responseData) } // ./metadata in json } // ./data is json } catch let e { self.response = Response(error: e) } // ./do-catch } // ./data received OperationQueue.main.addOperation { if let delegate = self.delegate { delegate.connectionDidComplete(response: self.response!) } } // ./addOperation } // ./completionHandler // Send Request func sendRequest() { if let request = self.request?.urlRequest() { let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: self.completionHandler) task.resume() } } // ./sendRequest // Set Request func setRequest(object: String, action: String, attributes: [String:String]?) { self.request = Request(url: self.object.url, key: self.object.key, method: self.object.method) self.request!.setValue(action, forKey: "action") self.request!.setValue(object, forKey: "object") if let attr = attributes { for (key, value) in attr { self.request!.setValue(value, forKey: key) } } } // ./setRequest }
mit
8256002ab37d8d09ce7ef27d2efbe3b3
25.731092
119
0.624961
4.418056
false
false
false
false
noprom/swiftmi-app
swiftmi/swiftmi/CodeCell.swift
2
1038
// // CodeCell.swift // swiftmi // // Created by yangyin on 15/4/1. // Copyright (c) 2015年 swiftmi. All rights reserved. // import UIKit class CodeCell: UICollectionViewCell { @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var preview: UIImageView! @IBOutlet weak var title: UILabel! override func awakeFromNib() { super.awakeFromNib() //self.layer.cornerRadius = 4 self.layer.borderWidth = 1 self.layer.borderColor = UIColor(red: 0.85, green: 0.85, blue:0.85, alpha: 0.9).CGColor self.layer.masksToBounds = false // addShadow() } func addShadow(){ self.layer.shadowColor = UIColor(red: 0, green: 0, blue:0, alpha: 0.3).CGColor self.layer.shadowOpacity = 0.5 self.layer.shadowRadius = 2 self.layer.shadowOffset = CGSize(width: 0, height: 0) self.layer.shadowPath = UIBezierPath(rect: self.bounds).CGPath print(" ...add... shadow.....") } }
mit
7312969c21af27f4cb40215dc509aa03
24.268293
95
0.596525
4
false
false
false
false
mbuchetics/DataSource
Example/ViewControllers/Examples/FormViewController.swift
1
4845
// // FormViewController.swift // DataSource // // Created by Matthias Buchetics on 28/02/2017. // Copyright © 2017 aaa - all about apps GmbH. All rights reserved. // import UIKit import DataSource // MARK: - View Controller class FormViewController: UITableViewController { lazy var firstNameField: Form.TextField = { Form.TextField(id: "firstname", placeholder: "First Name", changed: self.textFieldChanged) }() lazy var lastNameField: Form.TextField = { Form.TextField(id: "lastname", placeholder: "Last Name", changed: self.textFieldChanged) }() lazy var switchField: Form.SwitchField = { Form.SwitchField(id: "additional", title: "Show additional options", changed: self.switchFieldChanged) }() lazy var emailField: Form.TextField = { Form.TextField(id: "email", placeholder: "E-Mail", keyboardType: .emailAddress, changed: self.textFieldChanged) }() lazy var dataSource: DataSource = { DataSource( cellDescriptors: [ TextFieldCell.descriptor .isHidden { (field, indexPath) in if field.id == self.lastNameField.id { return self.firstNameField.text?.isEmpty ?? true } else { return false } }, SwitchCell.descriptor, TitleCell.descriptor, ], sectionDescriptors: [ SectionDescriptor<Void>("section-name") .headerHeight { .zero }, SectionDescriptor<Void>("section-additional") .header { .title("Additional Fields") } .footer { .title("Here are some additional fields") } .isHidden { !self.switchField.isOn } ]) }() override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = dataSource tableView.delegate = dataSource dataSource.sections = [ Section(items: [ firstNameField, lastNameField, switchField ]).with(identifier: "section-name"), Section(items: [ emailField, "some random text" ]).with(identifier: "section-additional") ] dataSource.reloadData(tableView, animated: false) } func textFieldChanged(id: String, text: String) { print("changed field \(id): \(text)") dataSource.reloadData(tableView, animated: true) } func switchFieldChanged(id: String, isOn: Bool) { print("changed field \(id): \(isOn)") dataSource.reloadData(tableView, animated: true) } } // MARK: - Form protocol FormField: Diffable { var id: String { get } } extension FormField { var diffIdentifier: String { return id } } struct Form { class TextField: FormField { let id: String var text: String? let placeholder: String? let keyboardType: UIKeyboardType let changed: ((String, String) -> ())? init(id: String, text: String? = nil, placeholder: String? = nil, keyboardType: UIKeyboardType = .default, changed: ((String, String) -> ())? = nil) { self.id = id self.text = text self.placeholder = placeholder self.keyboardType = keyboardType self.changed = changed } func isEqualToDiffable(_ other: Diffable?) -> Bool { guard let other = other as? TextField else { return false } return self.id == other.id && self.text == other.text && self.placeholder == other.placeholder && self.keyboardType == other.keyboardType } } class SwitchField: FormField { let id: String let title: String var isOn: Bool let changed: ((String, Bool) -> ())? init(id: String, title: String, isOn: Bool = false, changed: ((String, Bool) -> ())? = nil) { self.id = id self.title = title self.isOn = isOn self.changed = changed } func isEqualToDiffable(_ other: Diffable?) -> Bool { guard let other = other as? SwitchField else { return false } return self.id == other.id && self.title == other.title && self.isOn == other.isOn } } }
mit
21d6ee133da7cbf2eb0327fcb9d06607
28.536585
158
0.513832
5.186296
false
false
false
false
niceagency/Base
Base/Datastore.swift
1
4684
// // Datastore.swift // NABase // // Created by Wain on 27/09/2016. // Copyright © 2017 Nice Agency. All rights reserved. // import Foundation import CoreData public enum ContextSavePolicy { case none case autoSaveToParent(owner: Datastore) } public extension NSManagedObjectContext { public func backgroundChildContext(savePolicy: ContextSavePolicy = .none) -> NSManagedObjectContext { let moc = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) moc.parent = self if case let .autoSaveToParent(datastore) = savePolicy { datastore.forwardSaveToParentContexts.append(Weak(moc)) } return moc } } public final class Datastore { // MARK: Core Data fileprivate var forwardSaveToParentContexts = [Weak<NSManagedObjectContext>]() private let persistentContainer: NSPersistentContainer public var viewContext: NSManagedObjectContext { return persistentContainer.viewContext } public class var documentsDirectory: URL { return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! } public func newBackgroundContext() -> NSManagedObjectContext { return persistentContainer.newBackgroundContext() } public init(modelName: String, storePathDirectory: URL? = Datastore.documentsDirectory, manualMigration: Bool = false, isReady: (() -> Void)? = nil) { let persistentContainer = NSPersistentContainer(name: modelName) let description: NSPersistentStoreDescription if var storePathDirectory = storePathDirectory { storePathDirectory.appendPathComponent("\(modelName).sqlite") description = NSPersistentStoreDescription(url: storePathDirectory) description.shouldInferMappingModelAutomatically = !manualMigration description.shouldMigrateStoreAutomatically = !manualMigration } else { description = NSPersistentStoreDescription() description.type = NSInMemoryStoreType } persistentContainer.persistentStoreDescriptions = [description] persistentContainer.loadPersistentStores { storeDescription, error in persistentContainer.viewContext.automaticallyMergesChangesFromParent = true BaseLog.coreData.log(.trace, "Loaded persistent store: \(storeDescription)") if let error = error { fatalError("Failed to load persistent stores \(error)") } if let completion = isReady { completion() } } self.persistentContainer = persistentContainer NotificationCenter.default.addObserver(self, selector: #selector(mocDidSave), name: NSNotification.Name.NSManagedObjectContextDidSave, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc fileprivate func mocDidSave(note: Notification) { guard let moc = note.object as? NSManagedObjectContext, moc.persistentStoreCoordinator == viewContext.persistentStoreCoordinator else { return } if forwardSaveToParentContexts.contains(moc), let parent = moc.parent { parent.perform { BaseLog.coreData.log(.trace, "Data loading context saved") do { try parent.save() } catch { BaseLog.coreData.log(.error, "Error trying to save the store: \(error)") } } } if let userInfo = note.userInfo { if let updatedObjects = userInfo[NSUpdatedObjectsKey] as? Set<NSManagedObject>, !updatedObjects.isEmpty { let viewContextObjects = updatedObjects .map { $0.objectID } .map { viewContext.object(with: $0) } viewContext.perform { [unowned self] in for object in viewContextObjects { BaseLog.coreData.log(.trace, "Refreshing \(object) on context: \(self.viewContext)") self.viewContext.refresh(object, mergeChanges: false) } } } } } }
mit
f270eab5fb4815d3df239570106b9c67
33.947761
117
0.585949
6.269076
false
false
false
false
openHPI/xikolo-ios
Common/Data/Model/Quiz.swift
1
1484
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import CoreData import Foundation import Stockpile final class Quiz: Content { @NSManaged var id: String @NSManaged var instructions: String? @NSManaged var lockSubmissionsAt: Date? @NSManaged var publishResultsAt: Date? @NSManaged var timeLimit: Int32 @NSManaged var allowedAttempts: Int32 @NSManaged var questions: Set<QuizQuestion> @nonobjc public class func fetchRequest() -> NSFetchRequest<Quiz> { return NSFetchRequest<Quiz>(entityName: "Quiz") } } extension Quiz: JSONAPIPullable { static var type: String { return "quizzes" } public func update(from object: ResourceData, with context: SynchronizationContext) throws { let attributes = try object.value(for: "attributes") as JSON self.instructions = try attributes.value(for: "instructions") self.lockSubmissionsAt = try attributes.value(for: "lock_submissions_at") self.publishResultsAt = try attributes.value(for: "publish_results_at") self.timeLimit = try attributes.value(for: "time_limit") self.allowedAttempts = try attributes.value(for: "allowed_attempts") // let relationships = try object.value(for: "relationships") as JSON // try self.updateRelationship(forKeyPath: \Self.questions, forKey: "questions", fromObject: relationships, including: includes, inContext: context) } }
gpl-3.0
5ffe896380936a8152929bae8cafd300
32.704545
155
0.706001
4.177465
false
false
false
false
noxytrux/RescueKopter
RescueKopter/KPTHeightMap.swift
1
6347
// // KPTHeightMap.swift // RescueKopter // // Created by Marcin Pędzimąż on 15.11.2014. // Copyright (c) 2014 Marcin Pedzimaz. All rights reserved. // import UIKit class KPTHeightMap { internal var data = [Float32]() internal var normal = [Float32]() internal var w: Int = 0 internal var h: Int = 0 init(filename: String) { let mapData = loadMapData(filename) w = Int(mapData.width) h = Int(mapData.height) data = [Float32](count: w*h, repeatedValue: 0.0) normal = [Float32](count: w*h*3, repeatedValue: 0.0) var index:Int = 0 let dataStruct = UnsafePointer<mapDataStruct>(mapData.data) for var ax=0; ax < w; ax++ { for var ay=0; ay < h; ay++ { let imgData = dataStruct[ax + ay * w] data[index] = Float32(imgData.ground) index++ } } //normals calcualtion var ax:Float32 = 0, ay:Float32 = 0, az:Float32 = 0, sx:Float32 = 0, sy:Float32 = 0, sz:Float32 = 0, cx:Float32 = 0, cy:Float32 = 0 var x:Int = 0, y:Int = 0 for( x = 0; x < w; x++) { for( y = 0; y < h; y++) { sx = 0 sy = 0 sz = 0 cx = Float32(x) * 2.0 cy = Float32(y) * 2.0 makeNormal( cx, y1: At(x,y:y),z1: cy ,x2: cx+2, y2: At(x+1,y:y-1),z2: cy-2, x3: cx+2,y3: At(x+1,y:y),z3: cy, rx: &ax, ry: &ay, rz: &az ) sx += ax sy += ay sz += az makeNormal( cx, y1: At(x,y:y),z1: cy ,x2: cx+2, y2: At(x+1,y:y),z2: cy,x3: cx, y3: At(x,y:y+1),z3: cy+2, rx: &ax, ry: &ay, rz: &az ) sx += ax sy += ay sz += az makeNormal( cx, y1: At(x,y:y),z1: cy ,x2: cx ,y2: At(x,y:y+1),z2: cy+2, x3: cx-2,y3: At(x-1,y:y+1),z3: cy+2, rx: &ax, ry: &ay, rz: &az ) sx += ax sy += ay sz += az makeNormal( cx, y1: At(x,y:y),z1: cy ,x2: cx-2 ,y2: At(x-1,y:y+1),z2: cy+2, x3: cx-2,y3: At(x-1,y:y),z3: cy, rx: &ax, ry: &ay, rz: &az ) sx += ax sy += ay sz += az makeNormal( cx, y1: At(x,y:y),z1: cy ,x2: cx-2 ,y2: At(x-1,y:y),z2: cy, x3: cx,y3: At(x,y:y-1),z3: cy-2, rx: &ax, ry: &ay, rz: &az ) sx += ax sy += ay sz += az updateNormal(x, y: y, nx: sx, ny: sy, nz: sz) } } } func updateNormal(x:Int,y:Int, nx:Float32, ny:Float32, nz:Float32) { let index: Int = ( x + y * w ) * 3 let l:Float32 = sqrt(nx*nx + ny*ny + nz*nz) if l > 0.0001 { normal[ index+0 ] = nx / l normal[ index+1 ] = ny / l normal[ index+2 ] = nz / l } else { normal[index+0] = nx normal[index+1] = ny normal[index+2] = nz } } func At(x:Int, y:Int) -> Float32 { if x < 0 || y < 0 || x >= w || y >= h { return 0 } let vertexIndex: Int = x + y * w return data[vertexIndex] } func normAt(x:Int, y:Int, d:Int) -> Float32 { var rx = x var ry = y if x < 0 || y < 0 || x >= w || y >= h { rx = 0 ry = 0 } let index: Int = ( rx + ry * w ) * 3 + d return normal[index] } func normalVectorAt(x:Int,y:Int) -> Vector3 { let nx = normAt(x, y: y, d: 0) let ny = normAt(x, y: y, d: 1) let nz = normAt(x, y: y, d: 2) return Vector3(x:nx, y:ny, z:nz) } func GetHeight(x: Float32, z:Float32 ) -> Float32 { var rx = x var rz = z let a: Int = Int(x) let b: Int = Int(z) if a < 0 || b < 0 || a > w-1 || b > h-1 { return 0.0 } rx -= Float32(a) rz -= Float32(b) if( rz < 0.001 ) { return mix( At(a,y:b) ,b: At(a+1,y:b) , f: rx ) } if( rx < 0.001 ) { return mix( At(a,y:b) ,b: At(a,y:b+1) , f: rz ) } if( rx < rz ) { let w1 = rz*( At(a,y:b+1) - At(a,y:b) ) + At(a,y:b) let w2 = rz*( At(a+1,y:b+1) - At(a,y:b) ) + At(a,y:b) return w1 + rx/rz*( w2 - w1 ) } else { let w1 = rx*( At(a+1,y:b) - At(a,y:b) ) + At(a,y:b) let w2 = rx*( At(a+1,y:b+1) - At(a,y:b) ) + At(a,y:b) return w1 + rz/rx*( w2 - w1 ) } } func GetNormal(x:Float32, z:Float32) -> Vector3 { let a = Int(x) let b = Int(z) var v = Vector3(x:0.0, y:1.0, z:0.0) if( a < 0 || b < 0 || a > w-1 || b > h-1 ) { return v } var w1:Float32 = 0, w2:Float32 = 0 var rx = x var rz = z rx -= Float32(a) rz -= Float32(b) w1 = z * ( normAt(a,y:b+1,d:0) - normAt(a,y:b,d:0) ) + normAt(a,y:b,d:0) w2 = z * ( normAt(a+1,y:b+1,d:0) - normAt(a+1,y:b,d:0) ) + normAt(a+1,y:b,d:0) v.x = w1 + x*( w2 - w1 ) w1 = z * ( normAt(a,y:b+1,d:1) - normAt(a,y:b,d:1) ) + normAt(a,y:b,d:1) w2 = z * ( normAt(a+1,y:b+1,d:1) - normAt(a+1,y:b,d:1) ) + normAt(a+1,y:b,d:1) v.y = w1 + x*( w2 - w1 ) w1 = z * ( normAt(a,y:b+1,d:2) - normAt(a,y:b,d:2) ) + normAt(a,y:b,d:2) w2 = z * ( normAt(a+1,y:b+1,d:2) - normAt(a+1,y:b,d:2) ) + normAt(a+1,y:b,d:2) v.z = w1 + x*( w2 - w1 ) v.normalize() return v } }
mit
e1bdb35e8eaef1adf9a9ca248fca7fb2
25.767932
152
0.363966
2.851236
false
false
false
false
VladimirDinic/WDSideMenu
WDSideMenu/WDSideMenu/AppDelegate.swift
1
4790
// // AppDelegate.swift // WDSideMenu // // Created by Vladimir Dinic on 2/18/17. // Copyright © 2017 Vladimir Dinic. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor(red: 0.0, green: 105.0/255.0, blue: 105.0/255.0, alpha: 1.0)] return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "WDSideMenu") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
2757b481242726433d881dbf337d6142
48.885417
285
0.685112
5.714797
false
false
false
false
jboullianne/EndlessTunes
EndlessSoundFeed/NPViewController.swift
1
6925
// // NPViewController.swift // EndlessSoundFeed // // Created by Jean-Marc Boullianne on 5/2/17. // Copyright © 2017 Jean-Marc Boullianne. All rights reserved. // import UIKit import AVFoundation import Alamofire import AlamofireImage class NPViewController: UIViewController, ESFNowPlayingDelegate { @IBOutlet var albumBackground: UIImageView! @IBOutlet var albumForeground: UIImageView! @IBOutlet var titleLabel: UILabel! @IBOutlet var authorLabel: UILabel! @IBOutlet var dismissPanGesture: UIPanGestureRecognizer! var gradientLayer:CAGradientLayer! @IBOutlet var dismissIcon: UIImageView! //Seek Bar Outlets @IBOutlet var seekLeftLabel: UILabel! @IBOutlet var seekRightLabel: UILabel! @IBOutlet var seekBarSlider: UISlider! @IBOutlet var ppButton: UIImageView! override func viewDidLoad() { super.viewDidLoad() let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = albumBackground.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] albumBackground.addSubview(blurEffectView) // Do any additional setup after loading the view. MediaManager.sharedInstance.nowPlayingDelegate = self createGradientLayer() dismissIcon.image = dismissIcon.image!.withRenderingMode(.alwaysTemplate) dismissIcon.tintColor = UIColor(red: 0, green: 38/255, blue: 69/255, alpha: 1.0) if MediaManager.sharedInstance.isPlaying { ppButton.image = UIImage(named: "icons8-Circled Pause Filled-100") }else{ ppButton.image = UIImage(named: "icons8-Circled Play Filled-100") } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let manager = MediaManager.sharedInstance if let track = manager.currentTrack{ albumBackground.image = track.thumbnailImage albumForeground.image = track.thumbnailImage titleLabel.text = track.title authorLabel.text = track.author if let time = manager.currentTime, let duration = manager.durationTime{ updateSeekbar(current: time, duration: duration) } //Load External Thumbnail if it Exists if(track.thumbnailURL != "" && track.thumbnailImage == nil){ Alamofire.request(track.thumbnailURL).responseImage { response in if let image = response.result.value { print("image downloaded: \(image)") DispatchQueue.main.async { self.albumBackground.image = image self.albumForeground.image = image } MediaManager.sharedInstance.currentTrack?.thumbnailImage = image //Set Image Inside Track } } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override var preferredStatusBarStyle: UIStatusBarStyle{ return .lightContent } func didStartPlayingTrack(track: Track) { if let image = track.thumbnailImage{ albumBackground.image = image albumForeground.image = image } titleLabel.text = track.title authorLabel.text = track.author } func didReceiveTimeUpdate(time: CMTime, duration: CMTime) { print("NP Time:", time.durationText) updateSeekbar(current: time, duration: duration) } @IBAction func dismissNPController(_ sender: Any) { print("DISMISS NP CONTROLLER") self.dismiss(animated: true, completion: nil) } func createGradientLayer() { gradientLayer = CAGradientLayer() gradientLayer.frame = self.view.bounds //End Color For The Buttons let endColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1) gradientLayer.colors = [UIColor.clear.cgColor, endColor.cgColor ] gradientLayer.locations = [0.0, 0.55] self.albumBackground.layer.addSublayer(gradientLayer) } /* // 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. } */ @IBAction func seekValueChanged(_ sender: UISlider) { let val = sender.value MediaManager.sharedInstance.seekTo(value: val) } func updateSeekbar(current: CMTime, duration: CMTime){ seekLeftLabel.text = current.durationText seekRightLabel.text = duration.durationText let seekBarValue = current.seconds/duration.seconds seekBarSlider.value = Float(seekBarValue) } // Play/Pause Pressed @IBAction func ppButtonPressed(_ sender: UITapGestureRecognizer) { print("NowPlaying: PPButtonPressed, \(MediaManager.sharedInstance.isPlaying)") if MediaManager.sharedInstance.isPlaying { MediaManager.sharedInstance.pause() ppButton.image = UIImage(named: "icons8-Circled Play Filled-100") }else{ MediaManager.sharedInstance.play() ppButton.image = UIImage(named: "icons8-Circled Pause Filled-100") } } // Previous Button Pressed @IBAction func prevButtonPressed(_ sender: Any) { print("NowPlaying: PREV Button Pressed") MediaManager.sharedInstance.prev() } // Next Button Pressed @IBAction func nextButtonPressed(_ sender: Any) { print("NowPlaying: NEXT Button Pressed") MediaManager.sharedInstance.next() } } extension CMTime { var durationText:String { let totalSeconds = CMTimeGetSeconds(self) guard !(totalSeconds.isNaN || totalSeconds.isInfinite) else { return "0:00" } let minutes:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 3600) / 60) let seconds:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 60)) if minutes > 9 { return String(format: "%02i:%02i", minutes, seconds) } else { return String(format: "%01i:%02i", minutes, seconds) } } }
gpl-3.0
4d0e3cf9d1679c53523002a7141b652c
32.61165
106
0.613663
5.23356
false
false
false
false
BrunoMazzo/CocoaHeadsApp
CocoaHeadsApp/Classes/Base/Models/GroupModel.swift
3
459
import UIKit import Unbox /** The response for a group of a meetup */ class GroupModel: Unboxable { let joinMode :String let name :String let id :Int let urlName :String let who :String required init(unboxer: Unboxer) { joinMode = unboxer.unbox("join_mode") name = unboxer.unbox("name") id = unboxer.unbox("id") urlName = unboxer.unbox("urlname") who = unboxer.unbox("who") } }
mit
074a6420bf0ef9f3b182a4154119b960
18.956522
45
0.599129
3.889831
false
false
false
false
brightify/Bond
Bond/Shared/Bond+NSLayoutConstraint.swift
1
1970
// // Bond+UIActivityIndicatorView.swift // Bond // // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if os(iOS) import UIKit #else import AppKit #endif private var activeDynamicHandleNSLayoutConstraint: UInt8 = 0; extension NSLayoutConstraint { public var dynActive: Dynamic<Bool> { if let d: AnyObject = objc_getAssociatedObject(self, &activeDynamicHandleNSLayoutConstraint) { return (d as? Dynamic<Bool>)! } else { let d = InternalDynamic<Bool>(self.active) let bond = Bond<Bool>() { [weak self] v in if let s = self { s.active = v } } d.bindTo(bond, fire: false, strongly: false) d.retain(bond) objc_setAssociatedObject(self, &activeDynamicHandleNSLayoutConstraint, d, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return d } } }
mit
6f947cdbf784ce1e18e48ac96a33dc09
39.22449
121
0.703553
4.273319
false
false
false
false
likojack/weDrive
parse-starter-project-1-2/ParseSwiftStarterProject/ParseStarterProject/AppDelegate.swift
1
6416
// // AppDelegate.swift // // Copyright 2011-present Parse Inc. All rights reserved. // import UIKit import Bolts import Parse // If you want to use any of the UI components, uncomment this line // import ParseUI // If you want to use Crash Reporting - uncomment this line // import ParseCrashReporting @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? //-------------------------------------- // MARK: - UIApplicationDelegate //-------------------------------------- func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Enable storing and querying data from Local Datastore. // Remove this line if you don't want to use Local Datastore features or want to use cachePolicy. Parse.enableLocalDatastore() // **************************************************************************** // Uncomment this line if you want to enable Crash Reporting // ParseCrashReporting.enable() // // Uncomment and fill in with your Parse credentials: // Parse.setApplicationId("your_application_id", clientKey: "your_client_key") // // If you are using Facebook, uncomment and add your FacebookAppID to your bundle's plist as // described here: https://developers.facebook.com/docs/getting-started/facebook-sdk-for-ios/ // Uncomment the line inside ParseStartProject-Bridging-Header and the following line here: // PFFacebookUtils.initializeFacebook() // **************************************************************************** Parse.setApplicationId("w0x2zMF6iNZybWXztr3n9tz292lgO7e7IIOxYRa2", clientKey: "5VWmZAbc1hRcsL2Fd4eLt4omFEEkmnnG5nTsTQOs") PFUser.enableAutomaticUser() let defaultACL = PFACL(); // If you would like all objects to be private by default, remove this line. defaultACL.setPublicReadAccess(true) PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser:true) if application.applicationState != UIApplicationState.Background { // Track an app open here if we launch with a push, unless // "content_available" was used to trigger a background push (introduced in iOS 7). // In that case, we skip tracking here to avoid double counting the app-open. let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus") let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:") var noPushPayload = false; if let options = launchOptions { noPushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil; } if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) { PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions) } } if application.respondsToSelector("registerUserNotificationSettings:") { let userNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } else { let types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Alert | UIRemoteNotificationType.Sound application.registerForRemoteNotificationTypes(types) } return true } //-------------------------------------- // MARK: Push Notifications //-------------------------------------- func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let installation = PFInstallation.currentInstallation() installation.setDeviceTokenFromData(deviceToken) installation.saveInBackground() PFPush.subscribeToChannelInBackground("") { (succeeded: Bool, error: NSError?) in if succeeded { println("ParseStarterProject successfully subscribed to push notifications on the broadcast channel."); } else { println("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %@.", error) } } } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { if error.code == 3010 { println("Push notifications are not supported in the iOS Simulator.") } else { println("application:didFailToRegisterForRemoteNotificationsWithError: %@", error) } } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { PFPush.handlePush(userInfo) if application.applicationState == UIApplicationState.Inactive { PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo) } } /////////////////////////////////////////////////////////// // Uncomment this method if you want to use Push Notifications with Background App Refresh /////////////////////////////////////////////////////////// // func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { // if application.applicationState == UIApplicationState.Inactive { // PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo) // } // } //-------------------------------------- // MARK: Facebook SDK Integration //-------------------------------------- /////////////////////////////////////////////////////////// // Uncomment this method if you are using Facebook /////////////////////////////////////////////////////////// // func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { // return FBAppCall.handleOpenURL(url, sourceApplication:sourceApplication, session:PFFacebookUtils.session()) // } }
apache-2.0
e8b62654dfe69908598f80970aa759c8
45.832117
193
0.627805
6.041431
false
false
false
false
izqui/Poker.swift
Poker/Hand.swift
1
6074
// // Hand.swift // Poker // // Created by Jorge Izquierdo on 9/22/15. // Copyright © 2015 Jorge Izquierdo. All rights reserved. // public struct Hand { public let cards: [Card] public init(cards: [Card]) { self.cards = cards } public enum Value: Int { case HighCard = 0 case Pair case DoublePair case ThreeOfAKind case Straight case Flush case FullHouse case FourOfAKind case StraightFlush } public struct RealValue: CustomStringConvertible { let value: Value let order: [Number] public var description: String { return String(value) + self.order.reduce(" ") { $0 + $1.emojiValue } } } public func valueHand() -> RealValue { let numbers = self.cards.map { $0.number } // Shared detections let (isFlush, flushNumbers) = detectFlush(self.cards) let (isStraight, straightNumbers) = detectStraight(numbers) let (isPair, pairNumbers) = detectGroup(numbers, count: 2) // Detect first pair let (isTrio, trioNs) = detectGroup(numbers, count: 3) // Check for Straight Flush guard !isFlush || !isStraight else { return RealValue(value: .StraightFlush, order: straightNumbers)} // Check for Four of a Kind let (isFour, fourNs) = detectGroup(numbers, count: 4) guard !isFour else { return RealValue(value: .FourOfAKind, order: fourNs) } // Check for full let (isFullPair, fullNumbers) = detectGroup(trioNs, count: 2) guard !isPair || !isFullPair else { let firsts = [trioNs[0], fullNumbers[0]] let merged = firsts + fullNumbers.filter { !firsts.contains($0) } return RealValue(value: .FullHouse, order: merged) } // Check for Flush guard !isFlush else { return RealValue(value: .Flush, order: flushNumbers)} // Check for Straight guard !isStraight else { return RealValue(value: .Straight, order: straightNumbers)} // Check for Three of a Kind guard !isTrio else { return RealValue(value: .ThreeOfAKind, order: trioNs) } // Check for Double Pair let (p2, n2) = detectGroup(pairNumbers, count: 2) guard !isPair || !p2 else { let firsts = [max(pairNumbers[0], n2[0]), min(pairNumbers[0], n2[0])] // First in the array are the paired numbers ordered let merged = firsts + n2.filter { !firsts.contains($0) } // And then all the order numbers return RealValue(value: .DoublePair, order: merged) } // Check for Pair guard !isPair else { return RealValue(value: .Pair, order: pairNumbers) } // Last option is just high card return RealValue(value: .HighCard, order: numbers.sort { $0.rawValue > $1.rawValue }) } } public func bestHand(hand1: Hand, _ hand2: Hand) -> Hand { let v1 = hand1.valueHand() let v2 = hand2.valueHand() // Direct value if v1.value.rawValue > v2.value.rawValue { return hand1 } if v2.value.rawValue > v1.value.rawValue { return hand2 } // Compare numbers // We assume the same amount of numbers, since the value is the same, numbers should be the same for (one, two) in zip(v1.order, v2.order) { if one > two { return hand1 } if two > one { return hand2 } } // If we come to the end and it hasn't returned, it means there is a tie. So we can return whatever hand return hand1 } extension Hand: CustomStringConvertible { public var description: String { return self.cards.reduce("Hand: ") { $0 + $1.description + " " } } } extension Hand: Equatable { } public func ==(lhs: Hand, rhs: Hand) -> Bool { let c1 = lhs.cards let c2 = rhs.cards guard c1.count == c2.count else { return false } for i in 0..<c1.count { if c1[i] != c2[i] { return false } } return true } // This function is a bit dirty, it could use some refactor func detectStraight(numbers: [Number]) -> (Bool, [Number]){ // Beware of the ace. It can be used in A2345 and 10JQKA let sortedNumbers = numbers.flatMap { $0.straightValues }.sort() var allowedErrors = sortedNumbers.count - numbers.count guard sortedNumbers.count <= numbers.count + 1 else { return (false, [])} var lastNumber = sortedNumbers[0] var straightNumber = sortedNumbers[0] for i in 1..<sortedNumbers.count { if sortedNumbers[i]-lastNumber != 1 { if allowedErrors-- <= 0 { return (false, []) } } else { straightNumber = sortedNumbers[i] } lastNumber = sortedNumbers[i] } return (true, [Number(rawValue: straightNumber)!]) } func detectFlush(cards: [Card]) -> (Bool, [Number]) { let firstCard = cards[0] let sameSuit = cards.filter { $0.suit == firstCard.suit } guard sameSuit.count == cards.count else { return (false, []) } let orderedNumbers = cards.map { $0.number }.sort { $0.rawValue > $1.rawValue } return (true, orderedNumbers) } func detectGroup(numbers: [Number], count: Int) -> (Bool, [Number]) { let frecuencies = numberFrecuencies(numbers) let paired = frecuencies.filter { _, v in v == count }.map { k,_ in k } guard paired.count > 0 else { return (false, []) } let pair = paired[0] let notPaired = numbers.map { $0.rawValue }.filter { $0 != pair }.sort { $0 > $1 } let remaining = ([pair] + notPaired).map { Number(rawValue: $0)! } return (true, remaining) } func numberFrecuencies(numbers: [Number]) -> [Int:Int] { return numbers.map { $0.rawValue }.reduce([Int:Int]()) { a, e in var newa = a newa[e] = (a[e] ?? 0) + 1 return newa } }
mit
cbc7a68cb46721d4c003b408895a01a4
29.984694
134
0.581097
3.821901
false
false
false
false
brunophilipe/tune
tune/Window Controllers/NowPlayingWindowController.swift
1
8723
// // NowPlayingWindowController.swift // tune // // Created by Bruno Philipe on 30/4/17. // Copyright © 2017 Bruno Philipe. All rights reserved. // // 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 class NowPlayingWindowController: UIWindowController, DesiresTrackInfo, DesiresPlaybackInfo { internal weak var userInterface: UserInterface? private var windowStorage: UIWindow private var boxPanel: UIBoxPanel? = nil private var titlePanel: UICenteredTitlePanel? = nil private var songInfoPanel: SongInfoPanel? = nil var window: UIWindow { return windowStorage } var track: MediaPlayerItem? = nil var playbackInfo: MediaPlayerPlaybackInfo? = nil required init(userInterface: UserInterface) { self.userInterface = userInterface self.windowStorage = UIDialog(frame: UIFrame(x: 40, y: 0, w: userInterface.width - 40, h: 11)) self.windowStorage.controller = self window.frame = windowFrame buildPanels() } func availableSizeChanged(newSize: UISize) { window.frame = windowFrame boxPanel?.frame = boxPanelFrame titlePanel?.frame = titlePanelFrame songInfoPanel?.frame = songInfoPanelFrame if let frameChars = boxPanel?.frameChars { if (userInterface?.width ?? 70) < 70 { boxPanel?.frameChars = frameChars.replacing(topLeft: "┣", topRight: "┫") } else { boxPanel?.frameChars = frameChars.replacing(topLeft: "┳", topRight: "┓") } } } private func buildPanels() { if let ui = self.userInterface { let color = ui.sharedColorWhiteOnBlack let boxPanel = UIBoxPanel(frame: boxPanelFrame, frameColor: color) boxPanel.frameChars = UIBoxPanel.FrameChars.thickLine.replacing(topLeft: "┳", bottom: " ") window.container.addSubPanel(boxPanel) let titlePanel = UICenteredTitlePanel(frame: titlePanelFrame) titlePanel.title = "Now Playing:" window.container.addSubPanel(titlePanel) let songInfoPanel = SongInfoPanel(frame: songInfoPanelFrame, textColor: color) window.container.addSubPanel(songInfoPanel) self.boxPanel = boxPanel self.titlePanel = titlePanel self.songInfoPanel = songInfoPanel } } private var windowFrame: UIFrame { if let ui = userInterface { if ui.width < 70 { return UIFrame(x: 0, y: 2, w: ui.width, h: 11) } else { return UIFrame(x: 40, y: 0, w: ui.width - 40, h: 11) } } else { return UIFrame(x: 40, y: 0, w: 40, h: 11) } } private var boxPanelFrame: UIFrame { return UIFrame(origin: .zero, size: window.frame.size) } private var titlePanelFrame: UIFrame { return UIFrame(origin: UIPoint(1, 1), size: window.frame.size.offset(x: -2).replacing(y: 1)) } private var songInfoPanelFrame: UIFrame { return UIFrame(origin: UIPoint(1, 2), size: window.frame.size.offset(x: -2, y: -2)) } } private class SongInfoPanel: UIPanel { private var oldTrack: MediaPlayerItem? = nil private var songNamePanel: UICenteredTitlePanel? = nil private var artistNamePanel: UICenteredTitlePanel? = nil private var albumNamePanel: UICenteredTitlePanel? = nil private var infoIconsPanel: UICenteredTitlePanel? = nil var textColor: UIColorPair override var frame: UIFrame { didSet { resizeSongInfoPanels() } } override var window: UIWindow? { didSet { if songNamePanel == nil { initializeSongInfoPanels() } } } init(frame: UIFrame, textColor: UIColorPair) { self.textColor = textColor super.init(frame: frame) } override func draw() { if let window = self.window, let controller = (window.controller as? NowPlayingWindowController) { let track = controller.track let playbackInfo = controller.playbackInfo let maxLength = Int(frame.width - 3) // Clean if the track changed if track != oldTrack { window.cleanRegion(frame: frame) oldTrack = track } if maxLength > 7, let track = track { let info = processTrackInformation(track) songNamePanel?.title = info.title.truncated(to: maxLength) artistNamePanel?.title = info.artist.truncated(to: maxLength) albumNamePanel?.title = info.album.truncated(to: maxLength) // Separator window.drawText("╍" * frame.width, at: UIPoint(frame.origin.x, frame.height - 2), withColorPair: textColor) // Track progress + duration bar let pY = frame.height let availableWidth = frame.width - 4 let lengthStr = info.duration let progressStr = (playbackInfo?.progress ?? 0.0).durationString window.drawText(progressStr, at: UIPoint(frame.origin.x + 2, pY), withColorPair: textColor) window.drawText(lengthStr, at: UIPoint(frame.origin.x + 2 + availableWidth - lengthStr.width, pY), withColorPair: textColor) let barLength = availableWidth - lengthStr.width - progressStr.width - 4 var playedBarLength: Int32 = 0 if let duration = track.time, let progress = playbackInfo?.progress, progress > 0 { playedBarLength = Int32(ceil(Double(barLength) * (progress / duration))) } if playedBarLength > 0 { window.drawText("▓" * playedBarLength, at: UIPoint(frame.origin.x + progressStr.width + 4, pY), withColorPair: textColor) } window.drawText("░" * (barLength - playedBarLength), at: UIPoint(frame.origin.x + progressStr.width + playedBarLength + 4, pY), withColorPair: textColor) } else { songNamePanel?.title = "Nothing..." artistNamePanel?.title = nil albumNamePanel?.title = "press s to search for music" } if let playbackInfo = playbackInfo { var infoString = "" if playbackInfo.shuffleOn { infoString += "⤨ " } if playbackInfo.repeatOn { infoString += "⟳ " } infoIconsPanel?.title = infoString } else { infoIconsPanel?.title = nil } } super.draw() } private func initializeSongInfoPanels() { if let textColor = window?.controller?.userInterface?.registerColorPair(fore: COLOR_BLACK, back: COLOR_WHITE) { let attributes: UITextAttributes = [.reverse] let songNamePanel = UICenteredTitlePanel(frame: songNamePanelFrame) songNamePanel.attributes = attributes songNamePanel.textColor = textColor addSubPanel(songNamePanel) let artistNamePanel = UICenteredTitlePanel(frame: artistNamePanelFrame) artistNamePanel.attributes = attributes artistNamePanel.textColor = textColor addSubPanel(artistNamePanel) let albumNamePanel = UICenteredTitlePanel(frame: albumNamePanelFrame) albumNamePanel.attributes = attributes albumNamePanel.textColor = textColor addSubPanel(albumNamePanel) let infoIconsPanel = UICenteredTitlePanel(frame: infoIconsPanelFrame) infoIconsPanel.attributes = attributes infoIconsPanel.textColor = textColor addSubPanel(infoIconsPanel) self.songNamePanel = songNamePanel self.artistNamePanel = artistNamePanel self.albumNamePanel = albumNamePanel self.infoIconsPanel = infoIconsPanel } } private var songNamePanelFrame: UIFrame { return UIFrame(origin: UIPoint(1, 3), size: UISize(frame.width, 1)) } private var artistNamePanelFrame: UIFrame { return UIFrame(origin: UIPoint(1, 4), size: UISize(frame.width, 1)) } private var albumNamePanelFrame: UIFrame { return UIFrame(origin: UIPoint(1, 5), size: UISize(frame.width, 1)) } private var infoIconsPanelFrame: UIFrame { return UIFrame(origin: UIPoint(1, 6), size: UISize(frame.width, 1)) } private func resizeSongInfoPanels() { songNamePanel?.frame = songNamePanelFrame artistNamePanel?.frame = artistNamePanelFrame albumNamePanel?.frame = albumNamePanelFrame infoIconsPanel?.frame = infoIconsPanelFrame } private func processTrackInformation(_ track: MediaPlayerItem) -> ProcessedTrackInfo { var album = track.album if let year = track.year { album += " (\(year))" } return ProcessedTrackInfo(title: track.name, artist: track.artist, album: album, duration: track.time?.durationString ?? "--:--") } private struct ProcessedTrackInfo { let title, artist, album, duration: String } }
gpl-3.0
a496cdd9e580297bc1febad53537cd48
24.745562
131
0.707079
3.443609
false
false
false
false
domenicosolazzo/practice-swift
Security/Authenticating the User with Touch ID/Authenticating the User with Touch ID/ViewController.swift
1
2421
// // ViewController.swift // Authenticating the User with Touch ID // // Created by Domenico on 24/05/15. // License MIT // import UIKit import LocalAuthentication class ViewController: UIViewController { @IBOutlet weak var checkButton: UIButton! @IBOutlet weak var useButton: UIButton! @IBAction func checkAvailability(_ sender: UIButton) { // Handle for using the TouchID API let context = LAContext() var error: NSError? let isTouchIDAvailable = context.canEvaluatePolicy( LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &error) useButton.isEnabled = isTouchIDAvailable if isTouchIDAvailable == false{ displayAlertWithTitle("TouchID error", message: "Sorry! TouchID is not available"); } } @IBAction func useTouchID(_ sender: UIButton) { let context = LAContext() var _: NSError let reason = "Please authenticate with TouchID" context.evaluatePolicy( LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) {[weak self](success:Bool, error:NSError?) -> Void in let title = "Touch ID Result"; var message = "You have been authenticated" if success == false{ message = "Failed to authenticate you." if let theError = error{ message = "\(message). Error: \(theError)" } } self!.displayAlertWithTitle(title, message: message); } as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void } func displayAlertWithTitle(_ title: String, message: String){ let alertController = UIAlertController( title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alertController.addAction( UIAlertAction( title: "OK", style: UIAlertActionStyle.default, handler: nil ) ) self.present(alertController, animated: true, completion: nil) } }
mit
bed4ab110105bcb0ad4f7bd7bcdc2993
33.098592
198
0.562577
5.489796
false
false
false
false
remlostime/one
one/one/ViewControllers/SharePostViewController.swift
1
3513
// // SharePostViewController.swift // one // // Created by Kai Chen on 1/2/17. // Copyright © 2017 Kai Chen. All rights reserved. // import UIKit import Parse import MBProgressHUD class SharePostViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var contentTextField: UITextField! @IBOutlet weak var shareButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "One" let imageViewTap = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped)) imageView.addGestureRecognizer(imageViewTap) let keyboardDismissTap = UITapGestureRecognizer(target: self, action: #selector(keyboardDismissTapped)) self.view.addGestureRecognizer(keyboardDismissTap) } func keyboardDismissTapped() { self.contentTextField.endEditing(true) } func imageViewTapped() { let pickerVC = UIImagePickerController() pickerVC.delegate = self pickerVC.allowsEditing = true pickerVC.sourceType = .photoLibrary present(pickerVC, animated: true, completion: nil) } func postImage() { let object = PFObject(className: Post.modelName.rawValue) object[User.id.rawValue] = PFUser.current()?.username object[User.profileImage.rawValue] = PFUser.current()?.value(forKey: User.profileImage.rawValue) as? PFFile if (contentTextField.text?.isEmpty)! { object[Post.title.rawValue] = "" } else { object[Post.title.rawValue] = contentTextField.text?.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) } let imageData = UIImagePNGRepresentation(imageView.image!) let imageFile = PFFile(name: "post.png", data: imageData!) object[Post.picture.rawValue] = imageFile object[Post.uuid.rawValue] = UUID().uuidString MBProgressHUD.showAdded(to: self.view, animated: true) object.saveInBackground { [weak self](success: Bool, error: Error?) in guard let strongSelf = self else { return } if error == nil { MBProgressHUD.hide(for: strongSelf.view, animated: true) NotificationCenter.default.post(name: .newPostIsSent, object: nil) strongSelf.tabBarController?.selectedIndex = 0 } } } @IBAction func topRightPostButtonTapped(_ sender: UIBarButtonItem) { postImage() } @IBAction func sharePostButtonTapped(_ sender: UIButton) { postImage() } @IBAction func removeButtonTapped(_ sender: UIButton) { imageView.image = nil shareButton.isEnabled = false shareButton.backgroundColor = .lightGray } } extension SharePostViewController: UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { imageView.image = info[UIImagePickerControllerEditedImage] as? UIImage dismiss(animated: true, completion: nil) shareButton.isEnabled = true shareButton.backgroundColor = .sharePostButtonColor } public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } } extension SharePostViewController: UINavigationControllerDelegate { }
gpl-3.0
9de277dc5bb6009fc676db9e8cfb34f6
31.82243
126
0.666572
5.249626
false
false
false
false
twocentstudios/tinykittenstv
tinykittenstv/InfoViewController.swift
1
1286
// // InfoViewController.swift // tinykittenstv // // Created by Christopher Trott on 4/13/17. // Copyright © 2017 twocentstudios. All rights reserved. // import UIKit import Mortar final class InfoViewController: UIViewController { enum ViewData { case normal(String) case error(String) } let infoLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.title2) label.numberOfLines = 0 label.textAlignment = .center return label }() let viewData: ViewData init(_ viewData: ViewData) { self.viewData = viewData super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view |+| [ infoLabel ] infoLabel |=| view.m_edges ~ (80, 80, 80, 80) switch viewData { case .normal(let text): infoLabel.text = text infoLabel.textColor = Color.gray85 case .error(let text): infoLabel.text = text infoLabel.textColor = Color.danger } } }
mit
431ea1a8cafb223dd120c42ebf5caa22
23.245283
79
0.582101
4.589286
false
false
false
false
rajagp/iOS-WKWebViewBridgeExample-Swift
WKWebViewBridgeExample/ViewController.swift
1
7034
// // ViewController.swift // WKWebViewBridgeExample // // Created by Priya Rajagopal on 12/8/14. // Copyright (c) 2014 Lunaria Software LLC. All rights reserved. // import UIKit import WebKit class ViewController: UIViewController, WKScriptMessageHandler, WKNavigationDelegate { var webView: WKWebView? var buttonClicked:Int = 0 var colors:[String] = ["0xff00ff","#ff0000","#ffcc00","#ccff00","#ff0033","#ff0099","#cc0099","#0033ff","#0066ff","#ffff00","#0000ff","#0099cc"]; var webConfig:WKWebViewConfiguration { get { // Create WKWebViewConfiguration instance var webCfg:WKWebViewConfiguration = WKWebViewConfiguration() // Setup WKUserContentController instance for injecting user script var userController:WKUserContentController = WKUserContentController() // Add a script message handler for receiving "buttonClicked" event notifications posted from the JS document using window.webkit.messageHandlers.buttonClicked.postMessage script message userController.addScriptMessageHandler(self, name: "buttonClicked") // Get script that's to be injected into the document let js:String = buttonClickEventTriggeredScriptToAddToDocument() // Specify when and where and what user script needs to be injected into the web document var userScript:WKUserScript = WKUserScript(source: js, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: false) // Add the user script to the WKUserContentController instance userController.addUserScript(userScript) // Configure the WKWebViewConfiguration instance with the WKUserContentController webCfg.userContentController = userController; return webCfg; } } override func viewDidLoad() { super.viewDidLoad() // Create a WKWebView instance webView = WKWebView (frame: self.view.frame, configuration: webConfig) // Delegate to handle navigation of web content webView!.navigationDelegate = self view.addSubview(webView!) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // Load the HTML document loadHtml() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) var fileName:String = String("\( NSProcessInfo.processInfo().globallyUniqueString)_TestFile.html") var error:NSError? var tempHtmlPath:String = NSTemporaryDirectory().stringByAppendingPathComponent(fileName) NSFileManager.defaultManager().removeItemAtPath(tempHtmlPath, error: &error) webView = nil } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // WKNavigationDelegate func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { NSLog("%s", __FUNCTION__) } func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) { NSLog("%s. With Error %@", __FUNCTION__,error) showAlertWithMessage("Failed to load file with error \(error.localizedDescription)!") } // File Loading func loadHtml() { // NOTE: Due to a bug in webKit as of iOS 8.1.1 we CANNOT load a local resource when running on device. Once that is fixed, we can get rid of the temp copy let mainBundle:NSBundle = NSBundle(forClass: ViewController.self) var error:NSError? var fileName:String = String("\( NSProcessInfo.processInfo().globallyUniqueString)_TestFile.html") var tempHtmlPath:String? = NSTemporaryDirectory().stringByAppendingPathComponent(fileName) if let htmlPath = mainBundle.pathForResource("TestFile", ofType: "html") { NSFileManager.defaultManager().copyItemAtPath(htmlPath, toPath: tempHtmlPath!, error: &error) if tempHtmlPath != nil { let requestUrl = NSURLRequest(URL: NSURL(fileURLWithPath: tempHtmlPath!)!) webView?.loadRequest(requestUrl) } } else { showAlertWithMessage("Could not load HTML File!") } } // Button Click Script to Add to Document func buttonClickEventTriggeredScriptToAddToDocument() ->String{ // Script: When window is loaded, execute an anonymous function that adds a "click" event handler function to the "ClickMeButton" button element. The "click" event handler calls back into our native code via the window.webkit.messageHandlers.buttonClicked.postMessage call var script:String? if let filePath:String = NSBundle(forClass: ViewController.self).pathForResource("ClickMeEventRegister", ofType:"js") { script = String (contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil) } return script!; } // WKScriptMessageHandler Delegate func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if let messageBody:NSDictionary = message.body as? NSDictionary { let idOfTappedButton:String = messageBody["ButtonId"] as String updateColorOfButtonWithId(idOfTappedButton) } } // Update color of Button with specified Id func updateColorOfButtonWithId(buttonId:String) { let count:UInt32 = UInt32(colors.count) let index:Int = Int(arc4random_uniform(count)) let color:String = colors [index] // Script that changes the color of tapped button var js2:String = String(format: "var button = document.getElementById('%@'); button.style.backgroundColor='%@';", buttonId,color) webView?.evaluateJavaScript(js2, completionHandler: { (AnyObject, NSError) -> Void in NSLog("%s", __FUNCTION__) }) } // Helper func showAlertWithMessage(message:String) { let alertAction:UIAlertAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (UIAlertAction) -> Void in self.dismissViewControllerAnimated(true, completion: { () -> Void in }) } let alertView:UIAlertController = UIAlertController(title: nil, message: message, preferredStyle: UIAlertControllerStyle.Alert) alertView.addAction(alertAction) self.presentViewController(alertView, animated: true, completion: { () -> Void in }) } }
mit
c16ab2cd667d603a6ea30e283e537abb
39.65896
280
0.644583
5.551697
false
true
false
false
cloudant/swift-cloudant
Source/SwiftCloudant/Operations/Documents/DeleteAttachmentOperation.swift
1
2919
// // DeleteAttachmentOperation.swift // SwiftCloudant // // Created by Rhys Short on 17/05/2016. // Copyright (c) 2016 IBM Corp. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // import Foundation /** An Operation to delete an attachment from a document. Example usage: ``` let deleteAttachment = DeleteAttachmentOperation(name: "myAwesomeAttachment", documentID: "exampleDocId", revision: "1-arevision", databaseName: "exampledb"){(response, info, error) in if let error = error { // handle the error } else { // process successful response } } client.add(operation: deleteAttachment) ``` */ public class DeleteAttachmentOperation: CouchDatabaseOperation, JSONOperation { /** Creates the operation - parameter name : The name of the attachment to delete - parameter documentID : the ID of the document that the attachment is attached to. - parameter revision : the revision of the document that the attachment is attached to. - parameter databaseName : the name of the database that the contains the attachment. - parameter completionHandler: optional handler to run when the operation completes. */ public init(name: String, documentID: String, revision: String, databaseName: String, completionHandler: (([String : Any]?, HTTPInfo?, Error?) -> Void)? = nil) { self.name = name self.documentID = documentID self.revision = revision self.databaseName = databaseName self.completionHandler = completionHandler } public let databaseName: String public let completionHandler: (( [String : Any]?, HTTPInfo?, Error?) -> Void)? /** The ID of the document that the attachment is attached to. */ public let documentID: String /** The revision of the document that the attachment is attached to. */ public let revision: String /** The name of the attachment. */ public let name: String public var endpoint: String { return "/\(self.databaseName)/\(documentID)/\(name)" } public var parameters: [String: String] { return ["rev": revision] } public var method: String { return "DELETE" } }
apache-2.0
03d4d5de2c0d70db65b27e354063a57a
31.076923
165
0.641316
4.856905
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureAuthentication/Sources/FeatureAuthenticationUI/EmailLogin/Credentials/TwoFAReducer.swift
1
2665
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import ComposableArchitecture import FeatureAuthenticationDomain import WalletPayloadKit // MARK: - Type public enum TwoFAAction: Equatable { public enum IncorrectTwoFAContext: Equatable { case incorrect case missingCode case none var hasError: Bool { self != .none } } case didChangeTwoFACode(String) case didChangeTwoFACodeAttemptsLeft(Int) case showIncorrectTwoFACodeError(IncorrectTwoFAContext) case showResendSMSButton(Bool) case showTwoFACodeField(Bool) } private enum Constants { static let twoFACodeMaxAttemptsLeft = 5 } // MARK: - Properties struct TwoFAState: Equatable { var twoFACode: String var twoFAType: WalletAuthenticatorType var isTwoFACodeFieldVisible: Bool var isResendSMSButtonVisible: Bool var isTwoFACodeIncorrect: Bool var twoFACodeIncorrectContext: TwoFAAction.IncorrectTwoFAContext var twoFACodeAttemptsLeft: Int init( twoFACode: String = "", twoFAType: WalletAuthenticatorType = .standard, isTwoFACodeFieldVisible: Bool = false, isResendSMSButtonVisible: Bool = false, isTwoFACodeIncorrect: Bool = false, twoFACodeIncorrectContext: TwoFAAction.IncorrectTwoFAContext = .none, twoFACodeAttemptsLeft: Int = Constants.twoFACodeMaxAttemptsLeft ) { self.twoFACode = twoFACode self.twoFAType = twoFAType self.isTwoFACodeFieldVisible = isTwoFACodeFieldVisible self.isResendSMSButtonVisible = isResendSMSButtonVisible self.isTwoFACodeIncorrect = isTwoFACodeIncorrect self.twoFACodeIncorrectContext = twoFACodeIncorrectContext self.twoFACodeAttemptsLeft = twoFACodeAttemptsLeft } } let twoFAReducer = Reducer< TwoFAState, TwoFAAction, CredentialsEnvironment > { state, action, _ in switch action { case .didChangeTwoFACode(let code): state.twoFACode = code return .none case .didChangeTwoFACodeAttemptsLeft(let attemptsLeft): state.twoFACodeAttemptsLeft = attemptsLeft return Effect(value: .showIncorrectTwoFACodeError(.incorrect)) case .showIncorrectTwoFACodeError(let context): state.twoFACodeIncorrectContext = context state.isTwoFACodeIncorrect = context.hasError return .none case .showResendSMSButton(let shouldShow): state.isResendSMSButtonVisible = shouldShow return .none case .showTwoFACodeField(let isVisible): state.twoFACode = "" state.isTwoFACodeFieldVisible = isVisible return .none } }
lgpl-3.0
95befe94c96bd66ee358627d31de60e4
30.341176
77
0.718844
4.289855
false
false
false
false
huonw/swift
stdlib/public/SDK/Foundation/Data.swift
1
80832
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if DEPLOYMENT_RUNTIME_SWIFT #if os(macOS) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif import CoreFoundation internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) { munmap(mem, length) } internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) { free(mem) } internal func __NSDataIsCompact(_ data: NSData) -> Bool { return data._isCompact() } #else @_exported import Foundation // Clang module import _SwiftFoundationOverlayShims import _SwiftCoreFoundationOverlayShims internal func __NSDataIsCompact(_ data: NSData) -> Bool { if #available(OSX 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) { return data._isCompact() } else { var compact = true let len = data.length data.enumerateBytes { (_, byteRange, stop) in if byteRange.length != len { compact = false } stop.pointee = true } return compact } } #endif @usableFromInline internal final class _DataStorage { @usableFromInline enum Backing { // A mirror of the Objective-C implementation that is suitable to inline in Swift case swift // these two storage points for immutable and mutable data are reserved for references that are returned by "known" // cases from Foundation in which implement the backing of struct Data, these have signed up for the concept that // the backing bytes/mutableBytes pointer does not change per call (unless mutated) as well as the length is ok // to be cached, this means that as long as the backing reference is retained no further objc_msgSends need to be // dynamically dispatched out to the reference. case immutable(NSData) // This will most often (perhaps always) be NSConcreteData case mutable(NSMutableData) // This will often (perhaps always) be NSConcreteMutableData // These are reserved for foreign sources where neither Swift nor Foundation are fully certain whom they belong // to from an object inheritance standpoint, this means that all bets are off and the values of bytes, mutableBytes, // and length cannot be cached. This also means that all methods are expected to dynamically dispatch out to the // backing reference. case customReference(NSData) // tracks data references that are only known to be immutable case customMutableReference(NSMutableData) // tracks data references that are known to be mutable } static let maxSize = Int.max >> 1 static let vmOpsThreshold = NSPageSize() * 4 static func allocate(_ size: Int, _ clear: Bool) -> UnsafeMutableRawPointer? { if clear { return calloc(1, size) } else { return malloc(size) } } @usableFromInline static func move(_ dest_: UnsafeMutableRawPointer, _ source_: UnsafeRawPointer?, _ num_: Int) { var dest = dest_ var source = source_ var num = num_ if _DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 { let pages = NSRoundDownToMultipleOfPageSize(num) NSCopyMemoryPages(source!, dest, pages) source = source!.advanced(by: pages) dest = dest.advanced(by: pages) num -= pages } if num > 0 { memmove(dest, source!, num) } } static func shouldAllocateCleared(_ size: Int) -> Bool { return (size > (128 * 1024)) } @usableFromInline var _bytes: UnsafeMutableRawPointer? @usableFromInline var _length: Int @usableFromInline var _capacity: Int @usableFromInline var _needToZero: Bool @usableFromInline var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? @usableFromInline var _backing: Backing = .swift @usableFromInline var _offset: Int @usableFromInline var bytes: UnsafeRawPointer? { @inlinable get { switch _backing { case .swift: return UnsafeRawPointer(_bytes)?.advanced(by: -_offset) case .immutable: return UnsafeRawPointer(_bytes)?.advanced(by: -_offset) case .mutable: return UnsafeRawPointer(_bytes)?.advanced(by: -_offset) case .customReference(let d): return d.bytes.advanced(by: -_offset) case .customMutableReference(let d): return d.bytes.advanced(by: -_offset) } } } @usableFromInline @discardableResult func withUnsafeBytes<Result>(in range: Range<Int>, apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { switch _backing { case .swift: fallthrough case .immutable: fallthrough case .mutable: return try apply(UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, _length))) case .customReference(let d): if __NSDataIsCompact(d) { let len = d.length guard len > 0 else { return try apply(UnsafeRawBufferPointer(start: nil, count: 0)) } return try apply(UnsafeRawBufferPointer(start: d.bytes.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, len))) } else { var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: range.count, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let sliceRange = NSRange(location: range.lowerBound - _offset, length: range.count) var enumerated = 0 d.enumerateBytes { (ptr, byteRange, stop) in if byteRange.upperBound - _offset < range.lowerBound { // before the range that we are looking for... } else if byteRange.lowerBound - _offset > range.upperBound { stop.pointee = true // we are past the range in question so we need to stop } else { // the byteRange somehow intersects the range in question that we are looking for... let lower = Swift.max(byteRange.lowerBound - _offset, range.lowerBound) let upper = Swift.min(byteRange.upperBound - _offset, range.upperBound) let len = upper - lower memcpy(buffer.baseAddress!.advanced(by: enumerated), ptr.advanced(by: lower - (byteRange.lowerBound - _offset)), len) enumerated += len if upper == range.upperBound { stop.pointee = true } } } return try apply(UnsafeRawBufferPointer(buffer)) } case .customMutableReference(let d): if __NSDataIsCompact(d) { let len = d.length guard len > 0 else { return try apply(UnsafeRawBufferPointer(start: nil, count: 0)) } return try apply(UnsafeRawBufferPointer(start: d.bytes.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, len))) } else { var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: range.count, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let sliceRange = NSRange(location: range.lowerBound - _offset, length: range.count) var enumerated = 0 d.enumerateBytes { (ptr, byteRange, stop) in if byteRange.upperBound - _offset < range.lowerBound { // before the range that we are looking for... } else if byteRange.lowerBound - _offset > range.upperBound { stop.pointee = true // we are past the range in question so we need to stop } else { // the byteRange somehow intersects the range in question that we are looking for... let lower = Swift.max(byteRange.lowerBound - _offset, range.lowerBound) let upper = Swift.min(byteRange.upperBound - _offset, range.upperBound) let len = upper - lower memcpy(buffer.baseAddress!.advanced(by: enumerated), ptr.advanced(by: lower - (byteRange.lowerBound - _offset)), len) enumerated += len if upper == range.upperBound { stop.pointee = true } } } return try apply(UnsafeRawBufferPointer(buffer)) } } } @usableFromInline @discardableResult func withUnsafeMutableBytes<Result>(in range: Range<Int>, apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { switch _backing { case .swift: fallthrough case .mutable: return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, _length))) case .customMutableReference(let d): let len = d.length return try apply(UnsafeMutableRawBufferPointer(start: d.mutableBytes.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, len))) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData _backing = .mutable(data) _bytes = data.mutableBytes return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, _length))) case .customReference(let d): let data = d.mutableCopy() as! NSMutableData _backing = .customMutableReference(data) let len = data.length return try apply(UnsafeMutableRawBufferPointer(start: data.mutableBytes.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, len))) } } var mutableBytes: UnsafeMutableRawPointer? { @inlinable get { switch _backing { case .swift: return _bytes?.advanced(by: -_offset) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .mutable(data) _bytes = data.mutableBytes return _bytes?.advanced(by: -_offset) case .mutable: return _bytes?.advanced(by: -_offset) case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .customMutableReference(data) return data.mutableBytes.advanced(by: -_offset) case .customMutableReference(let d): return d.mutableBytes.advanced(by: -_offset) } } } @usableFromInline var length: Int { @inlinable get { switch _backing { case .swift: return _length case .immutable: return _length case .mutable: return _length case .customReference(let d): return d.length case .customMutableReference(let d): return d.length } } @inlinable set { setLength(newValue) } } func _freeBytes() { if let bytes = _bytes { if let dealloc = _deallocator { dealloc(bytes, length) } else { free(bytes) } } } func enumerateBytes(in range: Range<Int>, _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) { var stopv: Bool = false var data: NSData switch _backing { case .swift: fallthrough case .immutable: fallthrough case .mutable: block(UnsafeBufferPointer<UInt8>(start: _bytes?.advanced(by: range.lowerBound - _offset).assumingMemoryBound(to: UInt8.self), count: Swift.min(range.count, _length)), 0, &stopv) return case .customReference(let d): data = d break case .customMutableReference(let d): data = d break } data.enumerateBytes { (ptr, region, stop) in // any region that is not in the range should be skipped guard range.contains(region.lowerBound) || range.contains(region.upperBound) else { return } var regionAdjustment = 0 if region.lowerBound < range.lowerBound { regionAdjustment = range.lowerBound - (region.lowerBound - _offset) } let bytePtr = ptr.advanced(by: regionAdjustment).assumingMemoryBound(to: UInt8.self) let effectiveLength = Swift.min((region.location - _offset) + region.length, range.upperBound) - (region.location - _offset) block(UnsafeBufferPointer(start: bytePtr, count: effectiveLength - regionAdjustment), region.location + regionAdjustment - _offset, &stopv) if stopv { stop.pointee = true } } } @usableFromInline @inline(never) func _grow(_ newLength: Int, _ clear: Bool) { let cap = _capacity var additionalCapacity = (newLength >> (_DataStorage.vmOpsThreshold <= newLength ? 2 : 1)) if Int.max - additionalCapacity < newLength { additionalCapacity = 0 } var newCapacity = Swift.max(cap, newLength + additionalCapacity) let origLength = _length var allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity) var newBytes: UnsafeMutableRawPointer? = nil if _bytes == nil { newBytes = _DataStorage.allocate(newCapacity, allocateCleared) if newBytes == nil { /* Try again with minimum length */ allocateCleared = clear && _DataStorage.shouldAllocateCleared(newLength) newBytes = _DataStorage.allocate(newLength, allocateCleared) } } else { let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4) if allocateCleared && tryCalloc { newBytes = _DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { _DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } /* Where calloc/memmove/free fails, realloc might succeed */ if newBytes == nil { allocateCleared = false if _deallocator != nil { newBytes = _DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { _DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() _deallocator = nil } } else { newBytes = realloc(_bytes!, newCapacity) } } /* Try again with minimum length */ if newBytes == nil { newCapacity = newLength allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity) if allocateCleared && tryCalloc { newBytes = _DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { _DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } if newBytes == nil { allocateCleared = false newBytes = realloc(_bytes!, newCapacity) } } } if newBytes == nil { /* Could not allocate bytes */ // At this point if the allocation cannot occur the process is likely out of memory // and Bad-Things™ are going to happen anyhow fatalError("unable to allocate memory for length (\(newLength))") } if origLength < newLength && clear && !allocateCleared { memset(newBytes!.advanced(by: origLength), 0, newLength - origLength) } /* _length set by caller */ _bytes = newBytes _capacity = newCapacity /* Realloc/memset doesn't zero out the entire capacity, so we must be safe and clear next time we grow the length */ _needToZero = !allocateCleared } @inlinable func setLength(_ length: Int) { switch _backing { case .swift: let origLength = _length let newLength = length if _capacity < newLength || _bytes == nil { _grow(newLength, true) } else if origLength < newLength && _needToZero { memset(_bytes! + origLength, 0, newLength - origLength) } else if newLength < origLength { _needToZero = true } _length = newLength case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .mutable(data) _length = length _bytes = data.mutableBytes case .mutable(let d): d.length = length _length = length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .customMutableReference(data) case .customMutableReference(let d): d.length = length } } @inlinable func append(_ bytes: UnsafeRawPointer, length: Int) { precondition(length >= 0, "Length of appending bytes must not be negative") switch _backing { case .swift: let origLength = _length let newLength = origLength + length if _capacity < newLength || _bytes == nil { _grow(newLength, false) } _length = newLength _DataStorage.move(_bytes!.advanced(by: origLength), bytes, length) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.append(bytes, length: length) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.append(bytes, length: length) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.append(bytes, length: length) _backing = .customMutableReference(data) case .customMutableReference(let d): d.append(bytes, length: length) } } // fast-path for appending directly from another data storage @inlinable func append(_ otherData: _DataStorage, startingAt start: Int, endingAt end: Int) { let otherLength = otherData.length if otherLength == 0 { return } if let bytes = otherData.bytes { append(bytes.advanced(by: start), length: end - start) } } @inlinable func append(_ otherData: Data) { otherData.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, _, _) in append(buffer.baseAddress!, length: buffer.count) } } @inlinable func increaseLength(by extraLength: Int) { if extraLength == 0 { return } switch _backing { case .swift: let origLength = _length let newLength = origLength + extraLength if _capacity < newLength || _bytes == nil { _grow(newLength, true) } else if _needToZero { memset(_bytes!.advanced(by: origLength), 0, extraLength) } _length = newLength case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.increaseLength(by: extraLength) _backing = .mutable(data) _length += extraLength _bytes = data.mutableBytes case .mutable(let d): d.increaseLength(by: extraLength) _length += extraLength _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.increaseLength(by: extraLength) _backing = .customReference(data) case .customMutableReference(let d): d.increaseLength(by: extraLength) } } @usableFromInline func get(_ index: Int) -> UInt8 { switch _backing { case .swift: fallthrough case .immutable: fallthrough case .mutable: return _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee case .customReference(let d): if __NSDataIsCompact(d) { return d.bytes.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee } else { var byte: UInt8 = 0 d.enumerateBytes { (ptr, range, stop) in if NSLocationInRange(index, range) { let offset = index - range.location - _offset byte = ptr.advanced(by: offset).assumingMemoryBound(to: UInt8.self).pointee stop.pointee = true } } return byte } case .customMutableReference(let d): if __NSDataIsCompact(d) { return d.bytes.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee } else { var byte: UInt8 = 0 d.enumerateBytes { (ptr, range, stop) in if NSLocationInRange(index, range) { let offset = index - range.location - _offset byte = ptr.advanced(by: offset).assumingMemoryBound(to: UInt8.self).pointee stop.pointee = true } } return byte } } } @inlinable func set(_ index: Int, to value: UInt8) { switch _backing { case .swift: fallthrough case .mutable: _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee = value default: var theByte = value let range = NSRange(location: index, length: 1) replaceBytes(in: range, with: &theByte, length: 1) } } @inlinable func replaceBytes(in range: NSRange, with bytes: UnsafeRawPointer?) { if range.length == 0 { return } switch _backing { case .swift: if _length < range.location + range.length { let newLength = range.location + range.length if _capacity < newLength { _grow(newLength, false) } _length = newLength } _DataStorage.move(_bytes!.advanced(by: range.location - _offset), bytes!, range.length) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) _backing = .customMutableReference(data) case .customMutableReference(let d): d.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) } } @inlinable func replaceBytes(in range_: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) { let range = NSRange(location: range_.location - _offset, length: range_.length) let currentLength = _length let resultingLength = currentLength - range.length + replacementLength switch _backing { case .swift: let shift = resultingLength - currentLength var mutableBytes = _bytes if resultingLength > currentLength { setLength(resultingLength) mutableBytes = _bytes! } /* shift the trailing bytes */ let start = range.location let length = range.length if shift != 0 { memmove(mutableBytes! + start + replacementLength, mutableBytes! + start + length, currentLength - start - length) } if replacementLength != 0 { if let replacementBytes = replacementBytes { memmove(mutableBytes! + start, replacementBytes, replacementLength) } else { memset(mutableBytes! + start, 0, replacementLength) } } if resultingLength < currentLength { setLength(resultingLength) } case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) _backing = .mutable(d) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) _backing = .customMutableReference(data) case .customMutableReference(let d): d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) } } @inlinable func resetBytes(in range_: NSRange) { let range = NSRange(location: range_.location - _offset, length: range_.length) if range.length == 0 { return } switch _backing { case .swift: if _length < range.location + range.length { let newLength = range.location + range.length if _capacity < newLength { _grow(newLength, false) } _length = newLength } memset(_bytes!.advanced(by: range.location), 0, range.length) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.resetBytes(in: range) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.resetBytes(in: range) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.resetBytes(in: range) _backing = .customMutableReference(data) case .customMutableReference(let d): d.resetBytes(in: range) } } @usableFromInline convenience init() { self.init(capacity: 0) } @usableFromInline init(length: Int) { precondition(length < _DataStorage.maxSize) var capacity = (length < 1024 * 1024 * 1024) ? length + (length >> 2) : length if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } let clear = _DataStorage.shouldAllocateCleared(length) _bytes = _DataStorage.allocate(capacity, clear)! _capacity = capacity _needToZero = !clear _length = 0 _offset = 0 setLength(length) } @usableFromInline init(capacity capacity_: Int) { var capacity = capacity_ precondition(capacity < _DataStorage.maxSize) if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = 0 _bytes = _DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _offset = 0 } @usableFromInline init(bytes: UnsafeRawPointer?, length: Int) { precondition(length < _DataStorage.maxSize) _offset = 0 if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil } else if _DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = _DataStorage.allocate(length, false)! _DataStorage.move(_bytes!, bytes, length) } else { var capacity = length if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = _DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _DataStorage.move(_bytes!, bytes, length) } } @usableFromInline init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?, offset: Int) { precondition(length < _DataStorage.maxSize) _offset = offset if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil if let dealloc = deallocator, let bytes_ = bytes { dealloc(bytes_, length) } } else if !copy { _capacity = length _length = length _needToZero = false _bytes = bytes _deallocator = deallocator } else if _DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = _DataStorage.allocate(length, false)! _DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } else { var capacity = length if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = _DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } } @usableFromInline init(immutableReference: NSData, offset: Int) { _offset = offset _bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes) _capacity = 0 _needToZero = false _length = immutableReference.length _backing = .immutable(immutableReference) } @usableFromInline init(mutableReference: NSMutableData, offset: Int) { _offset = offset _bytes = mutableReference.mutableBytes _capacity = 0 _needToZero = false _length = mutableReference.length _backing = .mutable(mutableReference) } @usableFromInline init(customReference: NSData, offset: Int) { _offset = offset _bytes = nil _capacity = 0 _needToZero = false _length = 0 _backing = .customReference(customReference) } @usableFromInline init(customMutableReference: NSMutableData, offset: Int) { _offset = offset _bytes = nil _capacity = 0 _needToZero = false _length = 0 _backing = .customMutableReference(customMutableReference) } deinit { switch _backing { case .swift: _freeBytes() default: break } } @inlinable func mutableCopy(_ range: Range<Int>) -> _DataStorage { switch _backing { case .swift: return _DataStorage(bytes: _bytes?.advanced(by: range.lowerBound - _offset), length: range.count, copy: true, deallocator: nil, offset: range.lowerBound) case .immutable(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } case .mutable(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } case .customReference(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } case .customMutableReference(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } } } func withInteriorPointerReference<T>(_ range: Range<Int>, _ work: (NSData) throws -> T) rethrows -> T { if range.isEmpty { return try work(NSData()) // zero length data can be optimized as a singleton } switch _backing { case .swift: return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false)) case .immutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false)) } return try work(d) case .mutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false)) } return try work(d) case .customReference(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: d.bytes.advanced(by: range.lowerBound - _offset)), length: range.count, freeWhenDone: false)) } return try work(d) case .customMutableReference(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: d.bytes.advanced(by: range.lowerBound - _offset)), length: range.count, freeWhenDone: false)) } return try work(d) } } func bridgedReference(_ range: Range<Int>) -> NSData { if range.isEmpty { return NSData() // zero length data can be optimized as a singleton } switch _backing { case .swift: return _NSSwiftData(backing: self, range: range) case .immutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return _NSSwiftData(backing: self, range: range) } return d case .mutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return _NSSwiftData(backing: self, range: range) } return d case .customReference(let d): guard range.lowerBound == 0 && range.upperBound == d.length else { return _NSSwiftData(backing: self, range: range) } return d case .customMutableReference(let d): guard range.lowerBound == 0 && range.upperBound == d.length else { return d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC() } return d.copy() as! NSData } } @usableFromInline func subdata(in range: Range<Data.Index>) -> Data { switch _backing { case .customReference(let d): return d.subdata(with: NSRange(location: range.lowerBound - _offset, length: range.count)) case .customMutableReference(let d): return d.subdata(with: NSRange(location: range.lowerBound - _offset, length: range.count)) default: return Data(bytes: _bytes!.advanced(by: range.lowerBound - _offset), count: range.count) } } } internal class _NSSwiftData : NSData { var _backing: _DataStorage! var _range: Range<Data.Index>! convenience init(backing: _DataStorage, range: Range<Data.Index>) { self.init() _backing = backing _range = range } override var length: Int { return _range.count } override var bytes: UnsafeRawPointer { // NSData's byte pointer methods are not annotated for nullability correctly // (but assume non-null by the wrapping macro guards). This placeholder value // is to work-around this bug. Any indirection to the underlying bytes of an NSData // with a length of zero would have been a programmer error anyhow so the actual // return value here is not needed to be an allocated value. This is specifically // needed to live like this to be source compatible with Swift3. Beyond that point // this API may be subject to correction. guard let bytes = _backing.bytes else { return UnsafeRawPointer(bitPattern: 0xBAD0)! } return bytes.advanced(by: _range.lowerBound) } override func copy(with zone: NSZone? = nil) -> Any { return self } override func mutableCopy(with zone: NSZone? = nil) -> Any { return NSMutableData(bytes: bytes, length: length) } #if !DEPLOYMENT_RUNTIME_SWIFT @objc override func _isCompact() -> Bool { return true } #endif #if DEPLOYMENT_RUNTIME_SWIFT override func _providesConcreteBacking() -> Bool { return true } #else @objc(_providesConcreteBacking) func _providesConcreteBacking() -> Bool { return true } #endif } public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection { public typealias ReferenceType = NSData public typealias ReadingOptions = NSData.ReadingOptions public typealias WritingOptions = NSData.WritingOptions public typealias SearchOptions = NSData.SearchOptions public typealias Base64EncodingOptions = NSData.Base64EncodingOptions public typealias Base64DecodingOptions = NSData.Base64DecodingOptions public typealias Index = Int public typealias Indices = Range<Int> @usableFromInline internal var _backing : _DataStorage @usableFromInline internal var _sliceRange: Range<Index> // A standard or custom deallocator for `Data`. /// /// When creating a `Data` with the no-copy initializer, you may specify a `Data.Deallocator` to customize the behavior of how the backing store is deallocated. public enum Deallocator { /// Use a virtual memory deallocator. #if !DEPLOYMENT_RUNTIME_SWIFT case virtualMemory #endif /// Use `munmap`. case unmap /// Use `free`. case free /// Do nothing upon deallocation. case none /// A custom deallocator. case custom((UnsafeMutableRawPointer, Int) -> Void) fileprivate var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void) { #if DEPLOYMENT_RUNTIME_SWIFT switch self { case .unmap: return { __NSDataInvokeDeallocatorUnmap($0, $1) } case .free: return { __NSDataInvokeDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return { (ptr, len) in b(ptr, len) } } #else switch self { case .virtualMemory: return { NSDataDeallocatorVM($0, $1) } case .unmap: return { NSDataDeallocatorUnmap($0, $1) } case .free: return { NSDataDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return { (ptr, len) in b(ptr, len) } } #endif } } // MARK: - // MARK: Init methods /// Initialize a `Data` with copied memory content. /// /// - parameter bytes: A pointer to the memory. It will be copied. /// - parameter count: The number of bytes to copy. public init(bytes: UnsafeRawPointer, count: Int) { _backing = _DataStorage(bytes: bytes, length: count) _sliceRange = 0..<count } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. public init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) { let count = MemoryLayout<SourceType>.stride * buffer.count _backing = _DataStorage(bytes: buffer.baseAddress, length: count) _sliceRange = 0..<count } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. public init<SourceType>(buffer: UnsafeMutableBufferPointer<SourceType>) { let count = MemoryLayout<SourceType>.stride * buffer.count _backing = _DataStorage(bytes: buffer.baseAddress, length: count) _sliceRange = 0..<count } /// Initialize a `Data` with a repeating byte pattern /// /// - parameter repeatedValue: A byte to initialize the pattern /// - parameter count: The number of bytes the data initially contains initialized to the repeatedValue public init(repeating repeatedValue: UInt8, count: Int) { self.init(count: count) withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) -> Void in memset(bytes, Int32(repeatedValue), count) } } /// Initialize a `Data` with the specified size. /// /// This initializer doesn't necessarily allocate the requested memory right away. `Data` allocates additional memory as needed, so `capacity` simply establishes the initial capacity. When it does allocate the initial memory, though, it allocates the specified amount. /// /// This method sets the `count` of the data to 0. /// /// If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page. /// /// - parameter capacity: The size of the data. public init(capacity: Int) { _backing = _DataStorage(capacity: capacity) _sliceRange = 0..<0 } /// Initialize a `Data` with the specified count of zeroed bytes. /// /// - parameter count: The number of bytes the data initially contains. public init(count: Int) { _backing = _DataStorage(length: count) _sliceRange = 0..<count } /// Initialize an empty `Data`. public init() { _backing = _DataStorage(length: 0) _sliceRange = 0..<0 } /// Initialize a `Data` without copying the bytes. /// /// If the result is mutated and is not a unique reference, then the `Data` will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with `let` or ensure that no other references to the underlying data are formed. /// - parameter bytes: A pointer to the bytes. /// - parameter count: The size of the bytes. /// - parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`. public init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Deallocator) { let whichDeallocator = deallocator._deallocator _backing = _DataStorage(bytes: bytes, length: count, copy: false, deallocator: whichDeallocator, offset: 0) _sliceRange = 0..<count } /// Initialize a `Data` with the contents of a `URL`. /// /// - parameter url: The `URL` to read. /// - parameter options: Options for the read operation. Default value is `[]`. /// - throws: An error in the Cocoa domain, if `url` cannot be read. public init(contentsOf url: URL, options: Data.ReadingOptions = []) throws { let d = try NSData(contentsOf: url, options: ReadingOptions(rawValue: options.rawValue)) _backing = _DataStorage(immutableReference: d, offset: 0) _sliceRange = 0..<d.length } /// Initialize a `Data` from a Base-64 encoded String using the given options. /// /// Returns nil when the input is not recognized as valid Base-64. /// - parameter base64String: The string to parse. /// - parameter options: Encoding options. Default value is `[]`. public init?(base64Encoded base64String: String, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64String, options: Base64DecodingOptions(rawValue: options.rawValue)) { _backing = _DataStorage(immutableReference: d, offset: 0) _sliceRange = 0..<d.length } else { return nil } } /// Initialize a `Data` from a Base-64, UTF-8 encoded `Data`. /// /// Returns nil when the input is not recognized as valid Base-64. /// /// - parameter base64Data: Base-64, UTF-8 encoded input data. /// - parameter options: Decoding options. Default value is `[]`. public init?(base64Encoded base64Data: Data, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64Data, options: Base64DecodingOptions(rawValue: options.rawValue)) { _backing = _DataStorage(immutableReference: d, offset: 0) _sliceRange = 0..<d.length } else { return nil } } /// Initialize a `Data` by adopting a reference type. /// /// You can use this initializer to create a `struct Data` that wraps a `class NSData`. `struct Data` will use the `class NSData` for all operations. Other initializers (including casting using `as Data`) may choose to hold a reference or not, based on a what is the most efficient representation. /// /// If the resulting value is mutated, then `Data` will invoke the `mutableCopy()` function on the reference to copy the contents. You may customize the behavior of that function if you wish to return a specialized mutable subclass. /// /// - parameter reference: The instance of `NSData` that you wish to wrap. This instance will be copied by `struct Data`. public init(referencing reference: NSData) { #if DEPLOYMENT_RUNTIME_SWIFT let providesConcreteBacking = reference._providesConcreteBacking() #else let providesConcreteBacking = (reference as AnyObject)._providesConcreteBacking?() ?? false #endif if providesConcreteBacking { _backing = _DataStorage(immutableReference: reference.copy() as! NSData, offset: 0) _sliceRange = 0..<reference.length } else { _backing = _DataStorage(customReference: reference.copy() as! NSData, offset: 0) _sliceRange = 0..<reference.length } } // slightly faster paths for common sequences @inlinable public init<S: Sequence>(_ elements: S) where S.Iterator.Element == UInt8 { let backing = _DataStorage(capacity: Swift.max(elements.underestimatedCount, 1)) var (iter, endIndex) = elements._copyContents(initializing: UnsafeMutableBufferPointer(start: backing._bytes?.bindMemory(to: UInt8.self, capacity: backing._capacity), count: backing._capacity)) backing._length = endIndex while var element = iter.next() { backing.append(&element, length: 1) } self.init(backing: backing, range: 0..<backing._length) } @inlinable public init<S: Sequence>(bytes elements: S) where S.Iterator.Element == UInt8 { self.init(elements) } @usableFromInline internal init(backing: _DataStorage, range: Range<Index>) { _backing = backing _sliceRange = range } @usableFromInline internal func _validateIndex(_ index: Int, message: String? = nil) { precondition(_sliceRange.contains(index), message ?? "Index \(index) is out of bounds of range \(_sliceRange)") } @usableFromInline internal func _validateRange<R: RangeExpression>(_ range: R) where R.Bound == Int { let lower = R.Bound(_sliceRange.lowerBound) let upper = R.Bound(_sliceRange.upperBound) let r = range.relative(to: lower..<upper) precondition(r.lowerBound >= _sliceRange.lowerBound && r.lowerBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)") precondition(r.upperBound >= _sliceRange.lowerBound && r.upperBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)") } // ----------------------------------- // MARK: - Properties and Functions /// The number of bytes in the data. public var count: Int { get { return _sliceRange.count } set { precondition(count >= 0, "count must not be negative") if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.length = newValue _sliceRange = _sliceRange.lowerBound..<(_sliceRange.lowerBound + newValue) } } /// Access the bytes in the data. /// /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { return try _backing.withUnsafeBytes(in: _sliceRange) { return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafePointer<ContentType>(bitPattern: 0xBAD0)!) } } /// Mutate the bytes in the data. /// /// This function assumes that you are mutating the contents. /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. public mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ body: (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } return try _backing.withUnsafeMutableBytes(in: _sliceRange) { return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafeMutablePointer<ContentType>(bitPattern: 0xBAD0)!) } } // MARK: - // MARK: Copy Bytes /// Copy the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter count: The number of bytes to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) { precondition(count >= 0, "count of bytes to copy must not be negative") if count == 0 { return } _backing.withUnsafeBytes(in: _sliceRange) { memcpy(UnsafeMutableRawPointer(pointer), $0.baseAddress!, Swift.min(count, $0.count)) } } private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: NSRange) { if range.length == 0 { return } _backing.withUnsafeBytes(in: range.lowerBound..<range.upperBound) { memcpy(UnsafeMutableRawPointer(pointer), $0.baseAddress!, Swift.min(range.length, $0.count)) } } /// Copy a subset of the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter range: The range in the `Data` to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) { _copyBytesHelper(to: pointer, from: NSRange(range)) } // Copy the contents of the data into a buffer. /// /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer. /// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called. /// - parameter buffer: A buffer to copy the data into. /// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied. /// - returns: Number of bytes copied into the destination buffer. public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int { let cnt = count guard cnt > 0 else { return 0 } let copyRange : Range<Index> if let r = range { guard !r.isEmpty else { return 0 } copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.count)) } else { copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt) } _validateRange(copyRange) guard !copyRange.isEmpty else { return 0 } let nsRange = NSRange(location: copyRange.lowerBound, length: copyRange.upperBound - copyRange.lowerBound) _copyBytesHelper(to: buffer.baseAddress!, from: nsRange) return copyRange.count } // MARK: - #if !DEPLOYMENT_RUNTIME_SWIFT private func _shouldUseNonAtomicWriteReimplementation(options: Data.WritingOptions = []) -> Bool { // Avoid a crash that happens on OS X 10.11.x and iOS 9.x or before when writing a bridged Data non-atomically with Foundation's standard write() implementation. if !options.contains(.atomic) { #if os(macOS) return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber10_11_Max) #else return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber_iOS_9_x_Max) #endif } else { return false } } #endif /// Write the contents of the `Data` to a location. /// /// - parameter url: The location to write the data into. /// - parameter options: Options for writing the data. Default value is `[]`. /// - throws: An error in the Cocoa domain, if there is an error writing to the `URL`. public func write(to url: URL, options: Data.WritingOptions = []) throws { try _backing.withInteriorPointerReference(_sliceRange) { #if DEPLOYMENT_RUNTIME_SWIFT try $0.write(to: url, options: WritingOptions(rawValue: options.rawValue)) #else if _shouldUseNonAtomicWriteReimplementation(options: options) { var error: NSError? = nil guard __NSDataWriteToURL($0, url, options, &error) else { throw error! } } else { try $0.write(to: url, options: options) } #endif } } // MARK: - /// Find the given `Data` in the content of this `Data`. /// /// - parameter dataToFind: The data to be searched for. /// - parameter options: Options for the search. Default value is `[]`. /// - parameter range: The range of this data in which to perform the search. Default value is `nil`, which means the entire content of this data. /// - returns: A `Range` specifying the location of the found data, or nil if a match could not be found. /// - precondition: `range` must be in the bounds of the Data. public func range(of dataToFind: Data, options: Data.SearchOptions = [], in range: Range<Index>? = nil) -> Range<Index>? { let nsRange : NSRange if let r = range { _validateRange(r) nsRange = NSRange(location: r.lowerBound - startIndex, length: r.upperBound - r.lowerBound) } else { nsRange = NSRange(location: 0, length: count) } let result = _backing.withInteriorPointerReference(_sliceRange) { $0.range(of: dataToFind, options: options, in: nsRange) } if result.location == NSNotFound { return nil } return (result.location + startIndex)..<((result.location + startIndex) + result.length) } /// Enumerate the contents of the data. /// /// In some cases, (for example, a `Data` backed by a `dispatch_data_t`, the bytes may be stored discontiguously. In those cases, this function invokes the closure for each contiguous region of bytes. /// - parameter block: The closure to invoke for each region of data. You may stop the enumeration by setting the `stop` parameter to `true`. public func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) { _backing.enumerateBytes(in: _sliceRange, block) } @inlinable internal mutating func _append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { if buffer.isEmpty { return } if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.replaceBytes(in: NSRange(location: _sliceRange.upperBound, length: _backing.length - (_sliceRange.upperBound - _backing._offset)), with: buffer.baseAddress, length: buffer.count * MemoryLayout<SourceType>.stride) _sliceRange = _sliceRange.lowerBound..<(_sliceRange.upperBound + buffer.count * MemoryLayout<SourceType>.stride) } public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) { if count == 0 { return } _append(UnsafeBufferPointer(start: bytes, count: count)) } public mutating func append(_ other: Data) { other.enumerateBytes { (buffer, _, _) in _append(buffer) } } /// Append a buffer of bytes to the data. /// /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`. public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { _append(buffer) } public mutating func append(contentsOf bytes: [UInt8]) { bytes.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) -> Void in _append(buffer) } } @inlinable public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Iterator.Element == Iterator.Element { let underestimatedCount = Swift.max(newElements.underestimatedCount, 1) _withStackOrHeapBuffer(underestimatedCount) { (buffer) in let capacity = buffer.pointee.capacity let base = buffer.pointee.memory.bindMemory(to: UInt8.self, capacity: capacity) var (iter, endIndex) = newElements._copyContents(initializing: UnsafeMutableBufferPointer(start: base, count: capacity)) _append(UnsafeBufferPointer(start: base, count: endIndex)) while var element = iter.next() { append(&element, count: 1) } } } // MARK: - /// Set a region of the data to `0`. /// /// If `range` exceeds the bounds of the data, then the data is resized to fit. /// - parameter range: The range in the data to set to `0`. public mutating func resetBytes(in range: Range<Index>) { // it is worth noting that the range here may be out of bounds of the Data itself (which triggers a growth) precondition(range.lowerBound >= 0, "Ranges must not be negative bounds") precondition(range.upperBound >= 0, "Ranges must not be negative bounds") let range = NSRange(location: range.lowerBound, length: range.upperBound - range.lowerBound) if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.resetBytes(in: range) if _sliceRange.upperBound < range.upperBound { _sliceRange = _sliceRange.lowerBound..<range.upperBound } } /// Replace a region of bytes in the data with new data. /// /// This will resize the data if required, to fit the entire contents of `data`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. If `subrange.lowerBound == data.count && subrange.count == 0` then this operation is an append. /// - parameter data: The replacement data. public mutating func replaceSubrange(_ subrange: Range<Index>, with data: Data) { let cnt = data.count data.withUnsafeBytes { replaceSubrange(subrange, with: $0, count: cnt) } } /// Replace a region of bytes in the data with new bytes from a buffer. /// /// This will resize the data if required, to fit the entire contents of `buffer`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter buffer: The replacement bytes. public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) { guard !buffer.isEmpty else { return } replaceSubrange(subrange, with: buffer.baseAddress!, count: buffer.count * MemoryLayout<SourceType>.stride) } /// Replace a region of bytes in the data with new bytes from a collection. /// /// This will resize the data if required, to fit the entire contents of `newElements`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter newElements: The replacement bytes. public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection) where ByteCollection.Iterator.Element == Data.Iterator.Element { _validateRange(subrange) let totalCount: Int = numericCast(newElements.count) _withStackOrHeapBuffer(totalCount) { conditionalBuffer in let buffer = UnsafeMutableBufferPointer(start: conditionalBuffer.pointee.memory.assumingMemoryBound(to: UInt8.self), count: totalCount) var (iterator, index) = newElements._copyContents(initializing: buffer) while let byte = iterator.next() { buffer[index] = byte index = buffer.index(after: index) } replaceSubrange(subrange, with: conditionalBuffer.pointee.memory, count: totalCount) } } public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) { _validateRange(subrange) let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound) if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } let upper = _sliceRange.upperBound _backing.replaceBytes(in: nsRange, with: bytes, length: cnt) let resultingUpper = upper - nsRange.length + cnt _sliceRange = _sliceRange.lowerBound..<resultingUpper } /// Return a new copy of the data in a specified range. /// /// - parameter range: The range to copy. public func subdata(in range: Range<Index>) -> Data { _validateRange(range) if isEmpty { return Data() } return _backing.subdata(in: range) } // MARK: - // /// Returns a Base-64 encoded string. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded string. public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String { return _backing.withInteriorPointerReference(_sliceRange) { return $0.base64EncodedString(options: options) } } /// Returns a Base-64 encoded `Data`. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded data. public func base64EncodedData(options: Data.Base64EncodingOptions = []) -> Data { return _backing.withInteriorPointerReference(_sliceRange) { return $0.base64EncodedData(options: options) } } // MARK: - // /// The hash value for the data. public var hashValue: Int { var hashValue = 0 let hashRange: Range<Int> = _sliceRange.lowerBound..<Swift.min(_sliceRange.lowerBound + 80, _sliceRange.upperBound) _withStackOrHeapBuffer(hashRange.count + 1) { buffer in if !hashRange.isEmpty { _backing.withUnsafeBytes(in: hashRange) { memcpy(buffer.pointee.memory, $0.baseAddress!, hashRange.count) } } hashValue = Int(bitPattern: CFHashBytes(buffer.pointee.memory.assumingMemoryBound(to: UInt8.self), hashRange.count)) } return hashValue } public func advanced(by amount: Int) -> Data { _validateIndex(startIndex + amount) let length = count - amount precondition(length > 0) return withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Data in return Data(bytes: ptr.advanced(by: amount), count: length) } } // MARK: - // MARK: - // MARK: Index and Subscript /// Sets or returns the byte at the specified index. public subscript(index: Index) -> UInt8 { get { _validateIndex(index) return _backing.get(index) } set { _validateIndex(index) if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.set(index, to: newValue) } } public subscript(bounds: Range<Index>) -> Data { get { _validateRange(bounds) return Data(backing: _backing, range: bounds) } set { replaceSubrange(bounds, with: newValue) } } public subscript<R: RangeExpression>(_ rangeExpression: R) -> Data where R.Bound: FixedWidthInteger, R.Bound.Stride : SignedInteger { get { let lower = R.Bound(_sliceRange.lowerBound) let upper = R.Bound(_sliceRange.upperBound) let range = rangeExpression.relative(to: lower..<upper) let start: Int = numericCast(range.lowerBound) let end: Int = numericCast(range.upperBound) let r: Range<Int> = start..<end _validateRange(r) return Data(backing: _backing, range: r) } set { let lower = R.Bound(_sliceRange.lowerBound) let upper = R.Bound(_sliceRange.upperBound) let range = rangeExpression.relative(to: lower..<upper) let start: Int = numericCast(range.lowerBound) let end: Int = numericCast(range.upperBound) let r: Range<Int> = start..<end _validateRange(r) replaceSubrange(r, with: newValue) } } /// The start `Index` in the data. public var startIndex: Index { get { return _sliceRange.lowerBound } } /// The end `Index` into the data. /// /// This is the "one-past-the-end" position, and will always be equal to the `count`. public var endIndex: Index { get { return _sliceRange.upperBound } } public func index(before i: Index) -> Index { return i - 1 } public func index(after i: Index) -> Index { return i + 1 } public var indices: Range<Int> { get { return startIndex..<endIndex } } public func _copyContents(initializing buffer: UnsafeMutableBufferPointer<UInt8>) -> (Iterator, UnsafeMutableBufferPointer<UInt8>.Index) { guard !isEmpty else { return (makeIterator(), buffer.startIndex) } guard let p = buffer.baseAddress else { preconditionFailure("Attempt to copy contents into nil buffer pointer") } let cnt = count precondition(cnt <= buffer.count, "Insufficient space allocated to copy Data contents") withUnsafeBytes { p.initialize(from: $0, count: cnt) } return (Iterator(endOf: self), buffer.index(buffer.startIndex, offsetBy: cnt)) } /// An iterator over the contents of the data. /// /// The iterator will increment byte-by-byte. public func makeIterator() -> Data.Iterator { return Iterator(self) } public struct Iterator : IteratorProtocol { // Both _data and _endIdx should be 'let' rather than 'var'. // They are 'var' so that the stored properties can be read // independently of the other contents of the struct. This prevents // an exclusivity violation when reading '_endIdx' and '_data' // while simultaneously mutating '_buffer' with the call to // withUnsafeMutablePointer(). Once we support accessing struct // let properties independently we should make these variables // 'let' again. private var _data: Data private var _buffer: ( UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) private var _idx: Data.Index private var _endIdx: Data.Index fileprivate init(_ data: Data) { _data = data _buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) _idx = data.startIndex _endIdx = data.endIndex } fileprivate init(endOf data: Data) { self._data = data _buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) _idx = data.endIndex _endIdx = data.endIndex } public mutating func next() -> UInt8? { guard _idx < _endIdx else { return nil } defer { _idx += 1 } let bufferSize = MemoryLayout.size(ofValue: _buffer) return withUnsafeMutablePointer(to: &_buffer) { ptr_ in let ptr = UnsafeMutableRawPointer(ptr_).assumingMemoryBound(to: UInt8.self) let bufferIdx = (_idx - _data.startIndex) % bufferSize if bufferIdx == 0 { // populate the buffer _data.copyBytes(to: ptr, from: _idx..<(_endIdx - _idx > bufferSize ? _idx + bufferSize : _endIdx)) } return ptr[bufferIdx] } } } // MARK: - // @available(*, unavailable, renamed: "count") public var length: Int { get { fatalError() } set { fatalError() } } @available(*, unavailable, message: "use withUnsafeBytes instead") public var bytes: UnsafeRawPointer { fatalError() } @available(*, unavailable, message: "use withUnsafeMutableBytes instead") public var mutableBytes: UnsafeMutableRawPointer { fatalError() } /// Returns `true` if the two `Data` arguments are equal. public static func ==(d1 : Data, d2 : Data) -> Bool { let backing1 = d1._backing let backing2 = d2._backing if backing1 === backing2 { if d1._sliceRange == d2._sliceRange { return true } } let length1 = d1.count if length1 != d2.count { return false } if backing1.bytes == backing2.bytes { if d1._sliceRange == d2._sliceRange { return true } } if length1 > 0 { return d1.withUnsafeBytes { (b1) in return d2.withUnsafeBytes { (b2) in return memcmp(b1, b2, length1) == 0 } } } return true } } extension Data : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { /// A human-readable description for the data. public var description: String { return "\(self.count) bytes" } /// A human-readable debug description for the data. public var debugDescription: String { return self.description } public var customMirror: Mirror { let nBytes = self.count var children: [(label: String?, value: Any)] = [] children.append((label: "count", value: nBytes)) self.withUnsafeBytes { (bytes : UnsafePointer<UInt8>) in children.append((label: "pointer", value: bytes)) } // Minimal size data is output as an array if nBytes < 64 { children.append((label: "bytes", value: Array(self[startIndex..<Swift.min(nBytes + startIndex, endIndex)]))) } let m = Mirror(self, children:children, displayStyle: Mirror.DisplayStyle.struct) return m } } extension Data { @available(*, unavailable, renamed: "copyBytes(to:count:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, length: Int) { } @available(*, unavailable, renamed: "copyBytes(to:from:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, range: NSRange) { } } /// Provides bridging functionality for struct Data to class NSData and vice-versa. extension Data : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSData { return _backing.bridgedReference(_sliceRange) } public static func _forceBridgeFromObjectiveC(_ input: NSData, result: inout Data?) { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) } public static func _conditionallyBridgeFromObjectiveC(_ input: NSData, result: inout Data?) -> Bool { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSData?) -> Data { guard let src = source else { return Data() } return Data(referencing: src) } } extension NSData : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(Data._unconditionallyBridgeFromObjectiveC(self)) } } extension Data : Codable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() // It's more efficient to pre-allocate the buffer if we can. if let count = container.count { self.init(count: count) // Loop only until count, not while !container.isAtEnd, in case count is underestimated (this is misbehavior) and we haven't allocated enough space. // We don't want to write past the end of what we allocated. for i in 0 ..< count { let byte = try container.decode(UInt8.self) self[i] = byte } } else { self.init() } while !container.isAtEnd { var byte = try container.decode(UInt8.self) self.append(&byte, count: 1) } } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() // Since enumerateBytes does not rethrow, we need to catch the error, stow it away, and rethrow if we stopped. var caughtError: Error? = nil self.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, byteIndex: Data.Index, stop: inout Bool) in do { try container.encode(contentsOf: buffer) } catch { caughtError = error stop = true } } if let error = caughtError { throw error } } }
apache-2.0
9480e3ce44211c63fb4151fe757ebd68
40.47255
352
0.593183
4.936183
false
false
false
false
jovito-royeca/Decktracker
osx/DataSource/DataSource/TCGPlayerPricing.swift
1
1443
// // TCGPlayerPricing.swift // DataSource // // Created by Jovit Royeca on 14/07/2016. // Copyright © 2016 Jovito Royeca. All rights reserved. // import Foundation import CoreData @objc(TCGPlayerPricing) class TCGPlayerPricing: NSManagedObject { struct Keys { static let FetchDate = "fetchDate" static let FoilPrice = "foilavgprice" static let HighPrice = "hiprice" static let Link = "link" static let LowPrice = "lowprice" static let MidPrice = "avgprice" } override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { super.init(entity: entity, insertIntoManagedObjectContext: context) } init(dictionary: [String : AnyObject], context: NSManagedObjectContext) { let entity = NSEntityDescription.entityForName("TCGPlayerPricing", inManagedObjectContext: context)! super.init(entity: entity,insertIntoManagedObjectContext: context) update(dictionary) } func update(dictionary: [String : AnyObject]) { fetchDate = dictionary[Keys.FetchDate] as? NSDate foilPrice = dictionary[Keys.FoilPrice] as? NSNumber highPrice = dictionary[Keys.HighPrice] as? NSNumber link = dictionary[Keys.Link] as? String lowPrice = dictionary[Keys.LowPrice] as? NSNumber midPrice = dictionary[Keys.MidPrice] as? NSNumber } }
apache-2.0
a938270fcdbdda40e077a05d76d9a48d
31.772727
113
0.685853
4.492212
false
false
false
false
iOS-mamu/SS
P/PotatsoModel/RuleSet.swift
1
3414
// // RuleSet.swift // Potatso // // Created by LEI on 4/6/16. // Copyright © 2016 TouchingApp. All rights reserved. // import RealmSwift public enum RuleSetError: Error { case invalidRuleSet case emptyName case nameAlreadyExists } extension RuleSetError: CustomStringConvertible { public var description: String { switch self { case .invalidRuleSet: return "Invalid rule set" case .emptyName: return "Empty name" case .nameAlreadyExists: return "Name already exists" } } } public final class RuleSet: BaseModel { public dynamic var editable = true public dynamic var name = "" public dynamic var remoteUpdatedAt: TimeInterval = Date().timeIntervalSince1970 public dynamic var desc = "" public dynamic var ruleCount = 0 public dynamic var rulesJSON = "" public dynamic var isSubscribe = false public dynamic var isOfficial = false fileprivate var cachedRules: [Rule]? = nil public var rules: [Rule] { get { if let cachedRules = cachedRules { return cachedRules } updateCahcedRules() return cachedRules! } set { let json = (newValue.map({ $0.json }) as NSArray).jsonString() ?? "" rulesJSON = json updateCahcedRules() ruleCount = newValue.count } } public override func validate(inRealm realm: Realm) throws { guard name.characters.count > 0 else { throw RuleSetError.emptyName } } fileprivate func updateCahcedRules() { guard let jsonArray = rulesJSON.jsonArray() as? [[String: AnyObject]] else { cachedRules = [] return } cachedRules = jsonArray.flatMap({ Rule(json: $0) }) } public func addRule(_ rule: Rule) { var newRules = rules newRules.append(rule) rules = newRules } public func insertRule(_ rule: Rule, atIndex index: Int) { var newRules = rules newRules.insert(rule, at: index) rules = newRules } public func removeRule(atIndex index: Int) { var newRules = rules newRules.remove(at: index) rules = newRules } public func move(_ fromIndex: Int, toIndex: Int) { var newRules = rules let rule = newRules[fromIndex] newRules.remove(at: fromIndex) insertRule(rule, atIndex: toIndex) rules = newRules } } extension RuleSet { public override static func indexedProperties() -> [String] { return ["name"] } } extension RuleSet { public convenience init(dictionary: [String: AnyObject], inRealm realm: Realm) throws { self.init() guard let name = dictionary["name"] as? String else { throw RuleSetError.invalidRuleSet } self.name = name if realm.objects(RuleSet).filter("name = '\(name)'").first != nil { self.name = "\(name) \(RuleSet.dateFormatter.string(from: Date()))" } guard let rulesStr = dictionary["rules"] as? [String] else { throw RuleSetError.invalidRuleSet } rules = try rulesStr.map({ try Rule(str: $0) }) } } public func ==(lhs: RuleSet, rhs: RuleSet) -> Bool { return lhs.uuid == rhs.uuid }
mit
64ce5afafe8d07118ca66fb7afe28c0e
25.253846
91
0.588339
4.375641
false
false
false
false
silence0201/Swift-Study
SwiftLearn/MySwift02_syntax.playground/Contents.swift
1
10423
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" //if a=3 print("hello world");} //赋值语句不能当作条件判断语句来使用 var x = 10 var y = 3 var z = 0 //双目运算符 x + y x - y x * y x / y x % y Double(x) / Double(y) let u = 2.5 let v = 1.2 //u % v //swift3 中%求余运算只支持整数类型. var xx = +x var yy = -y //单目运算符++ -- //swift3 中移除了 ++ -- 操作符. x += 1 y -= 1 x += 1 y -= 1 x += 2 x %= 3 /*** ** 比较运算符, 逻辑运算符 ***/ var a = 3, b = 4 a == b a != b a > b a >= b a < b a <= b var stra = "Hello" var strb = "Hello" //stra === strb // !== 引用运算符 let money = 100 let price = 70 if money >= price{ print("buy it") } let capacity = 30 let volume = 50 if money >= price || capacity >= volume{ print("can not buy it") } if !(money >= price && capacity >= volume){ print("can buy it") } /*** ** 三目运算符 条件? value1: value2 ***/ var battery = 18 let batteryColor: UIColor //声明了一个常量, 但是可以不赋 初值, 可以在以后进行一次赋值. //print(batteryColor) //声明了常量, 必须给其赋值完初值后才可以使用. if battery <= 20{ batteryColor = UIColor.red } else{ batteryColor = UIColor.green } //batteryColor = UIColor.yellowColor() //不再给常量赋值了. batteryColor let batteryColor2 = battery <= 20 ? UIColor.red: UIColor.green /*** ** 区间运算符 ** 闭区间运算符[a,b] a...b ** 前闭后开区间运算符 [a,b) a..<b ***/ for index in 1...10 { //循环执行10次, 每一交都会将数值赋值给 index这个常量. index //print(index) //index = 5 //由于index是一个常量, 所以不能对其进行赋值. } //前闭后开 适用于遍历数组 for index in 0..<10 { //从0遍历到9, 不包含10; 例如当遍历数组时, 从数组下标0到数组长度-1的位置. print(index, terminator:" ") } print("") /*** ** 控制流 ** 顺序结构 ** 循环结构 ** 选择结构 ***/ //循环结构 ////for in 计算2的10次方 var result = 1 var base = 2 var power = 10 for _ in 1...power{ //使用_下划线占位, 代表运算10次. result *= base } result //for循环 //循环体即使只有一句话也应该使用{}包起来. //swift3已经废弃了C Style的循环语句 // for initialization; condition; increments{ // statements // } //for var a = -6.28; a <= 6.28; a += 0.1 { // sin(a) //} print("Swift3 new for style -- stride >>>") for x in stride(from: -6.28, to: 6.28, by: 0.1) { // from ..< to print(x, separator: " ", terminator: " ") } var index = -99 var step = 1 //for ;index <= 99; index += step{ //用分号隔开的for循环初值, 判断, 增量, 都可以抽出 // index * index // step *= 2 //} for x in stride(from: -99, through: 99, by: step){ // from ... through print(x, separator: " ", terminator: " ") } print("==== while 循环实例====================") // while 循环 适用于不清楚循环多少次结束 // initialization // while condition{ // statements // increments // } // a 和 b 同时掷骰子 只要连续赢3次就退出循环. var aWin = 0 var bWin = 0 var game = 0 while aWin < 3 && bWin < 3{ game += 1 let a = arc4random_uniform(6) + 1 let b = arc4random_uniform(6) + 1 print("a is \(a), b is \(b).", terminator: "") if a > b{ print("A win!") bWin = 0 aWin += 1 } else if a < b{ print("B win!") aWin = 0 bWin += 1 } else{ print("draw") aWin = 0 bWin = 0 } } //print(game) let winner = aWin == 3 ? "A": "B" print("After \(game) games, \(winner) win!") print("====repeat while 循环实例=======================") // repeat-while 类似于 do while 循环至少执行一次循环体 // iniaialization // repeat{ //关键字repeat , do关键字被错误处理所使用了 // statements // increments // } while condition var aaWin = false var bbWin = false repeat { let a = arc4random_uniform(6) + 1 let b = arc4random_uniform(6) + 1 print("a is \(a), b is \(b).", terminator: " ") if a > b { aaWin = true } else if a < b{ bbWin = true } else{ print("draw ", terminator:"") } } while !aaWin && !bbWin let winner2 = aaWin ? "A" : "B" print(winner2, "win!") // 控制转移 break 和 continue print("==== 控制转移 break 和 continue ===============") while true{ let a = arc4random_uniform(6) + 1 let b = arc4random_uniform(6) + 1 print("a is \(a), b is \(b).", terminator:" ") if a == b { print("draw") continue //继续执行下一次循环 } let winner = a > b ? "A" : "B" print("\(winner) win!") break //结束循环 } // 选择结构 if - else - else if; switch //不需要break退出switch, // switch 能对多种类型进行case // switch 如果不能对所有情况进行case判断, 那么就必须使用default选项; 如果可以穷举则不需要default选择(示例3) // switch 当case或default选项 不需要进行处理时可以使用break或者()来作默认不处理操作. print("==== 选择结构 if - else - else if; switch =======") // switch some value to consider{ // case value1: // respond to value1 // case value2: // respond to value2 // default: // otherwise, do something else // } let rating = "A" switch rating{ case "A", "a": //同时满足 "A" 和 "a"的条件时都执行print("Great!") print("Great!") case "B", "b": print("Just so-so") case "C": print("It's Bad") case "": break //或者使用() default: //switch时必须有default选项 print("Error") } let aInt = 3 switch aInt{ case 0: print("I'm 0") case 3: print("I'm right") default: () } let boolean = true switch boolean{ case true: print("I'm true") case false: print("I'm false") } //因为可以穷举boolean值, 所以此处不需要default选项了. print("==== switch 的高级用法 ============") //对区间进行判断 let score = 95 switch score{ case 0: print("You got an egg!") case 1..<60: //前闭后开区间 print("You failed.") case 60: print("Just passed") case 61..<80: print("Just so-so") case 80..<90: print("Good") case 90...94: //闭区间 print("Very Good") case 95..<100: print("Great!") case 100: print("Perfect!") default: print("Error score.") } //对元组进行判断 把匹配, 解包, 赋值融合在一起了. let point:(x:Int, y:Int) = (x:1, y:4) switch point{ case (0,0): print("It's origin!") case (1,0): print("It an unit vector on the positive x-axis.") case (-1, 0): print("It an unit vector on the negative x-axis.") case (_, 3): //元组的 x 坐标不管是什么都会匹配 print("It an unit vector on the positive y-axis.") case (3, let p): //单方面将point的y值赋于p, 并使用它. print("print p is \(p)") case (-2...2, -2...2): //在元组中使用区间运算符 print("(\(point.0), \(point.y)) is near the origin.") //在执行体中也可以使用point判断条件的值. case (let x, let y): //将point赋值于了元组(x, y) 同时去匹配, 由于穷举了所有值, 就不需要default了. print("no match! (\(x), \(y)) ") } //swith fallthrough关键字 print("==== switch fallthrough 继续执行后续case语句 ====") let ppp = (0, 0) switch ppp{ case (0, 0): print("It's origin") fallthrough case (_, 0): print("It's on the x-axis.") fallthrough case (0, _): print("It's on the y-axis.") default: print("It's just an ordinary point."); } print("==== break flagLoop 类似于goto语句 ====") // 求 x^4 - y^2 = 15 * x * y 在300以内的一个正整数解 var gotAnswer = false findAnswer: for m in 1...300{ for n in 1...300{ if(m*m*m*m - n*n == 15*m*n){ print(m, n) gotAnswer = true break findAnswer } } } print("==== where 限定语句在switch中的使用 ====") // case value2 where condition: let point2 = (3, 13) switch point2{ case let(x, y) where x == y: //匹配point2坐标,并赋值于(x, y)元组, 同时又限定坐标的 x == y print("It's on the line x == y") case (let x, let y) where x == -y: //类似上面的用法, 将point2解包并赋值于(x, y) print("It's on the line x == -y") case let(x, y): print("It's just an ordinary point.") print("The point is (\(x), \(point2.1) )") } //判断age是否在10岁到19岁之间 let age = 19 if case 10...19 = age{ //case 10...19 模式要放在 判断条件前. print("You're a teenager.") } print("==== where 限定语句, 只要表达式返回一个boolean值即可 ====") //age匹配在10...19之间, 同时限定age要大于等于18岁 if case 10...19 = age, age >= 18{ print("You're a teenager and in a college.") } // for 循环中使用 限定语句 where. for i in 1...100 where i % 3 == 0{ print(i, terminator:" ") //由于没有指定 //i += 6 //会报错, 因为for in循环时, i是常量, 可为限定语句和循环体使用, 但是不能改变其值. } print("") //与上个循环无区别? case let 显示赋值常量 i 为区间循环值, 并为限定where所使用. for case let i in 1...100 where i % 3 == 0{ print(i, terminator:" ") } print("\n==== guard(保卫) 及代码风格初探:: 使用if else 也能实现 但是Swift建议使用guard代码风格 ====") print("==== Swift建议我们首先进行边界的检查, 把和程序的核心逻辑不相关的程序剥离开, 最后就是核心逻辑 ====") func buy(money: Int, price: Int, capacity: Int, volume: Int){ guard money >= price else{ //保证 money >= price 即我们有足够的钱去买这件商品, 否则else打印"Not enough money", 然后return print("Not enough money") return } guard capacity >= volume else{ //保证 capacity >= volume 即我们有足够的空间来放置这件商品, 否则else打印"Not enough capacity", 然后return print("Not enough capacity") return } //当保证条件都满足后, 就可以真正的执行函数的主体部分了. print("I can buy it!") print("\(money-price) Yuan left.") print("\(capacity-volume) cubic meters left") } //buy(100, 90, 100, 100);
mit
06726395acd6f36778d29163f8cba147
19.178147
89
0.571984
2.696825
false
false
false
false
sonnygauran/trailer
PocketTrailer WatchKit Extension/GlanceController.swift
1
4970
import WatchKit import ClockKit import WatchConnectivity let shortDateFormatter = { () -> NSDateFormatter in let d = NSDateFormatter() d.dateStyle = NSDateFormatterStyle.ShortStyle d.timeStyle = NSDateFormatterStyle.ShortStyle d.doesRelativeDateFormatting = true return d }() final class GlanceController: WKInterfaceController, WCSessionDelegate { @IBOutlet weak var totalCount: WKInterfaceLabel! @IBOutlet var totalGroup: WKInterfaceGroup! @IBOutlet var errorText: WKInterfaceLabel! @IBOutlet weak var myCount: WKInterfaceLabel! @IBOutlet weak var myGroup: WKInterfaceGroup! @IBOutlet weak var mergedCount: WKInterfaceLabel! @IBOutlet weak var mergedGroup: WKInterfaceGroup! @IBOutlet weak var closedCount: WKInterfaceLabel! @IBOutlet weak var closedGroup: WKInterfaceGroup! @IBOutlet weak var participatedCount: WKInterfaceLabel! @IBOutlet weak var participatedGroup: WKInterfaceGroup! @IBOutlet weak var otherCount: WKInterfaceLabel! @IBOutlet weak var otherGroup: WKInterfaceGroup! @IBOutlet weak var unreadCount: WKInterfaceLabel! @IBOutlet weak var unreadGroup: WKInterfaceGroup! @IBOutlet weak var lastUpdate: WKInterfaceLabel! @IBOutlet weak var prIcon: WKInterfaceImage! @IBOutlet weak var issueIcon: WKInterfaceImage! private var showIssues: Bool = false override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) errorText.setText("Loading...") setErrorMode(true) } override func willActivate() { super.willActivate() let session = WCSession.defaultSession() session.delegate = self session.activateSession() if session.iOSDeviceNeedsUnlockAfterRebootForReachability { errorText.setText("Please unlock your iPhone first") setErrorMode(true) } else if session.receivedApplicationContext.count > 0 { self.updateFromContext(session.receivedApplicationContext) } } func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) { dispatch_async(dispatch_get_main_queue()) { self.updateFromContext(applicationContext) } } func sessionReachabilityDidChange(session: WCSession) { dispatch_async(dispatch_get_main_queue()) { self.updateFromContext(session.receivedApplicationContext) } } private func updateFromContext(applicationContext: [String : AnyObject]) { if let result = applicationContext["overview"] as? [String : AnyObject] { showIssues = result["preferIssues"] as! Bool prIcon.setHidden(showIssues) issueIcon.setHidden(!showIssues) let r = result[showIssues ? "issues" : "prs"] as! [String : AnyObject] let tc = r["total"] as! Int totalCount.setText("\(tc)") let mc = r[PullRequestSection.Mine.apiName()]?["total"] as! Int myCount.setText("\(mc) \(PullRequestSection.Mine.watchMenuName().uppercaseString)") myGroup.setAlpha(mc==0 ? 0.4 : 1.0) let pc = r[PullRequestSection.Participated.apiName()]?["total"] as! Int participatedCount.setText("\(pc) \(PullRequestSection.Participated.watchMenuName().uppercaseString)") participatedGroup.setAlpha(pc==0 ? 0.4 : 1.0) if !showIssues { let rc = r[PullRequestSection.Merged.apiName()]?["total"] as! Int mergedCount.setText("\(rc) \(PullRequestSection.Merged.watchMenuName().uppercaseString)") mergedGroup.setAlpha(rc==0 ? 0.4 : 1.0) } let cc = r[PullRequestSection.Closed.apiName()]?["total"] as! Int closedCount.setText("\(cc) \(PullRequestSection.Closed.watchMenuName().uppercaseString)") closedGroup.setAlpha(cc==0 ? 0.4 : 1.0) let oc = r[PullRequestSection.All.apiName()]?["total"] as! Int otherCount.setText("\(oc) \(PullRequestSection.All.watchMenuName().uppercaseString)") otherGroup.setAlpha(oc==0 ? 0.4 : 1.0) let uc = r["unread"] as! Int if uc==0 { unreadCount.setText("NONE UNREAD") unreadGroup.setAlpha(0.3) } else if uc==1 { unreadCount.setText("1 COMMENT") unreadGroup.setAlpha(1.0) } else { unreadCount.setText("\(uc) COMMENTS") unreadGroup.setAlpha(1.0) } let lastRefresh = result["lastUpdated"] as! NSDate if lastRefresh.isEqualToDate(never()) { lastUpdate.setText("Not refreshed yet") } else { lastUpdate.setText(shortDateFormatter.stringFromDate(lastRefresh)) } errorText.setText(nil) setErrorMode(false) updateComplications() } } private func setErrorMode(mode: Bool) { myGroup.setHidden(mode) participatedGroup.setHidden(mode) mergedGroup.setHidden(mode ? mode : showIssues) closedGroup.setHidden(mode) otherGroup.setHidden(mode) unreadGroup.setHidden(mode) totalGroup.setHidden(mode) lastUpdate.setHidden(mode) errorText.setHidden(!mode) } private func updateComplications() { let complicationServer = CLKComplicationServer.sharedInstance() if let activeComplications = complicationServer.activeComplications { for complication in activeComplications { complicationServer.reloadTimelineForComplication(complication) } } } }
mit
d59fd6c0723f253a96c71a547766f761
30.455696
106
0.747686
3.894984
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab4Brand/SLV_445_BrandProductsKid.swift
1
12391
// // SLV_445_BrandProductsKid.swift // selluv-ios // // Created by 조백근 on 2017. 2. 17.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import Foundation import UIKit import SwifterSwift import PullToRefresh class SLV_445_BrandProductsKid: UICollectionViewController { let refresher = PullToRefresh() var itemInfo: IndicatorInfo = IndicatorInfo(title: "키즈")//tab 정보 let selluvWaterFallCellIdentify = "userPageItemWaterFallCellIdentify" var itemList: [SLVDetailProduct] = [] let delegateHolder = SLVTabContainNavigationControllerDelegate() weak var delegate: SLVButtonBarDelegate?// 델리게이트. weak var myNavigationDelegate: SLVNavigationControllerDelegate?// push를 위한 네비게이션 override func viewDidLoad() { super.viewDidLoad() self.prepare() self.setupLongPress() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func linkDelegate(controller: AnyObject) { self.delegate = controller as? SLVButtonBarDelegate // self.myNavigationDelegate = controller as? SLVNavigationControllerDelegate } func prepare() { self.navigationController!.delegate = delegateHolder self.view.backgroundColor = UIColor.clear self.automaticallyAdjustsScrollViewInsets = false self.loadProducts(isContinue: false) let collection :UICollectionView = collectionView!; collection.remembersLastFocusedIndexPath = true collection.frame = screenBounds collection.setCollectionViewLayout(CHTCollectionViewWaterfallLayout(), animated: false) collection.backgroundColor = UIColor.clear collection.register(UINib(nibName: "SLVUserProductCell", bundle: nil), forCellWithReuseIdentifier: selluvWaterFallCellIdentify) collection.reloadData() refresher.position = .bottom collection.addPullToRefresh(refresher) { self.loadProducts(isContinue: true) } } func setupLongPress() { let overlay = GHContextMenuView() overlay.delegate = self overlay.dataSource = self let selector = #selector(GHContextMenuView.longPressDetected(_:)) let longPress = UILongPressGestureRecognizer(target: overlay, action: selector) self.collectionView?.addGestureRecognizer(longPress) } deinit { self.collectionView?.removePullToRefresh((self.collectionView?.bottomPullToRefresh!)!) } override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let parent = self.delegate as! SLV_441_BrandPageController let definer = parent.myCustomBar?.behaviorDefiner definer?.scrollViewDidEndDecelerating(scrollView) } override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { let parent = self.delegate as! SLV_441_BrandPageController let definer = parent.myCustomBar?.behaviorDefiner definer?.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate) } override func scrollViewDidScroll(_ scrollView: UIScrollView) { let parent = self.delegate as! SLV_441_BrandPageController let definer = parent.myCustomBar?.behaviorDefiner definer?.scrollViewDidScroll(scrollView) parent.updateSubScrollViewDidScroll(scrollView) if scrollView == self.collectionView { let off = scrollView.contentOffset if off.y > 0 { // hide self.delegate?.hideByScroll() } else { //show self.delegate?.showByScroll() } } } //MARK: DataCalling func loadProducts(isContinue: Bool) { let parent = self.delegate as! SLV_441_BrandPageController let brandId = parent.brandId let kind = "kid" BrandTabModel.shared.brandProducts(brandId: brandId!, kind: kind, same: isContinue) { (success, products) in if let products = products { self.itemList.append(contentsOf: products) parent.delay(time: 0.2) { self.collectionView?.reloadData() } } } } } // MARK: - IndicatorInfoProvider extension SLV_445_BrandProductsKid: IndicatorInfoProvider { func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return itemInfo } } // MARK: - Collection View extension SLV_445_BrandProductsKid { override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let collectionCell: SLVUserProductCell = collectionView.dequeueReusableCell(withReuseIdentifier: selluvWaterFallCellIdentify, for: indexPath as IndexPath) as! SLVUserProductCell collectionCell.delegate = self let item = self.itemList[indexPath.row] collectionCell.setupData(item: item) return collectionCell } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return self.itemList.count; } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! SLVUserProductCell collectionView.setToIndexPath(indexPath: indexPath as NSIndexPath) let board = UIStoryboard(name:"Main", bundle: nil) let productController = board.instantiateViewController(withIdentifier: "SLV_501_ProcuctDetailController") as! SLV_501_ProcuctDetailController productController.listProductInfo = cell.info productController.parentCellImage = cell.imageViewContent!.image productController.imagePath = indexPath as NSIndexPath? navigationController?.pushViewController(productController, animated: true) } func pageViewControllerLayout () -> UICollectionViewFlowLayout { let flowLayout = UICollectionViewFlowLayout() let itemSize = self.navigationController!.isNavigationBarHidden ? CGSize(width: screenWidth, height: screenHeight+20) : CGSize(width: screenWidth, height: screenHeight-navigationHeaderAndStatusbarHeight) flowLayout.itemSize = itemSize flowLayout.minimumLineSpacing = 0 flowLayout.minimumInteritemSpacing = 0 flowLayout.scrollDirection = .horizontal return flowLayout } } extension SLV_445_BrandProductsKid: CHTCollectionViewDelegateWaterfallLayout, SLVCollectionTransitionProtocol { func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { var itemSize = DEFAULT_PHOTO_SIZE var isFinish = true if self.itemList.count > 0 && self.itemList.count >= indexPath.row + 1 { let info = self.itemList[indexPath.row] var name = "" if info.photos != nil { if (info.photos?.count)! > 0 { name = (info.photos?.first)! } } if name != "" { let from = URL(string: "\(dnProduct)\(name)") isFinish = false ImageScout.shared.scoutImage(url: from!) { error, size, type in isFinish = true if let error = error { print(error.code) } else { print("Size: \(size)") print("Type: \(type.rawValue)") itemSize = size } } } } var cnt: Int = 0 var sec: Double = 0 while(isFinish == false && 2 < sec ) { RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01)) cnt = cnt + 1 sec = Double(cnt) * Double(0.01) } let imageHeight = itemSize.height*gridWidth/itemSize.width + SLVUserProductCell.infoHeight + SLVUserProductCell.humanHeight log.debug("remote image calc cell width: \(gridWidth) , height: \(imageHeight)") return CGSize(width: gridWidth, height: imageHeight) } func transitionTabCollectionView() -> UICollectionView!{ return collectionView } } extension SLV_445_BrandProductsKid: SLVCollectionLinesDelegate { // 스타일 영역을 터치한다. func didTouchedStyleThumbnail(info: AnyObject) { } // 좋아요를 터치한다. func didTouchedLikeButton(info: AnyObject) { } func didTouchedItemDescription(info: AnyObject) { } func didTouchedUserDescription(info: AnyObject) { } } extension SLV_445_BrandProductsKid: GHContextOverlayViewDataSource, GHContextOverlayViewDelegate { func shouldShowMenu(at point: CGPoint) -> Bool { let path = self.collectionView?.indexPathForItem(at: point) if path != nil { let cell = self.collectionView?.cellForItem(at: path!) return cell != nil } return false } func shouldShowMenuOnParentImage(at point: CGPoint) -> UIImage! { let path = self.collectionView?.indexPathForItem(at: point) if path != nil { let cell = self.collectionView?.cellForItem(at: path!) as? SLVUserProductCell if cell != nil { let image = cell!.imageViewContent?.image return image } } return nil } func shouldShowMenuParentImageFrame(at point: CGPoint) -> CGRect { let path = self.collectionView?.indexPathForItem(at: point) if path != nil { let cell = self.collectionView?.cellForItem(at: path!) as? SLVUserProductCell if cell != nil { let frame = cell?.imageViewContent?.frame var newFrame = self.view?.convert(frame!, to: nil) let x = ((screenWidth/2) > point.x) ? 17:(screenWidth/2 + 5) newFrame?.origin.x = x return newFrame! } } return .zero } func numberOfMenuItems() -> Int { return 4 } func itemInfoForItem(at index: Int) -> GHContextItemView! { let itemView = GHContextItemView() switch index { case 0: itemView.typeDesc = "좋아요" itemView.baseImage = UIImage(named: "longpress-like-nor.png") itemView.selectedImage = UIImage(named: "longpress-like-focus.png") // itemView.baseImage = UIImage(named: "longpress-like-not-nor.png") // itemView.selectedImage = UIImage(named: "longpress-like-not-focus.png") break case 1: itemView.typeDesc = "피드" itemView.baseImage = UIImage(named: "longpress-feed-nor.png") itemView.selectedImage = UIImage(named: "longpress-feed-focus.png") break case 2: itemView.typeDesc = "공유" itemView.baseImage = UIImage(named: "longpress-share-nor.png") itemView.selectedImage = UIImage(named: "longpress-share-focus.png") break case 3: itemView.typeDesc = "더보기" itemView.baseImage = UIImage(named: "longpress-more-nor.png") itemView.selectedImage = UIImage(named: "longpress-more-focus.png") break default: break } return itemView } func didSelectItem(at selectedIndex: Int, forMenuAt point: CGPoint) { // let path = self.collectionView?.indexPathForItem(at: point) var message = "" switch selectedIndex { case 0: message = "좋아요 selected" break case 1: message = "피드 selected" break case 2: message = "공유 selected" break case 3: message = "더보기 selected" break default: break } AlertHelper.alert(message: message) } }
mit
3a70ad0dd89ff4a3a31b5b3cd7ac200b
35.742515
185
0.626222
5.321769
false
false
false
false
JohnEstropia/CoreStore
Sources/ListMonitor.swift
1
64427
// // ListMonitor.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // 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 CoreData // MARK: - ListMonitor /** The `ListMonitor` monitors changes to a list of `DynamicObject` instances. Observers that implement the `ListObserver` protocol may then register themselves to the `ListMonitor`'s `addObserver(_:)` method: ``` let monitor = dataStack.monitorList( From<Person>(), Where("title", isEqualTo: "Engineer"), OrderBy(.ascending("lastName")) ) monitor.addObserver(self) ``` The `ListMonitor` instance needs to be held on (retained) for as long as the list needs to be observed. Observers registered via `addObserver(_:)` are not retained. `ListMonitor` only keeps a `weak` reference to all observers, thus keeping itself free from retain-cycles. Lists created with `monitorList(...)` keep a single-section list of objects, where each object can be accessed by index: ``` let firstPerson: MyPersonEntity = monitor[0] ``` Accessing the list with an index above the valid range will raise an exception. Creating a sectioned-list is also possible with the `monitorSectionedList(...)` method: ``` let monitor = dataStack.monitorSectionedList( From<Person>(), SectionBy("age") { "Age \($0)" }, Where("title", isEqualTo: "Engineer"), OrderBy(.ascending("lastName")) ) monitor.addObserver(self) ``` Objects from `ListMonitor`s created this way can be accessed either by an `IndexPath` or a tuple: ``` let indexPath = IndexPath(forItem: 3, inSection: 2) let person1 = monitor[indexPath] let person2 = monitor[2, 3] ``` In the example above, both `person1` and `person2` will contain the object at section=2, index=3. */ public final class ListMonitor<O: DynamicObject>: Hashable { // MARK: Public (Accessors) /** The type for the objects contained bye the `ListMonitor` */ public typealias ObjectType = O /** Returns the object at the given index within the first section. This subscript indexer is typically used for `ListMonitor`s created with `monitorList(_:)`. - parameter index: the index of the object. Using an index above the valid range will raise an exception. - returns: the `DynamicObject` at the specified index */ public subscript(index: Int) -> O { Internals.assert( !self.isPendingRefetch || Thread.isMainThread, "Attempted to access a \(Internals.typeName(self)) outside the main thread while a refetch is in progress." ) if self.isSectioned { return O.cs_fromRaw(object: (self.fetchedResultsController.fetchedObjects as NSArray?)![index] as! NSManagedObject) } return self[0, index] } /** Returns the object at the given index, or `nil` if out of bounds. This subscript indexer is typically used for `ListMonitor`s created with `monitorList(_:)`. - parameter index: the index for the object. Using an index above the valid range will return `nil`. - returns: the `DynamicObject` at the specified index, or `nil` if out of bounds */ public subscript(safeIndex index: Int) -> O? { if self.isSectioned { let fetchedObjects = (self.fetchedResultsController.fetchedObjects as NSArray?)! if index < fetchedObjects.count && index >= 0 { return O.cs_fromRaw(object: fetchedObjects[index] as! NSManagedObject) } return nil } return self[safeSectionIndex: 0, safeItemIndex: index] } /** Returns the object at the given `sectionIndex` and `itemIndex`. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`. - parameter sectionIndex: the section index for the object. Using a `sectionIndex` with an invalid range will raise an exception. - parameter itemIndex: the index for the object within the section. Using an `itemIndex` with an invalid range will raise an exception. - returns: the `DynamicObject` at the specified section and item index */ public subscript(sectionIndex: Int, itemIndex: Int) -> O { return self[IndexPath(indexes: [sectionIndex, itemIndex])] } /** Returns the object at the given section and item index, or `nil` if out of bounds. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`. - parameter sectionIndex: the section index for the object. Using a `sectionIndex` with an invalid range will return `nil`. - parameter itemIndex: the index for the object within the section. Using an `itemIndex` with an invalid range will return `nil`. - returns: the `DynamicObject` at the specified section and item index, or `nil` if out of bounds */ public subscript(safeSectionIndex sectionIndex: Int, safeItemIndex itemIndex: Int) -> O? { guard let section = self.sectionInfo(safelyAt: sectionIndex) else { return nil } guard itemIndex >= 0 && itemIndex < section.numberOfObjects else { return nil } return self[IndexPath(indexes: [sectionIndex, itemIndex])] } /** Returns the object at the given `IndexPath`. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`. - parameter indexPath: the `IndexPath` for the object. Using an `indexPath` with an invalid range will raise an exception. - returns: the `DynamicObject` at the specified index path */ public subscript(indexPath: IndexPath) -> O { Internals.assert( !self.isPendingRefetch || Thread.isMainThread, "Attempted to access a \(Internals.typeName(self)) outside the main thread while a refetch is in progress." ) return O.cs_fromRaw(object: self.fetchedResultsController.object(at: indexPath)) } /** Returns the object at the given `IndexPath`, or `nil` if out of bounds. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`. - parameter indexPath: the `IndexPath` for the object. Using an `indexPath` with an invalid range will return `nil`. - returns: the `DynamicObject` at the specified index path, or `nil` if out of bounds */ public subscript(safeIndexPath indexPath: IndexPath) -> O? { return self[ safeSectionIndex: indexPath[0], safeItemIndex: indexPath[1] ] } /** Checks if the `ListMonitor` has at least one section - returns: `true` if at least one section exists, `false` otherwise */ public func hasSections() -> Bool { return self.sections().count > 0 } /** Checks if the `ListMonitor` has at least one object in any section. - returns: `true` if at least one object in any section exists, `false` otherwise */ public func hasObjects() -> Bool { return self.numberOfObjects() > 0 } /** Checks if the `ListMonitor` has at least one object the specified section. - parameter section: the section index. Using an index outside the valid range will return `false`. - returns: `true` if at least one object in the specified section exists, `false` otherwise */ public func hasObjects(in section: Int) -> Bool { return self.numberOfObjects(safelyIn: section)! > 0 } /** Returns the number of sections - returns: the number of sections */ public func numberOfSections() -> Int { Internals.assert( !self.isPendingRefetch || Thread.isMainThread, "Attempted to access a \(Internals.typeName(self)) outside the main thread while a refetch is in progress." ) return self.fetchedResultsController.sections?.count ?? 0 } /** Returns the number of objects in all sections - returns: the number of objects in all sections */ public func numberOfObjects() -> Int { Internals.assert( !self.isPendingRefetch || Thread.isMainThread, "Attempted to access a \(Internals.typeName(self)) outside the main thread while a refetch is in progress." ) return (self.fetchedResultsController.fetchedObjects as NSArray?)?.count ?? 0 } /** Returns the number of objects in the specified section - parameter section: the section index. Using an index outside the valid range will raise an exception. - returns: the number of objects in the specified section */ public func numberOfObjects(in section: Int) -> Int { return self.sectionInfo(at: section).numberOfObjects } /** Returns the number of objects in the specified section, or `nil` if out of bounds. - parameter section: the section index. Using an index outside the valid range will return `nil`. - returns: the number of objects in the specified section */ public func numberOfObjects(safelyIn section: Int) -> Int? { return self.sectionInfo(safelyAt: section)?.numberOfObjects } /** Returns the `NSFetchedResultsSectionInfo` for the specified section - parameter section: the section index. Using an index outside the valid range will raise an exception. - returns: the `NSFetchedResultsSectionInfo` for the specified section */ public func sectionInfo(at section: Int) -> NSFetchedResultsSectionInfo { Internals.assert( !self.isPendingRefetch || Thread.isMainThread, "Attempted to access a \(Internals.typeName(self)) outside the main thread while a refetch is in progress." ) return self.fetchedResultsController.sections![section] } /** Returns the `NSFetchedResultsSectionInfo` for the specified section, or `nil` if out of bounds. - parameter section: the section index. Using an index outside the valid range will return `nil`. - returns: the `NSFetchedResultsSectionInfo` for the specified section, or `nil` if the section index is out of bounds. */ public func sectionInfo(safelyAt section: Int) -> NSFetchedResultsSectionInfo? { Internals.assert( !self.isPendingRefetch || Thread.isMainThread, "Attempted to access a \(Internals.typeName(self)) outside the main thread while a refetch is in progress." ) guard section >= 0 else { return nil } guard let sections = self.fetchedResultsController.sections, section < sections.count else { return nil } return sections[section] } /** Returns the `NSFetchedResultsSectionInfo`s for all sections - returns: the `NSFetchedResultsSectionInfo`s for all sections */ public func sections() -> [NSFetchedResultsSectionInfo] { Internals.assert( !self.isPendingRefetch || Thread.isMainThread, "Attempted to access a \(Internals.typeName(self)) outside the main thread while a refetch is in progress." ) return self.fetchedResultsController.sections ?? [] } /** Returns the target section for a specified "Section Index" title and index. - parameter sectionIndexTitle: the title of the Section Index - parameter sectionIndex: the index of the Section Index - returns: the target section for the specified "Section Index" title and index. */ public func targetSection(forSectionIndexTitle sectionIndexTitle: String, at sectionIndex: Int) -> Int { Internals.assert( !self.isPendingRefetch || Thread.isMainThread, "Attempted to access a \(Internals.typeName(self)) outside the main thread while a refetch is in progress." ) return self.fetchedResultsController.section(forSectionIndexTitle: sectionIndexTitle, at: sectionIndex) } /** Returns the section index titles for all sections - returns: the section index titles for all sections */ public func sectionIndexTitles() -> [String] { Internals.assert( !self.isPendingRefetch || Thread.isMainThread, "Attempted to access a \(Internals.typeName(self)) outside the main thread while a refetch is in progress." ) return self.fetchedResultsController.sectionIndexTitles } /** Returns the index of the `DynamicObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found. - parameter object: the `DynamicObject` to search the index of - returns: the index of the `DynamicObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found. */ public func index(of object: O) -> Int? { Internals.assert( !self.isPendingRefetch || Thread.isMainThread, "Attempted to access a \(Internals.typeName(self)) outside the main thread while a refetch is in progress." ) if self.isSectioned { return (self.fetchedResultsController.fetchedObjects as NSArray?)?.index(of: object.cs_toRaw()) } return self.fetchedResultsController.indexPath(forObject: object.cs_toRaw())?[1] } /** Returns the `IndexPath` of the `DynamicObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found. - parameter object: the `DynamicObject` to search the index of - returns: the `IndexPath` of the `DynamicObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found. */ public func indexPath(of object: O) -> IndexPath? { Internals.assert( !self.isPendingRefetch || Thread.isMainThread, "Attempted to access a \(Internals.typeName(self)) outside the main thread while a refetch is in progress." ) return self.fetchedResultsController.indexPath(forObject: object.cs_toRaw()) } // MARK: Public (Observers) /** Registers a `ListObserver` to be notified when changes to the receiver's list occur. To prevent retain-cycles, `ListMonitor` only keeps `weak` references to its observers. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. Calling `addObserver(_:)` multiple times on the same observer is safe, as `ListMonitor` unregisters previous notifications to the observer before re-registering them. - parameter observer: a `ListObserver` to send change notifications to */ public func addObserver<U: ListObserver>(_ observer: U) where U.ListEntityType == O { self.unregisterObserver(observer) self.registerObserver( observer, willChange: { (observer, monitor) in observer.listMonitorWillChange( monitor, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, didChange: { (observer, monitor) in observer.listMonitorDidChange( monitor, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, willRefetch: { (observer, monitor) in observer.listMonitorWillRefetch( monitor, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, didRefetch: { (observer, monitor) in observer.listMonitorDidRefetch( monitor, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) } ) } /** Registers a `ListObjectObserver` to be notified when changes to the receiver's list occur. To prevent retain-cycles, `ListMonitor` only keeps `weak` references to its observers. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. Calling `addObserver(_:)` multiple times on the same observer is safe, as `ListMonitor` unregisters previous notifications to the observer before re-registering them. - parameter observer: a `ListObjectObserver` to send change notifications to */ public func addObserver<U: ListObjectObserver>(_ observer: U) where U.ListEntityType == O { self.unregisterObserver(observer) self.registerObserver( observer, willChange: { (observer, monitor) in observer.listMonitorWillChange( monitor, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, didChange: { (observer, monitor) in observer.listMonitorDidChange( monitor, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, willRefetch: { (observer, monitor) in observer.listMonitorWillRefetch( monitor, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, didRefetch: { (observer, monitor) in observer.listMonitorDidRefetch( monitor, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) } ) self.registerObserver( observer, didInsertObject: { (observer, monitor, object, toIndexPath) in observer.listMonitor( monitor, didInsertObject: object, toIndexPath: toIndexPath, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, didDeleteObject: { (observer, monitor, object, fromIndexPath) in observer.listMonitor( monitor, didDeleteObject: object, fromIndexPath: fromIndexPath, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, didUpdateObject: { (observer, monitor, object, atIndexPath) in observer.listMonitor( monitor, didUpdateObject: object, atIndexPath: atIndexPath, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, didMoveObject: { (observer, monitor, object, fromIndexPath, toIndexPath) in observer.listMonitor( monitor, didMoveObject: object, fromIndexPath: fromIndexPath, toIndexPath: toIndexPath, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) } ) } /** Registers a `ListSectionObserver` to be notified when changes to the receiver's list occur. To prevent retain-cycles, `ListMonitor` only keeps `weak` references to its observers. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. Calling `addObserver(_:)` multiple times on the same observer is safe, as `ListMonitor` unregisters previous notifications to the observer before re-registering them. - parameter observer: a `ListSectionObserver` to send change notifications to */ public func addObserver<U: ListSectionObserver>(_ observer: U) where U.ListEntityType == O { self.unregisterObserver(observer) self.registerObserver( observer, willChange: { (observer, monitor) in observer.listMonitorWillChange( monitor, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, didChange: { (observer, monitor) in observer.listMonitorDidChange( monitor, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, willRefetch: { (observer, monitor) in observer.listMonitorWillRefetch( monitor, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, didRefetch: { (observer, monitor) in observer.listMonitorDidRefetch( monitor, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) } ) self.registerObserver( observer, didInsertObject: { (observer, monitor, object, toIndexPath) in observer.listMonitor( monitor, didInsertObject: object, toIndexPath: toIndexPath, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, didDeleteObject: { (observer, monitor, object, fromIndexPath) in observer.listMonitor( monitor, didDeleteObject: object, fromIndexPath: fromIndexPath, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, didUpdateObject: { (observer, monitor, object, atIndexPath) in observer.listMonitor( monitor, didUpdateObject: object, atIndexPath: atIndexPath, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, didMoveObject: { (observer, monitor, object, fromIndexPath, toIndexPath) in observer.listMonitor( monitor, didMoveObject: object, fromIndexPath: fromIndexPath, toIndexPath: toIndexPath, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) } ) self.registerObserver( observer, didInsertSection: { (observer, monitor, sectionInfo, toIndex) in observer.listMonitor( monitor, didInsertSection: sectionInfo, toSectionIndex: toIndex, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) }, didDeleteSection: { (observer, monitor, sectionInfo, fromIndex) in observer.listMonitor( monitor, didDeleteSection: sectionInfo, fromSectionIndex: fromIndex, sourceIdentifier: monitor.fetchedResultsController.managedObjectContext.saveMetadata?.sourceIdentifier ) } ) } /** Unregisters a `ListObserver` from receiving notifications for changes to the receiver's list. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. - parameter observer: a `ListObserver` to unregister notifications to */ public func removeObserver<U: ListObserver>(_ observer: U) where U.ListEntityType == O { self.unregisterObserver(observer) } // MARK: Public (Refetching) /** Returns `true` if a call to `refetch(...)` was made to the `ListMonitor` and is currently waiting for the fetching to complete. Returns `false` otherwise. */ public private(set) var isPendingRefetch = false /** Asks the `ListMonitor` to refetch its objects using the specified series of `FetchClause`s. Note that this method does not execute the fetch immediately; the actual fetching will happen after the `NSFetchedResultsController`'s last `controllerDidChangeContent(_:)` notification completes. `refetch(...)` broadcasts `listMonitorWillRefetch(...)` to its observers immediately, and then `listMonitorDidRefetch(...)` after the new fetch request completes. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter sourceIdentifier: an optional value that identifies the source of this transaction. This identifier will be passed to the change notifications and callers can use it for custom handling that depends on the source. - Important: Starting CoreStore 4.0, all `FetchClause`s required by the `ListMonitor` should be provided in the arguments list of `refetch(...)`. */ public func refetch( _ fetchClauses: FetchClause..., sourceIdentifier: Any? = nil ) { self.refetch( fetchClauses, sourceIdentifier: sourceIdentifier ) } /** Asks the `ListMonitor` to refetch its objects using the specified series of `FetchClause`s. Note that this method does not execute the fetch immediately; the actual fetching will happen after the `NSFetchedResultsController`'s last `controllerDidChangeContent(_:)` notification completes. `refetch(...)` broadcasts `listMonitorWillRefetch(...)` to its observers immediately, and then `listMonitorDidRefetch(...)` after the new fetch request completes. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter sourceIdentifier: an optional value that identifies the source of this transaction. This identifier will be passed to the change notifications and callers can use it for custom handling that depends on the source. - Important: Starting CoreStore 4.0, all `FetchClause`s required by the `ListMonitor` should be provided in the arguments list of `refetch(...)`. */ public func refetch( _ fetchClauses: [FetchClause], sourceIdentifier: Any? = nil ) { self.refetch( { (fetchRequest) in fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) } }, sourceIdentifier: sourceIdentifier ) } // MARK: Public (3rd Party Utilities) /** Allow external libraries to store custom data in the `ListMonitor`. App code should rarely have a need for this. ``` enum Static { static var myDataKey: Void? } monitor.userInfo[&Static.myDataKey] = myObject ``` - Important: Do not use this method to store thread-sensitive data. */ public let userInfo = UserInfo() // MARK: Equatable public static func == (lhs: ListMonitor<O>, rhs: ListMonitor<O>) -> Bool { return lhs.fetchedResultsController === rhs.fetchedResultsController } public static func == <T, U>(lhs: ListMonitor<T>, rhs: ListMonitor<U>) -> Bool { return lhs.fetchedResultsController === rhs.fetchedResultsController } public static func ~= (lhs: ListMonitor<O>, rhs: ListMonitor<O>) -> Bool { return lhs.fetchedResultsController === rhs.fetchedResultsController } public static func ~= <T, U>(lhs: ListMonitor<T>, rhs: ListMonitor<U>) -> Bool { return lhs.fetchedResultsController === rhs.fetchedResultsController } // MARK: Hashable public func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } // MARK: Internal internal convenience init( dataStack: DataStack, from: From<O>, sectionBy: SectionBy<O>?, applyFetchClauses: @escaping (_ fetchRequest: Internals.CoreStoreFetchRequest<NSManagedObject>) -> Void ) { self.init( context: dataStack.mainContext, transactionQueue: dataStack.childTransactionQueue, from: from, sectionBy: sectionBy, applyFetchClauses: applyFetchClauses, createAsynchronously: nil ) } internal convenience init( dataStack: DataStack, from: From<O>, sectionBy: SectionBy<O>?, applyFetchClauses: @escaping (_ fetchRequest: Internals.CoreStoreFetchRequest<NSManagedObject>) -> Void, createAsynchronously: @escaping (ListMonitor<O>) -> Void ) { self.init( context: dataStack.mainContext, transactionQueue: dataStack.childTransactionQueue, from: from, sectionBy: sectionBy, applyFetchClauses: applyFetchClauses, createAsynchronously: createAsynchronously ) } internal convenience init( unsafeTransaction: UnsafeDataTransaction, from: From<O>, sectionBy: SectionBy<O>?, applyFetchClauses: @escaping (_ fetchRequest: Internals.CoreStoreFetchRequest<NSManagedObject>) -> Void ) { self.init( context: unsafeTransaction.context, transactionQueue: unsafeTransaction.transactionQueue, from: from, sectionBy: sectionBy, applyFetchClauses: applyFetchClauses, createAsynchronously: nil ) } internal convenience init( unsafeTransaction: UnsafeDataTransaction, from: From<O>, sectionBy: SectionBy<O>?, applyFetchClauses: @escaping (_ fetchRequest: Internals.CoreStoreFetchRequest<NSManagedObject>) -> Void, createAsynchronously: @escaping (ListMonitor<O>) -> Void ) { self.init( context: unsafeTransaction.context, transactionQueue: unsafeTransaction.transactionQueue, from: from, sectionBy: sectionBy, applyFetchClauses: applyFetchClauses, createAsynchronously: createAsynchronously ) } internal func registerChangeNotification( _ notificationKey: UnsafeRawPointer, name: Notification.Name, toObserver observer: AnyObject, callback: @escaping (_ monitor: ListMonitor<O>) -> Void ) { Internals.setAssociatedRetainedObject( Internals.NotificationObserver( notificationName: name, object: self, closure: { [weak self] (note) -> Void in guard let self = self else { return } callback(self) } ), forKey: notificationKey, inObject: observer ) } internal func registerObjectNotification( _ notificationKey: UnsafeRawPointer, name: Notification.Name, toObserver observer: AnyObject, callback: @escaping ( _ monitor: ListMonitor<O>, _ object: O, _ indexPath: IndexPath?, _ newIndexPath: IndexPath? ) -> Void) { Internals.setAssociatedRetainedObject( Internals.NotificationObserver( notificationName: name, object: self, closure: { [weak self] (note) -> Void in guard let self = self, let userInfo = note.userInfo, let rawObject = userInfo[String(describing: NSManagedObject.self)] as? NSManagedObject else { return } callback( self, O.cs_fromRaw(object: rawObject), userInfo[String(describing: IndexPath.self)] as? IndexPath, userInfo["\(String(describing: IndexPath.self)).New"] as? IndexPath ) } ), forKey: notificationKey, inObject: observer ) } internal func registerSectionNotification( _ notificationKey: UnsafeRawPointer, name: Notification.Name, toObserver observer: AnyObject, callback: @escaping ( _ monitor: ListMonitor<O>, _ sectionInfo: NSFetchedResultsSectionInfo, _ sectionIndex: Int ) -> Void ) { Internals.setAssociatedRetainedObject( Internals.NotificationObserver( notificationName: name, object: self, closure: { [weak self] (note) -> Void in guard let self = self, let userInfo = note.userInfo, let sectionInfo = userInfo[String(describing: NSFetchedResultsSectionInfo.self)] as? NSFetchedResultsSectionInfo, let sectionIndex = (userInfo[String(describing: NSNumber.self)] as? NSNumber)?.intValue else { return } callback(self, sectionInfo, sectionIndex) } ), forKey: notificationKey, inObject: observer ) } internal func registerObserver<U: AnyObject>( _ observer: U, willChange: @escaping ( _ observer: U, _ monitor: ListMonitor<O> ) -> Void, didChange: @escaping ( _ observer: U, _ monitor: ListMonitor<O> ) -> Void, willRefetch: @escaping ( _ observer: U, _ monitor: ListMonitor<O> ) -> Void, didRefetch: @escaping ( _ observer: U, _ monitor: ListMonitor<O> ) -> Void) { Internals.assert( Thread.isMainThread, "Attempted to add an observer of type \(Internals.typeName(observer)) outside the main thread." ) self.registerChangeNotification( &self.willChangeListKey, name: Notification.Name.listMonitorWillChangeList, toObserver: observer, callback: { [weak observer] (monitor) -> Void in guard let observer = observer else { return } willChange(observer, monitor) } ) self.registerChangeNotification( &self.didChangeListKey, name: Notification.Name.listMonitorDidChangeList, toObserver: observer, callback: { [weak observer] (monitor) -> Void in guard let observer = observer else { return } didChange(observer, monitor) } ) self.registerChangeNotification( &self.willRefetchListKey, name: Notification.Name.listMonitorWillRefetchList, toObserver: observer, callback: { [weak observer] (monitor) -> Void in guard let observer = observer else { return } willRefetch(observer, monitor) } ) self.registerChangeNotification( &self.didRefetchListKey, name: Notification.Name.listMonitorDidRefetchList, toObserver: observer, callback: { [weak observer] (monitor) -> Void in guard let observer = observer else { return } didRefetch(observer, monitor) } ) } internal func registerObserver<U: AnyObject>( _ observer: U, didInsertObject: @escaping ( _ observer: U, _ monitor: ListMonitor<O>, _ object: O, _ toIndexPath: IndexPath ) -> Void, didDeleteObject: @escaping ( _ observer: U, _ monitor: ListMonitor<O>, _ object: O, _ fromIndexPath: IndexPath ) -> Void, didUpdateObject: @escaping ( _ observer: U, _ monitor: ListMonitor<O>, _ object: O, _ atIndexPath: IndexPath ) -> Void, didMoveObject: @escaping ( _ observer: U, _ monitor: ListMonitor<O>, _ object: O, _ fromIndexPath: IndexPath, _ toIndexPath: IndexPath ) -> Void) { Internals.assert( Thread.isMainThread, "Attempted to add an observer of type \(Internals.typeName(observer)) outside the main thread." ) self.registerObjectNotification( &self.didInsertObjectKey, name: Notification.Name.listMonitorDidInsertObject, toObserver: observer, callback: { [weak observer] (monitor, object, indexPath, newIndexPath) -> Void in guard let observer = observer else { return } didInsertObject(observer, monitor, object, newIndexPath!) } ) self.registerObjectNotification( &self.didDeleteObjectKey, name: Notification.Name.listMonitorDidDeleteObject, toObserver: observer, callback: { [weak observer] (monitor, object, indexPath, newIndexPath) -> Void in guard let observer = observer else { return } didDeleteObject(observer, monitor, object, indexPath!) } ) self.registerObjectNotification( &self.didUpdateObjectKey, name: Notification.Name.listMonitorDidUpdateObject, toObserver: observer, callback: { [weak observer] (monitor, object, indexPath, newIndexPath) -> Void in guard let observer = observer else { return } didUpdateObject(observer, monitor, object, indexPath!) } ) self.registerObjectNotification( &self.didMoveObjectKey, name: Notification.Name.listMonitorDidMoveObject, toObserver: observer, callback: { [weak observer] (monitor, object, indexPath, newIndexPath) -> Void in guard let observer = observer else { return } didMoveObject(observer, monitor, object, indexPath!, newIndexPath!) } ) } internal func registerObserver<U: AnyObject>( _ observer: U, didInsertSection: @escaping ( _ observer: U, _ monitor: ListMonitor<O>, _ sectionInfo: NSFetchedResultsSectionInfo, _ toIndex: Int ) -> Void, didDeleteSection: @escaping ( _ observer: U, _ monitor: ListMonitor<O>, _ sectionInfo: NSFetchedResultsSectionInfo, _ fromIndex: Int ) -> Void) { Internals.assert( Thread.isMainThread, "Attempted to add an observer of type \(Internals.typeName(observer)) outside the main thread." ) self.registerSectionNotification( &self.didInsertSectionKey, name: Notification.Name.listMonitorDidInsertSection, toObserver: observer, callback: { [weak observer] (monitor, sectionInfo, sectionIndex) -> Void in guard let observer = observer else { return } didInsertSection(observer, monitor, sectionInfo, sectionIndex) } ) self.registerSectionNotification( &self.didDeleteSectionKey, name: Notification.Name.listMonitorDidDeleteSection, toObserver: observer, callback: { [weak observer] (monitor, sectionInfo, sectionIndex) -> Void in guard let observer = observer else { return } didDeleteSection(observer, monitor, sectionInfo, sectionIndex) } ) } internal func unregisterObserver(_ observer: AnyObject) { Internals.assert( Thread.isMainThread, "Attempted to remove an observer of type \(Internals.typeName(observer)) outside the main thread." ) let nilValue: AnyObject? = nil Internals.setAssociatedRetainedObject(nilValue, forKey: &self.willChangeListKey, inObject: observer) Internals.setAssociatedRetainedObject(nilValue, forKey: &self.didChangeListKey, inObject: observer) Internals.setAssociatedRetainedObject(nilValue, forKey: &self.willRefetchListKey, inObject: observer) Internals.setAssociatedRetainedObject(nilValue, forKey: &self.didRefetchListKey, inObject: observer) Internals.setAssociatedRetainedObject(nilValue, forKey: &self.didInsertObjectKey, inObject: observer) Internals.setAssociatedRetainedObject(nilValue, forKey: &self.didDeleteObjectKey, inObject: observer) Internals.setAssociatedRetainedObject(nilValue, forKey: &self.didUpdateObjectKey, inObject: observer) Internals.setAssociatedRetainedObject(nilValue, forKey: &self.didMoveObjectKey, inObject: observer) Internals.setAssociatedRetainedObject(nilValue, forKey: &self.didInsertSectionKey, inObject: observer) Internals.setAssociatedRetainedObject(nilValue, forKey: &self.didDeleteSectionKey, inObject: observer) } internal func refetch( _ applyFetchClauses: @escaping (_ fetchRequest: Internals.CoreStoreFetchRequest<NSManagedObject>) -> Void, sourceIdentifier: Any? ) { Internals.assert( Thread.isMainThread, "Attempted to refetch a \(Internals.typeName(self)) outside the main thread." ) if !self.isPendingRefetch { self.isPendingRefetch = true NotificationCenter.default.post( name: Notification.Name.listMonitorWillRefetchList, object: self ) } self.applyFetchClauses = applyFetchClauses self.taskGroup.notify(queue: .main) { [weak self] () -> Void in guard let self = self else { return } let (newFetchedResultsController, newFetchedResultsControllerDelegate) = Self.recreateFetchedResultsController( context: self.fetchedResultsController.managedObjectContext, from: self.from, sectionBy: self.sectionBy, applyFetchClauses: self.applyFetchClauses ) newFetchedResultsControllerDelegate.enabled = false newFetchedResultsControllerDelegate.handler = self self.transactionQueue.async { [weak self] in guard let self = self else { return } do { try newFetchedResultsController.performFetchFromSpecifiedStores() } catch { // DataStack may have been deallocated return } self.fetchedResultsControllerDelegate.taskGroup.notify(queue: .main) { self.fetchedResultsControllerDelegate.enabled = false } newFetchedResultsControllerDelegate.taskGroup.notify(queue: .main) { [weak self] () -> Void in guard let self = self else { return } (self.fetchedResultsController, self.fetchedResultsControllerDelegate) = (newFetchedResultsController, newFetchedResultsControllerDelegate) newFetchedResultsControllerDelegate.enabled = true self.isPendingRefetch = false newFetchedResultsController.managedObjectContext.saveMetadata = .init( isSavingSynchronously: false, sourceIdentifier: sourceIdentifier ) NotificationCenter.default.post( name: Notification.Name.listMonitorDidRefetchList, object: self ) newFetchedResultsController.managedObjectContext.saveMetadata = nil } } } } deinit { self.fetchedResultsControllerDelegate.fetchedResultsController = nil self.isPersistentStoreChanging = false } // MARK: Private fileprivate var fetchedResultsController: Internals.CoreStoreFetchedResultsController fileprivate let taskGroup = DispatchGroup() internal let sectionByIndexTransformer: (_ sectionName: KeyPathString?) -> String? private let isSectioned: Bool private var willChangeListKey: Void? private var didChangeListKey: Void? private var willRefetchListKey: Void? private var didRefetchListKey: Void? private var didInsertObjectKey: Void? private var didDeleteObjectKey: Void? private var didUpdateObjectKey: Void? private var didMoveObjectKey: Void? private var didInsertSectionKey: Void? private var didDeleteSectionKey: Void? private var fetchedResultsControllerDelegate: Internals.FetchedResultsControllerDelegate private var observerForWillChangePersistentStore: Internals.NotificationObserver! private var observerForDidChangePersistentStore: Internals.NotificationObserver! private let transactionQueue: DispatchQueue private var applyFetchClauses: (_ fetchRequest: Internals.CoreStoreFetchRequest<NSManagedObject>) -> Void private var isPersistentStoreChanging: Bool = false { didSet { let newValue = self.isPersistentStoreChanging guard newValue != oldValue else { return } if newValue { self.taskGroup.enter() } else { self.taskGroup.leave() } } } private static func recreateFetchedResultsController( context: NSManagedObjectContext, from: From<O>, sectionBy: SectionBy<O>?, applyFetchClauses: @escaping (_ fetchRequest: Internals.CoreStoreFetchRequest<NSManagedObject>) -> Void ) -> ( controller: Internals.CoreStoreFetchedResultsController, delegate: Internals.FetchedResultsControllerDelegate ) { let fetchRequest = Internals.CoreStoreFetchRequest<NSManagedObject>() fetchRequest.fetchLimit = 0 fetchRequest.resultType = .managedObjectResultType fetchRequest.fetchBatchSize = 20 fetchRequest.includesPendingChanges = false fetchRequest.shouldRefreshRefetchedObjects = true let fetchedResultsController = Internals.CoreStoreFetchedResultsController( context: context, fetchRequest: fetchRequest, from: from, sectionBy: sectionBy, applyFetchClauses: applyFetchClauses ) let fetchedResultsControllerDelegate = Internals.FetchedResultsControllerDelegate() fetchedResultsControllerDelegate.fetchedResultsController = fetchedResultsController return (fetchedResultsController, fetchedResultsControllerDelegate) } private let from: From<O> private let sectionBy: SectionBy<O>? private init( context: NSManagedObjectContext, transactionQueue: DispatchQueue, from: From<O>, sectionBy: SectionBy<O>?, applyFetchClauses: @escaping (_ fetchRequest: Internals.CoreStoreFetchRequest<NSManagedObject>) -> Void, createAsynchronously: ((ListMonitor<O>) -> Void)? ) { self.isSectioned = (sectionBy != nil) self.from = from self.sectionBy = sectionBy (self.fetchedResultsController, self.fetchedResultsControllerDelegate) = Self.recreateFetchedResultsController( context: context, from: from, sectionBy: sectionBy, applyFetchClauses: applyFetchClauses ) if let sectionIndexTransformer = sectionBy?.sectionIndexTransformer { self.sectionByIndexTransformer = sectionIndexTransformer } else { self.sectionByIndexTransformer = { _ in nil } } self.transactionQueue = transactionQueue self.applyFetchClauses = applyFetchClauses self.fetchedResultsControllerDelegate.handler = self guard let coordinator = context.parentStack?.coordinator else { return } self.observerForWillChangePersistentStore = Internals.NotificationObserver( notificationName: NSNotification.Name.NSPersistentStoreCoordinatorStoresWillChange, object: coordinator, queue: OperationQueue.main, closure: { [weak self] (note) -> Void in guard let self = self else { return } self.isPersistentStoreChanging = true guard let removedStores = (note.userInfo?[NSRemovedPersistentStoresKey] as? [NSPersistentStore]).flatMap(Set.init), !Set(self.fetchedResultsController.typedFetchRequest.safeAffectedStores() ?? []).intersection(removedStores).isEmpty else { return } self.refetch(self.applyFetchClauses, sourceIdentifier: nil) } ) self.observerForDidChangePersistentStore = Internals.NotificationObserver( notificationName: NSNotification.Name.NSPersistentStoreCoordinatorStoresDidChange, object: coordinator, queue: OperationQueue.main, closure: { [weak self] (note) -> Void in guard let self = self else { return } if !self.isPendingRefetch { let previousStores = Set(self.fetchedResultsController.typedFetchRequest.safeAffectedStores() ?? []) let currentStores = previousStores .subtracting(note.userInfo?[NSRemovedPersistentStoresKey] as? [NSPersistentStore] ?? []) .union(note.userInfo?[NSAddedPersistentStoresKey] as? [NSPersistentStore] ?? []) if previousStores != currentStores { self.refetch(self.applyFetchClauses, sourceIdentifier: nil) } } self.isPersistentStoreChanging = false } ) if let createAsynchronously = createAsynchronously { transactionQueue.async { try! self.fetchedResultsController.performFetchFromSpecifiedStores() self.taskGroup.notify(queue: .main) { createAsynchronously(self) } } } else { try! self.fetchedResultsController.performFetchFromSpecifiedStores() } } } // MARK: - ListMonitor where O: NSManagedObject extension ListMonitor where O: NSManagedObject { /** Returns all objects in all sections - returns: all objects in all sections */ public func objectsInAllSections() -> [O] { Internals.assert( !self.isPendingRefetch || Thread.isMainThread, "Attempted to access a \(Internals.typeName(self)) outside the main thread while a refetch is in progress." ) return (self.fetchedResultsController.dynamicCast() as NSFetchedResultsController<O>).fetchedObjects ?? [] } /** Returns all objects in the specified section - parameter section: the section index. Using an index outside the valid range will raise an exception. - returns: all objects in the specified section */ public func objects(in section: Int) -> [O] { return (self.sectionInfo(at: section).objects as! [O]?) ?? [] } /** Returns all objects in the specified section, or `nil` if out of bounds. - parameter section: the section index. Using an index outside the valid range will return `nil`. - returns: all objects in the specified section */ public func objects(safelyIn section: Int) -> [O]? { return self.sectionInfo(safelyAt: section)?.objects as! [O]? } // MARK: Deprecated @available(*, deprecated, renamed: "objects(in:)") public func objectsInSection(_ section: Int) -> [O] { return self.objects(in: section) } @available(*, deprecated, renamed: "objects(safelyIn:)") public func objectsInSection(safeSectionIndex section: Int) -> [O]? { return self.objects(safelyIn: section) } } // MARK: - ListMonitor where O: CoreStoreObject extension ListMonitor where O: CoreStoreObject { /** Returns all objects in all sections - returns: all objects in all sections */ public func objectsInAllSections() -> [O] { Internals.assert( !self.isPendingRefetch || Thread.isMainThread, "Attempted to access a \(Internals.typeName(self)) outside the main thread while a refetch is in progress." ) return (self.fetchedResultsController.fetchedObjects ?? []) .map(O.cs_fromRaw) } /** Returns all objects in the specified section - parameter section: the section index. Using an index outside the valid range will raise an exception. - returns: all objects in the specified section */ public func objects(in section: Int) -> [O] { return (self.sectionInfo(at: section).objects ?? []) .map({ O.cs_fromRaw(object: $0 as! NSManagedObject) }) } /** Returns all objects in the specified section, or `nil` if out of bounds. - parameter section: the section index. Using an index outside the valid range will return `nil`. - returns: all objects in the specified section */ public func objects(safelyIn section: Int) -> [O]? { return (self.sectionInfo(safelyAt: section)?.objects)? .map({ O.cs_fromRaw(object: $0 as! NSManagedObject) }) } // MARK: Deprecated @available(*, deprecated, renamed: "O") public typealias D = O } // MARK: - ListMonitor: FetchedResultsControllerHandler extension ListMonitor: FetchedResultsControllerHandler { // MARK: FetchedResultsControllerHandler internal var sectionIndexTransformer: (_ sectionName: KeyPathString?) -> String? { return self.sectionByIndexTransformer } internal func controller( _ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeObject anObject: Any, atIndexPath indexPath: IndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: IndexPath? ) { switch type { case .insert: NotificationCenter.default.post( name: Notification.Name.listMonitorDidInsertObject, object: self, userInfo: [ String(describing: NSManagedObject.self): anObject, "\(String(describing: IndexPath.self)).New": newIndexPath! ] ) case .delete: NotificationCenter.default.post( name: Notification.Name.listMonitorDidDeleteObject, object: self, userInfo: [ String(describing: NSManagedObject.self): anObject, String(describing: IndexPath.self): indexPath! ] ) case .update: NotificationCenter.default.post( name: Notification.Name.listMonitorDidUpdateObject, object: self, userInfo: [ String(describing: NSManagedObject.self): anObject, String(describing: IndexPath.self): indexPath! ] ) case .move: NotificationCenter.default.post( name: Notification.Name.listMonitorDidMoveObject, object: self, userInfo: [ String(describing: NSManagedObject.self): anObject, String(describing: IndexPath.self): indexPath!, "\(String(describing: IndexPath.self)).New": newIndexPath! ] ) @unknown default: fatalError() } } internal func controller( _ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType ) { switch type { case .insert: NotificationCenter.default.post( name: Notification.Name.listMonitorDidInsertSection, object: self, userInfo: [ String(describing: NSFetchedResultsSectionInfo.self): sectionInfo, String(describing: NSNumber.self): NSNumber(value: sectionIndex) ] ) case .delete: NotificationCenter.default.post( name: Notification.Name.listMonitorDidDeleteSection, object: self, userInfo: [ String(describing: NSFetchedResultsSectionInfo.self): sectionInfo, String(describing: NSNumber.self): NSNumber(value: sectionIndex) ] ) default: break } } internal func controllerWillChangeContent( _ controller: NSFetchedResultsController<NSFetchRequestResult> ) { self.taskGroup.enter() NotificationCenter.default.post( name: Notification.Name.listMonitorWillChangeList, object: self ) } internal func controllerDidChangeContent( _ controller: NSFetchedResultsController<NSFetchRequestResult> ) { defer { self.taskGroup.leave() } NotificationCenter.default.post( name: Notification.Name.listMonitorDidChangeList, object: self ) } } // MARK: - Notification Keys extension Notification.Name { fileprivate static let listMonitorWillChangeList = Notification.Name(rawValue: "listMonitorWillChangeList") fileprivate static let listMonitorDidChangeList = Notification.Name(rawValue: "listMonitorDidChangeList") fileprivate static let listMonitorWillRefetchList = Notification.Name(rawValue: "listMonitorWillRefetchList") fileprivate static let listMonitorDidRefetchList = Notification.Name(rawValue: "listMonitorDidRefetchList") fileprivate static let listMonitorDidInsertObject = Notification.Name(rawValue: "listMonitorDidInsertObject") fileprivate static let listMonitorDidDeleteObject = Notification.Name(rawValue: "listMonitorDidDeleteObject") fileprivate static let listMonitorDidUpdateObject = Notification.Name(rawValue: "listMonitorDidUpdateObject") fileprivate static let listMonitorDidMoveObject = Notification.Name(rawValue: "listMonitorDidMoveObject") fileprivate static let listMonitorDidInsertSection = Notification.Name(rawValue: "listMonitorDidInsertSection") fileprivate static let listMonitorDidDeleteSection = Notification.Name(rawValue: "listMonitorDidDeleteSection") }
mit
1e96da423c762dae20561abf16990481
37.951632
293
0.596607
5.843098
false
false
false
false
wibosco/ApproachingParsers
ApproachingParsers/ViewControllers/Question/Cells/QuestionTableViewCell.swift
1
2392
// // QuestionTableViewCell.swift // ApproachingParsers // // Created by Home on 27/02/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit import PureLayout class QuestionTableViewCell: UITableViewCell { //MARK: - Accessors lazy var titleLabel : UILabel = { let label = UILabel.newAutoLayoutView() label.numberOfLines = 2 label.font = UIFont.boldSystemFontOfSize(15) return label }() lazy var authorLabel : UILabel = { let label = UILabel.newAutoLayoutView() label.font = UIFont.systemFontOfSize(14) return label }() //MARK: - Init override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.contentView.addSubview(self.titleLabel) self.contentView.addSubview(self.authorLabel) self.contentView.backgroundColor = UIColor.whiteColor() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARK: - Constraints override func updateConstraints() { self.titleLabel.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Left, ofView: self.contentView, withOffset: 10.0) self.titleLabel.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Top, ofView: self.contentView, withOffset: 8.0) self.titleLabel.autoPinEdge(ALEdge.Right, toEdge: ALEdge.Right, ofView: self.contentView, withOffset: -10.0) /*---------------------*/ self.authorLabel.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Left, ofView: self.contentView, withOffset: 10.0) self.authorLabel.autoPinEdge(ALEdge.Right, toEdge: ALEdge.Right, ofView: self.contentView, withOffset: -10.0) self.authorLabel.autoPinEdge(ALEdge.Bottom, toEdge: ALEdge.Bottom, ofView: self.contentView, withOffset: -5.0) /*---------------------*/ super.updateConstraints() } func layoutByApplyingConstraints() { self.setNeedsUpdateConstraints() self.updateConstraintsIfNeeded() self.setNeedsLayout() self.layoutIfNeeded() } //MARK: - ReuseIdentifier class func reuseIdentifier() -> String { return NSStringFromClass(QuestionTableViewCell.self) } }
mit
fd1f06553b04ef9a03d05e856e08f716
28.8875
118
0.63028
4.849899
false
false
false
false
dangnguyenhuu/JSQMessagesSwift
Sources/Views/JSQMessagesCollectionViewCell.swift
1
12839
// // JSQMessagesCollectionViewCell.swift // JSQMessagesViewController // // Created by Sylvain FAY-CHATELARD on 20/08/2015. // Copyright (c) 2015 Dviance. All rights reserved. // import UIKit public protocol JSQMessagesCollectionViewCellDelegate { func messagesCollectionViewCellDidTapAvatar(_ cell: JSQMessagesCollectionViewCell) func messagesCollectionViewCellDidTapMessageBubble(_ cell: JSQMessagesCollectionViewCell) func messagesCollectionViewCellDidTapCell(_ cell: JSQMessagesCollectionViewCell, atPosition position: CGPoint) func messagesCollectionViewCell(_ cell: JSQMessagesCollectionViewCell, didPerformAction action: Selector, withSender sender: AnyObject) } open class JSQMessagesCollectionViewCell: UICollectionViewCell { fileprivate static var jsqMessagesCollectionViewCellActions: Set<Selector> = Set() open var delegate: JSQMessagesCollectionViewCellDelegate? open var bubbleImage: UIImage? @IBOutlet fileprivate(set) open var sendTimeLabel: UILabel! @IBOutlet fileprivate(set) open var cellTopLabel: JSQMessagesLabel! @IBOutlet fileprivate(set) open var messageBubbleTopLabel: JSQMessagesLabel! @IBOutlet fileprivate(set) open var cellBottomLabel: JSQMessagesLabel! @IBOutlet fileprivate(set) open var messageBubbleContainerView: UIView! @IBOutlet fileprivate(set) open var messageBubbleImageView: UIImageView? @IBOutlet fileprivate(set) open var textView: JSQMessagesCellTextView? @IBOutlet fileprivate(set) open var avatarImageView: UIImageView! @IBOutlet fileprivate(set) open var avatarContainerView: UIView! @IBOutlet fileprivate var messageBubbleContainerWidthConstraint: NSLayoutConstraint! @IBOutlet fileprivate var textViewTopVerticalSpaceConstraint: NSLayoutConstraint! @IBOutlet fileprivate var textViewBottomVerticalSpaceConstraint: NSLayoutConstraint! @IBOutlet fileprivate var textViewAvatarHorizontalSpaceConstraint: NSLayoutConstraint! @IBOutlet fileprivate var textViewMarginHorizontalSpaceConstraint: NSLayoutConstraint! @IBOutlet fileprivate var cellTopLabelHeightConstraint: NSLayoutConstraint! @IBOutlet fileprivate var messageBubbleTopLabelHeightConstraint: NSLayoutConstraint! @IBOutlet fileprivate var cellBottomLabelHeightConstraint: NSLayoutConstraint! @IBOutlet fileprivate var avatarContainerViewWidthConstraint: NSLayoutConstraint! @IBOutlet fileprivate var avatarContainerViewHeightConstraint: NSLayoutConstraint! fileprivate(set) var tapGestureRecognizer: UITapGestureRecognizer? fileprivate var textViewFrameInsets: UIEdgeInsets { set { if UIEdgeInsetsEqualToEdgeInsets(newValue, self.textViewFrameInsets) { return } self.jsq_update(constraint: self.textViewTopVerticalSpaceConstraint, withConstant: newValue.top) self.jsq_update(constraint: self.textViewBottomVerticalSpaceConstraint, withConstant: newValue.bottom) self.jsq_update(constraint: self.textViewAvatarHorizontalSpaceConstraint, withConstant: newValue.right) self.jsq_update(constraint: self.textViewMarginHorizontalSpaceConstraint, withConstant: newValue.left) } get { return UIEdgeInsetsMake(self.textViewTopVerticalSpaceConstraint.constant, self.textViewMarginHorizontalSpaceConstraint.constant, self.textViewBottomVerticalSpaceConstraint.constant, self.textViewAvatarHorizontalSpaceConstraint.constant) } } fileprivate var avatarViewSize: CGSize { set { if newValue.equalTo(self.avatarViewSize) { return } self.jsq_update(constraint: self.avatarContainerViewWidthConstraint, withConstant: newValue.width) self.jsq_update(constraint: self.avatarContainerViewHeightConstraint, withConstant: newValue.height) } get { return CGSize(width: self.avatarContainerViewWidthConstraint.constant, height: self.avatarContainerViewHeightConstraint.constant) } } open var mediaView: UIView? { didSet { if let mediaView = self.mediaView { self.messageBubbleImageView?.removeFromSuperview() self.textView?.removeFromSuperview() mediaView.translatesAutoresizingMaskIntoConstraints = false mediaView.frame = self.messageBubbleContainerView.bounds self.messageBubbleContainerView.addSubview(mediaView) self.messageBubbleContainerView.jsq_pinAllEdgesOfSubview(mediaView) } } } open override var backgroundColor: UIColor? { didSet { self.cellTopLabel.backgroundColor = backgroundColor self.messageBubbleTopLabel.backgroundColor = backgroundColor self.cellBottomLabel.backgroundColor = backgroundColor self.messageBubbleImageView?.backgroundColor = backgroundColor self.avatarImageView.backgroundColor = backgroundColor self.messageBubbleContainerView.backgroundColor = backgroundColor self.avatarContainerView.backgroundColor = backgroundColor } } // MARK: - Class methods open class func nib() -> UINib { return UINib(nibName: JSQMessagesCollectionViewCell.jsq_className, bundle: Bundle(for: JSQMessagesCollectionViewCell.self)) } open class func cellReuseIdentifier() -> String { return JSQMessagesCollectionViewCell.jsq_className } open class func mediaCellReuseIdentifier() -> String { return JSQMessagesCollectionViewCell.jsq_className + "_JSQMedia" } open class func registerMenuAction(_ action: Selector) { JSQMessagesCollectionViewCell.jsqMessagesCollectionViewCellActions.insert(action) } // MARK: - Initialization open override func awakeFromNib() { super.awakeFromNib() self.translatesAutoresizingMaskIntoConstraints = false self.backgroundColor = UIColor.white self.cellTopLabelHeightConstraint.constant = 0 self.messageBubbleTopLabelHeightConstraint.constant = 0 self.cellBottomLabelHeightConstraint.constant = 0 self.cellTopLabel.textAlignment = .center self.cellTopLabel.font = UIFont.boldSystemFont(ofSize: 12) self.cellTopLabel.textColor = UIColor.lightGray self.messageBubbleTopLabel.font = UIFont.systemFont(ofSize: 12) self.messageBubbleTopLabel.textColor = UIColor.lightGray self.cellBottomLabel.font = UIFont.systemFont(ofSize: 11); self.cellBottomLabel.textColor = UIColor.lightGray let tap = UITapGestureRecognizer(target: self, action: #selector(JSQMessagesCollectionViewCell.jsq_handleTapGesture(_:))) self.addGestureRecognizer(tap) self.tapGestureRecognizer = tap } deinit { self.tapGestureRecognizer?.removeTarget(nil, action: nil) self.tapGestureRecognizer = nil } // MARK: - Collection view cell open override func prepareForReuse() { super.prepareForReuse() self.cellTopLabel.text = nil self.messageBubbleTopLabel.text = nil self.cellBottomLabel.text = nil self.textView?.dataDetectorTypes = UIDataDetectorTypes() self.textView?.text = nil self.textView?.attributedText = nil self.avatarImageView.image = nil self.avatarImageView.highlightedImage = nil } open override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { return layoutAttributes } open override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) { super.apply(layoutAttributes) if let customAttributes = layoutAttributes as? JSQMessagesCollectionViewLayoutAttributes { if let textView = self.textView { if textView.font != customAttributes.messageBubbleFont { textView.font = customAttributes.messageBubbleFont } if !UIEdgeInsetsEqualToEdgeInsets(textView.textContainerInset, customAttributes.textViewTextContainerInsets) { textView.textContainerInset = customAttributes.textViewTextContainerInsets } } self.textViewFrameInsets = customAttributes.textViewFrameInsets self.jsq_update(constraint: self.messageBubbleContainerWidthConstraint, withConstant: customAttributes.messageBubbleContainerViewWidth) self.jsq_update(constraint: self.cellTopLabelHeightConstraint, withConstant: customAttributes.cellTopLabelHeight) self.jsq_update(constraint: self.messageBubbleTopLabelHeightConstraint, withConstant: customAttributes.messageBubbleTopLabelHeight) self.jsq_update(constraint: self.cellBottomLabelHeightConstraint, withConstant: customAttributes.cellBottomLabelHeight) if self is JSQMessagesCollectionViewCellIncoming { self.avatarViewSize = customAttributes.incomingAvatarViewSize } else if self is JSQMessagesCollectionViewCellOutgoing { self.avatarViewSize = customAttributes.outgoingAvatarViewSize } } } open override var isHighlighted: Bool { didSet { self.messageBubbleImageView?.isHighlighted = self.isHighlighted } } open override var isSelected: Bool { didSet { self.messageBubbleImageView?.isHighlighted = self.isSelected } } open override var bounds: CGRect { didSet { if UIDevice.jsq_isCurrentDeviceBeforeiOS8() { self.contentView.frame = bounds } } } // MARK: - Menu actions open override func responds(to aSelector: Selector) -> Bool { if JSQMessagesCollectionViewCell.jsqMessagesCollectionViewCellActions.contains(aSelector) { return true } return super.responds(to: aSelector) } //TODO: Swift compatibility /*override func forwardInvocation(anInvocation: NSInvocation!) { if JSQMessagesCollectionViewCell.jsqMessagesCollectionViewCellActions.contains(aSelector) { return } } override func methodSignatureForSelector(aSelector: Selector) -> NSMethodSignature! { if JSQMessagesCollectionViewCell.jsqMessagesCollectionViewCellActions.contains(aSelector) { return NSMethodSign } }*/ // MARK: - Utilities func jsq_update(constraint: NSLayoutConstraint, withConstant constant: CGFloat) { if constraint.constant == constant { return } constraint.constant = constant } // MARK: - Gesture recognizers func jsq_handleTapGesture(_ tap: UITapGestureRecognizer) { let touchPoint = tap.location(in: self) if self.avatarContainerView.frame.contains(touchPoint) { self.delegate?.messagesCollectionViewCellDidTapAvatar(self) } else if self.messageBubbleContainerView.frame.contains(touchPoint) { self.delegate?.messagesCollectionViewCellDidTapMessageBubble(self) } else { self.delegate?.messagesCollectionViewCellDidTapCell(self, atPosition: touchPoint) } } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { let touchPoint = touch.location(in: self) if let _ = gestureRecognizer as? UILongPressGestureRecognizer { return self.messageBubbleContainerView.frame.contains(touchPoint) } return true } }
apache-2.0
f55acc46f37cdbbddd07a1c21c8bc608
35.787966
147
0.657294
6.601028
false
false
false
false
CSSE497/pathfinder-ios
framework/Pathfinder/PathfinderConnection.swift
1
8942
// // PathfinderConnection.swift // Pathfinder // // Created by Adam Michael on 10/18/15. // Copyright © 2015 Pathfinder. All rights reserved. // import Foundation import Starscream //// A PathfinderConnection handles communication with the Pathfinder backend. This class is not user-facing and does not need to be seen by client developers. class PathfinderConnection { typealias ApplicationFn = (ApplicationResponse) -> Void typealias ClusterFn = (ClusterResponse) -> Void typealias CommodityFn = (CommodityResponse) -> Void typealias TransportFn = (TransportResponse) -> Void var applicationFns: [ApplicationFn] var clusterFns: [ClusterFn] var commodityFns: [CommodityFn] var transportFns: [TransportFn] // This is a hack. var commodityStatuses = Dictionary<Int, Commodity.Status>() var transportRouteSubscribers: [Int:Transport] var clusterRouteSubscribers: [String:Cluster] let pathfinderSocketUrl: String! let pathfinderSocket: WebSocket let applicationIdentifier: String var queuedMessages = [[String:NSObject]]() let onConnectFn: String -> Void var onAuthenticateFn: (Bool -> Void)? var connected = false var authenticated: Bool = false init(applicationIdentifier: String, onConnectFn: (String) -> Void) { pathfinderSocketUrl = "wss://api.thepathfinder.xyz/socket?AppId=\(applicationIdentifier)" print("PathfinderConnection created, attempting to connect to \(pathfinderSocketUrl)") pathfinderSocket = WebSocket(url: NSURL(string: pathfinderSocketUrl)!) self.applicationIdentifier = applicationIdentifier self.onConnectFn = onConnectFn self.applicationFns = [ApplicationFn]() self.clusterFns = [ClusterFn]() self.commodityFns = [CommodityFn]() self.transportFns = [TransportFn]() self.transportRouteSubscribers = [Int:Transport]() self.clusterRouteSubscribers = [String:Cluster]() pathfinderSocket.delegate = self pathfinderSocket.connect() } func getClusterById(id: String, callback: ClusterFn) { clusterFns.append(callback) writeData([ "message": "Read", "model": "Cluster", "id": id ]) } func create(transport: Transport, callback: TransportFn) { transportFns.append(callback) writeData([ "message": "Create", "model": "Transport", "value": [ "latitude": transport.location!.latitude, "longitude": transport.location!.longitude, "metadata": transport.metadata!, "clusterId": transport.cluster.id ] ]) } func create(commodity: Commodity, callback: CommodityFn) { commodityFns.append(callback) writeData([ "message": "Create", "model": "Commodity", "value": [ "startLatitude": commodity.start!.latitude, "startLongitude": commodity.start!.longitude, "endLatitude": commodity.destination!.latitude, "endLongitude": commodity.destination!.longitude, "status": commodity.status.description, "metadata": commodity.metadata!, "clusterId": commodity.cluster.id ] ]) } func update(transport: Transport, callback: TransportFn) { transportFns.append(callback) writeData([ "message": "Update", "model": "Transport", "id": transport.id!, "value": [ "latitude": transport.location!.latitude, "longitude": transport.location!.longitude, "status": transport.status.description ] ]) } func update(commodity: Commodity, callback: CommodityFn) { commodityFns.append(callback) if (commodity.transport != nil) { writeData([ "message": "Update", "model": "Commodity", "id": commodity.id!, "value": [ "status": commodity.status.description, "transportId": commodity.transport!.id! ] ]) } else { writeData([ "message": "Update", "model": "Commodity", "id": commodity.id!, "value": [ "status": commodity.status.description ] ]) } } func subscribe(cluster: Cluster) { clusterRouteSubscribers[cluster.id] = cluster writeData([ "message": "RouteSubscribe", "model": "Cluster", "id": cluster.id ]) } func subscribe(transport: Transport) { transportRouteSubscribers[transport.id!] = transport writeData([ "message": "RouteSubscribe", "model": "Transport", "id": transport.id! ]) } func unsubscribe(transport: Transport) { writeData([ "message": "Unsubscribe", "model": "Transport", "id": transport.id! ]) } func subscribe(commodity: Commodity) { writeData([ "message": "Subscribe", "model": "Commodity", "id": commodity.id! ]) } func authenticate(onAuthenticateFn: (Bool) -> Void) { self.onAuthenticateFn = onAuthenticateFn writeDataNow(["message": "Authenticate"]) } func writeData(data: [String:NSObject]) { if connected == true && authenticated == true { writeDataNow(data) } else { print("Waiting to send message: \(data)") queuedMessages.append(data) } } func writeDataNow(data: [String:NSObject]) { print("Sending message: \(data)") do { let jsonData = try NSJSONSerialization.dataWithJSONObject(data, options: NSJSONWritingOptions(rawValue: 0)) let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) pathfinderSocket.writeString(jsonString! as String) } catch { print(error) } } func handle(message message: NSDictionary) { if let applicationResponse: ApplicationResponse = ApplicationResponse.parse(message) { print("PathfinderConnection handling ApplicationResponse") applicationFns.removeFirst()(applicationResponse) } else if let clusterResponse: ClusterResponse = ClusterResponse.parse(message) { print("PathfinderConnection handling ClusterResponse") clusterFns.removeFirst()(clusterResponse) } else if let transportResponse: TransportResponse = TransportResponse.parse(message) { print("PathfinderConnection handling TransportResponse") transportFns.removeFirst()(transportResponse) } else if let commodityResponse: CommodityResponse = CommodityResponse.parse(message) { print("PathfinderConnection handling CommodityResponse") commodityStatuses[commodityResponse.id] = commodityResponse.status commodityFns.removeFirst()(commodityResponse) } else if let clusterRoutedResponse = ClusterRoutedResponse.parse(message) { print("PathfinderConnection handling ClusterRoutedResponse") let cluster = clusterRouteSubscribers[clusterRoutedResponse.id] cluster?.routes = clusterRoutedResponse.routes cluster?.delegate?.clusterWasRouted(clusterRoutedResponse.routes) } else if let transportRoutedResponse = TransportRoutedResponse.parse(message) { print("PathfinderConnection handling TransportRoutedResponse") let transport = transportRouteSubscribers[transportRoutedResponse.route.transport.id!] transport?.route = transportRoutedResponse.route transport?.delegate?.wasRouted(transportRoutedResponse.route, transport: transport!) } else if message["message"] as! String == "ConnectionId" { print("PathfinderConnection handling ConnectionId response") onConnectFn(message["id"] as! String) } else if message["message"] as! String == "Authenticated" { print("PathfinderConnection handling Authenticated response") self.authenticated = true onAuthenticateFn?(true) queuedMessages.forEach { (data: [String:NSObject]) -> Void in writeData(data) } queuedMessages = [[String:NSObject]]() } else if message["message"] as! String == "Error" && message["error"] is String && message["error"]!.hasPrefix("Connection refused") { onAuthenticateFn?(false) } else { print("PathfinderConnection handling unparseable message: \(message)") } } } // MARK: - WebSocketDelegate extension PathfinderConnection: WebSocketDelegate { func websocketDidConnect(socket: WebSocket) { print("PathfinderConnection received connect from \(socket)") connected = true } func websocketDidDisconnect(socket: WebSocket, error: NSError?) { print("PathfinderConnection received disconnect from \(socket): \(error)") } func websocketDidReceiveMessage(socket: WebSocket, text: String) { print("PathfinderConnection received message from \(socket): \(text)") do { let json = try NSJSONSerialization.JSONObjectWithData(text.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.MutableContainers) handle(message: json as! NSDictionary) } catch { print(error) } } func websocketDidReceiveData(socket: WebSocket, data: NSData) { print("PathfinderConnection received data from \(socket): \(data)") } }
mit
8b370b30d3ce1891ef2df79123dbf3ba
32.612782
159
0.686277
4.33398
false
false
false
false
Killectro/RxGrailed
RxGrailed/Pods/AlgoliaSearch-Client-Swift/Source/Client.swift
1
10366
// // Copyright (c) 2015 Algolia // http://www.algolia.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 /// Entry point into the Swift API. /// @objc public class Client : AbstractClient { // MARK: Properties /// Algolia application ID. @objc public var appID: String { return _appID! } // will never be nil in this class /// Algolia API key. @objc public var apiKey: String { get { return _apiKey! } set { _apiKey = newValue } } /// Cache of already created indices. /// /// This dictionary is used to avoid creating two instances to represent the same index, as it is (1) inefficient /// and (2) potentially harmful since instances are stateful (that's especially true of mirrored/offline indices, /// but also of online indices because of the search cache). /// /// + Note: The values are zeroing weak references to avoid leaking memory when an index is no longer used. /// var indices: NSMapTable<NSString, AnyObject> = NSMapTable(keyOptions: [.strongMemory], valueOptions: [.weakMemory]) // MARK: Initialization /// Create a new Algolia Search client. /// /// - parameter appID: The application ID (available in your Algolia Dashboard). /// - parameter apiKey: A valid API key for the service. /// @objc public init(appID: String, apiKey: String) { // Initialize hosts to their default values. // // NOTE: The host list comes in two parts: // // 1. The fault-tolerant, load-balanced DNS host. // 2. The non-fault-tolerant hosts. Those hosts must be randomized to ensure proper load balancing in case // of the first host's failure. // let fallbackHosts = [ "\(appID)-1.algolianet.com", "\(appID)-2.algolianet.com", "\(appID)-3.algolianet.com" ].shuffle() let readHosts = [ "\(appID)-dsn.algolia.net" ] + fallbackHosts let writeHosts = [ "\(appID).algolia.net" ] + fallbackHosts super.init(appID: appID, apiKey: apiKey, readHosts: readHosts, writeHosts: writeHosts) } /// Obtain a proxy to an Algolia index (no server call required by this method). /// /// + Note: Only one instance can exist for a given index name. Subsequent calls to this method with the same /// index name will return the same instance, unless it has already been released. /// /// - parameter indexName: The name of the index. /// - returns: A proxy to the specified index. /// @objc(indexWithName:) public func index(withName indexName: String) -> Index { if let index = indices.object(forKey: indexName as NSString) { assert(index is Index, "An index with the same name but a different type has already been created") // may happen in offline mode return index as! Index } else { let index = Index(client: self, name: indexName) indices.setObject(index, forKey: indexName as NSString) return index } } // MARK: - Operations /// List existing indexes. /// /// - parameter completionHandler: Completion handler to be notified of the request's outcome. /// - returns: A cancellable operation. /// @objc(listIndexes:) @discardableResult public func listIndexes(completionHandler: @escaping CompletionHandler) -> Operation { return performHTTPQuery(path: "1/indexes", method: .GET, body: nil, hostnames: readHosts, completionHandler: completionHandler) } /// Delete an index. /// /// - parameter name: Name of the index to delete. /// - parameter completionHandler: Completion handler to be notified of the request's outcome. /// - returns: A cancellable operation. /// @objc(deleteIndexWithName:completionHandler:) @discardableResult public func deleteIndex(withName name: String, completionHandler: CompletionHandler? = nil) -> Operation { let path = "1/indexes/\(name.urlEncodedPathComponent())" return performHTTPQuery(path: path, method: .DELETE, body: nil, hostnames: writeHosts, completionHandler: completionHandler) } /// Move an existing index. /// /// If the destination index already exists, its specific API keys will be preserved and the source index specific /// API keys will be added. /// /// - parameter srcIndexName: Name of index to move. /// - parameter dstIndexName: The new index name. /// - parameter completionHandler: Completion handler to be notified of the request's outcome. /// - returns: A cancellable operation. /// @objc(moveIndexFrom:to:completionHandler:) @discardableResult public func moveIndex(from srcIndexName: String, to dstIndexName: String, completionHandler: CompletionHandler? = nil) -> Operation { let path = "1/indexes/\(srcIndexName.urlEncodedPathComponent())/operation" let request = [ "destination": dstIndexName, "operation": "move" ] return performHTTPQuery(path: path, method: .POST, body: request as [String : Any]?, hostnames: writeHosts, completionHandler: completionHandler) } /// Copy an existing index. /// /// If the destination index already exists, its specific API keys will be preserved and the source index specific /// API keys will be added. /// /// - parameter srcIndexName: Name of the index to copy. /// - parameter dstIndexName: The new index name. /// - parameter completionHandler: Completion handler to be notified of the request's outcome. /// - returns: A cancellable operation. /// @objc(copyIndexFrom:to:completionHandler:) @discardableResult public func copyIndex(from srcIndexName: String, to dstIndexName: String, completionHandler: CompletionHandler? = nil) -> Operation { let path = "1/indexes/\(srcIndexName.urlEncodedPathComponent())/operation" let request = [ "destination": dstIndexName, "operation": "copy" ] return performHTTPQuery(path: path, method: .POST, body: request as [String : Any]?, hostnames: writeHosts, completionHandler: completionHandler) } /// Strategy when running multiple queries. See `Client.multipleQueries(...)`. /// public enum MultipleQueriesStrategy: String { /// Execute the sequence of queries until the end. /// /// + Warning: Beware of confusion with `Optional.none` when using type inference! /// case none = "none" /// Execute the sequence of queries until the number of hits is reached by the sum of hits. case stopIfEnoughMatches = "stopIfEnoughMatches" } /// Query multiple indexes with one API call. /// /// - parameter queries: List of queries. /// - parameter strategy: The strategy to use. /// - parameter completionHandler: Completion handler to be notified of the request's outcome. /// - returns: A cancellable operation. /// @objc(multipleQueries:strategy:completionHandler:) @discardableResult public func multipleQueries(_ queries: [IndexQuery], strategy: String?, completionHandler: @escaping CompletionHandler) -> Operation { // IMPLEMENTATION NOTE: Objective-C bridgeable alternative. let path = "1/indexes/*/queries" var requests = [JSONObject]() requests.reserveCapacity(queries.count) for query in queries { requests.append([ "indexName": query.indexName as Any, "params": query.query.build() as Any ]) } var request = JSONObject() request["requests"] = requests if strategy != nil { request["strategy"] = strategy } return performHTTPQuery(path: path, method: .POST, body: request, hostnames: readHosts, completionHandler: completionHandler) } /// Query multiple indexes with one API call. /// /// - parameter queries: List of queries. /// - parameter strategy: The strategy to use. /// - parameter completionHandler: Completion handler to be notified of the request's outcome. /// - returns: A cancellable operation. /// @discardableResult public func multipleQueries(_ queries: [IndexQuery], strategy: MultipleQueriesStrategy? = nil, completionHandler: @escaping CompletionHandler) -> Operation { // IMPLEMENTATION NOTE: Not Objective-C bridgeable because of enum. return multipleQueries(queries, strategy: strategy?.rawValue, completionHandler: completionHandler) } /// Batch operations. /// /// - parameter operations: List of operations. /// - parameter completionHandler: Completion handler to be notified of the request's outcome. /// - returns: A cancellable operation. /// @objc(batchOperations:completionHandler:) @discardableResult public func batch(operations: [Any], completionHandler: CompletionHandler? = nil) -> Operation { let path = "1/indexes/*/batch" let body = ["requests": operations] return performHTTPQuery(path: path, method: .POST, body: body as [String : Any]?, hostnames: writeHosts, completionHandler: completionHandler) } }
mit
32d36dff458ca1ef483c52ca7aae6413
44.867257
180
0.666216
4.781365
false
false
false
false
material-components/material-components-ios
components/AppBar/examples/AppBarAnimatedGlitchExample.swift
2
5504
// Copyright 2019-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import CoreGraphics import UIKit import MaterialComponents.MaterialAppBar import MaterialComponents.MaterialAppBar_Theming import MaterialComponents.MaterialTabs import MaterialComponents.MaterialContainerScheme // This example demonstrates issues with flexible header tabs and animations. class AppBarAnimatedJumpExample: UIViewController { lazy var appBarViewController: MDCAppBarViewController = self.makeAppBar() @objc var containerScheme: MDCContainerScheming = MDCContainerScheme() fileprivate let tabs = [ SiblingOfTrackingScrollViewViewController(title: "First"), SiblingOfTrackingScrollViewViewController(title: "Second"), SiblingOfTrackingScrollViewViewController(title: "Third"), ] private var currentTab: SiblingOfTrackingScrollViewViewController? = nil lazy var tabBar: MDCTabBar = { let tabBar = MDCTabBar() tabBar.items = self.tabs.map { $0.tabBarItem } tabBar.delegate = self return tabBar }() override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.title = "Manual Tabs Jump (Animated)" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() for (offset, tab) in zip(0..., tabs) { tab.tabBarItem.tag = offset } appBarViewController.applyPrimaryTheme(withScheme: containerScheme) // Need to update the status bar style after applying the theme. appBarViewController.view.isOpaque = false setNeedsStatusBarAppearanceUpdate() view.isOpaque = false view.backgroundColor = containerScheme.colorScheme.backgroundColor view.addSubview(appBarViewController.view) appBarViewController.didMove(toParent: self) switchToTab(tabs[0], animated: false) } fileprivate func switchToTab( _ tab: SiblingOfTrackingScrollViewViewController, animated: Bool = true ) { appBarViewController.headerView.trackingScrollWillChange(toScroll: tab.tableView) // Hide old tab. let removeOld: (() -> Void) let animateOut: (() -> Void) if let currentTab = currentTab { currentTab.willMove(toParent: nil) animateOut = { currentTab.view.alpha = 0 } removeOld = { currentTab.headerView = nil currentTab.view.removeFromSuperview() currentTab.removeFromParent() } } else { removeOld = {} animateOut = {} } if let tabView = tab.view { tabView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tabView.frame = view.bounds } // Show new tab. view.addSubview(tab.view) view.sendSubviewToBack(tab.view) tab.didMove(toParent: self) tab.headerView = self.appBarViewController.headerView tab.view.alpha = 0 let animateIn = { tab.view.alpha = 1 } let finishMove = { self.appBarViewController.headerView.trackingScrollView = tab.tableView self.currentTab = tab } if animated { UIView.animate( withDuration: 1, animations: { animateOut() animateIn() }, completion: { _ in removeOld() finishMove() }) } else { animateOut() removeOld() animateIn() finishMove() } } @objc func changeAlignmentDidTouch(sender: UIButton) { tabs[0].title = "First" switchToTab(tabs[0]) } @objc func changeAppearance(fromSender sender: UIButton) { tabs[1].title = "Second" switchToTab(tabs[1]) } // MARK: Private private func makeAppBar() -> MDCAppBarViewController { let appBarViewController = MDCAppBarViewController() addChild(appBarViewController) // Give the tab bar enough height to accomodate all possible item appearances. appBarViewController.headerView.minMaxHeightIncludesSafeArea = false appBarViewController.inferTopSafeAreaInsetFromViewController = true appBarViewController.headerView.sharedWithManyScrollViews = true appBarViewController.headerView.minimumHeight = 56 appBarViewController.headerView.maximumHeight = 128 appBarViewController.headerStackView.bottomBar = tabBar return appBarViewController } override var childForStatusBarStyle: UIViewController? { return appBarViewController } } extension AppBarAnimatedJumpExample: MDCTabBarDelegate { func tabBar(_ tabBar: MDCTabBar, didSelect item: UITabBarItem) { switchToTab(tabs[item.tag]) } } extension AppBarAnimatedJumpExample { @objc class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["App Bar", "Manual Tabs Jump (Animated)"], "primaryDemo": false, "presentable": false, ] } @objc func catalogShouldHideNavigation() -> Bool { return true } }
apache-2.0
032b1da215744937be9c11b523ce474f
27.225641
87
0.708939
4.82807
false
false
false
false
debugsquad/nubecero
nubecero/Controller/Login/CLogin.swift
1
3297
import UIKit import UserNotifications import Firebase import FirebaseAuth class CLogin:CController { private weak var viewLogin:VLogin! private let kAskNotifications:TimeInterval = 4 deinit { NotificationCenter.default.removeObserver(self) } override func loadView() { let viewLogin:VLogin = VLogin(controller:self) self.viewLogin = viewLogin view = viewLogin } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver( self, selector:#selector(notifiedSettingsLoaded(sender:)), name:Notification.settingsLoaded, object:nil) MSession.sharedInstance.settings.loadSettings() registerNotifications() } //MARK: notified func notifiedSettingsLoaded(sender notification:Notification) { NotificationCenter.default.removeObserver(self) DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in guard let userId:MSession.UserId = FIRAuth.auth()?.currentUser?.uid else { self?.userNotLogged() return } MSession.sharedInstance.user.loadUser(userId:userId) DispatchQueue.main.async { [weak self] in let homeController:CHome = CHome(askAuth:true) self?.parentController.center( controller:homeController, pop:true, animate:true) } } } //MARK: private private func userNotLogged() { DispatchQueue.main.async { [weak self] in let controllerOnboard:COnboard = COnboard() self?.parentController.over( controller:controllerOnboard, pop:true, animate:true) } } private func registerNotifications() { DispatchQueue.main.asyncAfter( deadline:DispatchTime.now() + kAskNotifications) { if #available(iOS 10.0, *) { let authOptions:UNAuthorizationOptions = [ UNAuthorizationOptions.alert, UNAuthorizationOptions.badge, UNAuthorizationOptions.sound] UNUserNotificationCenter.current().requestAuthorization(options:authOptions) { (done:Bool, error:Error?) in } } else { let settings:UIUserNotificationSettings = UIUserNotificationSettings( types:[ UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound], categories:nil) UIApplication.shared.registerUserNotificationSettings(settings) } UIApplication.shared.registerForRemoteNotifications() } } }
mit
cf8f9460d53d1dca06405d40f89c6ac7
27.179487
92
0.525629
6.328215
false
false
false
false
petester42/SwiftCharts
SwiftCharts/Views/ChartLinesView.swift
7
2841
// // ChartLinesView.swift // swift_charts // // Created by ischuetz on 11/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public protocol ChartLinesViewPathGenerator { func generatePath(#points: [CGPoint], lineWidth: CGFloat) -> UIBezierPath } public class ChartLinesView: UIView { private let lineColor: UIColor private let lineWidth: CGFloat private let animDuration: Float private let animDelay: Float init(path: UIBezierPath, frame: CGRect, lineColor: UIColor, lineWidth: CGFloat, animDuration: Float, animDelay: Float) { self.lineColor = lineColor self.lineWidth = lineWidth self.animDuration = animDuration self.animDelay = animDelay super.init(frame: frame) self.backgroundColor = UIColor.clearColor() self.show(path: path) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func createLineMask(#frame: CGRect) -> CALayer { let lineMaskLayer = CAShapeLayer() var maskRect = frame maskRect.origin.y = 0 maskRect.size.height = frame.size.height let path = CGPathCreateWithRect(maskRect, nil) lineMaskLayer.path = path return lineMaskLayer } private func generateLayer(#path: UIBezierPath) -> CAShapeLayer { let lineLayer = CAShapeLayer() lineLayer.lineJoin = kCALineJoinBevel lineLayer.fillColor = UIColor.clearColor().CGColor lineLayer.lineWidth = self.lineWidth lineLayer.path = path.CGPath; lineLayer.strokeColor = self.lineColor.CGColor; if self.animDuration > 0 { lineLayer.strokeEnd = 0.0 let pathAnimation = CABasicAnimation(keyPath: "strokeEnd") pathAnimation.duration = CFTimeInterval(self.animDuration) pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) pathAnimation.fromValue = NSNumber(float: 0) pathAnimation.toValue = NSNumber(float: 1) pathAnimation.autoreverses = false pathAnimation.removedOnCompletion = false pathAnimation.fillMode = kCAFillModeForwards pathAnimation.beginTime = CACurrentMediaTime() + CFTimeInterval(self.animDelay) lineLayer.addAnimation(pathAnimation, forKey: "strokeEndAnimation") } else { lineLayer.strokeEnd = 1 } return lineLayer } private func show(#path: UIBezierPath) { let lineMask = self.createLineMask(frame: frame) self.layer.mask = lineMask self.layer.addSublayer(self.generateLayer(path: path)) } }
apache-2.0
222222c58eb825ed1d7efbb74a7b383a
32.034884
124
0.646603
5.232044
false
false
false
false
SuPair/firefox-ios
Client/Frontend/Browser/BrowserViewController.swift
1
109278
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Photos import UIKit import WebKit import Shared import Storage import SnapKit import XCGLogger import Alamofire import Account import MobileCoreServices import SDWebImage import SwiftyJSON import Telemetry import Sentry import Deferred private let KVOs: [KVOConstants] = [ .estimatedProgress, .loading, .canGoBack, .canGoForward, .URL, .title, ] private let ActionSheetTitleMaxLength = 120 private struct BrowserViewControllerUX { fileprivate static let ShowHeaderTapAreaHeight: CGFloat = 32 fileprivate static let BookmarkStarAnimationDuration: Double = 0.5 fileprivate static let BookmarkStarAnimationOffset: CGFloat = 80 } class BrowserViewController: UIViewController { var homePanelController: HomePanelViewController? var webViewContainer: UIView! var urlBar: URLBarView! var clipboardBarDisplayHandler: ClipboardBarDisplayHandler? var readerModeBar: ReaderModeBarView? var readerModeCache: ReaderModeCache var statusBarOverlay: UIView! fileprivate(set) var toolbar: TabToolbar? var searchController: SearchViewController? var screenshotHelper: ScreenshotHelper! fileprivate var homePanelIsInline = false fileprivate var searchLoader: SearchLoader? let alertStackView = UIStackView() // All content that appears above the footer should be added to this view. (Find In Page/SnackBars) var findInPageBar: FindInPageBar? lazy var mailtoLinkHandler: MailtoLinkHandler = MailtoLinkHandler() lazy fileprivate var customSearchEngineButton: UIButton = { let searchButton = UIButton() searchButton.setImage(UIImage(named: "AddSearch")?.withRenderingMode(.alwaysTemplate), for: []) searchButton.addTarget(self, action: #selector(addCustomSearchEngineForFocusedElement), for: .touchUpInside) searchButton.accessibilityIdentifier = "BrowserViewController.customSearchEngineButton" return searchButton }() fileprivate var customSearchBarButton: UIBarButtonItem? // popover rotation handling var displayedPopoverController: UIViewController? var updateDisplayedPopoverProperties: (() -> Void)? var openInHelper: OpenInHelper? // location label actions fileprivate var pasteGoAction: AccessibleAction! fileprivate var pasteAction: AccessibleAction! fileprivate var copyAddressAction: AccessibleAction! fileprivate weak var tabTrayController: TabTrayController? let profile: Profile let tabManager: TabManager // These views wrap the urlbar and toolbar to provide background effects on them var header: UIView! var footer: UIView! fileprivate var topTouchArea: UIButton! let urlBarTopTabsContainer = UIView(frame: CGRect.zero) var topTabsVisible: Bool { return topTabsViewController != nil } // Backdrop used for displaying greyed background for private tabs var webViewContainerBackdrop: UIView! var scrollController = TabScrollingController() fileprivate var keyboardState: KeyboardState? var pendingToast: Toast? // A toast that might be waiting for BVC to appear before displaying var downloadToast: DownloadToast? // A toast that is showing the combined download progress // Tracking navigation items to record history types. // TODO: weak references? var ignoredNavigation = Set<WKNavigation>() var typedNavigation = [WKNavigation: VisitType]() var navigationToolbar: TabToolbarProtocol { return toolbar ?? urlBar } var topTabsViewController: TopTabsViewController? let topTabsContainer = UIView() // Keep track of allowed `URLRequest`s from `webView(_:decidePolicyFor:decisionHandler:)` so // that we can obtain the originating `URLRequest` when a `URLResponse` is received. This will // allow us to re-trigger the `URLRequest` if the user requests a file to be downloaded. var pendingRequests = [String: URLRequest]() // This is set when the user taps "Download Link" from the context menu. We then force a // download of the next request through the `WKNavigationDelegate` that matches this web view. weak var pendingDownloadWebView: WKWebView? let downloadQueue = DownloadQueue() init(profile: Profile, tabManager: TabManager) { self.profile = profile self.tabManager = tabManager self.readerModeCache = DiskReaderModeCache.sharedInstance super.init(nibName: nil, bundle: nil) didInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) dismissVisibleMenus() coordinator.animate(alongsideTransition: { context in self.scrollController.updateMinimumZoom() self.topTabsViewController?.scrollToCurrentTab(false, centerCell: false) if let popover = self.displayedPopoverController { self.updateDisplayedPopoverProperties?() self.present(popover, animated: true, completion: nil) } }, completion: { _ in self.scrollController.setMinimumZoom() }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } fileprivate func didInit() { screenshotHelper = ScreenshotHelper(controller: self) tabManager.addDelegate(self) tabManager.addNavigationDelegate(self) downloadQueue.delegate = self NotificationCenter.default.addObserver(self, selector: #selector(displayThemeChanged), name: .DisplayThemeChanged, object: nil) } override var preferredStatusBarStyle: UIStatusBarStyle { return ThemeManager.instance.statusBarStyle } @objc func displayThemeChanged(notification: Notification) { applyTheme() } func shouldShowFooterForTraitCollection(_ previousTraitCollection: UITraitCollection) -> Bool { return previousTraitCollection.verticalSizeClass != .compact && previousTraitCollection.horizontalSizeClass != .regular } func shouldShowTopTabsForTraitCollection(_ newTraitCollection: UITraitCollection) -> Bool { return newTraitCollection.verticalSizeClass == .regular && newTraitCollection.horizontalSizeClass == .regular } func toggleSnackBarVisibility(show: Bool) { if show { UIView.animate(withDuration: 0.1, animations: { self.alertStackView.isHidden = false }) } else { alertStackView.isHidden = true } } fileprivate func updateToolbarStateForTraitCollection(_ newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator? = nil) { let showToolbar = shouldShowFooterForTraitCollection(newCollection) let showTopTabs = shouldShowTopTabsForTraitCollection(newCollection) urlBar.topTabsIsShowing = showTopTabs urlBar.setShowToolbar(!showToolbar) toolbar?.removeFromSuperview() toolbar?.tabToolbarDelegate = nil toolbar = nil if showToolbar { toolbar = TabToolbar() footer.addSubview(toolbar!) toolbar?.tabToolbarDelegate = self toolbar?.applyUIMode(isPrivate: tabManager.selectedTab?.isPrivate ?? false) toolbar?.applyTheme() updateTabCountUsingTabManager(self.tabManager) } if showTopTabs { if topTabsViewController == nil { let topTabsViewController = TopTabsViewController(tabManager: tabManager) topTabsViewController.delegate = self addChildViewController(topTabsViewController) topTabsViewController.view.frame = topTabsContainer.frame topTabsContainer.addSubview(topTabsViewController.view) topTabsViewController.view.snp.makeConstraints { make in make.edges.equalTo(topTabsContainer) make.height.equalTo(TopTabsUX.TopTabsViewHeight) } self.topTabsViewController = topTabsViewController topTabsViewController.applyTheme() } topTabsContainer.snp.updateConstraints { make in make.height.equalTo(TopTabsUX.TopTabsViewHeight) } } else { topTabsContainer.snp.updateConstraints { make in make.height.equalTo(0) } topTabsViewController?.view.removeFromSuperview() topTabsViewController?.removeFromParentViewController() topTabsViewController = nil } view.setNeedsUpdateConstraints() if let home = homePanelController { home.view.setNeedsUpdateConstraints() } if let tab = tabManager.selectedTab, let webView = tab.webView { updateURLBarDisplayURL(tab) navigationToolbar.updateBackStatus(webView.canGoBack) navigationToolbar.updateForwardStatus(webView.canGoForward) navigationToolbar.updateReloadStatus(tab.loading) } } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { super.willTransition(to: newCollection, with: coordinator) // During split screen launching on iPad, this callback gets fired before viewDidLoad gets a chance to // set things up. Make sure to only update the toolbar state if the view is ready for it. if isViewLoaded { updateToolbarStateForTraitCollection(newCollection, withTransitionCoordinator: coordinator) } displayedPopoverController?.dismiss(animated: true, completion: nil) coordinator.animate(alongsideTransition: { context in self.scrollController.showToolbars(animated: false) if self.isViewLoaded { self.statusBarOverlay.backgroundColor = self.shouldShowTopTabsForTraitCollection(self.traitCollection) ? UIColor.Photon.Grey80 : self.urlBar.backgroundColor self.setNeedsStatusBarAppearanceUpdate() } }, completion: nil) } func dismissVisibleMenus() { displayedPopoverController?.dismiss(animated: true) if let _ = self.presentedViewController as? PhotonActionSheet { self.presentedViewController?.dismiss(animated: true, completion: nil) } } @objc func appDidEnterBackgroundNotification() { displayedPopoverController?.dismiss(animated: false) { self.displayedPopoverController = nil } } @objc func tappedTopArea() { scrollController.showToolbars(animated: true) } @objc func appWillResignActiveNotification() { // Dismiss any popovers that might be visible displayedPopoverController?.dismiss(animated: false) { self.displayedPopoverController = nil } // If we are displying a private tab, hide any elements in the tab that we wouldn't want shown // when the app is in the home switcher guard let privateTab = tabManager.selectedTab, privateTab.isPrivate else { return } webViewContainerBackdrop.alpha = 1 webViewContainer.alpha = 0 urlBar.locationContainer.alpha = 0 topTabsViewController?.switchForegroundStatus(isInForeground: false) presentedViewController?.popoverPresentationController?.containerView?.alpha = 0 presentedViewController?.view.alpha = 0 } @objc func appDidBecomeActiveNotification() { // Re-show any components that might have been hidden because they were being displayed // as part of a private mode tab UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: { self.webViewContainer.alpha = 1 self.urlBar.locationContainer.alpha = 1 self.topTabsViewController?.switchForegroundStatus(isInForeground: true) self.presentedViewController?.popoverPresentationController?.containerView?.alpha = 1 self.presentedViewController?.view.alpha = 1 self.view.backgroundColor = UIColor.clear }, completion: { _ in self.webViewContainerBackdrop.alpha = 0 }) // Re-show toolbar which might have been hidden during scrolling (prior to app moving into the background) scrollController.showToolbars(animated: false) } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActiveNotification), name: .UIApplicationWillResignActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActiveNotification), name: .UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackgroundNotification), name: .UIApplicationDidEnterBackground, object: nil) KeyboardHelper.defaultHelper.addDelegate(self) webViewContainerBackdrop = UIView() webViewContainerBackdrop.backgroundColor = UIColor.Photon.Grey50 webViewContainerBackdrop.alpha = 0 view.addSubview(webViewContainerBackdrop) webViewContainer = UIView() view.addSubview(webViewContainer) // Temporary work around for covering the non-clipped web view content statusBarOverlay = UIView() view.addSubview(statusBarOverlay) topTouchArea = UIButton() topTouchArea.isAccessibilityElement = false topTouchArea.addTarget(self, action: #selector(tappedTopArea), for: .touchUpInside) view.addSubview(topTouchArea) // Setup the URL bar, wrapped in a view to get transparency effect urlBar = URLBarView() urlBar.translatesAutoresizingMaskIntoConstraints = false urlBar.delegate = self urlBar.tabToolbarDelegate = self header = urlBarTopTabsContainer urlBarTopTabsContainer.addSubview(urlBar) urlBarTopTabsContainer.addSubview(topTabsContainer) view.addSubview(header) // UIAccessibilityCustomAction subclass holding an AccessibleAction instance does not work, thus unable to generate AccessibleActions and UIAccessibilityCustomActions "on-demand" and need to make them "persistent" e.g. by being stored in BVC pasteGoAction = AccessibleAction(name: Strings.PasteAndGoTitle, handler: { () -> Bool in if let pasteboardContents = UIPasteboard.general.string { self.urlBar(self.urlBar, didSubmitText: pasteboardContents) return true } return false }) pasteAction = AccessibleAction(name: Strings.PasteTitle, handler: { () -> Bool in if let pasteboardContents = UIPasteboard.general.string { // Enter overlay mode and make the search controller appear. self.urlBar.enterOverlayMode(pasteboardContents, pasted: true, search: true) return true } return false }) copyAddressAction = AccessibleAction(name: Strings.CopyAddressTitle, handler: { () -> Bool in if let url = self.urlBar.currentURL { UIPasteboard.general.url = url as URL } return true }) view.addSubview(alertStackView) footer = UIView() view.addSubview(footer) alertStackView.axis = .vertical alertStackView.alignment = .center clipboardBarDisplayHandler = ClipboardBarDisplayHandler(prefs: profile.prefs, tabManager: tabManager) clipboardBarDisplayHandler?.delegate = self scrollController.urlBar = urlBar scrollController.readerModeBar = readerModeBar scrollController.header = header scrollController.footer = footer scrollController.snackBars = alertStackView self.updateToolbarStateForTraitCollection(self.traitCollection) setupConstraints() // Setup UIDropInteraction to handle dragging and dropping // links into the view from other apps. if #available(iOS 11, *) { let dropInteraction = UIDropInteraction(delegate: self) view.addInteraction(dropInteraction) } } fileprivate func setupConstraints() { topTabsContainer.snp.makeConstraints { make in make.leading.trailing.equalTo(self.header) make.top.equalTo(urlBarTopTabsContainer) } urlBar.snp.makeConstraints { make in make.leading.trailing.bottom.equalTo(urlBarTopTabsContainer) make.height.equalTo(UIConstants.TopToolbarHeight) make.top.equalTo(topTabsContainer.snp.bottom) } header.snp.makeConstraints { make in scrollController.headerTopConstraint = make.top.equalTo(self.topLayoutGuide.snp.bottom).constraint make.left.right.equalTo(self.view) } webViewContainerBackdrop.snp.makeConstraints { make in make.edges.equalTo(webViewContainer) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() statusBarOverlay.snp.remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(self.topLayoutGuide.length) } } override var canBecomeFirstResponder: Bool { return true } override func becomeFirstResponder() -> Bool { // Make the web view the first responder so that it can show the selection menu. return tabManager.selectedTab?.webView?.becomeFirstResponder() ?? false } func loadQueuedTabs(receivedURLs: [URL]? = nil) { // Chain off of a trivial deferred in order to run on the background queue. succeed().upon() { res in self.dequeueQueuedTabs(receivedURLs: receivedURLs ?? []) } } fileprivate func dequeueQueuedTabs(receivedURLs: [URL]) { assert(!Thread.current.isMainThread, "This must be called in the background.") self.profile.queue.getQueuedTabs() >>== { cursor in // This assumes that the DB returns rows in some kind of sane order. // It does in practice, so WFM. if cursor.count > 0 { // Filter out any tabs received by a push notification to prevent dupes. let urls = cursor.compactMap { $0?.url.asURL }.filter { !receivedURLs.contains($0) } if !urls.isEmpty { DispatchQueue.main.async { self.tabManager.addTabsForURLs(urls, zombie: false) } } // Clear *after* making an attempt to open. We're making a bet that // it's better to run the risk of perhaps opening twice on a crash, // rather than losing data. self.profile.queue.clearQueuedTabs() } // Then, open any received URLs from push notifications. if !receivedURLs.isEmpty { DispatchQueue.main.async { self.tabManager.addTabsForURLs(receivedURLs, zombie: false) if let lastURL = receivedURLs.last, let tab = self.tabManager.getTabForURL(lastURL) { self.tabManager.selectTab(tab) } } } } } // Because crashedLastLaunch is sticky, it does not get reset, we need to remember its // value so that we do not keep asking the user to restore their tabs. var displayedRestoreTabsAlert = false override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // On iPhone, if we are about to show the On-Boarding, blank out the tab so that it does // not flash before we present. This change of alpha also participates in the animation when // the intro view is dismissed. if UIDevice.current.userInterfaceIdiom == .phone { self.view.alpha = (profile.prefs.intForKey(PrefsKeys.IntroSeen) != nil) ? 1.0 : 0.0 } if !displayedRestoreTabsAlert && !cleanlyBackgrounded() && crashedLastLaunch() { displayedRestoreTabsAlert = true showRestoreTabsAlert() } else { tabManager.restoreTabs() } updateTabCountUsingTabManager(tabManager, animated: false) clipboardBarDisplayHandler?.checkIfShouldDisplayBar() } fileprivate func crashedLastLaunch() -> Bool { return Sentry.crashedLastLaunch } fileprivate func cleanlyBackgrounded() -> Bool { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return false } return appDelegate.applicationCleanlyBackgrounded } fileprivate func showRestoreTabsAlert() { guard tabManager.hasTabsToRestoreAtStartup() else { tabManager.selectTab(tabManager.addTab()) return } let alert = UIAlertController.restoreTabsAlert( okayCallback: { _ in self.tabManager.restoreTabs() }, noCallback: { _ in self.tabManager.selectTab(self.tabManager.addTab()) } ) self.present(alert, animated: true, completion: nil) } override func viewDidAppear(_ animated: Bool) { presentIntroViewController() screenshotHelper.viewIsVisible = true screenshotHelper.takePendingScreenshots(tabManager.tabs) super.viewDidAppear(animated) if shouldShowWhatsNewTab() { // Only display if the SUMO topic has been configured in the Info.plist (present and not empty) if let whatsNewTopic = AppInfo.whatsNewTopic, whatsNewTopic != "" { if let whatsNewURL = SupportUtils.URLForTopic(whatsNewTopic) { self.openURLInNewTab(whatsNewURL, isPrivileged: false) profile.prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey) } } } if let toast = self.pendingToast { self.pendingToast = nil show(toast: toast, afterWaiting: ButtonToastUX.ToastDelay) } showQueuedAlertIfAvailable() } // THe logic for shouldShowWhatsNewTab is as follows: If we do not have the LatestAppVersionProfileKey in // the profile, that means that this is a fresh install and we do not show the What's New. If we do have // that value, we compare it to the major version of the running app. If it is different then this is an // upgrade, downgrades are not possible, so we can show the What's New page. fileprivate func shouldShowWhatsNewTab() -> Bool { guard let latestMajorAppVersion = profile.prefs.stringForKey(LatestAppVersionProfileKey)?.components(separatedBy: ".").first else { return false // Clean install, never show What's New } return latestMajorAppVersion != AppInfo.majorAppVersion && DeviceInfo.hasConnectivity() } fileprivate func showQueuedAlertIfAvailable() { if let queuedAlertInfo = tabManager.selectedTab?.dequeueJavascriptAlertPrompt() { let alertController = queuedAlertInfo.alertController() alertController.delegate = self present(alertController, animated: true, completion: nil) } } override func viewWillDisappear(_ animated: Bool) { screenshotHelper.viewIsVisible = false super.viewWillDisappear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } func resetBrowserChrome() { // animate and reset transform for tab chrome urlBar.updateAlphaForSubviews(1) footer.alpha = 1 [header, footer, readerModeBar].forEach { view in view?.transform = .identity } statusBarOverlay.isHidden = false } override func updateViewConstraints() { super.updateViewConstraints() topTouchArea.snp.remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight) } readerModeBar?.snp.remakeConstraints { make in make.top.equalTo(self.header.snp.bottom) make.height.equalTo(UIConstants.ToolbarHeight) make.leading.trailing.equalTo(self.view) } webViewContainer.snp.remakeConstraints { make in make.left.right.equalTo(self.view) if let readerModeBarBottom = readerModeBar?.snp.bottom { make.top.equalTo(readerModeBarBottom) } else { make.top.equalTo(self.header.snp.bottom) } let findInPageHeight = (findInPageBar == nil) ? 0 : UIConstants.ToolbarHeight if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp.top).offset(-findInPageHeight) } else { make.bottom.equalTo(self.view).offset(-findInPageHeight) } } // Setup the bottom toolbar toolbar?.snp.remakeConstraints { make in make.edges.equalTo(self.footer) make.height.equalTo(UIConstants.BottomToolbarHeight) } footer.snp.remakeConstraints { make in scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp.bottom).constraint make.leading.trailing.equalTo(self.view) } urlBar.setNeedsUpdateConstraints() // Remake constraints even if we're already showing the home controller. // The home controller may change sizes if we tap the URL bar while on about:home. homePanelController?.view.snp.remakeConstraints { make in make.top.equalTo(self.urlBar.snp.bottom) make.left.right.equalTo(self.view) if self.homePanelIsInline { make.bottom.equalTo(self.toolbar?.snp.top ?? self.view.snp.bottom) } else { make.bottom.equalTo(self.view.snp.bottom) } } alertStackView.snp.remakeConstraints { make in make.centerX.equalTo(self.view) make.width.equalTo(self.view.snp.width) if let keyboardHeight = keyboardState?.intersectionHeightForView(self.view), keyboardHeight > 0 { make.bottom.equalTo(self.view).offset(-keyboardHeight) } else if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp.top) } else { make.bottom.equalTo(self.view) } } } fileprivate func showHomePanelController(inline: Bool) { homePanelIsInline = inline if homePanelController == nil { let homePanelController = HomePanelViewController() homePanelController.profile = profile homePanelController.delegate = self homePanelController.url = tabManager.selectedTab?.url?.displayURL homePanelController.view.alpha = 0 self.homePanelController = homePanelController addChildViewController(homePanelController) view.addSubview(homePanelController.view) homePanelController.didMove(toParentViewController: self) } guard let homePanelController = self.homePanelController else { assertionFailure("homePanelController is still nil after assignment.") return } homePanelController.applyTheme() let panelNumber = tabManager.selectedTab?.url?.fragment // splitting this out to see if we can get better crash reports when this has a problem var newSelectedButtonIndex = 0 if let numberArray = panelNumber?.components(separatedBy: "=") { if let last = numberArray.last, let lastInt = Int(last) { newSelectedButtonIndex = lastInt } } homePanelController.selectedPanel = HomePanelType(rawValue: newSelectedButtonIndex) // We have to run this animation, even if the view is already showing because there may be a hide animation running // and we want to be sure to override its results. UIView.animate(withDuration: 0.2, animations: { () -> Void in homePanelController.view.alpha = 1 }, completion: { finished in if finished { self.webViewContainer.accessibilityElementsHidden = true UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } }) view.setNeedsUpdateConstraints() } fileprivate func hideHomePanelController() { if let controller = homePanelController { self.homePanelController = nil UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { () -> Void in controller.view.alpha = 0 }, completion: { _ in controller.willMove(toParentViewController: nil) controller.view.removeFromSuperview() controller.removeFromParentViewController() self.webViewContainer.accessibilityElementsHidden = false UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // Refresh the reading view toolbar since the article record may have changed if let readerMode = self.tabManager.selectedTab?.getContentScript(name: ReaderMode.name()) as? ReaderMode, readerMode.state == .active { self.showReaderModeBar(animated: false) } }) } } fileprivate func updateInContentHomePanel(_ url: URL?) { if !urlBar.inOverlayMode { guard let url = url else { hideHomePanelController() return } if url.isAboutHomeURL { showHomePanelController(inline: true) } else if url.isErrorPageURL || !url.isLocalUtility || url.isReaderModeURL { hideHomePanelController() } } } fileprivate func showSearchController() { if searchController != nil { return } let isPrivate = tabManager.selectedTab?.isPrivate ?? false searchController = SearchViewController(profile: profile, isPrivate: isPrivate) searchController!.searchEngines = profile.searchEngines searchController!.searchDelegate = self searchLoader = SearchLoader(profile: profile, urlBar: urlBar) searchLoader?.addListener(searchController!) addChildViewController(searchController!) view.addSubview(searchController!.view) searchController!.view.snp.makeConstraints { make in make.top.equalTo(self.urlBar.snp.bottom) make.left.right.bottom.equalTo(self.view) return } homePanelController?.view?.isHidden = true searchController!.didMove(toParentViewController: self) } fileprivate func hideSearchController() { if let searchController = searchController { searchController.willMove(toParentViewController: nil) searchController.view.removeFromSuperview() searchController.removeFromParentViewController() self.searchController = nil homePanelController?.view?.isHidden = false searchLoader = nil } } func finishEditingAndSubmit(_ url: URL, visitType: VisitType) { urlBar.currentURL = url urlBar.leaveOverlayMode() guard let tab = tabManager.selectedTab else { return } if let webView = tab.webView { resetSpoofedUserAgentIfRequired(webView, newURL: url) } if let nav = tab.loadRequest(PrivilegedRequest(url: url) as URLRequest) { self.recordNavigationInTab(tab, navigation: nav, visitType: visitType) } } func addBookmark(_ tabState: TabState) { guard let url = tabState.url else { return } let absoluteString = url.absoluteString let shareItem = ShareItem(url: absoluteString, title: tabState.title, favicon: tabState.favicon) _ = profile.bookmarks.shareItem(shareItem) var userData = [QuickActions.TabURLKey: shareItem.url] if let title = shareItem.title { userData[QuickActions.TabTitleKey] = title } QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark, withUserData: userData, toApplication: UIApplication.shared) } override func accessibilityPerformEscape() -> Bool { if urlBar.inOverlayMode { urlBar.didClickCancel() return true } else if let selectedTab = tabManager.selectedTab, selectedTab.canGoBack { selectedTab.goBack() return true } return false } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard let webView = object as? WKWebView else { assert(false) return } guard let kp = keyPath, let path = KVOConstants(rawValue: kp) else { assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")") return } switch path { case .estimatedProgress: guard webView == tabManager.selectedTab?.webView else { break } if !(webView.url?.isLocalUtility ?? false) { urlBar.updateProgressBar(Float(webView.estimatedProgress)) // Profiler.end triggers a screenshot, and a delay is needed here to capture the correct screen // (otherwise the screen prior to this step completing is captured). if webView.estimatedProgress > 0.9 { Profiler.shared?.end(bookend: .load_url, delay: 0.200) } } else { urlBar.hideProgressBar() } case .loading: guard let loading = change?[.newKey] as? Bool else { break } if webView == tabManager.selectedTab?.webView { navigationToolbar.updateReloadStatus(loading) } if !loading { runScriptsOnWebView(webView) } case .URL: guard let tab = tabManager[webView] else { break } // To prevent spoofing, only change the URL immediately if the new URL is on // the same origin as the current URL. Otherwise, do nothing and wait for // didCommitNavigation to confirm the page load. if tab.url?.origin == webView.url?.origin { tab.url = webView.url if tab === tabManager.selectedTab && !tab.restoring { updateUIForReaderHomeStateForTab(tab) } } case .title: guard let tab = tabManager[webView] else { break } // Ensure that the tab title *actually* changed to prevent repeated calls // to navigateInTab(tab:). guard let title = tab.title else { break } if !title.isEmpty && title != tab.lastTitle { navigateInTab(tab: tab) } case .canGoBack: guard webView == tabManager.selectedTab?.webView, let canGoBack = change?[.newKey] as? Bool else { break } navigationToolbar.updateBackStatus(canGoBack) case .canGoForward: guard webView == tabManager.selectedTab?.webView, let canGoForward = change?[.newKey] as? Bool else { break } navigationToolbar.updateForwardStatus(canGoForward) default: assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")") } } fileprivate func runScriptsOnWebView(_ webView: WKWebView) { guard let url = webView.url, url.isWebPage(), !url.isLocal else { return } if #available(iOS 11, *) { if NoImageModeHelper.isActivated(profile.prefs) { webView.evaluateJavaScript("__firefox__.NoImageMode.setEnabled(true)", completionHandler: nil) } } } func updateUIForReaderHomeStateForTab(_ tab: Tab) { updateURLBarDisplayURL(tab) scrollController.showToolbars(animated: false) if let url = tab.url { if url.isReaderModeURL { showReaderModeBar(animated: false) NotificationCenter.default.addObserver(self, selector: #selector(dynamicFontChanged), name: .DynamicFontChanged, object: nil) } else { hideReaderModeBar(animated: false) NotificationCenter.default.removeObserver(self, name: .DynamicFontChanged, object: nil) } updateInContentHomePanel(url as URL) } } /// Updates the URL bar text and button states. /// Call this whenever the page URL changes. fileprivate func updateURLBarDisplayURL(_ tab: Tab) { urlBar.currentURL = tab.url?.displayURL let isPage = tab.url?.displayURL?.isWebPage() ?? false navigationToolbar.updatePageStatus(isPage) } // MARK: Opening New Tabs func switchToPrivacyMode(isPrivate: Bool) { if let tabTrayController = self.tabTrayController, tabTrayController.privateMode != isPrivate { tabTrayController.changePrivacyMode(isPrivate) } topTabsViewController?.applyUIMode(isPrivate: isPrivate) } func switchToTabForURLOrOpen(_ url: URL, isPrivate: Bool = false, isPrivileged: Bool) { popToBVC() if let tab = tabManager.getTabForURL(url) { tabManager.selectTab(tab) } else { openURLInNewTab(url, isPrivate: isPrivate, isPrivileged: isPrivileged) } } func openURLInNewTab(_ url: URL?, isPrivate: Bool = false, isPrivileged: Bool) { if let selectedTab = tabManager.selectedTab { screenshotHelper.takeScreenshot(selectedTab) } let request: URLRequest? if let url = url { request = isPrivileged ? PrivilegedRequest(url: url) as URLRequest : URLRequest(url: url) } else { request = nil } switchToPrivacyMode(isPrivate: isPrivate) tabManager.selectTab(tabManager.addTab(request, isPrivate: isPrivate)) } func openBlankNewTab(focusLocationField: Bool, isPrivate: Bool = false, searchFor searchText: String? = nil) { popToBVC() openURLInNewTab(nil, isPrivate: isPrivate, isPrivileged: true) let freshTab = tabManager.selectedTab if focusLocationField { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) { // Without a delay, the text field fails to become first responder // Check that the newly created tab is still selected. // This let's the user spam the Cmd+T button without lots of responder changes. guard freshTab == self.tabManager.selectedTab else { return } self.urlBar.tabLocationViewDidTapLocation(self.urlBar.locationView) if let text = searchText { self.urlBar.setLocation(text, search: true) } } } } func openSearchNewTab(isPrivate: Bool = false, _ text: String) { popToBVC() let engine = profile.searchEngines.defaultEngine if let searchURL = engine.searchURLForQuery(text) { openURLInNewTab(searchURL, isPrivate: isPrivate, isPrivileged: true) } else { // We still don't have a valid URL, so something is broken. Give up. print("Error handling URL entry: \"\(text)\".") assertionFailure("Couldn't generate search URL: \(text)") } } fileprivate func popToBVC() { guard let currentViewController = navigationController?.topViewController else { return } currentViewController.dismiss(animated: true, completion: nil) if currentViewController != self { _ = self.navigationController?.popViewController(animated: true) } else if urlBar.inOverlayMode { urlBar.didClickCancel() } } // MARK: User Agent Spoofing func resetSpoofedUserAgentIfRequired(_ webView: WKWebView, newURL: URL) { // Reset the UA when a different domain is being loaded if webView.url?.host != newURL.host { webView.customUserAgent = nil } } func restoreSpoofedUserAgentIfRequired(_ webView: WKWebView, newRequest: URLRequest) { // Restore any non-default UA from the request's header let ua = newRequest.value(forHTTPHeaderField: "User-Agent") webView.customUserAgent = ua != UserAgent.defaultUserAgent() ? ua : nil } fileprivate func presentActivityViewController(_ url: URL, tab: Tab? = nil, sourceView: UIView?, sourceRect: CGRect, arrowDirection: UIPopoverArrowDirection) { let helper = ShareExtensionHelper(url: url, tab: tab) let controller = helper.createActivityViewController({ [unowned self] completed, _ in // After dismissing, check to see if there were any prompts we queued up self.showQueuedAlertIfAvailable() // Usually the popover delegate would handle nil'ing out the references we have to it // on the BVC when displaying as a popover but the delegate method doesn't seem to be // invoked on iOS 10. See Bug 1297768 for additional details. self.displayedPopoverController = nil self.updateDisplayedPopoverProperties = nil }) if let popoverPresentationController = controller.popoverPresentationController { popoverPresentationController.sourceView = sourceView popoverPresentationController.sourceRect = sourceRect popoverPresentationController.permittedArrowDirections = arrowDirection popoverPresentationController.delegate = self } present(controller, animated: true, completion: nil) LeanPlumClient.shared.track(event: .userSharedWebpage) } @objc fileprivate func openSettings() { assert(Thread.isMainThread, "Opening settings requires being invoked on the main thread") let settingsTableViewController = AppSettingsTableViewController() settingsTableViewController.profile = profile settingsTableViewController.tabManager = tabManager settingsTableViewController.settingsDelegate = self let controller = SettingsNavigationController(rootViewController: settingsTableViewController) controller.popoverDelegate = self controller.modalPresentationStyle = .formSheet self.present(controller, animated: true, completion: nil) } fileprivate func postLocationChangeNotificationForTab(_ tab: Tab, navigation: WKNavigation?) { let notificationCenter = NotificationCenter.default var info = [AnyHashable: Any]() info["url"] = tab.url?.displayURL info["title"] = tab.title if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue { info["visitType"] = visitType } info["isPrivate"] = tab.isPrivate notificationCenter.post(name: .OnLocationChange, object: self, userInfo: info) } func navigateInTab(tab: Tab, to navigation: WKNavigation? = nil) { tabManager.expireSnackbars() guard let webView = tab.webView else { print("Cannot navigate in tab without a webView") return } if let url = webView.url { if !url.isErrorPageURL, !url.isAboutHomeURL, !url.isFileURL { postLocationChangeNotificationForTab(tab, navigation: navigation) // Fire the readability check. This is here and not in the pageShow event handler in ReaderMode.js anymore // because that event wil not always fire due to unreliable page caching. This will either let us know that // the currently loaded page can be turned into reading mode or if the page already is in reading mode. We // ignore the result because we are being called back asynchronous when the readermode status changes. webView.evaluateJavaScript("\(ReaderModeNamespace).checkReadability()", completionHandler: nil) // Re-run additional scripts in webView to extract updated favicons and metadata. runScriptsOnWebView(webView) } TabEvent.post(.didChangeURL(url), for: tab) } if tab === tabManager.selectedTab { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // must be followed by LayoutChanged, as ScreenChanged will make VoiceOver // cursor land on the correct initial element, but if not followed by LayoutChanged, // VoiceOver will sometimes be stuck on the element, not allowing user to move // forward/backward. Strange, but LayoutChanged fixes that. UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } else if let webView = tab.webView { // To Screenshot a tab that is hidden we must add the webView, // then wait enough time for the webview to render. view.insertSubview(webView, at: 0) // This is kind of a hacky fix for Bug 1476637 to prevent webpages from focusing the // touch-screen keyboard from the background even though they shouldn't be able to. webView.resignFirstResponder() DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) { self.screenshotHelper.takeScreenshot(tab) if webView.superview == self.view { webView.removeFromSuperview() } } } // Remember whether or not a desktop site was requested tab.desktopSite = webView.customUserAgent?.isEmpty == false } } extension BrowserViewController: ClipboardBarDisplayHandlerDelegate { func shouldDisplay(clipboardBar bar: ButtonToast) { show(toast: bar, duration: ClipboardBarToastUX.ToastDelay) } } extension BrowserViewController: QRCodeViewControllerDelegate { func didScanQRCodeWithURL(_ url: URL) { openBlankNewTab(focusLocationField: false) finishEditingAndSubmit(url, visitType: VisitType.typed) UnifiedTelemetry.recordEvent(category: .action, method: .scan, object: .qrCodeURL) } func didScanQRCodeWithText(_ text: String) { openBlankNewTab(focusLocationField: false) submitSearchText(text) UnifiedTelemetry.recordEvent(category: .action, method: .scan, object: .qrCodeText) } } extension BrowserViewController: SettingsDelegate { func settingsOpenURLInNewTab(_ url: URL) { self.openURLInNewTab(url, isPrivileged: false) } } extension BrowserViewController: PresentingModalViewControllerDelegate { func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) { self.dismiss(animated: animated, completion: nil) } } /** * History visit management. * TODO: this should be expanded to track various visit types; see Bug 1166084. */ extension BrowserViewController { func ignoreNavigationInTab(_ tab: Tab, navigation: WKNavigation) { self.ignoredNavigation.insert(navigation) } func recordNavigationInTab(_ tab: Tab, navigation: WKNavigation, visitType: VisitType) { self.typedNavigation[navigation] = visitType } /** * Untrack and do the right thing. */ func getVisitTypeForTab(_ tab: Tab, navigation: WKNavigation?) -> VisitType? { guard let navigation = navigation else { // See https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/NavigationState.mm#L390 return VisitType.link } if let _ = self.ignoredNavigation.remove(navigation) { return nil } return self.typedNavigation.removeValue(forKey: navigation) ?? VisitType.link } } extension BrowserViewController: URLBarDelegate { func showTabTray() { Sentry.shared.clearBreadcrumbs() updateFindInPageVisibility(visible: false) let tabTrayController = TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self) if let tab = tabManager.selectedTab { screenshotHelper.takeScreenshot(tab) } navigationController?.pushViewController(tabTrayController, animated: true) self.tabTrayController = tabTrayController } func urlBarDidPressReload(_ urlBar: URLBarView) { tabManager.selectedTab?.reload() } func urlBarDidPressQRButton(_ urlBar: URLBarView) { let qrCodeViewController = QRCodeViewController() qrCodeViewController.qrCodeDelegate = self let controller = QRCodeNavigationController(rootViewController: qrCodeViewController) self.present(controller, animated: true, completion: nil) } func urlBarDidPressPageOptions(_ urlBar: URLBarView, from button: UIButton) { let actionMenuPresenter: (URL, Tab, UIView, UIPopoverArrowDirection) -> Void = { (url, tab, view, _) in self.presentActivityViewController(url, tab: tab, sourceView: view, sourceRect: view.bounds, arrowDirection: .up) } let findInPageAction = { self.updateFindInPageVisibility(visible: true) } let successCallback: (String) -> Void = { (successMessage) in SimpleToast().showAlertWithText(successMessage, bottomContainer: self.webViewContainer) } guard let tab = tabManager.selectedTab, let urlString = tab.url?.absoluteString else { return } let deferredBookmarkStatus: Deferred<Maybe<Bool>> = fetchBookmarkStatus(for: urlString) let deferredPinnedTopSiteStatus: Deferred<Maybe<Bool>> = fetchPinnedTopSiteStatus(for: urlString) // Wait for both the bookmark status and the pinned status deferredBookmarkStatus.both(deferredPinnedTopSiteStatus).uponQueue(.main) { let isBookmarked = $0.successValue ?? false let isPinned = $1.successValue ?? false let pageActions = self.getTabActions(tab: tab, buttonView: button, presentShareMenu: actionMenuPresenter, findInPage: findInPageAction, presentableVC: self, isBookmarked: isBookmarked, isPinned: isPinned, success: successCallback) self.presentSheetWith(title: Strings.PageActionMenuTitle, actions: pageActions, on: self, from: button) } } func urlBarDidLongPressPageOptions(_ urlBar: URLBarView, from button: UIButton) { guard let tab = tabManager.selectedTab else { return } guard let url = tab.canonicalURL?.displayURL, self.presentedViewController == nil else { return } let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() presentActivityViewController(url, tab: tab, sourceView: button, sourceRect: button.bounds, arrowDirection: .up) } func urlBarDidTapShield(_ urlBar: URLBarView, from button: UIButton) { if #available(iOS 11.0, *), let tab = self.tabManager.selectedTab { let trackingProtectionMenu = self.getTrackingSubMenu(for: tab) guard !trackingProtectionMenu.isEmpty else { return } self.presentSheetWith(actions: trackingProtectionMenu, on: self, from: urlBar) } } func urlBarDidPressStop(_ urlBar: URLBarView) { tabManager.selectedTab?.stop() } func urlBarDidPressTabs(_ urlBar: URLBarView) { showTabTray() } func urlBarDidPressReaderMode(_ urlBar: URLBarView) { if let tab = tabManager.selectedTab { if let readerMode = tab.getContentScript(name: "ReaderMode") as? ReaderMode { switch readerMode.state { case .available: enableReaderMode() UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .readerModeOpenButton) LeanPlumClient.shared.track(event: .useReaderView) case .active: disableReaderMode() UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .readerModeCloseButton) case .unavailable: break } } } } func urlBarDidLongPressReaderMode(_ urlBar: URLBarView) -> Bool { guard let tab = tabManager.selectedTab, let url = tab.url?.displayURL else { UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading list", comment: "Accessibility message e.g. spoken by VoiceOver after adding current webpage to the Reading List failed.")) return false } let result = profile.readingList.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name) switch result.value { case .success: UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Added page to Reading List", comment: "Accessibility message e.g. spoken by VoiceOver after the current page gets added to the Reading List using the Reader View button, e.g. by long-pressing it or by its accessibility custom action.")) // TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=1158503 provide some form of 'this has been added' visual feedback? case .failure(let error): UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading List. Maybe it’s already there?", comment: "Accessibility message e.g. spoken by VoiceOver after the user wanted to add current page to the Reading List and this was not done, likely because it already was in the Reading List, but perhaps also because of real failures.")) print("readingList.createRecordWithURL(url: \"\(url.absoluteString)\", ...) failed with error: \(error)") } return true } func locationActionsForURLBar(_ urlBar: URLBarView) -> [AccessibleAction] { if UIPasteboard.general.string != nil { return [pasteGoAction, pasteAction, copyAddressAction] } else { return [copyAddressAction] } } func urlBarDisplayTextForURL(_ url: URL?) -> (String?, Bool) { // use the initial value for the URL so we can do proper pattern matching with search URLs var searchURL = self.tabManager.selectedTab?.currentInitialURL if searchURL?.isErrorPageURL ?? true { searchURL = url } if let query = profile.searchEngines.queryForSearchURL(searchURL as URL?) { return (query, true) } else { return (url?.absoluteString, false) } } func urlBarDidLongPressLocation(_ urlBar: URLBarView) { let urlActions = self.getLongPressLocationBarActions(with: urlBar) let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() if #available(iOS 11.0, *), let tab = self.tabManager.selectedTab { let trackingProtectionMenu = self.getTrackingMenu(for: tab, presentingOn: urlBar) self.presentSheetWith(actions: [urlActions, trackingProtectionMenu], on: self, from: urlBar) } else { self.presentSheetWith(actions: [urlActions], on: self, from: urlBar) } } func urlBarDidPressScrollToTop(_ urlBar: URLBarView) { if let selectedTab = tabManager.selectedTab, homePanelController == nil { // Only scroll to top if we are not showing the home view controller selectedTab.webView?.scrollView.setContentOffset(CGPoint.zero, animated: true) } } func urlBarLocationAccessibilityActions(_ urlBar: URLBarView) -> [UIAccessibilityCustomAction]? { return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction } } func urlBar(_ urlBar: URLBarView, didEnterText text: String) { if text.isEmpty { hideSearchController() } else { showSearchController() searchController?.searchQuery = text searchLoader?.query = text } } func urlBar(_ urlBar: URLBarView, didSubmitText text: String) { if let fixupURL = URIFixup.getURL(text) { // The user entered a URL, so use it. finishEditingAndSubmit(fixupURL, visitType: VisitType.typed) return } // We couldn't build a URL, so check for a matching search keyword. let trimmedText = text.trimmingCharacters(in: .whitespaces) guard let possibleKeywordQuerySeparatorSpace = trimmedText.index(of: " ") else { submitSearchText(text) return } let possibleKeyword = String(trimmedText[..<possibleKeywordQuerySeparatorSpace]) let possibleQuery = String(trimmedText[trimmedText.index(after: possibleKeywordQuerySeparatorSpace)...]) profile.bookmarks.getURLForKeywordSearch(possibleKeyword).uponQueue(.main) { result in if var urlString = result.successValue, let escapedQuery = possibleQuery.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed), let range = urlString.range(of: "%s") { urlString.replaceSubrange(range, with: escapedQuery) if let url = URL(string: urlString) { self.finishEditingAndSubmit(url, visitType: VisitType.typed) return } } self.submitSearchText(text) } } fileprivate func submitSearchText(_ text: String) { let engine = profile.searchEngines.defaultEngine if let searchURL = engine.searchURLForQuery(text) { // We couldn't find a matching search keyword, so do a search query. Telemetry.default.recordSearch(location: .actionBar, searchEngine: engine.engineID ?? "other") finishEditingAndSubmit(searchURL, visitType: VisitType.typed) } else { // We still don't have a valid URL, so something is broken. Give up. print("Error handling URL entry: \"\(text)\".") assertionFailure("Couldn't generate search URL: \(text)") } } func urlBarDidEnterOverlayMode(_ urlBar: URLBarView) { guard let profile = profile as? BrowserProfile else { return } if .blankPage == NewTabAccessors.getNewTabPage(profile.prefs) { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } else { if let toast = clipboardBarDisplayHandler?.clipboardToast { toast.removeFromSuperview() } showHomePanelController(inline: false) } LeanPlumClient.shared.track(event: .interactWithURLBar) } func urlBarDidLeaveOverlayMode(_ urlBar: URLBarView) { hideSearchController() updateInContentHomePanel(tabManager.selectedTab?.url as URL?) } func urlBarDidBeginDragInteraction(_ urlBar: URLBarView) { dismissVisibleMenus() } } extension BrowserViewController: TabToolbarDelegate, PhotonActionSheetProtocol { func tabToolbarDidPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goBack() } func tabToolbarDidLongPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) { let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() showBackForwardList() } func tabToolbarDidPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.reload() } func tabToolbarDidLongPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) { guard let tab = tabManager.selectedTab else { return } let urlActions = self.getRefreshLongPressMenu(for: tab) guard !urlActions.isEmpty else { return } let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() let shouldSuppress = !topTabsVisible && UIDevice.current.userInterfaceIdiom == .pad presentSheetWith(actions: [urlActions], on: self, from: button, suppressPopover: shouldSuppress) } func tabToolbarDidPressStop(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.stop() } func tabToolbarDidPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goForward() } func tabToolbarDidLongPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) { let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() showBackForwardList() } func tabToolbarDidPressMenu(_ tabToolbar: TabToolbarProtocol, button: UIButton) { // ensure that any keyboards or spinners are dismissed before presenting the menu UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) var actions: [[PhotonActionSheetItem]] = [] if let syncAction = syncMenuButton(showFxA: presentSignInViewController) { actions.append(syncAction) } actions.append(getHomePanelActions()) actions.append(getOtherPanelActions(vcDelegate: self)) // force a modal if the menu is being displayed in compact split screen let shouldSuppress = !topTabsVisible && UIDevice.current.userInterfaceIdiom == .pad presentSheetWith(actions: actions, on: self, from: button, suppressPopover: shouldSuppress) } func tabToolbarDidPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) { showTabTray() } func getTabToolbarLongPressActions() -> [PhotonActionSheetItem] { var count = 1 let infinity = "\u{221E}" if let selectedTab = tabManager.selectedTab { count = selectedTab.isPrivate ? tabManager.normalTabs.count : tabManager.privateTabs.count } let tabCount = (count < 100) ? count.description : infinity let privateBrowsingMode = PhotonActionSheetItem(title: Strings.privateBrowsingModeTitle, iconString: "nav-tabcounter", iconType: .TabsButton, tabCount: tabCount) { action in if let tab = self.tabManager.selectedTab { if self.tabManager.switchTabMode(tab) { let shouldFocusLocationField = NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage self.openBlankNewTab(focusLocationField: shouldFocusLocationField, isPrivate: true) } }} let normalBrowsingMode = PhotonActionSheetItem(title: Strings.normalBrowsingModeTitle, iconString: "nav-tabcounter", iconType: .TabsButton, tabCount: tabCount) { action in if let tab = self.tabManager.selectedTab { _ = self.tabManager.switchTabMode(tab) }} if let tab = self.tabManager.selectedTab { return tab.isPrivate ? [normalBrowsingMode] : [privateBrowsingMode] } return [privateBrowsingMode] } func getMoreTabToolbarLongPressActions() -> [PhotonActionSheetItem] { let newTab = PhotonActionSheetItem(title: Strings.NewTabTitle, iconString: "quick_action_new_tab", iconType: .Image) { action in let shouldFocusLocationField = NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage self.openBlankNewTab(focusLocationField: shouldFocusLocationField, isPrivate: false)} let newPrivateTab = PhotonActionSheetItem(title: Strings.NewPrivateTabTitle, iconString: "quick_action_new_tab", iconType: .Image) { action in let shouldFocusLocationField = NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage self.openBlankNewTab(focusLocationField: shouldFocusLocationField, isPrivate: true)} let closeTab = PhotonActionSheetItem(title: Strings.CloseTabTitle, iconString: "tab_close", iconType: .Image) { action in if let tab = self.tabManager.selectedTab { self.tabManager.removeTabAndUpdateSelectedIndex(tab) }} if let tab = self.tabManager.selectedTab { return tab.isPrivate ? [newPrivateTab, closeTab] : [newTab, closeTab] } return [newTab, closeTab] } func tabToolbarDidLongPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) { guard self.presentedViewController == nil else { return } var actions: [[PhotonActionSheetItem]] = [] actions.append(getTabToolbarLongPressActions()) actions.append(getMoreTabToolbarLongPressActions()) // force a modal if the menu is being displayed in compact split screen let shouldSuppress = !topTabsVisible && UIDevice.current.userInterfaceIdiom == .pad presentSheetWith(actions: actions, on: self, from: button, suppressPopover: shouldSuppress) /* let controller = AlertController(title: nil, message: nil, preferredStyle: .actionSheet) controller.addAction(UIAlertAction(title: Strings.NewTabTitle, style: .default, handler: { _ in let shouldFocusLocationField = NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage self.openBlankNewTab(focusLocationField: shouldFocusLocationField, isPrivate: false) }), accessibilityIdentifier: "toolbarTabButtonLongPress.newTab") controller.addAction(UIAlertAction(title: Strings.NewPrivateTabTitle, style: .default, handler: { _ in let shouldFocusLocationField = NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage self.openBlankNewTab(focusLocationField: shouldFocusLocationField, isPrivate: true) }), accessibilityIdentifier: "toolbarTabButtonLongPress.newPrivateTab") controller.addAction(UIAlertAction(title: Strings.CloseTabTitle, style: .destructive, handler: { _ in if let tab = self.tabManager.selectedTab { self.tabManager.removeTabAndUpdateSelectedIndex(tab) } }), accessibilityIdentifier: "toolbarTabButtonLongPress.closeTab") controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: nil), accessibilityIdentifier: "toolbarTabButtonLongPress.cancel") controller.popoverPresentationController?.sourceView = toolbar ?? urlBar controller.popoverPresentationController?.sourceRect = button.frame let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() present(controller, animated: true, completion: nil) */ } func showBackForwardList() { if let backForwardList = tabManager.selectedTab?.webView?.backForwardList { let backForwardViewController = BackForwardListViewController(profile: profile, backForwardList: backForwardList) backForwardViewController.tabManager = tabManager backForwardViewController.bvc = self backForwardViewController.modalPresentationStyle = .overCurrentContext backForwardViewController.backForwardTransitionDelegate = BackForwardListAnimator() self.present(backForwardViewController, animated: true, completion: nil) } } } extension BrowserViewController: TabDelegate { func tab(_ tab: Tab, didCreateWebView webView: WKWebView) { webView.frame = webViewContainer.frame // Observers that live as long as the tab. Make sure these are all cleared in willDeleteWebView below! KVOs.forEach { webView.addObserver(self, forKeyPath: $0.rawValue, options: .new, context: nil) } webView.scrollView.addObserver(self.scrollController, forKeyPath: KVOConstants.contentSize.rawValue, options: .new, context: nil) webView.uiDelegate = self let formPostHelper = FormPostHelper(tab: tab) tab.addContentScript(formPostHelper, name: FormPostHelper.name()) let readerMode = ReaderMode(tab: tab) readerMode.delegate = self tab.addContentScript(readerMode, name: ReaderMode.name()) // only add the logins helper if the tab is not a private browsing tab if !tab.isPrivate { let logins = LoginsHelper(tab: tab, profile: profile) tab.addContentScript(logins, name: LoginsHelper.name()) } let contextMenuHelper = ContextMenuHelper(tab: tab) contextMenuHelper.delegate = self tab.addContentScript(contextMenuHelper, name: ContextMenuHelper.name()) let errorHelper = ErrorPageHelper() tab.addContentScript(errorHelper, name: ErrorPageHelper.name()) let sessionRestoreHelper = SessionRestoreHelper(tab: tab) sessionRestoreHelper.delegate = self tab.addContentScript(sessionRestoreHelper, name: SessionRestoreHelper.name()) let findInPageHelper = FindInPageHelper(tab: tab) findInPageHelper.delegate = self tab.addContentScript(findInPageHelper, name: FindInPageHelper.name()) let noImageModeHelper = NoImageModeHelper(tab: tab) tab.addContentScript(noImageModeHelper, name: NoImageModeHelper.name()) let printHelper = PrintHelper(tab: tab) tab.addContentScript(printHelper, name: PrintHelper.name()) let customSearchHelper = CustomSearchHelper(tab: tab) tab.addContentScript(customSearchHelper, name: CustomSearchHelper.name()) let nightModeHelper = NightModeHelper(tab: tab) tab.addContentScript(nightModeHelper, name: NightModeHelper.name()) // XXX: Bug 1390200 - Disable NSUserActivity/CoreSpotlight temporarily // let spotlightHelper = SpotlightHelper(tab: tab) // tab.addHelper(spotlightHelper, name: SpotlightHelper.name()) tab.addContentScript(LocalRequestHelper(), name: LocalRequestHelper.name()) let historyStateHelper = HistoryStateHelper(tab: tab) historyStateHelper.delegate = self tab.addContentScript(historyStateHelper, name: HistoryStateHelper.name()) if #available(iOS 11, *) { if let blocker = tab.contentBlocker as? ContentBlockerHelper { blocker.setupTabTrackingProtection() tab.addContentScript(blocker, name: ContentBlockerHelper.name()) } } tab.addContentScript(FocusHelper(tab: tab), name: FocusHelper.name()) } func tab(_ tab: Tab, willDeleteWebView webView: WKWebView) { tab.cancelQueuedAlerts() KVOs.forEach { webView.removeObserver(self, forKeyPath: $0.rawValue) } webView.scrollView.removeObserver(self.scrollController, forKeyPath: KVOConstants.contentSize.rawValue) webView.uiDelegate = nil webView.scrollView.delegate = nil webView.removeFromSuperview() } fileprivate func findSnackbar(_ barToFind: SnackBar) -> Int? { let bars = alertStackView.arrangedSubviews for (index, bar) in bars.enumerated() where bar === barToFind { return index } return nil } func showBar(_ bar: SnackBar, animated: Bool) { view.layoutIfNeeded() UIView.animate(withDuration: animated ? 0.25 : 0, animations: { self.alertStackView.insertArrangedSubview(bar, at: 0) self.view.layoutIfNeeded() }) } func removeBar(_ bar: SnackBar, animated: Bool) { UIView.animate(withDuration: animated ? 0.25 : 0, animations: { bar.removeFromSuperview() }) } func removeAllBars() { alertStackView.arrangedSubviews.forEach { $0.removeFromSuperview() } } func tab(_ tab: Tab, didAddSnackbar bar: SnackBar) { showBar(bar, animated: true) } func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar) { removeBar(bar, animated: true) } func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String) { updateFindInPageVisibility(visible: true) findInPageBar?.text = selection } func tab(_ tab: Tab, didSelectSearchWithFirefoxForSelection selection: String) { openSearchNewTab(isPrivate: tab.isPrivate, selection) } } extension BrowserViewController: HomePanelViewControllerDelegate { func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectURL url: URL, visitType: VisitType) { finishEditingAndSubmit(url, visitType: visitType) } func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectPanel panel: Int) { if let url = tabManager.selectedTab?.url, url.isAboutHomeURL { tabManager.selectedTab?.webView?.evaluateJavaScript("history.replaceState({}, '', '#panel=\(panel)')", completionHandler: nil) } } func homePanelViewControllerDidRequestToCreateAccount(_ homePanelViewController: HomePanelViewController) { let fxaParams = FxALaunchParams(query: ["entrypoint": "homepanel"]) presentSignInViewController(fxaParams) // TODO UX Right now the flow for sign in and create account is the same } func homePanelViewControllerDidRequestToSignIn(_ homePanelViewController: HomePanelViewController) { let fxaParams = FxALaunchParams(query: ["entrypoint": "homepanel"]) presentSignInViewController(fxaParams) // TODO UX Right now the flow for sign in and create account is the same } func homePanelViewControllerDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) { let tab = self.tabManager.addTab(PrivilegedRequest(url: url) as URLRequest, afterTab: self.tabManager.selectedTab, isPrivate: isPrivate) // If we are showing toptabs a user can just use the top tab bar // If in overlay mode switching doesnt correctly dismiss the homepanels guard !topTabsVisible, !self.urlBar.inOverlayMode else { return } // We're not showing the top tabs; show a toast to quick switch to the fresh new tab. let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in if buttonPressed { self.tabManager.selectTab(tab) } }) self.show(toast: toast) } } extension BrowserViewController: SearchViewControllerDelegate { func searchViewController(_ searchViewController: SearchViewController, didSelectURL url: URL) { finishEditingAndSubmit(url, visitType: VisitType.typed) } func searchViewController(_ searchViewController: SearchViewController, didLongPressSuggestion suggestion: String) { self.urlBar.setLocation(suggestion, search: true) } func presentSearchSettingsController() { let settingsNavigationController = SearchSettingsTableViewController() settingsNavigationController.model = self.profile.searchEngines settingsNavigationController.profile = self.profile let navController = ModalSettingsNavigationController(rootViewController: settingsNavigationController) self.present(navController, animated: true, completion: nil) } func searchViewController(_ searchViewController: SearchViewController, didHighlightText text: String, search: Bool) { self.urlBar.setLocation(text, search: search) } } extension BrowserViewController: TabManagerDelegate { func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?, isRestoring: Bool) { // Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it // and having multiple views with the same label confuses tests. if let wv = previous?.webView { wv.endEditing(true) wv.accessibilityLabel = nil wv.accessibilityElementsHidden = true wv.accessibilityIdentifier = nil wv.removeFromSuperview() } if let tab = selected, let webView = tab.webView { updateURLBarDisplayURL(tab) if tab.isPrivate != previous?.isPrivate { applyTheme() let ui: [PrivateModeUI?] = [toolbar, topTabsViewController, urlBar] ui.forEach { $0?.applyUIMode(isPrivate: tab.isPrivate) } } readerModeCache = tab.isPrivate ? MemoryReaderModeCache.sharedInstance : DiskReaderModeCache.sharedInstance if let privateModeButton = topTabsViewController?.privateModeButton, previous != nil && previous?.isPrivate != tab.isPrivate { privateModeButton.setSelected(tab.isPrivate, animated: true) } ReaderModeHandlers.readerModeCache = readerModeCache scrollController.tab = selected webViewContainer.addSubview(webView) webView.snp.makeConstraints { make in make.left.right.top.bottom.equalTo(self.webViewContainer) } webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.accessibilityIdentifier = "contentView" webView.accessibilityElementsHidden = false if webView.url == nil { // The web view can go gray if it was zombified due to memory pressure. // When this happens, the URL is nil, so try restoring the page upon selection. tab.reload() } } if let selected = selected, let previous = previous, selected.isPrivate != previous.isPrivate { updateTabCountUsingTabManager(tabManager) } removeAllBars() if let bars = selected?.bars { for bar in bars { showBar(bar, animated: true) } } updateFindInPageVisibility(visible: false, tab: previous) navigationToolbar.updateReloadStatus(selected?.loading ?? false) navigationToolbar.updateBackStatus(selected?.canGoBack ?? false) navigationToolbar.updateForwardStatus(selected?.canGoForward ?? false) if !(selected?.webView?.url?.isLocalUtility ?? false) { self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0)) } if let readerMode = selected?.getContentScript(name: ReaderMode.name()) as? ReaderMode { urlBar.updateReaderModeState(readerMode.state) if readerMode.state == .active { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } } else { urlBar.updateReaderModeState(ReaderModeState.unavailable) } if topTabsVisible { topTabsDidChangeTab() } updateInContentHomePanel(selected?.url as URL?) if let tab = selected, tab.url == nil, !tab.restoring, NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage { self.urlBar.tabLocationViewDidTapLocation(self.urlBar.locationView) } } func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) { } func tabManager(_ tabManager: TabManager, didAddTab tab: Tab, isRestoring: Bool) { // If we are restoring tabs then we update the count once at the end if !isRestoring { updateTabCountUsingTabManager(tabManager) } tab.tabDelegate = self } func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) { if let url = tab.url, !url.isAboutURL && !tab.isPrivate { profile.recentlyClosedTabs.addTab(url as URL, title: tab.title, faviconURL: tab.displayFavicon?.url) } } func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab, isRestoring: Bool) { updateTabCountUsingTabManager(tabManager) } func tabManagerDidAddTabs(_ tabManager: TabManager) { updateTabCountUsingTabManager(tabManager) } func tabManagerDidRestoreTabs(_ tabManager: TabManager) { updateTabCountUsingTabManager(tabManager) } func show(toast: Toast, afterWaiting delay: DispatchTimeInterval = SimpleToastUX.ToastDelayBefore, duration: DispatchTimeInterval? = SimpleToastUX.ToastDismissAfter) { if let downloadToast = toast as? DownloadToast { self.downloadToast = downloadToast } // If BVC isnt visible hold on to this toast until viewDidAppear if self.view.window == nil { self.pendingToast = toast return } toast.showToast(viewController: self, delay: delay, duration: duration, makeConstraints: { make in make.left.right.equalTo(self.view) make.bottom.equalTo(self.webViewContainer) }) } func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) { guard let toast = toast, !(tabTrayController?.privateMode ?? false) else { return } show(toast: toast, afterWaiting: ButtonToastUX.ToastDelay) } fileprivate func updateTabCountUsingTabManager(_ tabManager: TabManager, animated: Bool = true) { if let selectedTab = tabManager.selectedTab { let count = selectedTab.isPrivate ? tabManager.privateTabs.count : tabManager.normalTabs.count toolbar?.updateTabCount(count, animated: animated) urlBar.updateTabCount(count, animated: !urlBar.inOverlayMode) topTabsViewController?.updateTabCount(count, animated: animated) } } } // MARK: - UIPopoverPresentationControllerDelegate extension BrowserViewController: UIPopoverPresentationControllerDelegate { func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { displayedPopoverController = nil updateDisplayedPopoverProperties = nil } } extension BrowserViewController: UIAdaptivePresentationControllerDelegate { // Returning None here makes sure that the Popover is actually presented as a Popover and // not as a full-screen modal, which is the default on compact device classes. func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } } extension BrowserViewController: IntroViewControllerDelegate { @discardableResult func presentIntroViewController(_ force: Bool = false, animated: Bool = true) -> Bool { if let deeplink = self.profile.prefs.stringForKey("AdjustDeeplinkKey"), let url = URL(string: deeplink) { self.launchFxAFromDeeplinkURL(url) return true } if force || profile.prefs.intForKey(PrefsKeys.IntroSeen) == nil { let introViewController = IntroViewController() introViewController.delegate = self // On iPad we present it modally in a controller if topTabsVisible { introViewController.preferredContentSize = CGSize(width: IntroUX.Width, height: IntroUX.Height) introViewController.modalPresentationStyle = .formSheet } present(introViewController, animated: animated) { // On first run (and forced) open up the homepage in the background. if let homePageURL = HomePageAccessors.getHomePage(self.profile.prefs), let tab = self.tabManager.selectedTab, DeviceInfo.hasConnectivity() { tab.loadRequest(URLRequest(url: homePageURL)) } } return true } return false } func launchFxAFromDeeplinkURL(_ url: URL) { self.profile.prefs.removeObjectForKey("AdjustDeeplinkKey") var query = url.getQuery() query["entrypoint"] = "adjust_deepklink_ios" let fxaParams: FxALaunchParams fxaParams = FxALaunchParams(query: query) self.presentSignInViewController(fxaParams) } func introViewControllerDidFinish(_ introViewController: IntroViewController, requestToLogin: Bool) { self.profile.prefs.setInt(1, forKey: PrefsKeys.IntroSeen) introViewController.dismiss(animated: true) { if self.navigationController?.viewControllers.count ?? 0 > 1 { _ = self.navigationController?.popToRootViewController(animated: true) } if requestToLogin { let fxaParams = FxALaunchParams(query: ["entrypoint": "firstrun"]) self.presentSignInViewController(fxaParams) } } } func presentSignInViewController(_ fxaOptions: FxALaunchParams? = nil) { // Show the settings page if we have already signed in. If we haven't then show the signin page let vcToPresent: UIViewController if profile.hasAccount(), let status = profile.getAccount()?.actionNeeded, status == .none { let settingsTableViewController = SyncContentSettingsViewController() settingsTableViewController.profile = profile vcToPresent = settingsTableViewController } else { let signInVC = FxAContentViewController(profile: profile, fxaOptions: fxaOptions) signInVC.delegate = self vcToPresent = signInVC } vcToPresent.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissSignInViewController)) let settingsNavigationController = SettingsNavigationController(rootViewController: vcToPresent) settingsNavigationController.modalPresentationStyle = .formSheet settingsNavigationController.navigationBar.isTranslucent = false self.present(settingsNavigationController, animated: true, completion: nil) } @objc func dismissSignInViewController() { self.dismiss(animated: true, completion: nil) } } extension BrowserViewController: FxAContentViewControllerDelegate { func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags flags: FxALoginFlags) { if flags.verified { self.dismiss(animated: true, completion: nil) } } func contentViewControllerDidCancel(_ viewController: FxAContentViewController) { self.dismiss(animated: true, completion: nil) } } extension BrowserViewController: ContextMenuHelperDelegate { func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UIGestureRecognizer) { // locationInView can return (0, 0) when the long press is triggered in an invalid page // state (e.g., long pressing a link before the document changes, then releasing after a // different page loads). let touchPoint = gestureRecognizer.location(in: view) guard touchPoint != CGPoint.zero else { return } let touchSize = CGSize(width: 0, height: 16) let actionSheetController = AlertController(title: nil, message: nil, preferredStyle: .actionSheet) var dialogTitle: String? if let url = elements.link, let currentTab = tabManager.selectedTab { dialogTitle = url.absoluteString let isPrivate = currentTab.isPrivate let addTab = { (rURL: URL, isPrivate: Bool) in let tab = self.tabManager.addTab(URLRequest(url: rURL as URL), afterTab: currentTab, isPrivate: isPrivate) LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "Long Press Context Menu"]) guard !self.topTabsVisible else { return } // We're not showing the top tabs; show a toast to quick switch to the fresh new tab. let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in if buttonPressed { self.tabManager.selectTab(tab) } }) self.show(toast: toast) } if !isPrivate { let newTabTitle = NSLocalizedString("Open in New Tab", comment: "Context menu item for opening a link in a new tab") let openNewTabAction = UIAlertAction(title: newTabTitle, style: .default) { _ in addTab(url, false) } actionSheetController.addAction(openNewTabAction, accessibilityIdentifier: "linkContextMenu.openInNewTab") } let openNewPrivateTabTitle = NSLocalizedString("Open in New Private Tab", tableName: "PrivateBrowsing", comment: "Context menu option for opening a link in a new private tab") let openNewPrivateTabAction = UIAlertAction(title: openNewPrivateTabTitle, style: .default) { _ in addTab(url, true) } actionSheetController.addAction(openNewPrivateTabAction, accessibilityIdentifier: "linkContextMenu.openInNewPrivateTab") let downloadTitle = NSLocalizedString("Download Link", comment: "Context menu item for downloading a link URL") let downloadAction = UIAlertAction(title: downloadTitle, style: .default) { _ in self.pendingDownloadWebView = currentTab.webView currentTab.webView?.evaluateJavaScript("window.__firefox__.download('\(url.absoluteString)', '\(UserScriptManager.securityToken)')") UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .downloadLinkButton) } actionSheetController.addAction(downloadAction, accessibilityIdentifier: "linkContextMenu.download") let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard") let copyAction = UIAlertAction(title: copyTitle, style: .default) { _ in UIPasteboard.general.url = url as URL } actionSheetController.addAction(copyAction, accessibilityIdentifier: "linkContextMenu.copyLink") let shareTitle = NSLocalizedString("Share Link", comment: "Context menu item for sharing a link URL") let shareAction = UIAlertAction(title: shareTitle, style: .default) { _ in self.presentActivityViewController(url as URL, sourceView: self.view, sourceRect: CGRect(origin: touchPoint, size: touchSize), arrowDirection: .any) } actionSheetController.addAction(shareAction, accessibilityIdentifier: "linkContextMenu.share") } if let url = elements.image { if dialogTitle == nil { dialogTitle = url.absoluteString } let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus() let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu item for saving an image") let saveImageAction = UIAlertAction(title: saveImageTitle, style: .default) { _ in if photoAuthorizeStatus == .authorized || photoAuthorizeStatus == .notDetermined { self.getImage(url as URL) { UIImageWriteToSavedPhotosAlbum($0, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil) } } else { let accessDenied = UIAlertController(title: NSLocalizedString("Firefox would like to access your Photos", comment: "See http://mzl.la/1G7uHo7"), message: NSLocalizedString("This allows you to save the image to your Camera Roll.", comment: "See http://mzl.la/1G7uHo7"), preferredStyle: .alert) let dismissAction = UIAlertAction(title: Strings.CancelString, style: .default, handler: nil) accessDenied.addAction(dismissAction) let settingsAction = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "See http://mzl.la/1G7uHo7"), style: .default ) { _ in UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:]) } accessDenied.addAction(settingsAction) self.present(accessDenied, animated: true, completion: nil) } } actionSheetController.addAction(saveImageAction, accessibilityIdentifier: "linkContextMenu.saveImage") let copyImageTitle = NSLocalizedString("Copy Image", comment: "Context menu item for copying an image to the clipboard") let copyAction = UIAlertAction(title: copyImageTitle, style: .default) { _ in // put the actual image on the clipboard // do this asynchronously just in case we're in a low bandwidth situation let pasteboard = UIPasteboard.general pasteboard.url = url as URL let changeCount = pasteboard.changeCount let application = UIApplication.shared var taskId: UIBackgroundTaskIdentifier = 0 taskId = application.beginBackgroundTask (expirationHandler: { application.endBackgroundTask(taskId) }) Alamofire.request(url).validate(statusCode: 200..<300).response { response in // Only set the image onto the pasteboard if the pasteboard hasn't changed since // fetching the image; otherwise, in low-bandwidth situations, // we might be overwriting something that the user has subsequently added. if changeCount == pasteboard.changeCount, let imageData = response.data, response.error == nil { pasteboard.addImageWithData(imageData, forURL: url) } application.endBackgroundTask(taskId) } } actionSheetController.addAction(copyAction, accessibilityIdentifier: "linkContextMenu.copyImage") } // If we're showing an arrow popup, set the anchor to the long press location. if let popoverPresentationController = actionSheetController.popoverPresentationController { popoverPresentationController.sourceView = view popoverPresentationController.sourceRect = CGRect(origin: touchPoint, size: touchSize) popoverPresentationController.permittedArrowDirections = .any popoverPresentationController.delegate = self } if actionSheetController.popoverPresentationController != nil { displayedPopoverController = actionSheetController } actionSheetController.title = dialogTitle?.ellipsize(maxLength: ActionSheetTitleMaxLength) let cancelAction = UIAlertAction(title: Strings.CancelString, style: UIAlertActionStyle.cancel, handler: nil) actionSheetController.addAction(cancelAction) self.present(actionSheetController, animated: true, completion: nil) } fileprivate func getImage(_ url: URL, success: @escaping (UIImage) -> Void) { Alamofire.request(url).validate(statusCode: 200..<300).response { response in if let data = response.data, let image = data.isGIF ? UIImage.imageFromGIFDataThreadSafe(data) : UIImage.imageFromDataThreadSafe(data) { success(image) } } } func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didCancelGestureRecognizer: UIGestureRecognizer) { displayedPopoverController?.dismiss(animated: true) { self.displayedPopoverController = nil } } } extension BrowserViewController { @objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) { if error == nil { LeanPlumClient.shared.track(event: .saveImage) } } } extension BrowserViewController: HistoryStateHelperDelegate { func historyStateHelper(_ historyStateHelper: HistoryStateHelper, didPushOrReplaceStateInTab tab: Tab) { navigateInTab(tab: tab) tabManager.storeChanges() } } /** A third party search engine Browser extension **/ extension BrowserViewController { func addCustomSearchButtonToWebView(_ webView: WKWebView) { //check if the search engine has already been added. let domain = webView.url?.domainURL.host let matches = self.profile.searchEngines.orderedEngines.filter {$0.shortName == domain} if !matches.isEmpty { self.customSearchEngineButton.tintColor = UIColor.Photon.Grey50 self.customSearchEngineButton.isUserInteractionEnabled = false } else { self.customSearchEngineButton.tintColor = UIConstants.SystemBlueColor self.customSearchEngineButton.isUserInteractionEnabled = true } /* This is how we access hidden views in the WKContentView Using the public headers we can find the keyboard accessoryView which is not usually available. Specific values here are from the WKContentView headers. https://github.com/JaviSoto/iOS9-Runtime-Headers/blob/master/Frameworks/WebKit.framework/WKContentView.h */ guard let webContentView = UIView.findSubViewWithFirstResponder(webView) else { /* In some cases the URL bar can trigger the keyboard notification. In that case the webview isnt the first responder and a search button should not be added. */ return } guard let input = webContentView.perform(#selector(getter: UIResponder.inputAccessoryView)), let inputView = input.takeUnretainedValue() as? UIInputView, let nextButton = inputView.value(forKey: "_nextItem") as? UIBarButtonItem, let nextButtonView = nextButton.value(forKey: "view") as? UIView else { //failed to find the inputView instead lets use the inputAssistant addCustomSearchButtonToInputAssistant(webContentView) return } inputView.addSubview(self.customSearchEngineButton) self.customSearchEngineButton.snp.remakeConstraints { make in make.leading.equalTo(nextButtonView.snp.trailing).offset(20) make.width.equalTo(inputView.snp.height) make.top.equalTo(nextButtonView.snp.top) make.height.equalTo(inputView.snp.height) } } /** This adds the customSearchButton to the inputAssistant for cases where the inputAccessoryView could not be found for example on the iPad where it does not exist. However this only works on iOS9 **/ func addCustomSearchButtonToInputAssistant(_ webContentView: UIView) { guard customSearchBarButton == nil else { return //The searchButton is already on the keyboard } let inputAssistant = webContentView.inputAssistantItem let item = UIBarButtonItem(customView: customSearchEngineButton) customSearchBarButton = item _ = Try(withTry: { inputAssistant.trailingBarButtonGroups.last?.barButtonItems.append(item) }) { (exception) in Sentry.shared.send(message: "Failed adding custom search button to input assistant", tag: .general, severity: .error, description: "\(exception ??? "nil")") } } @objc func addCustomSearchEngineForFocusedElement() { guard let webView = tabManager.selectedTab?.webView else { return } webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in guard let searchQuery = result as? String, let favicon = self.tabManager.selectedTab!.displayFavicon else { //Javascript responded with an incorrectly formatted message. Show an error. let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } self.addSearchEngine(searchQuery, favicon: favicon) self.customSearchEngineButton.tintColor = UIColor.Photon.Grey50 self.customSearchEngineButton.isUserInteractionEnabled = false } } func addSearchEngine(_ searchQuery: String, favicon: Favicon) { guard searchQuery != "", let iconURL = URL(string: favicon.url), let url = URL(string: searchQuery.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!), let shortName = url.domainURL.host else { let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } let alert = ThirdPartySearchAlerts.addThirdPartySearchEngine { alert in self.customSearchEngineButton.tintColor = UIColor.Photon.Grey50 self.customSearchEngineButton.isUserInteractionEnabled = false SDWebImageManager.shared().loadImage(with: iconURL, options: .continueInBackground, progress: nil) { (image, _, _, _, _, _) in guard let image = image else { let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } self.profile.searchEngines.addSearchEngine(OpenSearchEngine(engineID: nil, shortName: shortName, image: image, searchTemplate: searchQuery, suggestTemplate: nil, isCustomEngine: true)) let Toast = SimpleToast() Toast.showAlertWithText(Strings.ThirdPartySearchEngineAdded, bottomContainer: self.webViewContainer) } } self.present(alert, animated: true, completion: {}) } } extension BrowserViewController: KeyboardHelperDelegate { func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { keyboardState = state updateViewConstraints() UIView.animate(withDuration: state.animationDuration) { UIView.setAnimationCurve(state.animationCurve) self.alertStackView.layoutIfNeeded() } guard let webView = tabManager.selectedTab?.webView else { return } webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in guard let _ = result as? String else { return } self.addCustomSearchButtonToWebView(webView) } } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) { } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { keyboardState = nil updateViewConstraints() //If the searchEngineButton exists remove it form the keyboard if let buttonGroup = customSearchBarButton?.buttonGroup { buttonGroup.barButtonItems = buttonGroup.barButtonItems.filter { $0 != customSearchBarButton } customSearchBarButton = nil } if self.customSearchEngineButton.superview != nil { self.customSearchEngineButton.removeFromSuperview() } UIView.animate(withDuration: state.animationDuration) { UIView.setAnimationCurve(state.animationCurve) self.alertStackView.layoutIfNeeded() } } } extension BrowserViewController: SessionRestoreHelperDelegate { func sessionRestoreHelper(_ helper: SessionRestoreHelper, didRestoreSessionForTab tab: Tab) { tab.restoring = false if let tab = tabManager.selectedTab, tab.webView === tab.webView { updateUIForReaderHomeStateForTab(tab) } } } extension BrowserViewController: TabTrayDelegate { // This function animates and resets the tab chrome transforms when // the tab tray dismisses. func tabTrayDidDismiss(_ tabTray: TabTrayController) { resetBrowserChrome() } func tabTrayDidAddTab(_ tabTray: TabTrayController, tab: Tab) {} func tabTrayDidAddBookmark(_ tab: Tab) { guard let url = tab.url?.absoluteString, !url.isEmpty else { return } self.addBookmark(tab.tabState) } func tabTrayDidAddToReadingList(_ tab: Tab) -> ReadingListItem? { guard let url = tab.url?.absoluteString, !url.isEmpty else { return nil } return profile.readingList.createRecordWithURL(url, title: tab.title ?? url, addedBy: UIDevice.current.name).value.successValue } func tabTrayRequestsPresentationOf(_ viewController: UIViewController) { self.present(viewController, animated: false, completion: nil) } } // MARK: Browser Chrome Theming extension BrowserViewController: Themeable { func applyTheme() { let ui: [Themeable?] = [urlBar, toolbar, readerModeBar, topTabsViewController, homePanelController, searchController] ui.forEach { $0?.applyTheme() } statusBarOverlay.backgroundColor = shouldShowTopTabsForTraitCollection(traitCollection) ? UIColor.Photon.Grey80 : urlBar.backgroundColor setNeedsStatusBarAppearanceUpdate() (presentedViewController as? Themeable)?.applyTheme() } } extension BrowserViewController: JSPromptAlertControllerDelegate { func promptAlertControllerDidDismiss(_ alertController: JSPromptAlertController) { showQueuedAlertIfAvailable() } } extension BrowserViewController: TopTabsDelegate { func topTabsDidPressTabs() { urlBar.leaveOverlayMode(didCancel: true) self.urlBarDidPressTabs(urlBar) } func topTabsDidPressNewTab(_ isPrivate: Bool) { openBlankNewTab(focusLocationField: false, isPrivate: isPrivate) } func topTabsDidTogglePrivateMode() { guard let _ = tabManager.selectedTab else { return } urlBar.leaveOverlayMode() } func topTabsDidChangeTab() { urlBar.leaveOverlayMode(didCancel: true) } } extension BrowserViewController: ClientPickerViewControllerDelegate, InstructionsViewControllerDelegate { func instructionsViewControllerDidClose(_ instructionsViewController: InstructionsViewController) { self.popToBVC() } func clientPickerViewControllerDidCancel(_ clientPickerViewController: ClientPickerViewController) { self.popToBVC() } func clientPickerViewController(_ clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) { guard let tab = tabManager.selectedTab, let url = tab.canonicalURL?.displayURL?.absoluteString else { return } let shareItem = ShareItem(url: url, title: tab.title, favicon: tab.displayFavicon) guard shareItem.isShareable else { let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .default) { _ in self.popToBVC()}) present(alert, animated: true, completion: nil) return } profile.sendItem(shareItem, toClients: clients).uponQueue(.main) { _ in self.popToBVC() } } }
mpl-2.0
d4290d1c83e43de02b5bba5d94e70557
43.331034
406
0.667548
5.797443
false
false
false
false
Akagi201/learning-ios
swift/ios/MakeView/MakeView/AppDelegate.swift
1
2950
// // AppDelegate.swift // MakeView // // Created by Bob Liu on 6/22/15. // Copyright © 2015 Akagi201. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window?.backgroundColor = UIColor.redColor() self.window?.makeKeyAndVisible() let rootView = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 400)) rootView.backgroundColor = UIColor.whiteColor() self.window?.addSubview(rootView) let label1 = UILabel(frame: CGRect(x:100, y:20, width: 100, height: 50)) label1.text = "Hello" label1.textColor = UIColor.blackColor() rootView.addSubview(label1) let button1 = UIButton(frame: CGRect(x:100, y:100, width: 100, height: 50)) button1.setTitle("ClickMe", forState: UIControlState.Normal) button1.backgroundColor = UIColor.grayColor() rootView.addSubview(button1) return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
daf1c4f569e7e759016c415d6303a759
45.078125
285
0.720922
5.093264
false
false
false
false
honghaoz/2048-Solver-AI
2048 AI/Components/Settings/View/AIAlgorithmCell.swift
1
2545
// Copyright © 2019 ChouTi. All rights reserved. import UIKit class AIAlgorithmCell: UITableViewCell { let titleLabel = UILabel() let selectionControl = BlackSelectionControl() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { setupViews() setupConstraints() } private func setupViews() { backgroundColor = UIColor.clear selectionStyle = .none titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(titleLabel) titleLabel.text = "(Title)" titleLabel.textColor = UIColor.black titleLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 20) titleLabel.textAlignment = .left titleLabel.numberOfLines = 1 selectionControl.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(selectionControl) selectionControl.isUserInteractionEnabled = false } private func setupConstraints() { let constraints = [ NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: titleLabel, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leadingMargin, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: selectionControl, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0.0, constant: 26), NSLayoutConstraint(item: selectionControl, attribute: .width, relatedBy: .equal, toItem: selectionControl, attribute: .height, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: selectionControl, attribute: .centerY, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: selectionControl, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailingMargin, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: titleLabel, attribute: .trailing, relatedBy: .lessThanOrEqual, toItem: selectionControl, attribute: .leading, multiplier: 1.0, constant: -10), ] NSLayoutConstraint.activate(constraints) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) selectionControl.isSelected = selected } }
gpl-2.0
bf984d0344a34350d5d7476d30135725
41.4
173
0.742531
4.711111
false
false
false
false
airbnb/lottie-ios
Sources/Private/Model/Text/TextDocument.swift
3
3235
// // TextDocument.swift // lottie-swift // // Created by Brandon Withrow on 1/9/19. // import Foundation // MARK: - TextJustification enum TextJustification: Int, Codable { case left case right case center } // MARK: - TextDocument final class TextDocument: Codable, DictionaryInitializable, AnyInitializable { // MARK: Lifecycle init(dictionary: [String: Any]) throws { text = try dictionary.value(for: CodingKeys.text) fontSize = try dictionary.value(for: CodingKeys.fontSize) fontFamily = try dictionary.value(for: CodingKeys.fontFamily) let justificationValue: Int = try dictionary.value(for: CodingKeys.justification) guard let justification = TextJustification(rawValue: justificationValue) else { throw InitializableError.invalidInput } self.justification = justification tracking = try dictionary.value(for: CodingKeys.tracking) lineHeight = try dictionary.value(for: CodingKeys.lineHeight) baseline = try dictionary.value(for: CodingKeys.baseline) if let fillColorRawValue = dictionary[CodingKeys.fillColorData.rawValue] { fillColorData = try? LottieColor(value: fillColorRawValue) } else { fillColorData = nil } if let strokeColorRawValue = dictionary[CodingKeys.strokeColorData.rawValue] { strokeColorData = try? LottieColor(value: strokeColorRawValue) } else { strokeColorData = nil } strokeWidth = try? dictionary.value(for: CodingKeys.strokeWidth) strokeOverFill = try? dictionary.value(for: CodingKeys.strokeOverFill) if let textFramePositionRawValue = dictionary[CodingKeys.textFramePosition.rawValue] { textFramePosition = try? LottieVector3D(value: textFramePositionRawValue) } else { textFramePosition = nil } if let textFrameSizeRawValue = dictionary[CodingKeys.textFrameSize.rawValue] { textFrameSize = try? LottieVector3D(value: textFrameSizeRawValue) } else { textFrameSize = nil } } convenience init(value: Any) throws { guard let dictionary = value as? [String: Any] else { throw InitializableError.invalidInput } try self.init(dictionary: dictionary) } // MARK: Internal /// The Text let text: String /// The Font size let fontSize: Double /// The Font Family let fontFamily: String /// Justification let justification: TextJustification /// Tracking let tracking: Int /// Line Height let lineHeight: Double /// Baseline let baseline: Double? /// Fill Color data let fillColorData: LottieColor? /// Scroke Color data let strokeColorData: LottieColor? /// Stroke Width let strokeWidth: Double? /// Stroke Over Fill let strokeOverFill: Bool? let textFramePosition: LottieVector3D? let textFrameSize: LottieVector3D? // MARK: Private private enum CodingKeys: String, CodingKey { case text = "t" case fontSize = "s" case fontFamily = "f" case justification = "j" case tracking = "tr" case lineHeight = "lh" case baseline = "ls" case fillColorData = "fc" case strokeColorData = "sc" case strokeWidth = "sw" case strokeOverFill = "of" case textFramePosition = "ps" case textFrameSize = "sz" } }
apache-2.0
5e485fb8807caf9c825ffdfd5ae4d6ea
25.300813
90
0.704482
4.26781
false
false
false
false
MHaubenstock/Endless-Dungeon
EndlessDungeon/EndlessDungeon/Cell.swift
1
1675
// // Cell.swift // EndlessDungeon // // Created by Michael Haubenstock on 9/25/14. // Copyright (c) 2014 Michael Haubenstock. All rights reserved. // import Foundation import SpriteKit class Cell { var index : (Int, Int) var cellType : CellType var cellImage : String var position : CGPoint var itemInCell : Item? var characterInCell : Character? var openableInCell : Openable? enum CellType { case Entrance case Exit case Wall case Empty } init() { index = (0, 0) cellType = .Wall position = CGPoint(x: 0, y: 0) cellImage = "UnexcevetedTile.png" } init(theIndex : (Int, Int)) { index = theIndex cellType = .Wall position = CGPoint(x: 0, y: 0) cellImage = "UnexcevetedTile.png" } init(type : CellType) { index = (0, 0) cellType = type position = CGPoint(x: 0, y: 0) cellImage = "UnexcevetedTile.png" } init(theIndex : (Int, Int), type : CellType) { index = theIndex cellType = type position = CGPoint(x: 0, y: 0) cellImage = "UnexcevetedTile.png" } init (type : CellType, thePosition : CGPoint) { index = (0, 0) cellType = type position = thePosition cellImage = "UnexcevetedTile.png" } init (theIndex : (Int, Int), type : CellType, thePosition : CGPoint) { index = theIndex cellType = type position = thePosition cellImage = "UnexcevetedTile.png" } func interact() { } }
mit
3fcbb61299b7ec2bdac7fd4db251bbf5
19.439024
72
0.539104
3.850575
false
false
false
false
edx/edx-app-ios
Test/FeedTests.swift
2
816
// // FeedTests.swift // edX // // Created by Akiva Leffert on 12/26/15. // Copyright © 2015 edX. All rights reserved. // @testable import edX class FeedTests : XCTestCase { func testMap() { var counter = 0 let feed = Feed<Int> {stream in let source = OEXStream(value:counter) stream.backWithStream(source) counter = counter + 1 } let valueFeed = feed.map { $0.description } valueFeed.output.listenOnce(self) { XCTAssertEqual($0.value!, "0") } valueFeed.refresh() waitForStream(valueFeed.output) valueFeed.refresh() valueFeed.output.listenOnce(self) { XCTAssertEqual($0.value!, "1") } waitForStream(valueFeed.output) } }
apache-2.0
c36a909777cff27fbd5db96b92757073
22.285714
51
0.557055
4.054726
false
true
false
false
fernandomarins/food-drivr-pt
hackathon-for-hunger/Location.swift
1
924
// // Location.swift // hackathon-for-hunger // // Created by Ian Gristock on 4/1/16. // Copyright © 2016 Hacksmiths. All rights reserved. // import Foundation import RealmSwift import MapKit import ObjectMapper class Location: Object, Mappable { typealias JsonDict = [String: AnyObject] var latitude: Double = 0.0 var longitude: Double = 0.0 dynamic var estimated: NSDate? = nil dynamic var actual: NSDate? = nil var coordinates: CLLocationCoordinate2D? { return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } required convenience init?(_ map: Map) { self.init() } func mapping(map: Map) { latitude <- map["latitude"] longitude <- map["longitude"] estimated <- (map["estimated"], DateTransform()) actual <- (map["participants.driver"], DateTransform()) } }
mit
4dbb54a05ad03dfba780dbdbd9c0c6c1
24.666667
79
0.624052
4.333333
false
false
false
false
thefuntasty/Sonar
Example/Sonar/ViewController.swift
1
2141
import CoreLocation import MapKit import Sonar import UIKit final class ViewController: UIViewController { @IBOutlet private weak var sonarView: SonarView! private lazy var distanceFormatter: MKDistanceFormatter = MKDistanceFormatter() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.sonarView.delegate = self self.sonarView.dataSource = self } @IBAction private func reloadData(_ sender: AnyObject) { sonarView.reloadData() } } extension ViewController: SonarViewDataSource { func numberOfWaves(sonarView: SonarView) -> Int { 4 } func sonarView(sonarView: SonarView, numberOfItemForWaveIndex waveIndex: Int) -> Int { switch waveIndex { case 0: return 2 case 1: return 3 case 2: return 4 default: return 2 } } func sonarView(sonarView: SonarView, itemViewForWave waveIndex: Int, atIndex: Int) -> SonarItemView { let itemView = self.newItemView() itemView.imageView.image = randomAvatar() return itemView } // MARK: - Helpers private func randomAvatar() -> UIImage { UIImage(named: "avatar\(Int.random(in: 1...3))")! } private func newItemView() -> TestSonarItemView { // swiftlint:disable:next force_cast return Bundle.main.loadNibNamed("TestSonarItemView", owner: self, options: nil)!.first as! TestSonarItemView } } extension ViewController: SonarViewDelegate { func sonarView(sonarView: SonarView, didSelectObjectInWave waveIndex: Int, atIndex: Int) { print("Did select item in wave \(waveIndex) at index \(atIndex)") } func sonarView(sonarView: SonarView, textForWaveAtIndex waveIndex: Int) -> String? { if self.sonarView(sonarView: sonarView, numberOfItemForWaveIndex: waveIndex).isMultiple(of: 2) { return self.distanceFormatter.string(fromDistance: 100.0 * Double(waveIndex + 1)) } else { return nil } } }
mit
eb28b42d7eb0febb5caebdf5c901bac9
27.546667
116
0.651565
4.441909
false
false
false
false
sameertotey/LimoService
LimoService/CustomerMenuViewController.swift
1
4472
// // CustomerMenuViewController.swift // LimoService // // Created by Sameer Totey on 5/13/15. // Copyright (c) 2015 Sameer Totey. All rights reserved. // import UIKit class CustomerMenuViewController: MainMenuViewController { var listner: MapLocationSelectViewController! override var comments: String { didSet { listner?.specialComments = comments } } override var numBags: Int { didSet { listner?.numBags = numBags } } override var numPassengers: Int { didSet { listner?.numPassengers = numPassengers } } override var preferredVehicle: String { didSet { listner?.preferredVehicle = preferredVehicle } } override func viewDidLoad() { super.viewDidLoad() numPassengersCell.configureSteppers(Double(numPassengers), minimum: 0, maximum: 10, step: 1) numPassengersCell.delegate = self numBagsCell.configureSteppers(Double(numBags), minimum: 0, maximum: 10, step: 1) numBagsCell.delegate = self preferredVehicleCell.configureSegmentedControl() preferredVehicleCell.delegate = self commentCell.delegate = self } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.row { case 0: goHome() case 1: performSegueWithIdentifier("Destination", sender: nil) case 2: performSegueWithIdentifier("History", sender: nil) case 3: performSegueWithIdentifier("Profile", sender: nil) case 4: goHome() case 5: goHome() default: break } } // MARK: - Navigation // override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // println("prepare for segue") // if let identifier = segue.identifier { // switch identifier { // case "Profile": // println("segue from main menu to Profile") // if let toNavVC = segue.destinationViewController as? UINavigationController { // if let toVC = (segue.destinationViewController.viewControllers as? [UIViewController])?.first as? UserProfileTableViewController { // toVC.modalPresentationStyle = .Custom // toVC.transitioningDelegate = self.transitioningDelegate // } // toNavVC.modalPresentationStyle = .Custom // toNavVC.transitioningDelegate = self.transitioningDelegate // } // // case "History": // if let toNavVC = segue.destinationViewController as? UINavigationController { // if let toVC = (segue.destinationViewController.viewControllers as? [UIViewController])?.first as? RequestsTableViewController { // toVC.modalPresentationStyle = .Custom // toVC.transitioningDelegate = self.transitioningDelegate // } // toNavVC.modalPresentationStyle = .Custom // toNavVC.transitioningDelegate = self.transitioningDelegate // } // case "Destination": // if let toNavVC = segue.destinationViewController as? UINavigationController { // toNavVC.modalPresentationStyle = .Custom // toNavVC.transitioningDelegate = self.transitioningDelegate // } // default: // break // } // } // } @IBAction func unwindToHome(sender: UIStoryboardSegue) { let sourceViewController: AnyObject = sender.sourceViewController // Pull any data from the view controller which initiated the unwind segue. // This is a destination search return if let sVC = sourceViewController as? LocationSelectionViewController { // if let presentingViewController = presentingViewController { // println("\(presentingViewController)") // } listner?.toLocation = sVC.selectedLocation } // // This is a history search return // if let sVC = sourceViewController as? RequestsTableViewController { // listner?.limoRequest = sVC.selectedRequest // } goHome() } }
mit
dc13997ce47f88912a24f65346a598e5
36.579832
152
0.594812
5.493857
false
false
false
false
mshhmzh/firefox-ios
Storage/Bookmarks/CachingItemSource.swift
4
6285
/* 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 Deferred import Foundation import Shared private let log = Logger.syncLogger private class CachedSource { // We track not just mappings between values and non-nil items, but also whether we've tried // to look up a value at all. This allows us to distinguish between a cache miss and a // cache hit that didn't find an item in the backing store. // We expect, given our prefetching, that cache misses will be rare. private var cache: [GUID: BookmarkMirrorItem] = [:] private var seen: Set<GUID> = Set() subscript(guid: GUID) -> BookmarkMirrorItem? { get { return self.cache[guid] } set(value) { self.cache[guid] = value } } func lookup(guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>>? { guard self.seen.contains(guid) else { log.warning("Cache miss for \(guid).") return nil } guard let found = self.cache[guid] else { log.verbose("Cache hit, but no record found for \(guid).") return deferMaybe(NoSuchRecordError(guid: guid)) } log.verbose("Cache hit for \(guid).") return deferMaybe(found) } var isEmpty: Bool { return self.cache.isEmpty } // fill and seen are separate: we won't find every item in the DB. func fill(items: [GUID: BookmarkMirrorItem]) -> Success { for (x, y) in items { self.cache[x] = y } return succeed() } func markSeen(guid: GUID) { self.seen.insert(guid) } func markSeen<T: CollectionType where T.Generator.Element == GUID>(guids: T) { self.seen.unionInPlace(guids) } func takingGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> { var out: [GUID: BookmarkMirrorItem] = [:] guids.forEach { if let v = self.cache[$0] { out[$0] = v } } return deferMaybe(out) } } // Sorry about the boilerplate. // These are separate protocols so that the method names don't collide when implemented // by the same class, but that means extracting more base implementation is more trouble than // it's worth. public class CachingLocalItemSource: LocalItemSource { private let cache: CachedSource private let source: LocalItemSource public init(source: LocalItemSource) { self.cache = CachedSource() self.source = source } public func getLocalItemWithGUID(guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { if let found = self.cache.lookup(guid) { return found } return self.source.getLocalItemWithGUID(guid) >>== effect { self.cache.markSeen(guid) self.cache[guid] = $0 } } public func getLocalItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> { return self.prefetchLocalItemsWithGUIDs(guids) >>> { self.cache.takingGUIDs(guids) } } public func prefetchLocalItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Success { log.debug("Prefetching \(guids.count) local items: \(guids.prefix(10))….") if guids.isEmpty { return succeed() } return self.source.getLocalItemsWithGUIDs(guids) >>== { self.cache.markSeen(guids) return self.cache.fill($0) } } } public class CachingMirrorItemSource: MirrorItemSource { private let cache: CachedSource private let source: MirrorItemSource public init(source: MirrorItemSource) { self.cache = CachedSource() self.source = source } public func getMirrorItemWithGUID(guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { if let found = self.cache.lookup(guid) { return found } return self.source.getMirrorItemWithGUID(guid) >>== effect { self.cache.markSeen(guid) self.cache[guid] = $0 } } public func getMirrorItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> { return self.prefetchMirrorItemsWithGUIDs(guids) >>> { self.cache.takingGUIDs(guids) } } public func prefetchMirrorItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Success { log.debug("Prefetching \(guids.count) mirror items: \(guids.prefix(10))….") if guids.isEmpty { return succeed() } return self.source.getMirrorItemsWithGUIDs(guids) >>== { self.cache.markSeen(guids) return self.cache.fill($0) } } } public class CachingBufferItemSource: BufferItemSource { private let cache: CachedSource private let source: BufferItemSource public init(source: BufferItemSource) { self.cache = CachedSource() self.source = source } public func getBufferItemWithGUID(guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { if let found = self.cache.lookup(guid) { return found } return self.source.getBufferItemWithGUID(guid) >>== effect { self.cache.markSeen(guid) self.cache[guid] = $0 } } public func getBufferItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> { return self.prefetchBufferItemsWithGUIDs(guids) >>> { self.cache.takingGUIDs(guids) } } public func prefetchBufferItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Success { log.debug("Prefetching \(guids.count) buffer items: \(guids.prefix(10))….") if guids.isEmpty { return succeed() } return self.source.getBufferItemsWithGUIDs(guids) >>== { self.cache.markSeen(guids) return self.cache.fill($0) } } }
mpl-2.0
937bbfa70fc9abed81c10fad26129deb
32.404255
151
0.628922
4.443737
false
false
false
false
Touchwonders/Transition
Examples/TabBarTransitionsExample/TabBarTransitionsExample/Transitioning/Transitions/ShapeTransitionAnimation.swift
1
4204
// // MIT License // // Copyright (c) 2017 Touchwonders B.V. // // 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 Transition class ShapeTransitionAnimation : TransitionAnimation { /// The operation will be useful later on to add some directionality in the transition animation let operation: TransitionOperation private weak var topView: UIView? private var targetEffect: UIVisualEffect? private var visualEffectView: UIVisualEffectView! let rightToLeft: Bool init(for operation: TransitionOperation, rightToLeft: Bool = false) { self.operation = operation self.rightToLeft = rightToLeft } /// We have a single animation layer (with full range, set by default). var layers: [AnimationLayer] { return [AnimationLayer(timingParameters: AnimationTimingParameters(animationCurve: .easeOut), animation: self.animation)] } /// We're about to animate. Set up any initial view state (alpha / transform etc.) and /// add the toView and any additional chrome views to the transition context's containerView. func setup(in operationContext: TransitionOperationContext) { let transitionContext = operationContext.context // Ensure the toView has the correct size and position transitionContext.toView.frame = transitionContext.finalFrame(for: transitionContext.toViewController) // Create a visual effect view and animate the effect in the transition animator targetEffect = UIBlurEffect(style: .dark) visualEffectView = UIVisualEffectView(effect: nil) visualEffectView.frame = transitionContext.containerView.bounds visualEffectView.autoresizingMask = [.flexibleWidth,.flexibleHeight] transitionContext.containerView.addSubview(visualEffectView) topView = transitionContext.toView transitionContext.containerView.addSubview(transitionContext.toView) let directional: CGFloat = (operation.isIncreasingIndex != rightToLeft) ? 1.0 : -1.0 // isIncreasingIndex XOR rightToLeft topView?.transform = CGAffineTransform(translationX: directional * transitionContext.containerView.bounds.width * 1.2, y: 0).scaledBy(x: 1.2, y: 1.2).rotated(by: directional * 0.05 * .pi) } /// The animation function that will be given to a UIViewPropertyAnimator. /// You should therefore regard this as the body of an animation, so do not /// perform any UIView.animate(withDuration: , animations: ) stuff here! func animation() { topView?.transform = .identity visualEffectView.effect = targetEffect } /// The completion function that will be given to a UIViewPropertyAnimator. /// Perform any required cleanup here, such as removing chrome views. /// You might also need to reset the toView if the transition was cancelled (i.e. position != .end) func completion(position: UIViewAnimatingPosition) { topView?.transform = .identity visualEffectView.removeFromSuperview() visualEffectView = nil } }
mit
98db1c78c2ac5c8f58eb6271e115a3c1
45.711111
195
0.716698
5.126829
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
Solutions/Solutions/Hard/Hard_087_Scramble_String.swift
1
3582
/* https://leetcode.com/problems/scramble-string/ #87 Scramble String Level: hard Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = "great": great / \ gr eat / \ / \ g r e at / \ a t To scramble the string, we may choose any non-leaf node and swap its two children. For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat". rgeat / \ rg eat / \ / \ r g e at / \ a t We say that "rgeat" is a scrambled string of "great". Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae". rgtae / \ rg tae / \ / \ r g ta e / \ t a We say that "rgtae" is a scrambled string of "great". Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1. Inspired by @Charles_p (recursion) at https://leetcode.com/discuss/3632/any-better-solution and @dtx0 (iteration) at https://leetcode.com/discuss/3632/any-better-solution */ import Foundation private extension String { subscript (range: Range<Int>) -> String { guard let localEndIndex = self.index(self.startIndex, offsetBy: range.upperBound, limitedBy: self.endIndex) else { return String(self[self.index(self.startIndex, offsetBy: range.lowerBound)..<self.endIndex]) } return String(self[self.index(self.startIndex, offsetBy: range.lowerBound)..<localEndIndex]) } subscript (index: Int) -> Character { return self[self.index(self.startIndex, offsetBy: index)] } } struct Hard_087_Scramble_String { static func isScramble(s1: String?, s2: String?) -> Bool { return isScramble_recursion(s1: s1, s2: s2) } static func isScramble_recursion(s1: String?, s2: String?) -> Bool { if s1 == nil || s2 == nil || s1?.count != s2?.count { return false } if s1 == s2 { return true } if (s1?.sorted())! != (s2?.sorted())! { return false } let count: Int = (s1?.count)! for i in 1 ..< count { if isScramble_recursion(s1: s1![0..<i], s2: s2![0..<i]) && isScramble_recursion(s1: s1![i..<Int.max], s2: s2![i..<Int.max]) { return true } if isScramble_recursion(s1: s1![0..<i], s2: s2![(s2?.count)! - i..<Int.max]) && isScramble_recursion(s1: s1![i..<Int.max], s2: s2![0..<(s2?.count)! - i]) { return true } } return false } static func isScramble_iteration(s1: String?, s2: String?) -> Bool { if s1 == nil || s2 == nil || s1?.count != s2?.count { return false } let len = s1?.count var dp: Array<Array<Array<Bool>>> = Array<Array<Array<Bool>>>(repeating: Array<Array<Bool>>(repeating: Array<Bool>(repeating: false, count: 100), count: 100), count: 100) for i in (0...len! - 1).reversed() { for j in (0...len!-1).reversed() { dp[i][j][1] = (s1![i] == s2![j]) var l = 2 while i + l <= len! && j + l <= len! { for n in 1 ..< l { dp[i][j][l] = dp[i][j][l] || ( dp[i][j][n] && dp[i+n][j+n][l-n] ) dp[i][j][l] = dp[i][j][l] || ( dp[i][j+l-n][n] && dp[i+n][j][l-n] ) } l += 1 } } } return dp[0][0][len!] } }
mit
e652aa8ca8ac5290b709670997ebebd1
31.563636
178
0.546064
3.155947
false
false
false
false
LYM-mg/DemoTest
其他功能/SwiftyDemo/Pods/SnapKit/Source/Typealiases.swift
58
1749
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // 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 #if os(iOS) || os(tvOS) import UIKit #if swift(>=4.2) typealias LayoutRelation = NSLayoutConstraint.Relation typealias LayoutAttribute = NSLayoutConstraint.Attribute #else typealias LayoutRelation = NSLayoutRelation typealias LayoutAttribute = NSLayoutAttribute #endif typealias LayoutPriority = UILayoutPriority #else import AppKit typealias LayoutRelation = NSLayoutConstraint.Relation typealias LayoutAttribute = NSLayoutConstraint.Attribute typealias LayoutPriority = NSLayoutConstraint.Priority #endif
mit
ce812bc589f9e30c73a2866df74fe1c6
40.642857
81
0.76215
4.778689
false
false
false
false
wvabrinskas/PopSwitch
PopSwitch/PopSwitch.swift
1
8268
// // PopSwitch.swift // PopSwitch // // Created by William Vabrinskas on 7/27/17. // Copyright © 2017 williamvabrinskas. All rights reserved. // import Foundation import UIKit import CoreGraphics import QuartzCore public typealias SwitchColor = (background: CGColor?, switch: CGColor?) open class PopSwitch: UIView { public enum State { case On,Off } public enum SwitchType { case Radio, Switch } open var state:State! open var delegate:PopSwitchDelegate? private var color:SwitchColor? private static let height:CGFloat = 30.0 private var switchType: SwitchType! private lazy var startOnXOrigin:CGFloat = { return self.frame.width - self.circle.frame.size.width }() private lazy var onXOrigin: CGFloat = { return self.frame.width - (self.circle.frame.size.width / 2) }() private lazy var offXOrigin: CGFloat = { return self.circle.frame.size.width / 2 }() private lazy var switchLayer:CAShapeLayer = { let shapeLayer = CAShapeLayer() shapeLayer.frame = self.bounds shapeLayer.path = UIBezierPath.init(roundedRect: self.bounds, cornerRadius: PopSwitch.height).cgPath if self.switchType == .Switch { if self.state == .On { shapeLayer.fillColor = self.color?.background ?? UIColor.white.cgColor self.circle.frame.origin = CGPoint(x: self.startOnXOrigin, y: 0) } else { shapeLayer.fillColor = self.getDarkerColor() self.circle.frame.origin = CGPoint(x: 0, y: 0) } } else { shapeLayer.fillColor = self.getDarkerColor() shapeLayer.lineWidth = 5.0 shapeLayer.strokeColor = self.color?.background ?? UIColor.white.cgColor } shapeLayer.addSublayer(self.circle) return shapeLayer }() private lazy var circle:CAShapeLayer = { let circleLayer = CAShapeLayer() var height = PopSwitch.height var center = CGPoint(x:0, y:0) if self.switchType == .Radio { height = PopSwitch.height - 7 center = CGPoint(x: (PopSwitch.height / 2) - (height / 2), y: (PopSwitch.height / 2) - (height / 2)) } circleLayer.frame = CGRect(x: center.x, y: center.y, width: height, height: height) circleLayer.path = UIBezierPath.init(ovalIn: circleLayer.bounds).cgPath circleLayer.fillColor = self.color?.switch ?? UIColor.green.cgColor return circleLayer }() fileprivate func getDarkerColor() -> CGColor { var newColor:CGColor? if let components = color?.background?.components { if components.count >= 3 { let r = (components[0] * 255) - 120 let g = (components[1] * 255) - 120 let b = (components[2] * 255) - 120 newColor = UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1.0).cgColor } } return newColor ?? color?.background ?? UIColor.white.cgColor } fileprivate func onSpringAnimation() -> CASpringAnimation { let spring = CASpringAnimation(keyPath: "position") spring.damping = 10.0 spring.duration = spring.settlingDuration spring.repeatCount = 0 spring.speed = 2 spring.toValue = [onXOrigin, self.circle.frame.size.height / 2] spring.initialVelocity = 0 spring.fillMode = .both spring.isRemovedOnCompletion = false return spring } fileprivate func offSpringAnimation() -> CASpringAnimation { let spring = CASpringAnimation(keyPath: "position") spring.damping = 10.0 spring.speed = 2 spring.duration = spring.settlingDuration spring.repeatCount = 0 spring.toValue = [offXOrigin, self.circle.frame.size.height / 2] spring.initialVelocity = 0 spring.fillMode = .both spring.isRemovedOnCompletion = false return spring } fileprivate func scaleDownAnimation() -> CASpringAnimation { let spring = CASpringAnimation(keyPath: "transform.scale") spring.damping = 10.0 spring.speed = 2 spring.duration = spring.settlingDuration spring.repeatCount = 0 spring.toValue = [0.0,0.0] if switchType == .Switch { spring.toValue = [0.6,0.6] } spring.initialVelocity = 0 spring.fillMode = .both spring.isRemovedOnCompletion = false return spring } fileprivate func scaleUpAnimation() -> CASpringAnimation { let spring = CASpringAnimation(keyPath: "transform.scale") spring.damping = 10.0 spring.speed = 2 spring.duration = spring.settlingDuration spring.repeatCount = 0 spring.toValue = [1.0,1.0] spring.initialVelocity = 0 spring.fillMode = .both spring.isRemovedOnCompletion = false return spring } fileprivate func colorOnChangeAnimation() -> CABasicAnimation { //backgroundColor let colorChange = CABasicAnimation(keyPath: "fillColor") colorChange.toValue = self.color?.background ?? UIColor.white.cgColor colorChange.isRemovedOnCompletion = false colorChange.fillMode = .both colorChange.repeatCount = 0 return colorChange } fileprivate func colorOffChangeAnimation() -> CABasicAnimation { //backgroundColor let colorChange = CABasicAnimation(keyPath: "fillColor") colorChange.toValue = getDarkerColor() colorChange.repeatCount = 0 colorChange.fillMode = .both colorChange.isRemovedOnCompletion = false return colorChange } private func animate(to state:State) { if switchType == .Switch { let scaleGroup = CAAnimationGroup() scaleGroup.animations = [self.scaleDownAnimation(), self.scaleUpAnimation()] circle.add(scaleGroup, forKey: "scale") if state == .On { //animating to the ON position circle.add(self.onSpringAnimation(), forKey: "onAnimation") switchLayer.add(self.colorOnChangeAnimation(), forKey: "onColorAnimation") } else { circle.add(self.offSpringAnimation(), forKey: "offAnimation") switchLayer.add(self.colorOffChangeAnimation(), forKey: "offColorAnimation") } } else { if state == .On { circle.add(self.scaleUpAnimation(), forKey: "onAnimation") } else { circle.add(self.scaleDownAnimation(), forKey: "offAnimation") } } } public init(position state:State, color: SwitchColor?, type:SwitchType) { let width = type == .Radio ? PopSwitch.height : PopSwitch.height * 1.8 super.init(frame: CGRect(x: 0, y: 0, width: width, height: PopSwitch.height)) self.switchType = type self.backgroundColor = .clear self.state = state self.color = color self.layer.addSublayer(switchLayer) let touchGesture = UITapGestureRecognizer(target: self, action: #selector(changeState)) touchGesture.numberOfTapsRequired = 1 touchGesture.numberOfTouchesRequired = 1 self.addGestureRecognizer(touchGesture) } //through touch gesture @objc private func changeState() { if self.state == .On { self.state = .Off } else { self.state = .On } animate(to: self.state) delegate?.valueChanged(control: self) } //programmatically set state open func setState(state: State, callback:Bool) { self.state = state animate(to: state) if callback { delegate?.valueChanged(control: self) } } required public init?(coder aDecoder: NSCoder) { fatalError("Cannot add PopSwitch as part of interface builder. Sorry =(") } }
mit
3992f263fcfac041fe6489839c3a700a
33.020576
112
0.598282
4.654842
false
false
false
false
zwaldowski/ParksAndRecreation
Latest/Deriving Scroll Views.playground/Sources/DerivingContentSizeCollectionView.swift
1
3010
// // DerivingContentSizeCollectionView.swift // Deriving // // Created by Zachary Waldowski on 10/26/16. // Copyright © 2016 Big Nerd Ranch. All rights reserved. // import UIKit public final class DerivingContentSizeCollectionView: UICollectionView, ScrollViewBoundsDeriving { private let helper = ScrollViewDerivedBoundsHelper() private func commonInit() { helper.owner = self helper.isEnabled = !isScrollEnabled } public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } deinit { helper.reset() } // MARK: - UIScrollView public override var contentSize: CGSize { didSet { if helper.isEnabled { invalidateIntrinsicContentSize() } } } public override var isScrollEnabled: Bool { didSet { helper.isEnabled = !isScrollEnabled invalidateIntrinsicContentSize() } } // MARK: - UIView public override var frame: CGRect { get { return super.frame } set { helper.whileClippingBounds { super.frame = newValue } } } public override var bounds: CGRect { get { return helper.shouldClipBounds ? helper.visibleBounds(forOriginalBounds: super.bounds) : super.bounds } set { helper.whileClippingBounds { super.bounds = newValue } } } public override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) helper.reset() } public override func didMoveToWindow() { super.didMoveToWindow() helper.validate() if helper.isEnabled { invalidateIntrinsicContentSize() } } public override func layoutSubviews() { helper.validate() helper.whileClippingBounds { super.layoutSubviews() } if helper.shouldSizeToFit && bounds.size != collectionViewLayout.collectionViewContentSize { invalidateIntrinsicContentSize() } } public override var intrinsicContentSize: CGSize { guard helper.shouldSizeToFit else { return super.intrinsicContentSize } return collectionViewLayout.collectionViewContentSize } // MARK: - ScrollViewBoundsDeriving func invalidateLayoutForVisibleBoundsChange() { // assigning bounds to get: // - collection view layout invalidation // - set the "scheduledUpdateVisibleCells" flag let oldBounds = super.bounds super.bounds = helper.visibleBounds(forOriginalBounds: oldBounds) super.bounds = oldBounds } }
mit
ca7e2a402b8cbc251461949898f220cb
23.663934
113
0.615155
5.561922
false
false
false
false