hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
4b053c6c0e542b9f4e362390dfe34e5a3bfbc535
900
// // LiteRSSTests.swift // LiteRSSTests // // Created by CoderDream on 2020/1/2. // Copyright © 2020 CoderDream. All rights reserved. // import XCTest @testable import LiteRSS class LiteRSSTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
25.714286
111
0.654444
690bf10e1416095aa222a689562c56d1f4a79157
813
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation class LocationWithPaginationTitleBubbleCell: LocationBubbleCell { override func setupViews() { super.setupViews() roomCellContentView?.showPaginationTitle = true } }
31.269231
75
0.733087
bb7910193c7e470d0e79c50097705e66b9d54b8d
3,073
// // NetworkDispatcher.swift // PuccaVideo // Copyright © 2018 Isabela Karen Louli. All rights reserved. // import RxSwift public enum HTTPMethod: String { case get = "GET" } protocol NetworkDispatcherProtocol { init(url: URL) func response<T: Codable>(of type: T.Type, from path: String, method: HTTPMethod) -> Observable<(T?)> } class NetworkDispatcher: NetworkDispatcherProtocol { // MARK: - Properties private(set) var url: URL // MARK: - Lifecycle /** Initialize the dispatcher with a base endpoint url - Parameter url: endpoint to request. */ required init(url: URL) { self.url = url } // MARK: - Responses // /** // - Parameter type: generic object type that conforms with Codable // - Returns: an Observable of item // */ public func response<T: Codable>(of type: T.Type, from path: String, method: HTTPMethod) -> Observable<(T?)> { return Observable.create { observable in self.dispatch(path: path, method: method, { (data, error) in if let error = error { // If the request couldn't be completed with success // send an error sequence so the subscribers can be notified and // the observable can be automatically deallocated observable.onError(error) } else if let data = data { let serializedObject = try? JSONDecoder().decode(T.self, from: data) observable.onNext(serializedObject) } else { observable.onNext(nil) } observable.onCompleted() }) return Disposables.create() } } // MARK: - URLSession handler private func dispatch(path: String, method: HTTPMethod, _ completion: @escaping (_ data: Data?, _ error: NetworkError?) -> Void) { guard let requestURL = getURL(with: path) else { completion(nil, NetworkError(message: "service.invalid.url".localized)) return } var request = URLRequest(url: requestURL) request.httpMethod = method.rawValue URLSession.shared.dataTask(with: request) { data, res, error in guard let statusCode = (res as? HTTPURLResponse)?.statusCode, (200...299 ~= statusCode) else { completion(nil, NetworkError(message: "service.error.generic".localized)) return } completion(data, nil) }.resume() } // MARK: - Helpers public func getURL(with path: String) -> URL? {//addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) guard let urlString = url.appendingPathComponent(path).absoluteString.removingPercentEncoding, let requestUrl = URL(string: urlString) else { return nil } return requestUrl } }
31.680412
134
0.569476
62d1cf2228e8298deb66878af873e2d3db5c6a63
469
// // ViewControllerCustomNaviBar.swift // NavigationDemo // // Created by dengliwen on 2020/9/2. // Copyright © 2020 dsjk. All rights reserved. // import UIKit /// 自定义导航栏样式协议 public protocol CustomNavigationBar { var navigationBarStyle: NavigationBarStyleProtocol { get } } public protocol NavigationBarStyleProtocol { func refresh(_ navigationBar: UINavigationBar?, from fromViewController: UIViewController?, to toViewController: UIViewController?) }
24.684211
135
0.771855
ccff477944bdda49bfdcd449e3c9808cb4c89ce1
5,640
// // Copyright © 2017 Jan Gorman. All rights reserved. // import XCTest import Hippolyte final class HippolyteTests: XCTestCase { override func tearDown() { super.tearDown() Hippolyte.shared.stop() } func testUnmatchedRequestThrows() { let request = TestRequest(method: .GET, url: URL(string: "http://www.apple.com")!) XCTAssertThrowsError(try Hippolyte.shared.response(for: request)) } func testMatchedRequest() { let url = URL(string: "http://www.apple.com")! var stub = StubRequest(method: .GET, url: url) let response = StubResponse(statusCode: 404) stub.response = response Hippolyte.shared.add(stubbedRequest: stub) let request = TestRequest(method: .GET, url: url) let result = try? Hippolyte.shared.response(for: request) XCTAssertEqual(result, response) Hippolyte.shared.clearStubs() } func testStubIsReplaceable() { let url = URL(string: "http://www.apple.com")! var stub1 = StubRequest(method: .GET, url: url) let response1 = StubResponse(statusCode: 404) stub1.response = response1 Hippolyte.shared.add(stubbedRequest: stub1) var stub2 = StubRequest(method: .GET, url: url) let response2 = StubResponse(statusCode: 200) stub2.response = response2 Hippolyte.shared.add(stubbedRequest: stub2) let request = TestRequest(method: .GET, url: url) let result = try? Hippolyte.shared.response(for: request) XCTAssertEqual(result, response2) Hippolyte.shared.clearStubs() } func testItStubsRegularNetworkCall() { let url = URL(string: "http://www.apple.com")! var stub = StubRequest(method: .GET, url: url) var response = StubResponse() let body = Data("Hippolyte".utf8) response.body = body stub.response = response Hippolyte.shared.add(stubbedRequest: stub) Hippolyte.shared.start() let expectation = self.expectation(description: "Stubs network call") let session = URLSession(configuration: .default) let task = session.dataTask(with: url) { data, _, _ in XCTAssertEqual(data, body) expectation.fulfill() } task.resume() wait(for: [expectation], timeout: 1) } func testItStubsRedirectNetworkCall() { let url = URL(string: "http://www.apple.com")! var stub = StubRequest(method: .GET, url: url) var response = StubResponse() response = StubResponse(statusCode: 301) response.headers = ["Location": "https://example.com/not/here"] let body = Data("Hippolyte Redirect".utf8) response.body = body stub.response = response Hippolyte.shared.add(stubbedRequest: stub) Hippolyte.shared.start() let expectation = self.expectation(description: "Stubs network redirect call") let delegate = BlockRedirectDelegate() let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil) let task = session.dataTask(with: url) { data, _, _ in XCTAssertEqual(data, body) expectation.fulfill() } task.resume() wait(for: [expectation], timeout: 1) XCTAssertEqual(delegate.redirectCallCount, 1) } func testItDoesNotStubsRedirectNoContent() { let url = URL(string: "http://www.apple.com")! var stub = StubRequest(method: .GET, url: url) var response = StubResponse() response = StubResponse(statusCode: 304) stub.response = response Hippolyte.shared.add(stubbedRequest: stub) Hippolyte.shared.start() let expectation = self.expectation(description: "Dies not stub network redirect call") let delegate = BlockRedirectDelegate() let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil) let task = session.dataTask(with: url) { _, _, _ in expectation.fulfill() } task.resume() wait(for: [expectation], timeout: 1) XCTAssertEqual(delegate.redirectCallCount, 0) } func testThatHippolyteCouldBePausedAndResumed() { let url = URL(string: "http://www.apple.com")! var stub = StubRequest(method: .GET, url: url) var response = StubResponse() let body = Data("Hippolyte".utf8) response.body = body stub.response = response Hippolyte.shared.add(stubbedRequest: stub) Hippolyte.shared.start() let firstExpectation = self.expectation(description: "Stubs network calls") URLSession(configuration: .default).dataTask(with: url) { data, _, _ in XCTAssertEqual(data, body) firstExpectation.fulfill() }.resume() wait(for: [firstExpectation], timeout: 1) Hippolyte.shared.pause() let secondExpectation = self.expectation(description: "Stubs network calls paused") URLSession(configuration: .default).dataTask(with: url) { data, _, _ in XCTAssertNotEqual(data, body) secondExpectation.fulfill() }.resume() wait(for: [secondExpectation], timeout: 1) Hippolyte.shared.resume() let thirdExpectation = self.expectation(description: "Stubs network calls resumed") URLSession(configuration: .default).dataTask(with: url) { data, _, _ in XCTAssertEqual(data, body) thirdExpectation.fulfill() }.resume() wait(for: [thirdExpectation], timeout: 1) } } final class BlockRedirectDelegate: NSObject, URLSessionDelegate, URLSessionTaskDelegate { var redirectCallCount: Int = 0 func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { redirectCallCount += 1 // disables redirect responses completionHandler(nil) } }
31.864407
116
0.69273
dd46ff54d22e170e498ead56ec1d3fd0aeeb8066
977
// // calculatorTests.swift // calculatorTests // // Created by Apple on 2016/12/16. // Copyright © 2016年 Xinmeng Li. All rights reserved. // import XCTest @testable import calculator class calculatorTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.405405
111
0.635619
4a42ce1c04486d63eef8e5066454d3f96f7d60ab
2,243
// // AppDelegate.swift // ARFacebookShareKitActivity // // Created by alexruperez on 06/01/2016. // Copyright (c) 2016 alexruperez. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { // Override point for customization after application launch. UIActivity.replaceFacebookSharing() 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:. } }
46.729167
285
0.755239
1d46d2b559fe02ad6ad7a4796f1b071ff7ddf9c0
651
// // FlowLayoutViewController.swift // FlexibleRowHeightGridLayout // // Created by Ross Butler on 08/06/2019. // Copyright (c) 2019 Ross Butler. All rights reserved. // import UIKit class FlowLayoutViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! private let dataSource = DataSource() override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = dataSource if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize } } }
26.04
92
0.714286
6a52fda87884f51b4a1137e349badd36d600d3c9
2,483
// // OutlineView.swift // CodeEdit // // Created by Lukas Pistrol on 05.04.22. // import SwiftUI import WorkspaceClient import AppPreferences import Combine /// Wraps an ``OutlineViewController`` inside a `NSViewControllerRepresentable` struct OutlineView: NSViewControllerRepresentable { @StateObject var workspace: WorkspaceDocument @StateObject var prefs: AppPreferencesModel = .shared typealias NSViewControllerType = OutlineViewController func makeNSViewController(context: Context) -> OutlineViewController { let controller = OutlineViewController() controller.workspace = workspace controller.iconColor = prefs.preferences.general.fileIconStyle context.coordinator.controller = controller return controller } func updateNSViewController(_ nsViewController: OutlineViewController, context: Context) { nsViewController.iconColor = prefs.preferences.general.fileIconStyle nsViewController.rowHeight = rowHeight nsViewController.fileExtensionsVisibility = prefs.preferences.general.fileExtensionsVisibility nsViewController.shownFileExtensions = prefs.preferences.general.shownFileExtensions nsViewController.hiddenFileExtensions = prefs.preferences.general.hiddenFileExtensions nsViewController.updateSelection() return } func makeCoordinator() -> Coordinator { return Coordinator(workspace) } class Coordinator: NSObject { init(_ workspace: WorkspaceDocument) { self.workspace = workspace super.init() listener = workspace.listenerModel.$highlightedFileItem .sink(receiveValue: { [weak self] fileItem in guard let fileItem = fileItem else { return } self?.controller?.reveal(fileItem) }) } var listener: AnyCancellable? var workspace: WorkspaceDocument var controller: OutlineViewController? deinit { listener?.cancel() } } /// Returns the row height depending on the `projectNavigatorSize` in `AppPreferences`. /// /// * `small`: 20 /// * `medium`: 22 /// * `large`: 24 private var rowHeight: Double { switch prefs.preferences.general.projectNavigatorSize { case .small: return 20 case .medium: return 22 case .large: return 24 } } }
29.559524
102
0.668143
56593aa33c6207c33796e0c543f6fff38ee9e192
1,968
// // SheetyColorsConfig.swift // SheetyColors // // Created by Christoph Wendt on 03.02.19. // import UIKit /// A struct defining options for configuring a SheetyColors view. public struct SheetyColorsConfig: SheetyColorsConfigProtocol { /// Defines whether an opacity slider should be displayed or not. public var alphaEnabled: Bool /// Defines whether haptic feedback is supported when changing a slider's value. public var hapticFeedbackEnabled: Bool /// The initial color used when displaying the SheetyColors view. public var initialColor: UIColor /// A description text displayed inside the SheetyColors view. public var message: String? /// A title text displayed inside the SheetyColors view. public var title: String? /// The color model used by the SheetyColors view. public var type: SheetyColorsType /** Creates a SheetyColorsConfig instance. - Parameter: - alphaEnabled: Defines whether an opacity slider should be displayed or not. Defaults to `true`. - hapticFeedbackEnabled: Defines whether haptic feedback is supported when changing a slider's value. Defaults to `true`. - initialColor: The initial color used when displaying the SheetyColors view. Defaults to `.white`. - title: A title text displayed inside the SheetyColors view. Defaults to `nil`. - message: A description text displayed inside the SheetyColors view. Defaults to `nil`. - type: The color model used by the SheetyColors view. Defaults to `.rgb`. */ public init(alphaEnabled: Bool = true, hapticFeedbackEnabled: Bool = true, initialColor: UIColor = .white, title: String? = nil, message: String? = nil, type: SheetyColorsType = .rgb) { self.alphaEnabled = alphaEnabled self.hapticFeedbackEnabled = hapticFeedbackEnabled self.initialColor = initialColor self.message = message self.title = title self.type = type } }
39.36
189
0.716463
fc3cb9a069c6225cb8d7bf09b465edb1bfdf013b
18,972
// // MedicationTrackingTests.swift // BridgeAppTests // // Copyright © 2018 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import XCTest @testable import BridgeApp @testable import DataTracking import Research class MedicationTrackingNavigationTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testMedicationTrackingNavigation_FirstRun_AddDetailsLater() { NSLocale.setCurrentTest(Locale(identifier: "en_US")) let (items, sections) = buildMedicationItems() let medTracker = SBAMedicationTrackingStepNavigatorWithReminders(identifier: "Test", items: items, sections: sections) var taskResult: RSDTaskResult = RSDTaskResultObject(identifier: "medication") let (introStep, _) = medTracker.step(after: nil, with: &taskResult) XCTAssertNotNil(introStep) XCTAssertEqual(introStep?.identifier, SBATrackedItemsStepNavigator.StepIdentifiers.introduction.stringValue) guard let _ = introStep else { XCTFail("Failed to create the selection step. Exiting.") return } taskResult.appendStepHistory(with: introStep!.instantiateStepResult()) let (selectStep, _) = medTracker.step(after: introStep, with: &taskResult) XCTAssertNotNil(selectStep) guard let selectionStep = selectStep as? SBATrackedSelectionStepObject else { XCTFail("Failed to create the selection step. Exiting.") return } XCTAssertNil(medTracker.step(before: selectionStep, with: &taskResult)) XCTAssertEqual(medTracker.step(with: selectionStep.identifier)?.identifier, selectionStep.identifier) XCTAssertFalse(medTracker.hasStep(before: selectionStep, with: taskResult)) XCTAssertTrue(medTracker.hasStep(after: selectionStep, with: taskResult)) guard let firstResult = selectionStep.instantiateStepResult() as? SBATrackedItemsResult else { XCTFail("Failed to create the expected result. Exiting.") return } var selectionResult = firstResult selectionResult.updateSelected(to: ["medA2", "medB4"], with: selectionStep.items) taskResult.appendStepHistory(with: selectionResult) // Next step after selection is review. let (rStep, _) = medTracker.step(after: selectionStep, with: &taskResult) XCTAssertNotNil(rStep) guard let reviewStep = rStep as? SBATrackedMedicationReviewStepObject else { XCTFail("Failed to create the initial review step. Exiting. step: \(String(describing: rStep))") return } let forwardAction = reviewStep.action(for: .navigation(.goForward), on: reviewStep) XCTAssertNotNil(forwardAction) XCTAssertEqual(forwardAction?.buttonTitle, "Save") // Check navigation state XCTAssertNil(medTracker.step(before: reviewStep, with: &taskResult)) XCTAssertEqual(medTracker.step(with: reviewStep.identifier)?.identifier, reviewStep.identifier) XCTAssertFalse(medTracker.hasStep(before: reviewStep, with: taskResult)) XCTAssertTrue(medTracker.hasStep(after: reviewStep, with: taskResult)) guard let secondResult = reviewStep.instantiateStepResult() as? SBAMedicationTrackingResult else { XCTFail("Failed to create the expected result. Exiting.") return } XCTAssertEqual(secondResult.selectedAnswers.count, 2) XCTAssertFalse(secondResult.hasRequiredValues) taskResult.appendStepHistory(with: secondResult) // If all details aren't filled in then exit. let (finalStep, _) = medTracker.step(after: reviewStep, with: &taskResult) XCTAssertNil(finalStep) } func testMedicationTrackingNavigation_FirstRun_SomeDetailsAdded() { NSLocale.setCurrentTest(Locale(identifier: "en_US")) let (items, sections) = buildMedicationItems() let medTracker = SBAMedicationTrackingStepNavigatorWithReminders(identifier: "Test", items: items, sections: sections) var taskResult: RSDTaskResult = RSDTaskResultObject(identifier: "medication") let (introStep, _) = medTracker.step(after: nil, with: &taskResult) XCTAssertNotNil(introStep) XCTAssertEqual(introStep?.identifier, SBATrackedItemsStepNavigator.StepIdentifiers.introduction.stringValue) guard let _ = introStep else { XCTFail("Failed to create the selection step. Exiting.") return } taskResult.appendStepHistory(with: introStep!.instantiateStepResult()) let (selectStep, _) = medTracker.step(after: introStep, with: &taskResult) XCTAssertNotNil(selectStep) guard let selectionStep = selectStep as? SBATrackedSelectionStepObject else { XCTFail("Failed to create the selection step. Exiting.") return } guard let firstResult = selectionStep.instantiateStepResult() as? SBATrackedItemsResult else { XCTFail("Failed to create the expected result. Exiting.") return } var selectionResult = firstResult selectionResult.updateSelected(to: ["medA2", "medB4"], with: selectionStep.items) taskResult.appendStepHistory(with: selectionResult) // Next step after selection is review. let (rStep, _) = medTracker.step(after: selectionStep, with: &taskResult) XCTAssertNotNil(rStep) guard let reviewStep = rStep as? SBATrackedMedicationReviewStepObject else { XCTFail("Failed to create the initial review step. Exiting. step: \(String(describing: rStep))") return } guard let rResult = reviewStep.instantiateStepResult() as? SBAMedicationTrackingResult else { XCTFail("Failed to create the expected result. Exiting.") return } var reviewResult = rResult reviewResult.medications = reviewResult.medications.map { var med = $0 if med.identifier == "medA2" { med.dosageItems = [ SBADosage(dosage: "1", daysOfWeek: [.monday, .wednesday, .friday], timestamps: [SBATimestamp(timeOfDay: "08:00", loggedDate: nil)], isAnytime: false) ] } return med } taskResult.appendStepHistory(with: reviewResult) // Then logging let (logStep, _) = medTracker.step(after: reviewStep, with: &taskResult) XCTAssertNotNil(logStep) guard let loggingStep = logStep as? SBAMedicationLoggingStepObject else { XCTFail("Failed to create the expected step. Exiting. \(String(describing: logStep))") return } taskResult.appendStepHistory(with: loggingStep.instantiateStepResult()) // Then reminder let (remStep, _) = medTracker.step(after: logStep, with: &taskResult) XCTAssertNotNil(remStep) guard let reminderStep = remStep as? SBATrackedItemRemindersStepObject else { XCTFail("Failed to return the reminderStep. Exiting. \(String(describing: remStep))") return } XCTAssertTrue(medTracker.hasStep(after: reminderStep, with: taskResult)) taskResult.appendStepHistory(with: reminderStep.instantiateStepResult()) let (exitStep, _) = medTracker.step(after: reminderStep, with: &taskResult) XCTAssertNil(exitStep) } func testMedicationTrackingNavigation_FollowupRun() { NSLocale.setCurrentTest(Locale(identifier: "en_US")) let (items, sections) = buildMedicationItems() let medTracker = SBAMedicationTrackingStepNavigatorWithReminders(identifier: "Test", items: items, sections: sections) var initialResult = SBAMedicationTrackingResult(identifier: RSDIdentifier.trackedItemsResult.identifier) var medA3 = SBAMedicationAnswer(identifier: "medA3") medA3.dosageItems = [ SBADosage(dosage: "1", daysOfWeek: [.monday, .wednesday, .friday], timestamps: [SBATimestamp(timeOfDay: "08:00", loggedDate: nil)], isAnytime: false) ] var medC3 = SBAMedicationAnswer(identifier: "medC3") medC3.dosageItems = [ SBADosage(dosage: "1", daysOfWeek: [.sunday, .thursday], timestamps: [SBATimestamp(timeOfDay: "20:00", loggedDate: nil)], isAnytime: false) ] initialResult.medications = [medA3, medC3] // This is how the previous answer of "no reminders please" looks. initialResult.reminders = [] let dataScore = try! initialResult.dataScore() medTracker.previousClientData = dataScore?.toClientData() // Check initial state let selectionStep = medTracker.getSelectionStep() as? SBATrackedSelectionStepObject XCTAssertNotNil(selectionStep) XCTAssertEqual(selectionStep?.result?.selectedAnswers.count, 2) let reviewStep = medTracker.getReviewStep() as? SBATrackedMedicationReviewStepObject XCTAssertNotNil(reviewStep) var taskResult: RSDTaskResult = RSDTaskResultObject(identifier: "medication") let (firstStep, _) = medTracker.step(after: nil, with: &taskResult) guard let loggingStep = firstStep as? SBAMedicationLoggingStepObject else { XCTFail("Failed to create the expected step. Exiting.") return } XCTAssertNotNil(loggingStep) XCTAssertEqual(loggingStep.result?.selectedAnswers.count, 2) taskResult.appendStepHistory(with: loggingStep.instantiateStepResult()) let (exitStep, _) = medTracker.step(after: firstStep, with: &taskResult) XCTAssertNil(exitStep) } func testMedicationTrackingNavigation_FollowupRun_AddDetailsLater() { NSLocale.setCurrentTest(Locale(identifier: "en_US")) let (items, sections) = buildMedicationItems() let medTracker = SBAMedicationTrackingStepNavigatorWithReminders(identifier: "Test", items: items, sections: sections) var initialResult = SBAMedicationTrackingResult(identifier: RSDIdentifier.trackedItemsResult.identifier) let medA3 = SBAMedicationAnswer(identifier: "medA3") let medC3 = SBAMedicationAnswer(identifier: "medC3") initialResult.medications = [medA3, medC3] let dataScore = try! initialResult.dataScore() medTracker.previousClientData = dataScore?.toClientData() var taskResult: RSDTaskResult = RSDTaskResultObject(identifier: "medication") let (firstStep, _) = medTracker.step(after: nil, with: &taskResult) guard let reviewStep = firstStep as? SBATrackedMedicationReviewStepObject else { XCTFail("Failed to create the expected step. Exiting.") return } // Add medication details to all the meds. guard let rResult = reviewStep.instantiateStepResult() as? SBAMedicationTrackingResult else { XCTFail("Failed to create the expected result. Exiting.") return } var reviewResult = rResult reviewResult.medications = reviewResult.medications.map { var med = $0 med.dosageItems = [ SBADosage(dosage: "1", daysOfWeek: [.monday, .wednesday, .friday], timestamps: [SBATimestamp(timeOfDay: "08:00", loggedDate: nil)], isAnytime: false) ] return med } taskResult.appendStepHistory(with: reviewResult) // Then logging let (logStep, _) = medTracker.step(after: reviewStep, with: &taskResult) XCTAssertNotNil(logStep) guard let loggingStep = logStep as? SBAMedicationLoggingStepObject else { XCTFail("Failed to create the expected step. Exiting. \(String(describing: logStep))") return } taskResult.appendStepHistory(with: loggingStep.instantiateStepResult()) // Then reminder let (remStep, _) = medTracker.step(after: logStep, with: &taskResult) XCTAssertNotNil(remStep) guard let reminderStep = remStep as? SBATrackedItemRemindersStepObject else { XCTFail("Failed to return the reminderStep. Exiting. \(String(describing: remStep))") return } XCTAssertTrue(medTracker.hasStep(after: reminderStep, with: taskResult)) taskResult.appendStepHistory(with: reminderStep.instantiateStepResult()) let (exitStep, _) = medTracker.step(after: reminderStep, with: &taskResult) XCTAssertNil(exitStep) } } // Helper methods func remindersResult(reminderStep: SBATrackedItemRemindersStepObject) -> RSDCollectionResultObject { var result = RSDCollectionResultObject(identifier: reminderStep.identifier) var answerResult = RSDAnswerResultObject(identifier: reminderStep.identifier, answerType: RSDAnswerResultType(baseType: .integer, sequenceType: .array, formDataType: .collection(.multipleChoice, .integer), dateFormat: nil, unit: nil, sequenceSeparator: nil)) answerResult.value = [45, 60] result.inputResults = [answerResult] return result } func buildMedicationItems() -> (items: [SBAMedicationItem], sections: [SBATrackedSection]) { let items = [ SBAMedicationItem(identifier: "medA1", sectionIdentifier: "section1"), SBAMedicationItem(identifier: "medA2", sectionIdentifier: "section2"), SBAMedicationItem(identifier: "medA3", sectionIdentifier: "section3"), SBAMedicationItem(identifier: "medA4", sectionIdentifier: "section4"), SBAMedicationItem(identifier: "medB1", sectionIdentifier: "section1"), SBAMedicationItem(identifier: "medB2", sectionIdentifier: "section2"), SBAMedicationItem(identifier: "medB3", sectionIdentifier: "section3"), SBAMedicationItem(identifier: "medB4", sectionIdentifier: "section4"), SBAMedicationItem(identifier: "medC1", sectionIdentifier: "section1"), SBAMedicationItem(identifier: "medC2", sectionIdentifier: "section2"), SBAMedicationItem(identifier: "medC3", sectionIdentifier: "section3"), SBAMedicationItem(identifier: "medC4", sectionIdentifier: "section4"), SBAMedicationItem(identifier: "medNoSection1", sectionIdentifier: nil), SBAMedicationItem(identifier: "medFooSection1", sectionIdentifier: "Foo"), SBAMedicationItem(identifier: "medFooSection2", sectionIdentifier: "Foo"), ] let sections = [ SBATrackedSectionObject(identifier: "section1"), SBATrackedSectionObject(identifier: "section2"), SBATrackedSectionObject(identifier: "section3"), SBATrackedSectionObject(identifier: "section4"), ] return (items, sections) } class SBAMedicationTrackingStepNavigatorWithReminders: SBAMedicationTrackingStepNavigator { /// return a step for the introduction. override class func buildIntroductionStep()-> RSDStep? { return RSDUIStepObject(identifier: "introduction") } /// return a step that will be used to set medication reminders. override class func buildReminderStep() -> SBATrackedItemRemindersStepObject? { guard let inputFields = try? [RSDChoiceInputFieldObject(identifier: "choices", choices: [RSDChoiceObject(value: 15), RSDChoiceObject(value: 30)], dataType: .collection(.multipleChoice, .integer))] else { return nil } let step = SBATrackedItemRemindersStepObject(identifier: "reminder", inputFields: inputFields, type: .medicationReminders) step.title = "reminder title" step.detail = "reminder detail" return step } }
49.277922
211
0.643
ddd5559f89932acf4164ff580cbff33ff9867ffd
4,743
// // ProfileViewController.swift // TwitterS // // Created by John Law on 1/3/2017. // Copyright © 2017 Chi Hon Law. All rights reserved. // import UIKit class ProfileViewController: UIViewController { var user: User! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var profileView: ProfileView! @IBOutlet weak var footerView: UIView! @IBOutlet weak var profileImageView: UIImageView! var max_id: String? var tweets: [Tweet]? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //self.navigationController?.isNavigationBarHidden = true; if user == nil { user = User.currentUser! self.navigationItem.leftBarButtonItem = nil } profileView.user = user profileView.updateView() tableView.dataSource = self tableView.delegate = self profileView.setNeedsLayout() profileView.layoutIfNeeded() profileView.frame.size = profileView.systemLayoutSizeFitting(UILayoutFittingCompressedSize) refreshControlAction(UIRefreshControl()) let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refreshControlAction(_:)), for: UIControlEvents.valueChanged) tableView.insertSubview(refreshControl, at: 0) tableView.estimatedRowHeight = 120 tableView.rowHeight = UITableViewAutomaticDimension tableView.tableHeaderView = profileView tableView.backgroundColor = footerView.backgroundColor } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage() for subview in (self.navigationController?.navigationBar.subviews)! { subview.removeFromSuperview() } } /* // 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. } */ func refreshControlAction(_ refreshControl: UIRefreshControl) { // ... Create the URLRequest `myRequest` ... TwitterClient.sharedInstance.userTimeline(id: user.id, max_id: max_id, success: { (tweets) in self.tweets = tweets self.tableView.reloadData() refreshControl.endRefreshing() }, failure: { (error) in let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default) alertController.addAction(OKAction) self.present(alertController, animated: true) } ) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let detailViewController = segue.destination as? TweetDetailViewController { let cell = sender as! TweetCell detailViewController.tweet = cell.tweet } } @IBAction func onBackButton(_ sender: Any) { self.dismiss(animated: true, completion: nil) let _ = self.navigationController?.popViewController(animated: true) } } extension ProfileViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let tweets = tweets { return tweets.count } else { return 0 } } // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier: // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "tweetCell", for: indexPath) as! TweetCell let tweet = tweets![indexPath.row] cell.tweet = tweet cell.updateCell() return cell } }
36.206107
188
0.661817
d5367207820aa971c60e4807334ea464d7935a60
1,683
// // RangeRule.swift // SBValidator // // Created by Soumen Bhuin on 25/06/19. // Copyright © 2019 smbhuin. All rights reserved. // import Foundation /** `RangeRule` is a subclass of `ValidationRule` that defines how value is validated with min & max limits. */ public class RangeRule<V> : ValidationRule<V> where V : Comparable, V : CustomStringConvertible { private let min: V private let max: V /** Initializes a `RangeRule` object to verify that quantity of value is in the range of min & max. - parameter min: Minimum required quantity of value. - parameter max: Maximum required quantity of value. - parameter message: String of error message. - returns: An initialized object. */ public init(min: V, max: V, message: String? = nil) { self.min = min self.max = max super.init(message: message ?? "is invalid. must be between \(min) and \(max).") } /** Method used to validate the provided value. - parameter value: Any value to be checked for validation. - returns: Error Message. nil if validation is successful; `String` if validation fails. */ public override func validate(_ value: V?) -> String? { guard let v = value else { return nil } if v >= min && v <= max { return nil } else { return self.message } } } public extension ValidationRule { /// Quick accessor for `RangeRule` class func range<V>(min: V, max: V) -> ValidationRule<V> where V : Comparable, V : CustomStringConvertible { return RangeRule(min: min, max: max) } }
28.05
112
0.615567
09fd2be3d8e2899c9d7a8c36e3b7ba85f675fe7a
142
import XCTest import DSFLabelledTextFieldTests var tests = [XCTestCaseEntry]() tests += DSFLabelledTextFieldTests.allTests() XCTMain(tests)
17.75
45
0.816901
4aa778155cebdc59a27a13c3cb05b607f3215703
246
// // Contacts.swift // MacroCosm // // Created by Anton Tekutov on 19.06.21. // import Foundation struct Contacts { static let mainContactEmail = "[email protected]" static let defaultDateFormat = "yyyy-MM-dd'T'HH:mm:ss" }
16.4
58
0.674797
dea15ee048b0f322431f405ba14ced52d5c7d5f9
6,501
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Baggage Context open source project // // Copyright (c) 2020 Moritz Lang and the Swift Baggage Context project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) import Darwin #else import Glibc #endif // ==== ---------------------------------------------------------------------------------------------------------------- // MARK: CountDownLatch internal class CountDownLatch { private var counter: Int private let condition: _Condition private let lock: _Mutex init(from: Int) { self.counter = from self.condition = _Condition() self.lock = _Mutex() } /// Returns previous value before the decrement was issued. func countDown() { self.lock.synchronized { self.counter -= 1 if self.counter == 0 { self.condition.signalAll() } } } var count: Int { self.lock.synchronized { self.counter } } func wait() { self.lock.synchronized { while true { if self.counter == 0 { return // done } self.condition.wait(lock) } } } } extension CountDownLatch: CustomStringConvertible { public var description: String { "CountDownLatch(remaining:\(self.count)" } } // ==== ---------------------------------------------------------------------------------------------------------------- // MARK: Condition final class _Condition { @usableFromInline var condition: pthread_cond_t = pthread_cond_t() public init() { let error = pthread_cond_init(&self.condition, nil) switch error { case 0: return default: fatalError("Condition could not be created: \(error)") } } deinit { pthread_cond_destroy(&condition) } @inlinable public func wait(_ mutex: _Mutex) { let error = pthread_cond_wait(&self.condition, &mutex.mutex) switch error { case 0: return case EPERM: fatalError("Wait failed, mutex is not owned by this thread") case EINVAL: fatalError("Wait failed, condition is not valid") default: fatalError("Wait failed with unspecified error: \(error)") } } // @inlinable // public func wait(_ mutex: _Mutex) -> Bool { // let error = withUnsafePointer(to: time) { p -> Int32 in // #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) // return pthread_cond_timedwait_relative_np(&condition, &mutex.mutex, p) // #else // return pthread_cond_timedwait(&condition, &mutex.mutex, p) // #endif // } // // switch error { // case 0: // return true // case ETIMEDOUT: // return false // case EPERM: // fatalError("Wait failed, mutex is not owned by this thread") // case EINVAL: // fatalError("Wait failed, condition is not valid") // default: // fatalError("Wait failed with unspecified error: \(error)") // } // } @inlinable public func signal() { let error = pthread_cond_signal(&self.condition) switch error { case 0: return case EINVAL: fatalError("Signal failed, condition is not valid") default: fatalError("Signal failed with unspecified error: \(error)") } } @inlinable public func signalAll() { let error = pthread_cond_broadcast(&self.condition) switch error { case 0: return case EINVAL: fatalError("Signal failed, condition is not valid") default: fatalError("Signal failed with unspecified error: \(error)") } } } // ==== ---------------------------------------------------------------------------------------------------------------- // MARK: Mutex final class _Mutex { @usableFromInline var mutex: pthread_mutex_t = pthread_mutex_t() public init() { var attr: pthread_mutexattr_t = pthread_mutexattr_t() pthread_mutexattr_init(&attr) pthread_mutexattr_settype(&attr, Int32(PTHREAD_MUTEX_RECURSIVE)) let error = pthread_mutex_init(&self.mutex, &attr) pthread_mutexattr_destroy(&attr) switch error { case 0: return default: fatalError("Could not create mutex: \(error)") } } deinit { pthread_mutex_destroy(&mutex) } @inlinable public func lock() { let error = pthread_mutex_lock(&self.mutex) switch error { case 0: return case EDEADLK: fatalError("Mutex could not be acquired because it would have caused a deadlock") default: fatalError("Failed with unspecified error: \(error)") } } @inlinable public func unlock() { let error = pthread_mutex_unlock(&self.mutex) switch error { case 0: return case EPERM: fatalError("Mutex could not be unlocked because it is not held by the current thread") default: fatalError("Unlock failed with unspecified error: \(error)") } } @inlinable public func tryLock() -> Bool { let error = pthread_mutex_trylock(&self.mutex) switch error { case 0: return true case EBUSY: return false case EDEADLK: fatalError("Mutex could not be acquired because it would have caused a deadlock") default: fatalError("Failed with unspecified error: \(error)") } } @inlinable public func synchronized<A>(_ f: () -> A) -> A { self.lock() defer { unlock() } return f() } @inlinable public func synchronized<A>(_ f: () throws -> A) throws -> A { self.lock() defer { unlock() } return try f() } }
25.594488
120
0.510229
e8a69bf4f1c1c731a9846feeaa3f623c10b72b02
268
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func < { for { protocol A { class a { { } var b { [ { } String { return m( { enum b { class case ,
14.105263
87
0.686567
e5241cfbb44f6713987f2171186c0f118a22888d
269
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol A{ struct B<H: B } class a{ enum S{ struct X
20.692308
87
0.736059
1a81bb6992151d1302291ebdfc4d112783e7aaa2
10,118
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir > %t.ll // RUN: %FileCheck %s -check-prefix=GLOBAL < %t.ll // RUN: %FileCheck %s < %t.ll // REQUIRES: CPU=x86_64 protocol P {} protocol Q {} protocol Assocked { associatedtype Assoc : P, Q } struct Universal : P, Q {} // CHECK: [[ASSOC_TYPE_NAMES:@.*]] = private constant [29 x i8] c"OneAssoc TwoAssoc ThreeAssoc\00" // CHECK: @"$s23associated_type_witness18HasThreeAssocTypesMp" = // CHECK-SAME: [[ASSOC_TYPE_NAMES]] to i64 protocol HasThreeAssocTypes { associatedtype OneAssoc associatedtype TwoAssoc associatedtype ThreeAssoc } // Witness table access functions for Universal : P and Universal : Q. // CHECK-LABEL: define hidden i8** @"$s23associated_type_witness9UniversalVAA1PAAWa"() // CHECK: ret i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s23associated_type_witness9UniversalVAA1PAAWP", i32 0, i32 0) // CHECK-LABEL: define hidden i8** @"$s23associated_type_witness9UniversalVAA1QAAWa"() // CHECK: ret i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s23associated_type_witness9UniversalVAA1QAAWP", i32 0, i32 0) // Witness table for WithUniversal : Assocked. // GLOBAL-LABEL: @"$s23associated_type_witness13WithUniversalVAA8AssockedAAWP" = hidden global [4 x i8*] [ // GLOBAL-SAME: @"$s23associated_type_witness13WithUniversalVAA8AssockedAAMc" // GLOBAL-SAME: i8* bitcast (i8** ()* @"$s23associated_type_witness9UniversalVAA1PAAWa" to i8*) // GLOBAL-SAME: i8* bitcast (i8** ()* @"$s23associated_type_witness9UniversalVAA1QAAWa" to i8*) // GLOBAL-SAME: i64 add (i64 ptrtoint (<{ [36 x i8], i8 }>* @"symbolic 23associated_type_witness9UniversalV" to i64), i64 1) to i8*) // GLOBAL-SAME: ] struct WithUniversal : Assocked { typealias Assoc = Universal } // Witness table for GenericWithUniversal : Assocked. // GLOBAL-LABEL: @"$s23associated_type_witness20GenericWithUniversalVyxGAA8AssockedAAWP" = hidden global [4 x i8*] [ // GLOBAL-SAME: @"$s23associated_type_witness20GenericWithUniversalVyxGAA8AssockedAAMc" // GLOBAL-SAME: i8* bitcast (i8** ()* @"$s23associated_type_witness9UniversalVAA1PAAWa" to i8*) // GLOBAL-SAME: i8* bitcast (i8** ()* @"$s23associated_type_witness9UniversalVAA1QAAWa" to i8*) // GLOBAL-SAME: @"symbolic 23associated_type_witness9UniversalV" // GLOBAL-SAME: ] struct GenericWithUniversal<T> : Assocked { typealias Assoc = Universal } // Witness table for Fulfilled : Assocked. // GLOBAL-LABEL: @"$s23associated_type_witness9FulfilledVyxGAA8AssockedAAWp" = internal constant [4 x i8*] [ // GLOBAL-SAME: @"$s23associated_type_witness9FulfilledVyxGAA8AssockedAAMc" // GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @"$s23associated_type_witness9FulfilledVyxGAA8AssockedAA5AssocAaEP_AA1PPWT" to i8*) // GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @"$s23associated_type_witness9FulfilledVyxGAA8AssockedAA5AssocAaEP_AA1QPWT" to i8*) // GLOBAL-SAME: @"symbolic x" // GLOBAL-SAME: ] struct Fulfilled<T : P & Q> : Assocked { typealias Assoc = T } // Associated type witness table access function for Fulfilled.Assoc : P. // CHECK-LABEL: define internal swiftcc i8** @"$s23associated_type_witness9FulfilledVyxGAA8AssockedAA5AssocAaEP_AA1PPWT"(%swift.type* %"Fulfilled<T>.Assoc", %swift.type* %"Fulfilled<T>", i8** %"Fulfilled<T>.Assocked") // CHECK: [[T0:%.*]] = bitcast %swift.type* %"Fulfilled<T>" to i8*** // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], i64 3 // CHECK-NEXT: [[T2:%.*]] = load i8**, i8*** [[T1]], align 8, !invariant.load // CHECK-NEXT: ret i8** [[T2]] // Associated type witness table access function for Fulfilled.Assoc : Q. // CHECK-LABEL: define internal swiftcc i8** @"$s23associated_type_witness9FulfilledVyxGAA8AssockedAA5AssocAaEP_AA1QPWT"(%swift.type* %"Fulfilled<T>.Assoc", %swift.type* %"Fulfilled<T>", i8** %"Fulfilled<T>.Assocked") // CHECK: [[T0:%.*]] = bitcast %swift.type* %"Fulfilled<T>" to i8*** // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], i64 4 // CHECK-NEXT: [[T2:%.*]] = load i8**, i8*** [[T1]], align 8, !invariant.load // CHECK-NEXT: ret i8** [[T2]] struct Pair<T, U> : P, Q {} // Generic witness table pattern for Computed : Assocked. // GLOBAL-LABEL: @"$s23associated_type_witness8ComputedVyxq_GAA8AssockedAAWp" = internal constant [4 x i8*] [ // GLOBAL-SAME: @"$s23associated_type_witness8ComputedVyxq_GAA8AssockedAAMc" // GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @"$s23associated_type_witness8ComputedVyxq_GAA8AssockedAA5Assoc_AA1PPWT" to i8*) // GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @"$s23associated_type_witness8ComputedVyxq_GAA8AssockedAA5Assoc_AA1QPWT" to i8*) // GLOBAL-SAME: @"symbolic 23associated_type_witness4PairVyxq_G" // GLOBAL-SAME: ] // Generic witness table cache for Computed : Assocked. // GLOBAL-LABEL: @"$s23associated_type_witness8ComputedVyxq_GAA8AssockedAAWG" = internal constant %swift.generic_witness_table_cache { // GLOBAL-SAME: i16 4, // GLOBAL-SAME: i16 1, // Relative reference to protocol // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint ({{.*}} @"$s23associated_type_witness8AssockedMp" to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @"$s23associated_type_witness8ComputedVyxq_GAA8AssockedAAWG", i32 0, i32 2) to i64)) to i32 // Relative reference to witness table template // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint ([4 x i8*]* @"$s23associated_type_witness8ComputedVyxq_GAA8AssockedAAWp" to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @"$s23associated_type_witness8ComputedVyxq_GAA8AssockedAAWG", i32 0, i32 3) to i64)) to i32 // Relative reference to resilient witnesses // GLOBAL-SAME: i32 0, // No instantiator function // GLOBAL-SAME: i32 0, // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint ([16 x i8*]* [[PRIVATE:@.*]] to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @"$s23associated_type_witness8ComputedVyxq_GAA8AssockedAAWG", i32 0, i32 6) to i64)) to i32) // GLOBAL-SAME: } // GLOBAL: [[PRIVATE]] = internal global [16 x i8*] zeroinitializer struct Computed<T, U> : Assocked { typealias Assoc = Pair<T, U> } // Witness table accessor function for Computed : Assocked. // CHECK-LABEL: define hidden i8** @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWa"(%swift.type*, i8***) // CHECK-NEXT: entry: // CHECK-NEXT: [[WTABLE:%.*]] = call i8** @swift_getGenericWitnessTable(%swift.generic_witness_table_cache* @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWG", %swift.type* %0, i8*** %1) // CHECK-NEXT: ret i8** [[WTABLE]] struct PBox<T: P> {} protocol HasSimpleAssoc { associatedtype Assoc } protocol DerivedFromSimpleAssoc : HasSimpleAssoc {} // Generic witness table pattern for GenericComputed : DerivedFromSimpleAssoc. // GLOBAL-LABEL: @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWp" = internal constant [2 x i8*] // GLOBAL-SAME: @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAMc" // GLOBAL-SAME: i8* null // Generic witness table cache for GenericComputed : DerivedFromSimpleAssoc. // GLOBAL-LABEL: @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWG" = internal constant %swift.generic_witness_table_cache { // GLOBAL-SAME: i16 2, // GLOBAL-SAME: i16 1, // Relative reference to protocol // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint ({{.*}} @"$s23associated_type_witness22DerivedFromSimpleAssocMp" to i64 // Relative reference to witness table template // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint ([2 x i8*]* @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWp" to i64 // Relative reference to resilient witnesses // GLOBAL-SAME: i32 0, // Relative reference to instantiator function // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint (void (i8**, %swift.type*, i8**)* @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWI" to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWG", i32 0, i32 5) to i64)) to i32) // Relative reference to private data struct GenericComputed<T: P> : DerivedFromSimpleAssoc { typealias Assoc = PBox<T> } // Instantiation function for GenericComputed : DerivedFromSimpleAssoc. // CHECK-LABEL: define internal void @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWI"(i8**, %swift.type* %"GenericComputed<T>", i8**) // CHECK: [[T0:%.*]] = call i8** @"$s23associated_type_witness15GenericComputedVyxGAA14HasSimpleAssocAAWa"(%swift.type* %"GenericComputed<T>", i8*** undef) // CHECK-NEXT: [[T1:%.*]] = bitcast i8** [[T0]] to i8* // CHECK-NEXT: [[T2:%.*]] = getelementptr inbounds i8*, i8** %0, i32 1 // CHECK-NEXT: store i8* [[T1]], i8** [[T2]], align 8 // CHECK-NEXT: ret void // Witness table accessor function for GenericComputed : HasSimpleAssoc.. // CHECK-LABEL: define hidden i8** @"$s23associated_type_witness15GenericComputedVyxGAA14HasSimpleAssocAAWa"(%swift.type*, i8***) // CHECK-NEXT: entry: // CHECK-NEXT: [[WTABLE:%.*]] = call i8** @swift_getGenericWitnessTable(%swift.generic_witness_table_cache* @"$s23associated_type_witness15GenericComputedVyxGAA14HasSimpleAssocAAWG", %swift.type* %0, i8*** %1) // CHECK-NEXT: ret i8** [[WTABLE]] protocol HasAssocked { associatedtype Contents : Assocked } struct FulfilledFromAssociatedType<T : HasAssocked> : HasSimpleAssoc { typealias Assoc = PBox<T.Contents.Assoc> } struct UsesVoid : HasSimpleAssoc { typealias Assoc = () }
57.163842
405
0.732161
5bf45f477a7d5457db16350014203e8a75372f7f
10,393
// // JRPPTransactionListVM.swift // Jarvis // // Created by Pankaj Singh on 03/01/20. // import Foundation import jarvis_network_ios // MARK: - Enums enum JRPPTransactionAPIStatus: String { case success = "S" } enum JRPCAccountingType: String { case CREDIT case DEBIT } enum JRPCTransactionType: String { case REWARD case REFUND case PAY } // MARK: - TransactionVM class JRPCTransactionVM { var coinsBalance: String = JRPCConstants.kPCInvalidCoinBalance var loyaltyPoints: [JRPCTransactionSecModel] = [] var pagination: JRPPPaginator? typealias completionType = (Error?) -> Void func fetchCoinBalance(data: (String , [String: Any]), completion: @escaping completionType) { let request = JRPaytmCoinsAPI.fetchBalance(url: data.0, bodyParam: data.1) let router = JRRouter<JRPaytmCoinsAPI>() router.request(type: JRDataType.self, request) { [weak self] (responseObject , response, error) in guard let self = self else { DispatchQueue.main.async { completion(JRPCNetworkHandler.requestNotValid()) } return } if let error = error { DispatchQueue.main.async { completion(error) } } else { guard let responseData = responseObject as? Data else { DispatchQueue.main.async { completion(JRPCNetworkHandler.fetchBalanceError()) } return } guard let statusCode = (response as? HTTPURLResponse)?.statusCode else { DispatchQueue.main.async { completion(JRPCNetworkHandler.fetchBalanceError()) } return } switch statusCode { case 200: self.processFetchBalanceResponse(responseData, completion) default: DispatchQueue.main.async { completion(JRPCNetworkHandler.fetchBalanceError()) } } } } } private func processFetchBalanceResponse(_ data: Data, _ completion: @escaping completionType) { do { let decoder = JSONDecoder() let fetchBalanceModel = try decoder.decode(JRPPTransactionListModel.self, from: data) if fetchBalanceModel.response?.result?.resultStatus == JRPPTransactionAPIStatus.success.rawValue { self.coinsBalance = fetchBalanceModel.response?.activeBalance?.value ?? JRPCConstants.kPCInvalidCoinBalance DispatchQueue.main.async { completion(nil) } } else { if let resultMsg = fetchBalanceModel.response?.result?.resultMsg { DispatchQueue.main.async { completion(NSError(domain: resultMsg, code: JRPCConstants.kPCErrorMessageCode, userInfo: ["NSLocalizedDescription": resultMsg])) } } else { DispatchQueue.main.async { completion(JRPCNetworkHandler.unknownError()) } } } } catch let error { DispatchQueue.main.async { completion(error) } } } func fetchTransactionList(data: (String , [String: Any]), completion: @escaping completionType) { let request = JRPaytmCoinsAPI.getTransactionList(url: data.0, bodyParam: data.1) let router = JRRouter<JRPaytmCoinsAPI>() router.request(type: JRDataType.self, request) { [weak self] (responseObject , response, error) in guard let self = self else { DispatchQueue.main.async { completion(JRPCNetworkHandler.requestNotValid()) } return } if let error = error { DispatchQueue.main.async { completion(error) } } else { guard let responseData = responseObject as? Data else { DispatchQueue.main.async { completion(JRPCNetworkHandler.unknownError()) } return } guard let statusCode = (response as? HTTPURLResponse)?.statusCode else { DispatchQueue.main.async { completion(JRPCNetworkHandler.unknownError()) } return } switch statusCode { case 200: self.processTransactionAPIResponse(responseData, completion) default: DispatchQueue.main.async { completion(JRPCNetworkHandler.unknownError()) } } } } } private func processTransactionAPIResponse(_ data: Data, _ completion: @escaping completionType) { do { let decoder = JSONDecoder() let transactionModel = try decoder.decode(JRPPTransactionListModel.self, from: data) if transactionModel.response?.result?.resultStatus == JRPPTransactionAPIStatus.success.rawValue { if let points = transactionModel.response?.loyaltyPoints { self.parseLoyalityPoints(points: points) } if let pagination = transactionModel.response?.paginator { self.pagination = pagination } DispatchQueue.main.async { completion(nil) } } else { if let resultMsg = transactionModel.response?.result?.resultMsg { DispatchQueue.main.async { completion(NSError(domain: resultMsg, code: JRPCConstants.kPCErrorMessageCode, userInfo: ["NSLocalizedDescription": resultMsg])) } } else { DispatchQueue.main.async { completion(JRPCNetworkHandler.unknownError()) } } } } catch let error { DispatchQueue.main.async { completion(error) } } } private func parseLoyalityPoints(points: [JRPPLoyaltyPoint]) { for coin in points { if let timestamp = coin.dateStringInfo { if let index = self.loyaltyPoints.firstIndex(where: { (model) -> Bool in return model.dateString == timestamp.date }) { var array = self.loyaltyPoints[index].transactionList array.append(coin) self.loyaltyPoints[index].transactionList = array } else { let model = JRPCTransactionSecModel(dateString: timestamp.date, transactionList: [coin]) self.loyaltyPoints.append(model) } } } } } // MARK: - Transaction Section Model struct JRPCTransactionSecModel { var dateString: String = "" var transactionList: [JRPPLoyaltyPoint] = [] } // MARK: - JRPPBalanceAPIModel struct JRPPTransactionListModel: Codable { let response: JRPPResponse? } // MARK: - Response struct JRPPResponse: Codable { let result: JRPPResult? let loyaltyPoints: [JRPPLoyaltyPoint]? let paginator: JRPPPaginator? let activeBalance, exchangeRate: JRPCGenericString? } // MARK: - LoyaltyPoint struct JRPPLoyaltyPoint: Codable { let extendedInfo: JRPCExtendedInfo? let accountingAmount: JRPCGenericString? let accountingTimeStamp: String? let accountingType: String? let activeBalance: JRPCGenericString? let orderID: String? let successful: Bool? let transactionType: String? let expiryTime: String? var dateStringInfo: (time: String, date: String)? { if let timeStamp = accountingTimeStamp, let formattedDate = JRPCUtilities.change(dateString: timeStamp) { let dateTimeArray = formattedDate.split(separator: ",") if dateTimeArray.count == 2 { return (String(dateTimeArray[0]), String(dateTimeArray[1])) } } return nil } enum CodingKeys: String, CodingKey { case accountingAmount, accountingType, activeBalance case orderID = "orderId" case accountingTimeStamp = "accountingTimestamp" case successful, transactionType, expiryTime case extendedInfo = "extendInfo" } } // MARK: - Paginator struct JRPPPaginator: Codable { let pageNum, pageSize, totalPage, totalCount: Int? } // MARK: - Result struct JRPPResult: Codable { let resultStatus, resultMsg: String? enum CodingKeys: String, CodingKey { case resultStatus case resultMsg } } struct JRPCExtendedInfo: Codable { let offerName: String? let displayName: String? let shortDescription: String? let offerIconImage: String? } class JRPCGenericString: Codable { let value: String static func decode(from container: SingleValueDecodingContainer) throws -> String { if let value: Bool = try? container.decode(Bool.self) { return String(value) } if let value: Int = try? container.decode(Int.self) { return String(value) } if let value: Double = try? container.decode(Double.self) { return String(value) } if let value: String = try? container.decode(String.self) { return value } return "" } public required init(from decoder: Decoder) throws { let container: SingleValueDecodingContainer = try decoder.singleValueContainer() self.value = try JRPCGenericString.decode(from: container) } public init(stringLiteral value: String) { self.value = value } }
33.964052
123
0.555855
9c00e4a0278013c08e8c109d175f09e10d91e52f
4,598
// swift-tools-version:5.0 import PackageDescription import Foundation let coreVersionStr = "5.23.3" let cocoaVersionStr = "3.18.0" let coreVersionPieces = coreVersionStr.split(separator: ".") let cxxSettings: [CXXSetting] = [ .headerSearchPath("."), .headerSearchPath("include"), .headerSearchPath("Realm/ObjectStore/src"), .define("REALM_SPM", to: "1"), .define("REALM_COCOA_VERSION", to: "@\"\(cocoaVersionStr)\""), .define("REALM_VERSION", to: "\"\(coreVersionStr)\""), .define("REALM_NO_CONFIG"), .defing("REALM_ENABLE_SYNC", to: "1"), .define("REALM_INSTALL_LIBEXECDIR", to: ""), .define("REALM_ENABLE_ASSERTIONS", to: "1"), .define("REALM_ENABLE_ENCRYPTION", to: "1"), .define("REALM_VERSION_MAJOR", to: String(coreVersionPieces[0])), .define("REALM_VERSION_MINOR", to: String(coreVersionPieces[1])), .define("REALM_VERSION_PATCH", to: String(coreVersionPieces[2])), .define("REALM_VERSION_EXTRA", to: "\"\""), .define("REALM_VERSION_STRING", to: "\"\(coreVersionStr)\""), ] let package = Package( name: "Realm", products: [ .library( name: "Realm", targets: ["Realm"]), .library( name: "RealmSwift", targets: ["Realm", "RealmSwift"]), ], dependencies: [ .package(url: "https://github.com/realm/realm-core", .exact(Version(coreVersionStr)!)), ], targets: [ .target( name: "Realm", dependencies: ["RealmCore"], path: ".", exclude: [ "Realm/NSError+RLMSync.m", "Realm/RLMJSONModels.m", "Realm/RLMNetworkClient.mm", "Realm/RLMRealm+Sync.mm", "Realm/RLMRealmConfiguration+Sync.mm", "Realm/RLMSyncConfiguration.mm", "Realm/RLMSyncCredentials.m", "Realm/RLMSyncManager.mm", "Realm/RLMSyncPermission.mm", "Realm/RLMSyncPermissionResults.mm", "Realm/RLMSyncSession.mm", "Realm/RLMSyncSessionRefreshHandle.mm", "Realm/RLMSyncSubscription.mm", "Realm/RLMSyncUser.mm", "Realm/RLMSyncUtil.mm", "Realm/ObjectServerTests", "Realm/Swift", "Realm/Tests", "Realm/TestUtils", "Realm/ObjectStore/external", "Realm/ObjectStore/tests", "Realm/ObjectStore/src/server", "Realm/ObjectStore/src/sync", "Realm/ObjectStore/src/impl/generic", "Realm/ObjectStore/src/impl/epoll", "Realm/ObjectStore/src/impl/android", "Realm/ObjectStore/src/impl/windows", ], sources: ["Realm"], publicHeadersPath: "include", cxxSettings: cxxSettings ), .target( name: "RealmSwift", dependencies: ["Realm"], path: "RealmSwift", exclude: [ "Sync.swift", "ObjectiveCSupport+Sync.swift", "Tests", ] ), .target( name: "RealmTestSupport", dependencies: ["Realm"], path: "Realm/TestUtils", cxxSettings: cxxSettings + [ // Command-line `swift build` resolves header search paths // relative to the package root, while Xcode resolves them // relative to the target root, so we need both. .headerSearchPath("Realm"), .headerSearchPath(".."), ] ), .testTarget( name: "RealmTests", dependencies: ["Realm", "RealmTestSupport"], path: "Realm/Tests", exclude: [ "Swift", "TestHost", "PrimitiveArrayPropertyTests.tpl.m", ], cxxSettings: cxxSettings + [ .headerSearchPath("Realm"), .headerSearchPath(".."), .headerSearchPath("../ObjectStore/src"), ] ), .testTarget( name: "RealmObjcSwiftTests", dependencies: ["Realm", "RealmTestSupport"], path: "Realm/Tests/Swift" ), .testTarget( name: "RealmSwiftTests", dependencies: ["RealmSwift", "RealmTestSupport"], path: "RealmSwift/Tests", exclude: ["TestUtils.mm"] ) ], cxxLanguageStandard: .cxx14 )
34.313433
95
0.520661
188e052aa83f47727ac560655ae1ff184f3b6af1
3,796
// // VersionMessage.swift // BitCore // // Created by SPARK-Daniel on 2022/1/12. // import Foundation public struct VersionMessage { public static let command = "version" public let version: Int32 public let services: UInt64 public let timestamp: Int64 public let receiverAddress: NetworkAddress public let senderAddress: NetworkAddress public let nonce: UInt64 public let userAgent: String public let latestBlock: Int32 public let relay: Bool init(version: Int32 = 70015, services: UInt64 = 0, timestamp: Int64? = nil, receiverAddress: NetworkAddress = .default, senderAddress: NetworkAddress = .default, nonce: UInt64? = nil, userAgent: String = "/BitcoinSwift:0.0.1/", latestBlock: Int32 = 0, relay: Bool = false) { self.version = version self.services = services self.timestamp = timestamp == nil ? Int64(Date().timeIntervalSince1970) : timestamp! self.receiverAddress = receiverAddress self.senderAddress = senderAddress self.nonce = nonce == nil ? UInt64.random() : nonce! self.userAgent = userAgent self.latestBlock = latestBlock self.relay = relay } func serialaize() -> Data { var result = version.littleEndian.data result += services.littleEndian.data result += timestamp.littleEndian.data result += receiverAddress.seriailze() result += senderAddress.seriailze() result += nonce.littleEndian.data let stringData = userAgent.toData() result += VarInt(stringData.count).serialize() result += stringData result += latestBlock.littleEndian.data result += relay ? Data(0x01) : Data(0x00) return result } static func parse(_ stream: ByteStream) -> Self { let version = stream.read(Int32.self) let services = stream.read(UInt64.self) let timestamp = stream.read(Int64.self) let receiverAddres = NetworkAddress.parse(stream) guard stream.availableByteCount > 0 else { return .init(version: version, services: services, timestamp: timestamp, receiverAddress: receiverAddres) } let senderAddress = NetworkAddress.parse(stream) let nonce = stream.read(UInt64.self) let userAgentLength = stream.read(VarInt.self).underlyingValue let userAgentData = stream.read(Data.self, count: Int(userAgentLength)) let userAgent = userAgentData.to(String.self) let latestBlock = stream.read(Int32.self) guard stream.availableByteCount > 0 else { return .init(version: version, services: services, timestamp: timestamp, receiverAddress: receiverAddres, senderAddress: senderAddress, nonce: nonce, userAgent: userAgent, latestBlock: latestBlock) } let relay = stream.read(Bool.self) return .init(version: version, services: services, timestamp: timestamp, receiverAddress: receiverAddres, senderAddress: senderAddress, nonce: nonce, userAgent: userAgent, latestBlock: latestBlock, relay: relay) } } // https://stackoverflow.com/questions/24007129/how-does-one-generate-a-random-number-in-swift private func arc4random<T: ExpressibleByIntegerLiteral>(_ type: T.Type) -> T { var r: T = 0 arc4random_buf(&r, MemoryLayout<T>.size) return r } private extension UInt64 { static func random(lower: UInt64 = min, upper: UInt64 = max) -> UInt64 { var m: UInt64 let u = upper - lower var r = arc4random(UInt64.self) if u > UInt64(Int64.max) { m = 1 + ~u } else { m = ((max - (u * 2)) + 1) % u } while r < m { r = arc4random(UInt64.self) } return (r % u) + lower } }
37.96
278
0.650948
e8fa6cd1f922959a63811b0f931ecc10fccc31cd
830
// // APIRouter.swift // Example Project // // Created by David Jennes on 06/03/2017. // Copyright © 2019 Appwise. All rights reserved. // import Alamofire import AppwiseCore enum APIRouter: AppwiseCore.Router { static var baseURLString = env( .dev("https://test.development.appwi.se/api/"), .stg("https://test.staging.appwi.se/api/"), .prd("https://test.production.appwi.se/api/") ) case user case tester(user: User.ID) } extension APIRouter { var path: String { switch self { case .user: return "user/me" case .tester(let userID): return "tester/\(userID)" } } var method: HTTPMethod { switch self { case .tester: return .post default: return .get } } var params: Parameters? { switch self { case .tester: return [ "test": 1 ] default: return nil } } }
15.660377
50
0.642169
3a5a9e7555a6795aae37299f1534a3d04b13abd7
1,629
import UIKit struct ModelA { let age: Int } class ModelB { var age: Int = 0 var name: String = "" } class ModelC: ModelB { } protocol AssociatedTypeProtocol { associatedtype T func testFunction(_ data: T) } extension AssociatedTypeProtocol where T : ModelB { func testFunctionExtension1(_ data: T) { print("testFunctionExtension AssociatedTypeProtocol 1") } } extension AssociatedTypeProtocol where T == ModelB { func testFunctionExtension2(_ data: T) { print("testFunctionExtension AssociatedTypeProtocol 2") } } class ClassA : AssociatedTypeProtocol { typealias T = ModelA func testFunction(_ data: T) { // do something ... print(data.age) } } class ClassB : AssociatedTypeProtocol { typealias T = ModelB func testFunction(_ data: T) { print(data.age) print(data.name) } } class ClassC : AssociatedTypeProtocol { typealias T = ModelC func testFunction(_ data: T) { print(data.age) print(data.name) } } let valueModelA = ModelA(age: 1) let valueClassA = ClassA() valueClassA.testFunction(valueModelA) let valueModelB = ModelB() valueModelB.age = 10 valueModelB.name = "test" let valueClassB = ClassB() valueClassB.testFunction(valueModelB) valueClassB.testFunctionExtension1(valueModelB) valueClassB.testFunctionExtension2(valueModelB) let valueModelC = ModelC() valueModelC.age = 10 valueModelC.name = "test" let valueClassC = ClassC() valueClassC.testFunction(valueModelC) valueClassC.testFunctionExtension1(valueModelC) valueClassC.testFunctionExtension2(valueModelC)
20.884615
63
0.709638
fb154bb3c4bb224db24ebac763eb67bb48a51905
4,076
// The MIT License (MIT) // // Copyright (c) 2015-2020 Alexander Grebenyuk (github.com/kean). import XCTest @testable import Nuke class ImagePipelineResumableDataTests: XCTestCase { private var dataLoader: _MockResumableDataLoader! private var pipeline: ImagePipeline! override func setUp() { dataLoader = _MockResumableDataLoader() ResumableData.cache.removeAll() pipeline = ImagePipeline { $0.dataLoader = dataLoader $0.imageCache = nil } } func testThatProgressIsReported() { // Given an initial request failed mid download // Expect the progress for the first part of the download to be reported. let expectedProgressInitial = expectProgress( [(3799, 22789), (7598, 22789), (11397, 22789)] ) expect(pipeline).toFailRequest(Test.request, progress: { _, completed, total in expectedProgressInitial.received((completed, total)) }) wait() // Expect progress closure to continue reporting the progress of the // entire download let expectedProgersRemaining = expectProgress( [(15196, 22789), (18995, 22789), (22789, 22789)] ) expect(pipeline).toLoadImage(with: Test.request, progress: { _, completed, total in expectedProgersRemaining.received((completed, total)) }) wait() } } private class _MockResumableDataLoader: DataLoading { private let queue = DispatchQueue(label: "_MockResumableDataLoader") let data: Data = Test.data(name: "fixture", extension: "jpeg") let eTag: String = "img_01" func loadData(with request: URLRequest, didReceiveData: @escaping (Data, URLResponse) -> Void, completion: @escaping (Error?) -> Void) -> Cancellable { let headers = request.allHTTPHeaderFields func sendChunks(_ chunks: [Data], of data: Data, statusCode: Int) { func sendChunk(_ chunk: Data) { let response = HTTPURLResponse( url: request.url!, statusCode: statusCode, httpVersion: "HTTP/1.2", headerFields: [ "Accept-Ranges": "bytes", "ETag": eTag, "Content-Range": "bytes \(chunk.startIndex)-\(chunk.endIndex)/\(data.count)", "Content-Length": "\(data.count)" ] )! didReceiveData(chunk, response) } var chunks = chunks while let chunk = chunks.first { chunks.removeFirst() queue.async { sendChunk(chunk) } } } // Check if the client already has some resumable data available. if let range = headers?["Range"], let validator = headers?["If-Range"] { let offset = _groups(regex: "bytes=(\\d*)-", in: range)[0] XCTAssertNotNil(offset) XCTAssertEqual(validator, eTag, "Expected validator to be equal to ETag") guard validator == eTag else { // Expected ETag return _Task() } // Send remaining data in chunks let remainingData = data[Int(offset)!...] let chunks = Array(_createChunks(for: remainingData, size: data.count / 6 + 1)) sendChunks(chunks, of: remainingData, statusCode: 206) queue.async { completion(nil) } } else { // Send half of chunks. var chunks = Array(_createChunks(for: data, size: data.count / 6 + 1)) chunks.removeLast(chunks.count / 2) sendChunks(chunks, of: data, statusCode: 200) queue.async { completion(NSError(domain: NSURLErrorDomain, code: URLError.networkConnectionLost.rawValue, userInfo: [:])) } } return _Task() } private class _Task: Cancellable { func cancel() { } } }
34.837607
155
0.566732
23703843f5d4d402e05c40be5a31cc3891d2cda4
2,457
// // ViewController.swift // UIControls // // Created by Eran Boudjnah on 27/05/2016. // Copyright © 2016 Eran Boudjnah. All rights reserved. // import UIKit import MTCircularSlider class ViewController: UIViewController { @IBOutlet weak var progressView: MTCircularSlider! @IBOutlet weak var valueLabel: UILabel! @IBOutlet weak var knobWithLabelView: MTCircularSlider! @IBOutlet weak var knobView1: MTCircularSlider! @IBOutlet weak var knobView2: MTCircularSlider! fileprivate var timer: Timer! fileprivate var direction: CGFloat = 0.01 override func viewDidLoad() { super.viewDidLoad() timer = Timer.scheduledTimer(timeInterval: 0.03, target: self, selector: #selector(update), userInfo: nil, repeats: true) setValueLabelText() initCustomKnobs() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) timer.invalidate() } @IBAction func onSlideChange(_ sender: MTCircularSlider) { setValueLabelText() } @objc func update(timer: Timer) { progressView.value += direction knobView1.value = progressView.value if progressView.value <= progressView.valueMinimum || progressView.value >= progressView.valueMaximum { direction = -direction } } fileprivate func setValueLabelText() { valueLabel.text = String(Int(knobWithLabelView.value)) } fileprivate func initCustomKnobs() { knobView1.applyAttributes([ /* Track */ Attributes.minTrackTint(.lightGray), Attributes.maxTrackTint(.darkGray), Attributes.trackWidth(4), Attributes.trackShadowRadius(0), Attributes.trackShadowDepth(0), Attributes.trackMinAngle(180), Attributes.trackMaxAngle(360), /* Thumb */ Attributes.hasThumb(false) ]) knobView1.valueMaximum = progressView.valueMaximum knobView2.applyAttributes([ /* Track */ Attributes.minTrackTint(.lightGray), Attributes.maxTrackTint(.lightGray), Attributes.trackWidth(12), Attributes.trackShadowRadius(0), Attributes.trackShadowDepth(0), Attributes.trackMinAngle(180), Attributes.trackMaxAngle(270), /* Thumb */ Attributes.hasThumb(true), Attributes.thumbTint(.darkGray), Attributes.thumbRadius(8), Attributes.thumbShadowRadius(0), Attributes.thumbShadowDepth(0) ]) knobView1.valueMaximum = progressView.valueMaximum } }
25.329897
65
0.700448
0ea587f67784945ed0420a9fcce3d7f1ed4dc58f
251
// // CellViewModel.swift // ytxIos // // Created by x j z l on 2019/9/4. // Copyright © 2019 spectator. All rights reserved. // import Foundation import RxCocoa class CellViewModel: NSObject { let title = BehaviorRelay<String>(value: "") }
16.733333
52
0.681275
265d3c343bb9140215481044c4687e8449463520
14,253
// SPDX-License-Identifier: MIT // Copyright © 2018-2021 WireGuard LLC. All Rights Reserved. import Cocoa protocol TunnelsListTableViewControllerDelegate: class { func tunnelsSelected(tunnelIndices: [Int]) func tunnelsListEmpty() } class TunnelsListTableViewController: NSViewController { let tunnelsManager: TunnelsManager weak var delegate: TunnelsListTableViewControllerDelegate? var isRemovingTunnelsFromWithinTheApp = false let tableView: NSTableView = { let tableView = NSTableView() tableView.addTableColumn(NSTableColumn(identifier: NSUserInterfaceItemIdentifier("TunnelsList"))) tableView.headerView = nil tableView.rowSizeStyle = .medium tableView.allowsMultipleSelection = true return tableView }() let addButton: NSPopUpButton = { let imageItem = NSMenuItem(title: "", action: nil, keyEquivalent: "") imageItem.image = NSImage(named: NSImage.addTemplateName)! let menu = NSMenu() menu.addItem(imageItem) menu.addItem(withTitle: tr("macMenuAddEmptyTunnel"), action: #selector(handleAddEmptyTunnelAction), keyEquivalent: "n") menu.addItem(withTitle: tr("macMenuImportTunnels"), action: #selector(handleImportTunnelAction), keyEquivalent: "o") menu.autoenablesItems = false let button = NSPopUpButton(frame: NSRect.zero, pullsDown: true) button.menu = menu button.bezelStyle = .smallSquare (button.cell as? NSPopUpButtonCell)?.arrowPosition = .arrowAtBottom return button }() let removeButton: NSButton = { let image = NSImage(named: NSImage.removeTemplateName)! let button = NSButton(image: image, target: self, action: #selector(handleRemoveTunnelAction)) button.bezelStyle = .smallSquare button.imagePosition = .imageOnly return button }() let actionButton: NSPopUpButton = { let imageItem = NSMenuItem(title: "", action: nil, keyEquivalent: "") imageItem.image = NSImage(named: NSImage.actionTemplateName)! let menu = NSMenu() menu.addItem(imageItem) menu.addItem(withTitle: tr("macMenuViewLog"), action: #selector(handleViewLogAction), keyEquivalent: "") menu.addItem(withTitle: tr("macMenuExportTunnels"), action: #selector(handleExportTunnelsAction), keyEquivalent: "") menu.autoenablesItems = false let button = NSPopUpButton(frame: NSRect.zero, pullsDown: true) button.menu = menu button.bezelStyle = .smallSquare (button.cell as? NSPopUpButtonCell)?.arrowPosition = .arrowAtBottom return button }() init(tunnelsManager: TunnelsManager) { self.tunnelsManager = tunnelsManager super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { tableView.dataSource = self tableView.delegate = self tableView.doubleAction = #selector(listDoubleClicked(sender:)) let isSelected = selectTunnelInOperation() || selectTunnel(at: 0) if !isSelected { delegate?.tunnelsListEmpty() } tableView.allowsEmptySelection = false let scrollView = NSScrollView() scrollView.hasVerticalScroller = true scrollView.autohidesScrollers = true scrollView.borderType = .bezelBorder let clipView = NSClipView() clipView.documentView = tableView scrollView.contentView = clipView let buttonBar = NSStackView(views: [addButton, removeButton, actionButton]) buttonBar.orientation = .horizontal buttonBar.spacing = -1 NSLayoutConstraint.activate([ removeButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 26), removeButton.topAnchor.constraint(equalTo: buttonBar.topAnchor), removeButton.bottomAnchor.constraint(equalTo: buttonBar.bottomAnchor) ]) let fillerButton = FillerButton() let containerView = NSView() containerView.addSubview(scrollView) containerView.addSubview(buttonBar) containerView.addSubview(fillerButton) scrollView.translatesAutoresizingMaskIntoConstraints = false buttonBar.translatesAutoresizingMaskIntoConstraints = false fillerButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ containerView.topAnchor.constraint(equalTo: scrollView.topAnchor), containerView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), containerView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), scrollView.bottomAnchor.constraint(equalTo: buttonBar.topAnchor, constant: 1), containerView.leadingAnchor.constraint(equalTo: buttonBar.leadingAnchor), containerView.bottomAnchor.constraint(equalTo: buttonBar.bottomAnchor), scrollView.bottomAnchor.constraint(equalTo: fillerButton.topAnchor, constant: 1), containerView.bottomAnchor.constraint(equalTo: fillerButton.bottomAnchor), buttonBar.trailingAnchor.constraint(equalTo: fillerButton.leadingAnchor, constant: 1), fillerButton.trailingAnchor.constraint(equalTo: containerView.trailingAnchor) ]) NSLayoutConstraint.activate([ containerView.widthAnchor.constraint(equalToConstant: 180), containerView.heightAnchor.constraint(greaterThanOrEqualToConstant: 120) ]) addButton.menu?.items.forEach { $0.target = self } actionButton.menu?.items.forEach { $0.target = self } view = containerView } override func viewWillAppear() { selectTunnelInOperation() } @discardableResult func selectTunnelInOperation() -> Bool { if let currentTunnel = tunnelsManager.tunnelInOperation(), let indexToSelect = tunnelsManager.index(of: currentTunnel) { return selectTunnel(at: indexToSelect) } return false } @objc func handleAddEmptyTunnelAction() { let tunnelEditVC = TunnelEditViewController(tunnelsManager: tunnelsManager, tunnel: nil) tunnelEditVC.delegate = self presentAsSheet(tunnelEditVC) } @objc func handleImportTunnelAction() { ImportPanelPresenter.presentImportPanel(tunnelsManager: tunnelsManager, sourceVC: self) } @objc func handleRemoveTunnelAction() { guard let window = view.window else { return } let selectedTunnelIndices = tableView.selectedRowIndexes.sorted().filter { $0 >= 0 && $0 < tunnelsManager.numberOfTunnels() } guard !selectedTunnelIndices.isEmpty else { return } var nextSelection = selectedTunnelIndices.last! + 1 if nextSelection >= tunnelsManager.numberOfTunnels() { nextSelection = max(selectedTunnelIndices.first! - 1, 0) } let alert = DeleteTunnelsConfirmationAlert() if selectedTunnelIndices.count == 1 { let firstSelectedTunnel = tunnelsManager.tunnel(at: selectedTunnelIndices.first!) alert.messageText = tr(format: "macDeleteTunnelConfirmationAlertMessage (%@)", firstSelectedTunnel.name) } else { alert.messageText = tr(format: "macDeleteMultipleTunnelsConfirmationAlertMessage (%d)", selectedTunnelIndices.count) } alert.informativeText = tr("macDeleteTunnelConfirmationAlertInfo") alert.onDeleteClicked = { [weak self] completion in guard let self = self else { return } self.selectTunnel(at: nextSelection) let selectedTunnels = selectedTunnelIndices.map { self.tunnelsManager.tunnel(at: $0) } self.isRemovingTunnelsFromWithinTheApp = true self.tunnelsManager.removeMultiple(tunnels: selectedTunnels) { [weak self] error in guard let self = self else { return } self.isRemovingTunnelsFromWithinTheApp = false defer { completion() } if let error = error { ErrorPresenter.showErrorAlert(error: error, from: self) return } } } alert.beginSheetModal(for: window) } @objc func handleViewLogAction() { let logVC = LogViewController() self.presentAsSheet(logVC) } @objc func handleExportTunnelsAction() { PrivateDataConfirmation.confirmAccess(to: tr("macExportPrivateData")) { [weak self] in guard let self = self else { return } guard let window = self.view.window else { return } let savePanel = NSSavePanel() savePanel.allowedFileTypes = ["zip"] savePanel.prompt = tr("macSheetButtonExportZip") savePanel.nameFieldLabel = tr("macNameFieldExportZip") savePanel.nameFieldStringValue = "wireguard-export.zip" let tunnelsManager = self.tunnelsManager savePanel.beginSheetModal(for: window) { [weak tunnelsManager] response in guard let tunnelsManager = tunnelsManager else { return } guard response == .OK else { return } guard let destinationURL = savePanel.url else { return } let count = tunnelsManager.numberOfTunnels() let tunnelConfigurations = (0 ..< count).compactMap { tunnelsManager.tunnel(at: $0).tunnelConfiguration } ZipExporter.exportConfigFiles(tunnelConfigurations: tunnelConfigurations, to: destinationURL) { [weak self] error in if let error = error { ErrorPresenter.showErrorAlert(error: error, from: self) return } } } } } @objc func listDoubleClicked(sender: AnyObject) { let tunnelIndex = tableView.clickedRow guard tunnelIndex >= 0 && tunnelIndex < tunnelsManager.numberOfTunnels() else { return } let tunnel = tunnelsManager.tunnel(at: tunnelIndex) if tunnel.status == .inactive { tunnelsManager.startActivation(of: tunnel) } else if tunnel.status == .active { tunnelsManager.startDeactivation(of: tunnel) } } @discardableResult private func selectTunnel(at index: Int) -> Bool { if index < tunnelsManager.numberOfTunnels() { tableView.scrollRowToVisible(index) tableView.selectRowIndexes(IndexSet(integer: index), byExtendingSelection: false) return true } return false } } extension TunnelsListTableViewController: TunnelEditViewControllerDelegate { func tunnelSaved(tunnel: TunnelContainer) { if let tunnelIndex = tunnelsManager.index(of: tunnel), tunnelIndex >= 0 { self.selectTunnel(at: tunnelIndex) } } func tunnelEditingCancelled() { // Nothing to do } } extension TunnelsListTableViewController { func tunnelAdded(at index: Int) { tableView.insertRows(at: IndexSet(integer: index), withAnimation: .slideLeft) if tunnelsManager.numberOfTunnels() == 1 { selectTunnel(at: 0) } if !NSApp.isActive { // macOS's VPN prompt might have caused us to lose focus NSApp.activate(ignoringOtherApps: true) } } func tunnelModified(at index: Int) { tableView.reloadData(forRowIndexes: IndexSet(integer: index), columnIndexes: IndexSet(integer: 0)) } func tunnelMoved(from oldIndex: Int, to newIndex: Int) { tableView.moveRow(at: oldIndex, to: newIndex) } func tunnelRemoved(at index: Int) { let selectedIndices = tableView.selectedRowIndexes let isSingleSelectedTunnelBeingRemoved = selectedIndices.contains(index) && selectedIndices.count == 1 tableView.removeRows(at: IndexSet(integer: index), withAnimation: .slideLeft) if tunnelsManager.numberOfTunnels() == 0 { delegate?.tunnelsListEmpty() } else if !isRemovingTunnelsFromWithinTheApp && isSingleSelectedTunnelBeingRemoved { let newSelection = min(index, tunnelsManager.numberOfTunnels() - 1) tableView.selectRowIndexes(IndexSet(integer: newSelection), byExtendingSelection: false) } } } extension TunnelsListTableViewController: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { return tunnelsManager.numberOfTunnels() } } extension TunnelsListTableViewController: NSTableViewDelegate { func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let cell: TunnelListRow = tableView.dequeueReusableCell() cell.tunnel = tunnelsManager.tunnel(at: row) return cell } func tableViewSelectionDidChange(_ notification: Notification) { let selectedTunnelIndices = tableView.selectedRowIndexes.sorted() if !selectedTunnelIndices.isEmpty { delegate?.tunnelsSelected(tunnelIndices: tableView.selectedRowIndexes.sorted()) } } } extension TunnelsListTableViewController { override func keyDown(with event: NSEvent) { if event.specialKey == .delete { handleRemoveTunnelAction() } } } extension TunnelsListTableViewController: NSMenuItemValidation { func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { if menuItem.action == #selector(TunnelsListTableViewController.handleRemoveTunnelAction) { return !tableView.selectedRowIndexes.isEmpty } return true } } class FillerButton: NSButton { override var intrinsicContentSize: NSSize { return NSSize(width: NSView.noIntrinsicMetric, height: NSView.noIntrinsicMetric) } init() { super.init(frame: CGRect.zero) title = "" bezelStyle = .smallSquare } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func mouseDown(with event: NSEvent) { // Eat mouseDown event, so that the button looks enabled but is unresponsive } }
40.149296
133
0.671017
724776724b0ffadc0b461ff4988545d08f2ec8d8
353
// // CoreDataStack+ImportingTests.swift // CoreDataKit // // Created by Mathijs Kadijk on 05-11-14. // Copyright (c) 2014 Mathijs Kadijk. All rights reserved. // import XCTest import CoreData import CoreDataKit class CoreDataStackImportingTests: TestCase { func testDumpImportConfiguration() { coreDataStack.dumpImportConfiguration() } }
19.611111
59
0.756374
754df894af90b7880b47cb7a2c83e24260f8d91f
2,849
// // PresentViewController.swift // HZSCustomTransition // // Created by HzS on 16/4/8. // Copyright © 2016年 HzS. All rights reserved. // import UIKit class PresentViewController: UIViewController { var interactiveTransition: UIPercentDrivenInteractiveTransition? deinit { print("present deinit") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blue let presentButton = UIButton(type: .system) presentButton.setTitle("present", for: .normal) presentButton.frame = CGRect(x: 0, y: 0, width: 100, height: 30) presentButton.center = view.center presentButton.addTarget(self, action: #selector(PresentViewController.presentAction(_:)), for: .touchUpInside) view.addSubview(presentButton) // let view1 = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) // view1.center = view.center // view1.backgroundColor = UIColor.red //// view1.layer.shadowPath = CGPath(rect: CGRect(x: 0, y: 0, width: 200, height: 200), transform: nil) //// view1.layer.shadowColor = UIColor.black.cgColor //// view1.layer.shadowOffset = CGSize(width: -1, height: 0) //// view1.layer.shadowOpacity = 0.6 // view.addSubview(view1) // // //// DispatchQueue.main.asyncAfter(deadline: .now() + 5) { //// view1.center.y += 100 //// } // // let view2 = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) // view2.backgroundColor = UIColor.yellow // view2.layer.shadowPath = CGPath(rect: CGRect(x: 0, y: 0, width: 200, height: 200), transform: nil) // view2.layer.shadowColor = UIColor.black.cgColor // view2.layer.shadowOffset = CGSize(width: -4, height: 0) // view2.layer.shadowOpacity = 1 // view1.addSubview(view2) // DispatchQueue.main.asyncAfter(deadline: .now() + 5) { // view2.transform = CGAffineTransform(translationX: 100, y: 0) // } } @objc func presentAction(_ sender: AnyObject) { let vc = DismissViewController() vc.transitioningDelegate = self present(vc, animated: true, completion: nil) } } // MARK: - UIViewControllerTransitioningDelegate extension PresentViewController: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return PoPresentOrDismissAnimator(type: .present) } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return PoPresentOrDismissAnimator(type: .dismiss) } }
37
170
0.645841
9c07d0de9ec3a962a8d6a8dc2564b29c01e0e9b1
2,140
// // AppDelegate.swift // TestProject // // Created by Chalomba on 17.05.16. // Copyright © 2016 Chalomba. 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. 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:. } }
45.531915
285
0.754206
8ae405be8bcbb39cc1bda3539b9bc6fc05422e9b
2,335
// // SGBaseViewController.swift // GitBucket // // Created by sulirong on 2018/1/30. // Copyright © 2018年 CleanAirGames. All rights reserved. // import UIKit import Toast_Swift class SGBaseViewController: UIViewController { deinit { showDeinitToast() } override func viewDidLoad() { super.viewDidLoad() setupBackButton() } } extension UIViewController { func showDeinitToast() { guard let keyWindow = UIApplication.shared.keyWindow else { return } var message: String? = nil if let title = self.title { message = "\(title)已释放" } else { let classString = NSStringFromClass(type(of: self)) message = "\(classString)已释放" } keyWindow.showToast(message!) } @objc func tapBackButton(_ button: UIButton) { navigationController?.popViewController(animated: true) } func setupBackButton() { //如果对应的NavigationController,栈中控制器的数量大于1,那么设置返回按钮 if let count = self.navigationController?.viewControllers.count, count > 1 { let normalImage = UIImage(named: "titlebar_back_normal")! let backButton = createCustomBarButton(normalImage: normalImage, selector: #selector(tapBackButton(_:))) let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) fixedSpace.width = -18 navigationItem.leftBarButtonItems = [fixedSpace, backButton] } } func createCustomBarButton(normalImage: UIImage, highlightImage: UIImage? = nil, selector: Selector) -> UIBarButtonItem { let button = UIButton(type: .custom) button.frame = CGRect(x: 0, y: 0, width: 40, height: 40) button.setImage(normalImage, for: .normal) button.setImage(highlightImage, for: .highlighted) button.addTarget(self, action: selector, for: .touchUpInside) return UIBarButtonItem(customView: button) } func handleRequestError(_ error: Error?) { if let nserror = error, (nserror as NSError).code == -1009 { self.view.showToast("您的网络不给力,请检查网络连接") } else { self.view.showToast("网络错误,请稍后再试") } } }
29.935897
125
0.613704
ff479520a38a986b0a6e5c4013ef1d8dced4d906
1,760
// MIT license. Copyright (c) 2019 SwiftyFORM. All rights reserved. import SwiftyFORM class HeaderFooterViewController: FormViewController { let headerView0 = SectionHeaderViewFormItem() let footerView0 = SectionFooterViewFormItem() override func populate(_ builder: FormBuilder) { configureHeaderView0() configureFooterView0() builder.navigationTitle = "Header & Footer" builder.demo_showInfo("Demonstration of\nsection headers\nand section footers") builder += SectionHeaderTitleFormItem().title("Standard Header Title") builder += StaticTextFormItem().title("Empty Row") builder += StaticTextFormItem().title("Empty Row") builder += StaticTextFormItem().title("Empty Row") builder += SectionFooterTitleFormItem().title("Standard Footer Title") builder += headerView0 builder += StaticTextFormItem().title("Empty Row") builder += StaticTextFormItem().title("Empty Row") builder += StaticTextFormItem().title("Empty Row") builder += footerView0 builder += SectionHeaderTitleFormItem().title("Line 1: Standard Header Title\nLine 2: Standard Header Title\nLine 3: Standard Header Title") builder += StaticTextFormItem().title("Empty Row") builder += StaticTextFormItem().title("Empty Row") builder += StaticTextFormItem().title("Empty Row") builder += SectionFooterTitleFormItem(title: "Line 1: Standard Footer Title\nLine 2: Standard Footer Title\nLine 3: Standard Footer Title") } func configureHeaderView0() { headerView0.viewBlock = { return InfoView(frame: CGRect(x: 0, y: 0, width: 0, height: 75), text: "Custom\nHeader\nView") } } func configureFooterView0() { footerView0.viewBlock = { return InfoView(frame: CGRect(x: 0, y: 0, width: 0, height: 75), text: "Custom\nFooter\nView") } } }
40
142
0.74375
4b100f28f7cfe6945ffd8db6b1f1125113b30618
4,068
//===--- BridgeStorage.swift - Discriminated storage for bridged types ----===// // // 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 // //===----------------------------------------------------------------------===// // // Types that are bridged to Objective-C need to manage an object // that may be either some native class or the @objc Cocoa // equivalent. _BridgeStorage discriminates between these two // possibilities and stores a single extra bit when the stored type is // native. It is assumed that the @objc class instance may in fact // be a tagged pointer, and thus no extra bits may be available. // //===----------------------------------------------------------------------===// import SwiftShims @frozen @usableFromInline internal struct _BridgeStorage<NativeClass: AnyObject> { @usableFromInline internal typealias Native = NativeClass @usableFromInline internal typealias ObjC = AnyObject // rawValue is passed inout to _isUnique. Although its value // is unchanged, it must appear mutable to the optimizer. @usableFromInline internal var rawValue: Builtin.BridgeObject @inlinable @inline(__always) internal init(native: Native, isFlagged flag: Bool) { // Note: Some platforms provide more than one spare bit, but the minimum is // a single bit. _internalInvariant(_usesNativeSwiftReferenceCounting(NativeClass.self)) rawValue = _makeNativeBridgeObject( native, flag ? (1 as UInt) << _objectPointerLowSpareBitShift : 0) } @inlinable @inline(__always) internal init(objC: ObjC) { _internalInvariant(_usesNativeSwiftReferenceCounting(NativeClass.self)) rawValue = _makeObjCBridgeObject(objC) } @inlinable @inline(__always) internal init(native: Native) { _internalInvariant(_usesNativeSwiftReferenceCounting(NativeClass.self)) rawValue = Builtin.reinterpretCast(native) } #if !(arch(i386) || arch(arm)) @inlinable @inline(__always) internal init(taggedPayload: UInt) { rawValue = _bridgeObject(taggingPayload: taggedPayload) } #endif @inlinable @inline(__always) internal mutating func isUniquelyReferencedNative() -> Bool { return _isUnique(&rawValue) } @inlinable internal var isNative: Bool { @inline(__always) get { let result = Builtin.classifyBridgeObject(rawValue) return !Bool(Builtin.or_Int1(result.isObjCObject, result.isObjCTaggedPointer)) } } @inlinable static var flagMask: UInt { @inline(__always) get { return (1 as UInt) << _objectPointerLowSpareBitShift } } @inlinable internal var isUnflaggedNative: Bool { @inline(__always) get { return (_bitPattern(rawValue) & (_bridgeObjectTaggedPointerBits | _objCTaggedPointerBits | _objectPointerIsObjCBit | _BridgeStorage.flagMask)) == 0 } } @inlinable internal var isObjC: Bool { @inline(__always) get { return !isNative } } @inlinable internal var nativeInstance: Native { @inline(__always) get { _internalInvariant(isNative) return Builtin.castReferenceFromBridgeObject(rawValue) } } @inlinable internal var unflaggedNativeInstance: Native { @inline(__always) get { _internalInvariant(isNative) _internalInvariant(_nonPointerBits(rawValue) == 0) return Builtin.reinterpretCast(rawValue) } } @inlinable @inline(__always) internal mutating func isUniquelyReferencedUnflaggedNative() -> Bool { _internalInvariant(isNative) return _isUnique_native(&rawValue) } @inlinable internal var objCInstance: ObjC { @inline(__always) get { _internalInvariant(isObjC) return Builtin.castReferenceFromBridgeObject(rawValue) } } }
28.647887
80
0.686824
e62bfe10cf04a203b8da612df4b5227b50ba02aa
3,801
import UIKit import MapKit protocol MapKitAnnotationViewDelegate { func didTapMapKitAnnotationView(_ _mapKitAnnotation: MapKitAnnotation) } class MapKitAnnotation:NSObject, MKAnnotation { let title: String? let locationName: String let discipline: String let coordinate: CLLocationCoordinate2D let mapModel : MapModel init(_ _mapModel: MapModel) { self.mapModel = _mapModel self.title = "" self.locationName = "" self.discipline = "" self.coordinate = CLLocationCoordinate2D(latitude: (mapModel.shopLocationModel.latitude?.doubleValue)! , longitude: (mapModel.shopLocationModel.longitude?.doubleValue)!) super.init() } } class MapKitAnnotationView: MKAnnotationView { open lazy var iconImageView: UIImageView = { let image = UIImageView() self.addSubview(image) return image }() open lazy var nameLabel: UILabel = { let imageView = UIImageView() imageView.image = UIImage(named: "ic_map_left_arrow") imageView.frame = CGRect(x:(image?.size.width)!+4, y: ((image?.size.height)!-(imageView.image?.size.height)!)/2+2, width: (imageView.image?.size.width)!, height: (imageView.image?.size.height)!) self.addSubview(imageView) let label = UILabel() label.numberOfLines = 1 label.backgroundColor = .white label.layer.borderWidth = 1 label.layer.borderColor = UIColor(red: 190/255.0, green: 190/255.0, blue:190/255.0, alpha: 0.3).cgColor label.font = UIFont (name: Global.FONT_NAME_NORMAL, size: Global.FONT_SIZE_NORMAL) label.textColor = .black label.textAlignment = .center self.addSubview(label) return label }() open lazy var clickButton: UIButton = { let button = UIButton(type: .custom) button.addTarget(self, action: #selector(didTapButton(_:)), for: .touchUpInside) self.addSubview(button) return button }() override var annotation: MKAnnotation? { willSet { guard let mapKitAnnotation = newValue as? MapKitAnnotation else {return} image = UIImage(named: "ic_map_red_pin") nameLabel.text = mapKitAnnotation.mapModel.address nameLabel.sizeToFit() nameLabel.frame = CGRect(x:(image?.size.width)!+10, y: (image?.size.height)!/4-2, width: nameLabel.frame.width+10, height: nameLabel.frame.height+4) clickButton.frame = CGRect(x:0, y: 0, width: nameLabel.frame.width+(image?.size.width)!+10, height: (image?.size.height)!) } } @objc func didTapButton(_ sender: UIButton){ if let mapView = mapView, let delegate = mapView.delegate as? MapKitAnnotationViewDelegate { let mapKitAnnotation = annotation as? MapKitAnnotation delegate.didTapMapKitAnnotationView(mapKitAnnotation!) } } var mapView: MKMapView? { var view = superview while view != nil { if let mapView = view as? MKMapView { return mapView } view = view?.superview } return nil } override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let hitView = super.hitTest(point, with: event) if (hitView != nil) { self.superview?.bringSubview(toFront: self) } return hitView } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let rect = self.bounds var isInside: Bool = rect.contains(point) if(!isInside){ for view in self.subviews{ isInside = view.frame.contains(point) if isInside{ break } } } return isInside } }
39.185567
202
0.626677
9cf00fb6f1f1ed82dc2d5bf396af6a642b360a6f
575
// // firstTableViewCell.swift // SwiftNew // // Created by apple on 2020/9/9. // Copyright © 2020 apple. All rights reserved. // import UIKit let identifyStr = "firstTableViewCell" class firstTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
19.166667
65
0.666087
280ae5a4d77babc1f26b258ed001be182c454581
580
// Copyright (c) 2020 Eduardo Vital Alencar Cunha // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. @available(OSX 10.12.2, *) enum ScrubberMode { case fixed case free init(_ mode: String) { switch mode { case "ScrubberMode.fixed": self = Self.fixed case "ScrubberMode.free": fallthrough default: self = Self.free } } func toMode() -> NSScrubber.Mode { switch self { case .fixed: return .fixed case .free: return .free } } }
19.333333
73
0.596552
eb076cc52403afd479849a1aed5e9ec40f6c121e
5,770
// // example.swift // Shapeshifter-Swift-TransportsPackageDescription // // Created by Mafalda on 9/16/19. // import Foundation import Datable import Protean import ProteanSwift import Optimizer #if os(Linux) import NetworkLinux #else import Network #endif /// This is example code to help illustrate how to use the transports provided in this library. /// This is an ongoing work in progress :) // MARK: Protean func exampleSequenceConfig() -> ByteSequenceShaper.Config? { let sequence = Data(string: "OH HELLO") guard let sequenceModel = ByteSequenceShaper.SequenceModel(index: 0, offset: 0, sequence: sequence, length: 256) else { return nil } let sequenceConfig = ByteSequenceShaper.Config(addSequences: [sequenceModel], removeSequences: [sequenceModel]) return sequenceConfig } public func exampleEncryptionConfig() -> EncryptionShaper.Config { let bytes = Data(count: 32) let encryptionConfig = EncryptionShaper.Config(key: bytes) return encryptionConfig } public func exampleHeaderConfig() -> HeaderShaper.Config { // Creates a sample (non-random) config, suitable for testing. let header = Data([139, 210, 37]) let headerConfig = HeaderShaper.Config(addHeader: header, removHeader: header) return headerConfig } func proteanExample() { let ipv4Address = IPv4Address("10.10.10.10")! let portUInt = UInt16("7007")! let port = NWEndpoint.Port(rawValue: portUInt)! let host = NWEndpoint.Host.ipv4(ipv4Address) // Create a Protean config using your chosen sequence, encryption, and header let proteanConfig = Protean.Config( byteSequenceConfig: exampleSequenceConfig(), encryptionConfig: exampleEncryptionConfig(), headerConfig: exampleHeaderConfig()) // Create the connection factory providing your config and the desires IP and port let proteanConnectionFactory = ProteanConnectionFactory(host: host, port: port, config: proteanConfig) // Create a connection using the Protean connection factory guard var connection = proteanConnectionFactory.connect else { print("Failed to create a Protean connection object.") return } // Set up your state update handler. connection.stateUpdateHandler = { (newState) in switch newState { case .ready: print("Connection is read") connected1.fulfill() case .failed(let error): print("Connection Failed") print("Failure Error: \(error.localizedDescription)\n") connected1.fulfill() default: print("Connection Other State: \(newState)") } } // Tell the connection to start. connection.start(queue: DispatchQueue(label: "TestQueue")) } // MARK: Optimizer /// This is an example of creating and starting a network connection using Optimizer's CoreML Strategy. /// This example also shows the way to get instances of some of our other transports. func coreMLStrategyExample() { let ipv4Address = IPv4Address("10.10.10.10")! let portUInt = UInt16("7007")! let port = NWEndpoint.Port(rawValue: portUInt)! let host = NWEndpoint.Host.ipv4(ipv4Address) let logQueue = Queue<String>() let certString = "examplecertstring" let serverPublicKey = Data(base64Encoded: "exampleserverpublickeystring")! // Create a Protean Transport Instance let proteanConfig = Protean.Config(byteSequenceConfig: exampleSequenceConfig(), encryptionConfig: exampleEncryptionConfig(), headerConfig: exampleHeaderConfig()) let proteanTransport = ProteanConnectionFactory(host: host, port: port, config: proteanConfig) // Create a Replicant transport instance. guard let replicantClientConfig = ReplicantConfig(serverPublicKey: serverPublicKey, chunkSize: 2000, chunkTimeout: 1000, toneBurst: nil) else { print("\nUnable to create ReplicantClient config.\n") return } let replicantTransport = ReplicantConnectionFactory(host: host, port: port, config: replicantClientConfig, logQueue: logQueue) // Create a Wisp transport instance. let wispTransport = WispConnectionFactory(host: host, port: port, cert: certString, iatMode: false) // Create an array with all of the transports that Optimizer should choose from. let possibleTransports:[ConnectionFactory] = [wispTransport, replicantTransport, proteanTransport] // Create an instance of your chosen Strategy using the array of transports let strategy = CoreMLStrategy(transports: possibleTransports) // Create an OptimizerConnectionFactory instance using your Strategy. let connectionFactory = OptimizerConnectionFactory(strategy: strategy) // Create the connection using the OptimizerConnectionFactory instance. guard var connection = connectionFactory!.connect(using: .tcp) else { return } // Set up your state update handler. connection.stateUpdateHandler = { (newState) in switch newState { case .ready: print("Connection is read") connected1.fulfill() case .failed(let error): print("Connection Failed") print("Failure Error: \(error.localizedDescription)\n") connected1.fulfill() default: print("Connection Other State: \(newState)") } } // Tell the connection to start. connection.start(queue: DispatchQueue(label: "TestQueue")) }
31.878453
140
0.670884
692c99c3c42160fb0e805e3291e04bc84934d52b
310
import RxSwift class DeepLinkService { private let deepLinkManager: DeepLinkManager init(deepLinkManager: DeepLinkManager) { self.deepLinkManager = deepLinkManager } var deepLinkObservable: Observable<DeepLinkManager.DeepLink?> { deepLinkManager.newSchemeObservable } }
20.666667
67
0.73871
01cb50f4cb80ca4fff48cbf571a4068f4530bc86
2,202
// Copyright 2021 Google LLC // // 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 final class AppDataStorage { var defaults: UserDefaults? = { guard let defaults = UserDefaults(suiteName: "AppDataStorage") else { assertionFailure("Unable to create UserDefaults for suiteName: AppDataStorage") return nil } return defaults }() func store<V: Codable>(_ value: V, for key: String) { defaults?.set(encodable: value, forKey: key) } func retrieve<T: Codable>(for key: String) -> T? { return defaults?.value(T.self, forKey: key) } func remove(key: String) { defaults?.removeObject(forKey: key) } } extension UserDefaults { private var primitiveTypes: [Encodable.Type] { return [ UInt.self, UInt8.self, UInt16.self, UInt32.self, UInt64.self, Int.self, Int8.self, Int16.self, Int32.self, Int64.self, Float.self, Double.self, String.self, Bool.self, Date.self, ] } /// Allows the storing of type T that conforms to the Encodable protocol. func set<T: Encodable>(encodable: T, forKey key: String) { if primitiveTypes.first(where: { return $0 is T.Type }) != nil { set(encodable, forKey: key) } else if let data = try? PropertyListEncoder().encode(encodable) { set(data, forKey: key) } } /// Allows for retrieval of type T that conforms to the Decodable protocol. func value<T: Decodable>(_ type: T.Type, forKey key: String) -> T? { if let value = object(forKey: key) as? T { return value } else if let data = object(forKey: key) as? Data, let value = try? PropertyListDecoder().decode(type, from: data) { return value } return nil } }
31.913043
100
0.682561
f8f7c01d30299dd19d8cc5c3b46fc1d08f4eae82
2,386
//////////////////////////////////////////////////////////////////////////// // // Copyright 2020 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import SwiftUI import RealmSwift struct RecipeFormView: View { let recipes: RealmSwift.List<Recipe> @State var showIngredientForm = false @State var draftRecipe = Recipe() @Binding var showRecipeFormView: Bool var body: some View { Form { Section(header: Text("recipe name")) { TextField("recipe name", text: self.$draftRecipe.name) } Section(header: Text("ingredients")) { VStack { ForEach(Array(self.draftRecipe.ingredients), id: \.self) { ingredient in HStack { URLImage(ingredient.foodType!.imgUrl) Text(ingredient.name!) } } Button("add ingredient") { self.showIngredientForm = true } } } Button("save") { self.recipes.realm?.beginWrite() self.recipes.append(self.draftRecipe) try! self.recipes.realm?.commitWrite() self.showRecipeFormView = false } }.navigationBarTitle("make recipe") .sheet(isPresented: $showIngredientForm, content: { IngredientFormView(recipe: self.$draftRecipe, showIngredientForm: self.$showIngredientForm) }) } } struct RecipeFormViewPreviews: PreviewProvider { static var previews: some View { RecipeFormView(recipes: RealmSwift.List<Recipe>(), showRecipeFormView: .constant(true)) } }
36.707692
95
0.544426
3aa52dd707c5c04db9c5fc57900e9286ec1fe702
513
import Foundation import enum BadondeKit.Log extension Logger { static func logBadondefileLog(_ log: Log) { let indentationLevel = 3 switch log { case .step(let description): step(indentationLevel: indentationLevel, description) case .info(let description): info(indentationLevel: indentationLevel, description) case .warn(let description): warn(indentationLevel: indentationLevel, description) case .fail(let description): fail(indentationLevel: indentationLevel, description) } } }
27
56
0.766082
1a6a3845abca479967003def31f45c76942b8b6d
1,836
// Generated using Sourcery 0.17.1 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT // swiftlint:disable vertical_whitespace trailing_newline import Foundation extension NSCoder { @nonobjc func decode(forKey: String) -> String? { return self.maybeDecode(forKey: forKey) as String? } @nonobjc func decode(forKey: String) -> TypeName? { return self.maybeDecode(forKey: forKey) as TypeName? } @nonobjc func decode(forKey: String) -> AccessLevel? { return self.maybeDecode(forKey: forKey) as AccessLevel? } @nonobjc func decode(forKey: String) -> Bool { return self.decodeBool(forKey: forKey) } @nonobjc func decode(forKey: String) -> Int { return self.decodeInteger(forKey: forKey) } func decode<E>(forKey: String) -> E? { return maybeDecode(forKey: forKey) as E? } fileprivate func maybeDecode<E>(forKey: String) -> E? { guard let object = self.decodeObject(forKey: forKey) else { return nil } return object as? E } } extension ArrayType: NSCoding {} extension AssociatedValue: NSCoding {} extension Attribute: NSCoding {} extension BytesRange: NSCoding {} extension ClosureType: NSCoding {} extension DictionaryType: NSCoding {} extension EnumCase: NSCoding {} extension FileParserResult: NSCoding {} extension GenericType: NSCoding {} extension GenericTypeParameter: NSCoding {} extension Method: NSCoding {} extension MethodParameter: NSCoding {} extension Subscript: NSCoding {} extension TemplateContext: NSCoding {} extension TupleElement: NSCoding {} extension TupleType: NSCoding {} extension Type: NSCoding {} extension TypeName: NSCoding {} extension Typealias: NSCoding {} extension Types: NSCoding {} extension Variable: NSCoding {}
20.175824
82
0.695534
221837e383681bc5cbe153f4d68401a9b9e40d86
22,055
// // PbUIRefreshView.swift // pb.swift.ui // 滚动视图使用的下拉或上拉刷新视图 // Created by Maqiang on 15/7/7. // Copyright (c) 2015年 Maqiang. All rights reserved. // import Foundation import UIKit /**枚举类型,刷新状态 * pulling :拖拽中 * normal :正常 * refreshing :刷新中 * willRefreshing :将要刷新 */ public enum PbUIRefreshState:Int { case pulling,normal,refreshing,willRefreshing } /**枚举类型,刷新位置 * header:头部 * footer:底部 */ public enum PbUIRefreshPosition:Int { case header,footer } /// 对刷新控件进行配置 public protocol PbUIRefreshConfigProtocol { /// 刷新控件的背景颜色 func pbUIRefreshViewBackgroudColor() -> UIColor /// 刷新控件的显示字体大小 func pbUIRefreshLabelFontSize() -> CGFloat /// 刷新控件的显示字体颜色 func pbUIRefreshLabelTextColor() -> UIColor /// 刷新控件的指示器 func pbUIRefreshActivityView() -> PbUIActivityIndicator? /// 刷新控件的指示器的默认尺寸 func pbUIRefreshActivityDefaultSize() -> CGSize /// 刷新控件的指示器的默认颜色 func pbUIRefreshActivityDefaultColor() -> UIColor } /// 箭头视图 open class PbUIArrowView:UIView { /// 初始化 override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor=UIColor.clear } required public init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) self.backgroundColor=UIColor.clear } /// 绘制内容 override open func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() let offset:CGFloat=4 context?.setLineWidth(2.0) context?.setStrokeColor(self.tintColor.cgColor) context?.move(to: CGPoint(x: self.bounds.midX, y: offset)) context?.addLine(to: CGPoint(x: self.bounds.midX, y: self.bounds.height-offset*2)) let offsetX=(self.bounds.width-offset*2)/4 let offsetY=(self.bounds.height-offset*2)/3 context?.addLine(to: CGPoint(x: self.bounds.midX-offsetX, y: self.bounds.height-offsetY-offset*2)) context?.move(to: CGPoint(x: self.bounds.midX, y: self.bounds.height-offset*2)) context?.addLine(to: CGPoint(x: self.bounds.midX+offsetX, y: self.bounds.height-offsetY-offset*2)) context?.strokePath() } } /// 刷新基本视图 open class PbUIRefreshBaseView:UIView { /// 默认颜色 let textColor=UIColor.darkGray /// 父类控件 var scrollView:UIScrollView! var scrollViewOriginalInset:UIEdgeInsets! /// 内部显示控件 var statusLabel:UILabel! var arrowView:PbUIArrowView! var activityView:PbUIActivityIndicator! /// 回执方法 var beginRefreshingCallback:(()->Void)? //记录状态 /// 历史状态 var oldState:PbUIRefreshState? /// 记录状态 var state=PbUIRefreshState.normal /// 配置协议 var config:PbUIRefreshConfigProtocol? /// 初始化方法 override init(frame: CGRect) { super.init(frame: frame) setup() } init(frame: CGRect,config:PbUIRefreshConfigProtocol) { super.init(frame: frame) self.config=config setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) setup() } /// 创建载入指示器 func createActivityView() -> PbUIActivityIndicator { let indicator=PbUIRingSpinnerView(frame: CGRect.zero) let size=(self.config == nil ? CGSize(width: 32,height: 32) : self.config!.pbUIRefreshActivityDefaultSize()) indicator.bounds=CGRect(x: 0, y: 0, width: size.width, height: size.height) indicator.tintColor=(self.config == nil ? UIColor(red:215/255, green: 49/255, blue: 69/255, alpha: 1) : self.config!.pbUIRefreshActivityDefaultColor()) indicator.stopAnimating() return indicator } /// 设置内部布局 override open func layoutSubviews() { super.layoutSubviews() //箭头 let arrowX:CGFloat = self.frame.size.width * 0.5 - 80 self.arrowView.center = CGPoint(x: arrowX, y: self.frame.size.height * 0.5) //指示器 (self.activityView as! UIView).center = self.arrowView.center (self.activityView as! UIView).isHidden=true } /// 设置父控件 override open func willMove(toSuperview newSuperview: UIView?) { if (self.superview != nil) { self.superview!.removeObserver(self,forKeyPath:"contentSize",context: nil) } if (newSuperview != nil) { newSuperview!.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil) var rect:CGRect = self.frame rect.size.width = newSuperview!.frame.size.width rect.origin.x = 0 self.frame = frame; scrollView = newSuperview as! UIScrollView scrollViewOriginalInset = scrollView.contentInset; } } /// 显示到屏幕上 override open func draw(_ rect: CGRect) { super.draw(rect) if(self.state == PbUIRefreshState.willRefreshing) { self.state = PbUIRefreshState.refreshing } } /// 开始刷新 func beginRefreshing() { if (self.window != nil) { self.state = PbUIRefreshState.refreshing; } else { state = PbUIRefreshState.willRefreshing; super.setNeedsDisplay() } } /// 结束刷新 func endRefreshing() { let delayInSeconds:Double = 0.3 let popTime:DispatchTime = DispatchTime.now() + Double(Int64(delayInSeconds)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: popTime, execute: { self.state = PbUIRefreshState.normal; }) } /// 设置状态 func setStateForView(_ newValue:PbUIRefreshState) { if self.state != PbUIRefreshState.refreshing { scrollViewOriginalInset = self.scrollView.contentInset; } if self.state == newValue {return} switch newValue { case .normal: self.arrowView.layer.opacity=1 self.activityView.stopAnimating() (self.activityView as! UIView).isHidden=true break case .pulling: break case .refreshing: self.arrowView.layer.opacity=0 (self.activityView as! UIView).isHidden=false activityView.startAnimating() if(beginRefreshingCallback != nil){beginRefreshingCallback!()} break default: break } } /// 初始化内部控件 fileprivate func setup() { //状态标签 statusLabel = UILabel() statusLabel.autoresizingMask = UIViewAutoresizing.flexibleWidth statusLabel.font = UIFont.boldSystemFont(ofSize: self.config == nil ? 12 : self.config!.pbUIRefreshLabelFontSize()) statusLabel.textColor = self.config == nil ? textColor : self.config!.pbUIRefreshLabelTextColor() statusLabel.backgroundColor = UIColor.clear statusLabel.textAlignment = NSTextAlignment.center self.addSubview(statusLabel) //箭头图片 arrowView = PbUIArrowView(frame:CGRect.zero) let size=(self.config == nil ? CGSize(width: 32,height: 32) : self.config!.pbUIRefreshActivityDefaultSize()) arrowView.bounds=CGRect(x: 0, y: 0, width: size.width, height: size.height) arrowView.tintColor=(self.config == nil ? UIColor(red:215/255, green: 49/255, blue: 69/255, alpha: 1) : self.config!.pbUIRefreshActivityDefaultColor()) arrowView.isHidden=true self.addSubview(arrowView) //状态标签 self.activityView=(self.config == nil ? self.createActivityView() : self.config!.pbUIRefreshActivityView()) self.activityView=(self.activityView == nil) ? self.createActivityView() : self.activityView (self.activityView as! UIView).isHidden=true self.addSubview(self.activityView as! UIView) //自己的属性 self.autoresizingMask = UIViewAutoresizing.flexibleWidth self.backgroundColor = UIColor.clear //设置默认状态 self.state = PbUIRefreshState.normal self.backgroundColor=(self.config == nil ? UIColor.clear : self.config!.pbUIRefreshViewBackgroudColor()) } } /// 顶部刷新视图 open class PbUIRefreshHeaderView:PbUIRefreshBaseView { /// 记录最后更新时间 var lastUpdateTime=Date(){willSet{}didSet{}} /// 更新时间标签 var updateTimeLabel:UILabel? /// 覆盖父类属性,增加设置状态 override var state:PbUIRefreshState { willSet { if(state==newValue){return} oldState=state setStateForView(newValue) } didSet { switch state { case .normal: self.statusLabel.text = "上拉可以刷新" if PbUIRefreshState.refreshing == oldState { self.arrowView.transform = CGAffineTransform.identity self.lastUpdateTime = Date() self.updateTimeLabel?.text=String.date("yyyy年MM月dd日 HH:mm") UIView.animate(withDuration: 0.3, animations: { var contentInset:UIEdgeInsets = self.scrollView.contentInset contentInset.top = self.scrollViewOriginalInset.top self.scrollView.contentInset = contentInset }) } else { UIView.animate(withDuration: 0.3, animations: { self.arrowView.transform = CGAffineTransform.identity }) } break case .pulling: self.statusLabel.text = "松开立即刷新" UIView.animate(withDuration: 0.3, animations: { self.arrowView.transform = CGAffineTransform(rotationAngle: CGFloat.pi) }) break case .refreshing: self.statusLabel.text = "正在刷新中..."; UIView.animate(withDuration: 0.3, animations: { let top:CGFloat = self.scrollViewOriginalInset.top + self.frame.size.height var inset:UIEdgeInsets = self.scrollView.contentInset inset.top = top self.scrollView.contentInset = inset var offset:CGPoint = self.scrollView.contentOffset offset.y = -top self.scrollView.contentOffset = offset }) break default: break } } } /// 初始化方法 override public init(frame: CGRect) { super.init(frame: frame) setup() } override public init(frame: CGRect, config: PbUIRefreshConfigProtocol) { super.init(frame: frame, config: config) } required public init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) setup() } /// 设置内部布局 override open func layoutSubviews() { super.layoutSubviews() let statusX:CGFloat = 0 let statusY:CGFloat = 6 let statusHeight:CGFloat = self.frame.size.height * 0.5 let statusWidth:CGFloat = self.frame.size.width //状态标签 self.statusLabel.frame = CGRect(x: statusX, y: statusY, width: statusWidth, height: statusHeight) //时间标签 let lastUpdateY:CGFloat = statusHeight-statusY let lastUpdateX:CGFloat = 0 let lastUpdateHeight:CGFloat = statusHeight let lastUpdateWidth:CGFloat = statusWidth self.updateTimeLabel!.frame = CGRect(x: lastUpdateX, y: lastUpdateY, width: lastUpdateWidth, height: lastUpdateHeight); } /// 设置自己的位置和尺寸 override open func willMove(toSuperview newSuperview: UIView!) { super.willMove(toSuperview: newSuperview) var rect:CGRect = self.frame rect.origin.y = -self.frame.size.height self.frame = rect } /// 监听UIScrollView的contentOffset属性 override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if (!self.isUserInteractionEnabled || self.isHidden){return} if (self.state == PbUIRefreshState.refreshing){return} if "contentOffset".isEqual(keyPath!) { self.adjustStateWithContentOffset() } } /// 调整状态 func adjustStateWithContentOffset() { let currentOffsetY:CGFloat = self.scrollView.contentOffset.y let happenOffsetY:CGFloat = -self.scrollViewOriginalInset.top if (currentOffsetY >= happenOffsetY){return} if self.scrollView.isDragging { let normal2pullingOffsetY:CGFloat = happenOffsetY - self.frame.size.height if(self.state == PbUIRefreshState.normal && currentOffsetY < normal2pullingOffsetY) { self.state = PbUIRefreshState.pulling } else if(self.state == PbUIRefreshState.pulling && currentOffsetY >= normal2pullingOffsetY) { self.state = PbUIRefreshState.normal } } else if(self.state == PbUIRefreshState.pulling) { self.state = PbUIRefreshState.refreshing } } /// 初始化内部控件 fileprivate override func setup() { super.setup() updateTimeLabel = UILabel() updateTimeLabel!.autoresizingMask = UIViewAutoresizing.flexibleWidth updateTimeLabel!.font = UIFont.boldSystemFont(ofSize: self.config == nil ? 12 : self.config!.pbUIRefreshLabelFontSize()) updateTimeLabel!.textColor = self.config == nil ? textColor : self.config!.pbUIRefreshLabelTextColor() updateTimeLabel!.backgroundColor = UIColor.clear updateTimeLabel!.textAlignment = NSTextAlignment.center self.addSubview(updateTimeLabel!); } } //PbUIRefreshFooterView:底部加载视图 //class PbUIRefreshFooterView:PbUIRefreshBaseView //{ // var lastRefreshCount:Int = 0 // //state:覆盖父类属性,增加设置状态 // override var state:PbUIRefreshState // { // willSet // { // if(state==newValue){return} // oldState=state // setStateForView(newValue) // } // didSet // { // switch state // { // case .Normal: // // self.statusLabel.text = "加载更多"; // if (PbUIRefreshState.Refreshing == oldState) // { // self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat.pi) // UIView.animateWithDuration(0.3, animations: // { // self.scrollView.contentInset.bottom = self.scrollViewOriginalInset.bottom // }) // } // else // { // UIView.animateWithDuration(0.3, animations: // { // self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat.pi); // }) // } // // var deltaH:CGFloat = self.heightForContentBreakView() // var currentCount:Int = self.totalDataCountInScrollView() // // if (PbUIRefreshState.Refreshing == oldState && deltaH > 0 && currentCount != self.lastRefreshCount) // { // var offset:CGPoint = self.scrollView.contentOffset; // offset.y = self.scrollView.contentOffset.y // self.scrollView.contentOffset = offset; // } // // break // // case .Pulling: // // self.statusLabel.text = "松开加载" // UIView.animateWithDuration(0.3, animations: // { // self.arrowView.transform = CGAffineTransformIdentity // }) // // break // // case .Refreshing: // // self.statusLabel.text = "正在加载"; // self.lastRefreshCount = self.totalDataCountInScrollView(); // UIView.animateWithDuration(0.3, animations: // { // var bottom:CGFloat = self.frame.size.height + self.scrollViewOriginalInset.bottom // var deltaH:CGFloat = self.heightForContentBreakView() // if(deltaH < 0){bottom = bottom - deltaH} // var inset:UIEdgeInsets = self.scrollView.contentInset; // inset.bottom = bottom; // self.scrollView.contentInset = inset; // }) // // break // default: // break // // } // } // } // // //layoutSubviews:设置内部布局 // override func layoutSubviews() // { // super.layoutSubviews() // self.statusLabel.frame = self.bounds // } // // //willMoveToSuperview:设置自己的位置和尺寸 // override func willMoveToSuperview(newSuperview: UIView?) // { // super.willMoveToSuperview(newSuperview) // // if(self.superview != nil) // { // self.superview!.removeObserver(self, forKeyPath:"contentSize", context: nil) // } // if (newSuperview != nil) // { // newSuperview!.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil) // // 重新调整frame // adjustFrameWithContentSize() // } // } // // //observeValueForKeyPath:监听UIScrollView的contentOffset属性 // override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) // { // if(!self.userInteractionEnabled || self.hidden){return} // // if("contentSize".isEqualToString(keyPath)) // { // adjustFrameWithContentSize() // } // else if("contentOffset".isEqualToString(keyPath)) // { // if(self.state == PbUIRefreshState.Refreshing){return} // adjustStateWithContentOffset() // } // } // // //adjustStateWithContentOffset:调整状态 // func adjustFrameWithContentSize() // { // var contentHeight:CGFloat = self.scrollView.contentSize.height // var scrollHeight:CGFloat = self.scrollView.frame.size.height - self.scrollViewOriginalInset.top - self.scrollViewOriginalInset.bottom // var rect:CGRect = self.frame; // rect.origin.y = contentHeight > scrollHeight ? contentHeight : scrollHeight // self.frame = rect; // } // // //adjustStateWithContentOffset:调整状态 // func adjustStateWithContentOffset() // { // var currentOffsetY:CGFloat = self.scrollView.contentOffset.y // var happenOffsetY:CGFloat = self.happenOffsetY() // if(currentOffsetY <= happenOffsetY){return} // // if self.scrollView.dragging // { // var normal2pullingOffsetY = happenOffsetY + self.frame.size.height // if self.state == PbUIRefreshState.Normal && currentOffsetY > normal2pullingOffsetY // { // self.state = PbUIRefreshState.Pulling; // } // else if (self.state == PbUIRefreshState.Pulling && currentOffsetY <= normal2pullingOffsetY) // { // self.state = PbUIRefreshState.Normal; // } // } // else if (self.state == PbUIRefreshState.Pulling) // { // self.state = PbUIRefreshState.Refreshing // } // } // // func totalDataCountInScrollView()->Int // { // var totalCount:Int = 0 // if self.scrollView is UITableView // { // var tableView:UITableView = self.scrollView as! UITableView // // for (var i:Int = 0 ; i < tableView.numberOfSections() ; i++) // { // totalCount = totalCount + tableView.numberOfRowsInSection(i) // } // } // else if self.scrollView is UICollectionView // { // var collectionView:UICollectionView = self.scrollView as! UICollectionView // for (var i:Int = 0 ; i < collectionView.numberOfSections() ; i++) // { // totalCount = totalCount + collectionView.numberOfItemsInSection(i) // } // } // return totalCount // } // // func heightForContentBreakView()->CGFloat // { // var h:CGFloat = self.scrollView.frame.size.height - self.scrollViewOriginalInset.bottom - self.scrollViewOriginalInset.top; // return self.scrollView.contentSize.height - h; // } // // // func happenOffsetY()->CGFloat // { // var deltaH:CGFloat = self.heightForContentBreakView() // if(deltaH > 0) // { // return deltaH - self.scrollViewOriginalInset.top; // } // else // { // return -self.scrollViewOriginalInset.top; // } // } //}
33.26546
159
0.555792
21d492edd068ffff71035e14e4a36824bc954e42
838
// // AssignAddressCommand.swift // OmniKit // // Created by Pete Schwamb on 2/12/18. // Copyright © 2018 Pete Schwamb. All rights reserved. // import Foundation public struct AssignAddressCommand : MessageBlock { public let blockType: MessageBlockType = .assignAddress public let length: Int = 6 let address: UInt32 public var data: Data { var data = Data(bytes: [ blockType.rawValue, 4 ]) data.appendBigEndian(self.address) return data } public init(encodedData: Data) throws { if encodedData.count < length { throw MessageBlockError.notEnoughData } self.address = encodedData[2...].toBigEndian(UInt32.self) } public init(address: UInt32) { self.address = address } }
21.487179
65
0.606205
6af1b6575334c960095cd3c0ce5e557ac0dd74be
2,948
// // ViewController.swift // SlideMenuControllerSwift // // Created by Yuji Hato on 12/3/14. // import UIKit class MainViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var mainContens = ["data1", "data2", "data3", "data4", "data5", "data6", "data7", "data8", "data9", "data10", "data11", "data12", "data13", "data14", "data15"] override func viewDidLoad() { super.viewDidLoad() self.tableView.registerCellNib(DataTableViewCell.self) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.setNavigationBarItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension MainViewController : UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return DataTableViewCell.height() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let storyboard = UIStoryboard(name: "SubContentsViewController", bundle: nil) let subContentsVC = storyboard.instantiateViewController(withIdentifier: "SubContentsViewController") as! SubContentsViewController self.navigationController?.pushViewController(subContentsVC, animated: true) } } extension MainViewController : UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.mainContens.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCell(withIdentifier: DataTableViewCell.identifier) as! DataTableViewCell let data = DataTableViewCellData(imageUrl: "dummy", text: mainContens[indexPath.row]) cell.setData(data) return cell } } extension MainViewController : SlideMenuControllerDelegate { func leftWillOpen() { print("SlideMenuControllerDelegate: leftWillOpen") } func leftDidOpen() { print("SlideMenuControllerDelegate: leftDidOpen") } func leftWillClose() { print("SlideMenuControllerDelegate: leftWillClose") } func leftDidClose() { print("SlideMenuControllerDelegate: leftDidClose") } func rightWillOpen() { print("SlideMenuControllerDelegate: rightWillOpen") } func rightDidOpen() { print("SlideMenuControllerDelegate: rightDidOpen") } func rightWillClose() { print("SlideMenuControllerDelegate: rightWillClose") } func rightDidClose() { print("SlideMenuControllerDelegate: rightDidClose") } }
30.708333
163
0.692673
e4de37bb86b30a9963cfb9b14b76f0549e9940f6
1,079
// // ObjectExtension.swift // XLProjectName // // Created by XLAuthorName // Copyright © 2018年 'XLOrganizationName'. All rights reserved. // //import Foundation //import RealmSwift // //public extension Object { // // public func insert(_ realm: Realm? = nil) throws { // let realm = (realm != nil) ? realm : RealmProvider.realm() // try realm?.write { // realm?.add(self) // } // } // // public func update(_ realm: Realm? = nil) throws { // let realm = (realm != nil) ? realm : RealmProvider.realm() // try realm?.write { // realm?.add(self, update: true) // } // } // // public func delete(_ realm: Realm? = nil) throws { // let realm = (realm != nil) ? realm : RealmProvider.realm() // try realm?.write { // realm?.delete(self) // } // } // // public func edit(_ realm: Realm? = nil, _ hundler: (() -> Void) ) throws { // let realm = (realm != nil) ? realm : RealmProvider.realm() // try realm?.write(hundler) // } //}
26.975
80
0.531974
71cfbf5aa57acc70db394642046fc963647d9c4f
2,746
// // Publisher+Retry.swift // SwiftUICombineNetworking // // Created by Peter Friese on 03.03.22. // import Foundation import Combine enum RetryStrategy { case retry(retries: Int = 2, delay: Int = 3) case skip } extension Publisher { func retry<T, E>(_ strategy: @escaping ((E) -> RetryStrategy)) -> Publishers.TryCatch<Self, AnyPublisher<T, E>> where T == Self.Output, E == Self.Failure { return self.tryCatch { error -> AnyPublisher<T, E> in let strategy = strategy(error) if case .retry(let retries, let delay) = strategy { return Just(Void()) .delay(for: .init(integerLiteral: delay), scheduler: DispatchQueue.global()) .flatMap { _ in return self } .retry(retries) .eraseToAnyPublisher() } else { throw error } } } func retry<T, E>(_ retries: Int, withDelay: @escaping ((E) -> Int)) -> Publishers.TryCatch<Self, AnyPublisher<T, E>> where T == Self.Output, E == Self.Failure { return self.tryCatch { error -> AnyPublisher<T, E> in let delay = withDelay(error) return Just(Void()) .delay(for: .init(integerLiteral: delay), scheduler: DispatchQueue.global()) .flatMap { _ in return self } .retry(retries) .eraseToAnyPublisher() } } func retry<T, E>(_ retries: Int, withDelay delay: Int, condition: ((E) -> Bool)? = nil) -> Publishers.TryCatch<Self, AnyPublisher<T, E>> where T == Self.Output, E == Self.Failure { return self.tryCatch { error -> AnyPublisher<T, E> in if condition?(error) == true { return Just(Void()) .delay(for: .init(integerLiteral: delay), scheduler: DispatchQueue.global()) .flatMap { _ in return self } .retry(retries) .eraseToAnyPublisher() } else { throw error } } } func retry<T, E>(_ retries: Int, withBackoff initialBackoff: Int, condition: ((E) -> Bool)? = nil) -> Publishers.TryCatch<Self, AnyPublisher<T, E>> where T == Self.Output, E == Self.Failure { return self.tryCatch { error -> AnyPublisher<T, E> in if condition?(error) ?? true { var backOff = initialBackoff return Just(Void()) .flatMap { _ -> AnyPublisher<T, E> in let result = Just(Void()) .delay(for: .init(integerLiteral: backOff), scheduler: DispatchQueue.global()) .flatMap { _ in return self } backOff = backOff * 2 return result.eraseToAnyPublisher() } .retry(retries - 1) .eraseToAnyPublisher() } else { throw error } } } }
31.204545
193
0.570648
e26946df82a49ba09cc85745cb78d9333f973fb6
13,690
import Foundation import UIKit import AmazonIVSPlayer @objc(AmazonIvsView) class AmazonIvsView: UIView, IVSPlayer.Delegate { @objc var onSeek: RCTDirectEventBlock? @objc var onData: RCTDirectEventBlock? @objc var onVideoStatistics: RCTDirectEventBlock? @objc var onPlayerStateChange: RCTDirectEventBlock? @objc var onDurationChange: RCTDirectEventBlock? @objc var onQualityChange: RCTDirectEventBlock? @objc var onRebuffering: RCTDirectEventBlock? @objc var onLoadStart: RCTDirectEventBlock? @objc var onLoad: RCTDirectEventBlock? @objc var onTextCue: RCTDirectEventBlock? @objc var onTextMetadataCue: RCTDirectEventBlock? @objc var onLiveLatencyChange: RCTDirectEventBlock? @objc var onProgress: RCTDirectEventBlock? @objc var onTimePoint: RCTDirectEventBlock? @objc var onError: RCTDirectEventBlock? private let player = IVSPlayer() private let playerView = IVSPlayerView() private var finishedLoading: Bool = false; private var progressObserverToken: Any? private var playerObserverToken: Any? private var timePointObserver: Any? private var oldQualities: [IVSQuality] = []; private var lastLiveLatency: Double?; private var lastBitrate: Int?; private var lastDuration: CMTime?; private var lastFramesDropped: Int?; private var lastFramesDecoded: Int?; override init(frame: CGRect) { self.muted = player.muted self.liveLowLatency = player.isLiveLowLatency self.autoQualityMode = player.autoQualityMode self.playbackRate = Double(player.playbackRate) self.logLevel = NSNumber(value: player.logLevel.rawValue) self.progressInterval = 1 self.volume = Double(player.volume) self.breakpoints = [] super.init(frame: frame) self.addSubview(self.playerView) self.playerView.autoresizingMask = [.flexibleHeight, .flexibleWidth] self.addProgressObserver() self.addPlayerObserver() self.addTimePointObserver() self.addApplicationLifecycleObservers() player.delegate = self self.playerView.player = player } deinit { self.removeProgressObserver() self.removePlayerObserver() self.removeTimePointObserver() self.removeApplicationLifecycleObservers() } func load(urlString: String) { finishedLoading = false let url = URL(string: urlString) onLoadStart?(["": NSNull()]) player.load(url) } @objc var progressInterval: NSNumber { // TODO: Figure out why updatating observer does not work and results in multiple calls per second didSet { self.removeProgressObserver() self.addProgressObserver() } } @objc var muted: Bool { didSet { player.muted = muted } } @objc var playbackRate: Double { didSet { player.playbackRate = Float(playbackRate) } } @objc var liveLowLatency: Bool { didSet { player.setLiveLowLatencyEnabled(liveLowLatency) } } @objc var quality: NSDictionary? { didSet { let newQuality = findQuality(quality: quality) player.quality = newQuality } } @objc var autoQualityMode: Bool { didSet { player.autoQualityMode = autoQualityMode } } @objc var autoMaxQuality: NSDictionary? { didSet { let quality = findQuality(quality: autoMaxQuality) player.setAutoMaxQuality(quality) } } private func findQuality(quality: NSDictionary?) -> IVSQuality? { let quality = player.qualities.first(where: { $0.name == quality?["name"] as? String && $0.codecs == quality?["codecs"] as? String && $0.bitrate == quality?["bitrate"] as? Int && $0.framerate == quality?["framerate"] as? Float && $0.width == quality?["width"] as? Int && $0.height == quality?["height"] as? Int }) return quality } private func getDuration(_ duration: CMTime) -> NSNumber? { let value: NSNumber? if duration.isNumeric { value = NSNumber(value: duration.seconds); } else { value = 0 } return value } @objc var streamUrl: String? { didSet { if let url = streamUrl, !streamUrl!.isEmpty { self.load(urlString: url) } } } @objc var volume: Double { didSet { player.volume = Float(volume) } } @objc var logLevel: NSNumber { didSet { switch logLevel { case 0: player.logLevel = IVSPlayer.LogLevel.debug case 1: player.logLevel = IVSPlayer.LogLevel.info case 2: player.logLevel = IVSPlayer.LogLevel.warning case 3: player.logLevel = IVSPlayer.LogLevel.error default: break } } } @objc var breakpoints: NSArray { didSet { self.removeTimePointObserver() self.addTimePointObserver() } } @objc func play() { player.play() } @objc func pause() { player.pause() } @objc func seek(position: Double) { let parsedTime = CMTimeMakeWithSeconds(position, preferredTimescale: 1000000) player.seek(to: parsedTime) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addPlayerObserver() { playerObserverToken = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: .main) { [weak self] time in if self?.lastLiveLatency != self?.player.liveLatency.seconds { if let liveLatency = self?.player.liveLatency.seconds { let parsedValue = 1000*liveLatency self?.onLiveLatencyChange?(["liveLatency": parsedValue]) } else { self?.onLiveLatencyChange?(["liveLatency": NSNull()]) } self?.lastLiveLatency = self?.player.liveLatency.seconds } if self?.lastBitrate != self?.player.videoBitrate || self?.lastDuration != self?.player.duration || self?.lastFramesDecoded != self?.player.videoFramesDecoded || self?.lastFramesDropped != self?.player.videoFramesDropped || self?.onVideoStatistics != nil { let videoData: [String: Any] = [ "duration": self?.getDuration(self!.player.duration) ?? NSNull(), "bitrate": self?.player.videoBitrate ?? NSNull(), "framesDropped": self?.player.videoFramesDropped ?? NSNull(), "framesDecoded": self?.player.videoFramesDecoded ?? NSNull() ] self?.onVideoStatistics?(["videoData": videoData]) self?.lastBitrate = self?.player.videoBitrate self?.lastDuration = self?.player.duration self?.lastFramesDropped = self?.player.videoFramesDropped self?.lastFramesDecoded = self?.player.videoFramesDecoded } } } private var didPauseOnBackground = false @objc private func applicationDidEnterBackground(notification: Notification) { if player.state == .playing || player.state == .buffering { didPauseOnBackground = true pause() } else { didPauseOnBackground = false } } @objc private func applicationDidBecomeActive(notification: Notification) { if didPauseOnBackground && player.error == nil { play() didPauseOnBackground = false } } private func addApplicationLifecycleObservers() { NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground(notification:)), name: UIApplication.didEnterBackgroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(notification:)), name: UIApplication.didBecomeActiveNotification, object: nil) } private func removeApplicationLifecycleObservers() { NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil) } private func mapPlayerState(state: IVSPlayer.State) -> String { switch state { case IVSPlayer.State.playing: return "Playing" case IVSPlayer.State.buffering: return "Buffering" case IVSPlayer.State.ready: return "Ready" case IVSPlayer.State.idle: return "Idle" case IVSPlayer.State.ended: return "Ended" } } func addProgressObserver() { progressObserverToken = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: Double(truncating: progressInterval), preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: .main) { [weak self] time in self?.onProgress?(["position": (self?.player.position.seconds ?? nil) as Any]) } } func addTimePointObserver() { timePointObserver = player.addBoundaryTimeObserver(forTimes: breakpoints as! [NSNumber], queue: .main) { [weak self] in self?.onTimePoint?(["position": (self?.player.position.seconds ?? nil) as Any]) } } func removePlayerObserver() { if let token = playerObserverToken { player.removeTimeObserver(token) self.playerObserverToken = nil } } func removeProgressObserver() { if let token = progressObserverToken { player.removeTimeObserver(token) self.progressObserverToken = nil } } func removeTimePointObserver() { if let token = timePointObserver { player.removeTimeObserver(token) self.timePointObserver = nil } } func player(_ player: IVSPlayer, didSeekTo time: CMTime) { onSeek?(["position": CMTimeGetSeconds(time)]) } func player(_ player: IVSPlayer, didChangeState state: IVSPlayer.State) { onPlayerStateChange?(["state": mapPlayerState(state: state)]) if state == IVSPlayer.State.playing, finishedLoading == false { let duration = getDuration(player.duration) onLoad?(["duration": duration ?? NSNull()]) finishedLoading = true } if state == IVSPlayer.State.ready { if player.qualities != oldQualities { let qualities: NSMutableArray = [] for quality in player.qualities { let qualityData: [String: Any] = [ "name": quality.name, "codecs": quality.codecs, "bitrate": quality.bitrate, "framerate": quality.framerate, "width": quality.width, "height": quality.height ] qualities.add(qualityData) } onData?(["playerData": [ "qualities": qualities, "version": player.version, "sessionId": player.sessionId ]]) } oldQualities = player.qualities } } func player(_ player: IVSPlayer, didChangeDuration duration: CMTime) { let parsedDuration = getDuration(duration) onDurationChange?(["duration": parsedDuration ?? NSNull()]) } func player(_ player: IVSPlayer, didChangeQuality quality: IVSQuality?) { if quality == nil { onQualityChange?(["quality": NSNull()]) } else { let qualityData: [String: Any] = [ "name": quality?.name ?? "", "codecs": quality?.codecs ?? "", "bitrate": quality?.bitrate ?? 0, "framerate": quality?.framerate ?? 0, "width": quality?.width ?? 0, "height": quality?.height ?? 0 ] onQualityChange?(["quality": qualityData]) } } func player(_ player: IVSPlayer, didOutputCue cue: IVSCue) { if let cue = cue as? IVSTextCue { let textCue: [String: Any] = [ "type": cue.type.rawValue, "line": cue.line, "size": cue.size, "position": cue.position, "text": cue.text, "textAlignment": cue.textAlignment ] onTextCue?(["textCue": textCue]) } if let cue = cue as? IVSTextMetadataCue { let textMetadataCue = [ "type": cue.type.rawValue, "text": cue.text, "textDescription": cue.textDescription ] onTextMetadataCue?(["textMetadataCue": textMetadataCue]) } } func playerWillRebuffer(_ player: IVSPlayer) { onRebuffering?(["": NSNull()]) } func player(_ player: IVSPlayer, didFailWithError error: Error) { onError?(["error": error.localizedDescription]) } }
33.636364
193
0.584587
abc37451dd11b27107ea2f5ba19332345aea808b
850
// // Optional+KK.swift // KakaJSON // // Created by MJ Lee on 2019/8/5. // Copyright © 2019 MJ Lee. All rights reserved. // protocol OptionalValue { var _value: Any? { get } var _valueString: String { get } } extension Optional: OptionalValue { var _value: Any? { guard self != nil else { return nil } let value = self! guard let osc = value as? OptionalValue else { return value } return osc._value } var _valueString: String { if let value = _value { return "\(value)" } return "nil" } } extension Optional: KKGenericCompatible { public typealias T = Wrapped } public extension KKGeneric where Base == Optional<T> { var valueString: String { return base._valueString } func print() { Swift.print(base._valueString) } }
21.794872
56
0.605882
461ab69b4243503d3b06674f320aee4fcff4a500
1,988
// // BaseViewController.swift // QuickIosComponent // // Created by brownsoo han on 26/12/2018. // import Foundation import RxSwift open class BaseViewController: UIViewController, LoadingVisible, ForegroundNotable, IntentContainer { public lazy var loadingView = LoadingView() private(set) var isFirstLayout = true public private(set) var intent: NSMutableDictionary = NSMutableDictionary() override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) bindUIEvents() } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) unbindUIEvents() } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if isFirstLayout { isFirstLayout = false firstDidLayout() } } /// once called at first layout time open func firstDidLayout() { } open func didBackground() { } open func didForeground() { } /// bind UI events /// called in viewWillAppear open func bindUIEvents() {} /// unbind UI events /// called in viewWillDisappear open func unbindUIEvents() { } } extension BaseViewController: AlertPop { public func alertPop(_ title: String?, message: String, positive: String? = nil, positiveCallback: ((_ action: UIAlertAction)->Void)? = nil, alt: String? = nil, altCallback: ((_ action: UIAlertAction) -> Void)? = nil) { alertPop(self, title: title, message: message, positive: positive, positiveCallback: positiveCallback, alt: alt, altCallback: altCallback) } }
26.157895
84
0.592555
b9600a3dd6d145b678b18fc7173351e0ea7c541c
1,434
// // LoginEpic.swift // Example // // Created by Robert on 8/16/19. // Copyright © 2019 Robert Nguyen. All rights reserved. // import CoreBase import CoreRedux import RxSwift class LoginEpic: Epic { typealias Action = Login.Action typealias State = Login.State let worker: UserWorker init() { self.worker = UserWorker() } func apply(dispatcher: Observable<Action>, actionStream: Observable<Action>, stateStream: Observable<State>) -> Observable<Action> { dispatcher .of(type: .login) .map { $0.payload as! (String, String) } .flatMap { [worker] in worker.login(userName: $0.0, password: $0.1) } .map { Action(type: .success, payload: $0) } .`catch` { .just($0.toAction()) } } } class RegisterEpic: Epic { typealias Action = Login.Action typealias State = Login.State let worker: UserWorker init() { self.worker = UserWorker() } func apply(dispatcher: Observable<Action>, actionStream: Observable<Action>, stateStream: Observable<State>) -> Observable<Action> { dispatcher .of(type: .register) .map { $0.payload as! (String, String) } .flatMap { [worker] in worker.signup(userName: $0.0, password: $0.1) } .map { Action(type: .success, payload: $0) } .`catch` { .just($0.toAction()) } } }
27.576923
136
0.587169
deb58141820ba784659ad55ea781bab6f3859b6e
1,348
// // PokemonInfoPanel.swift // PokeMaster // // Created by davidjia on 2021/11/8. // import SwiftUI struct PokemonInfoPanel: View { let model: PokemonViewModel var abilities: [AbilityViewModel] { AbilityViewModel.sample(pokemonID: model.id) } var topIndicator: some View { RoundedRectangle(cornerRadius: 3) .frame(width: 40, height: 6) .opacity(0.2) } var pokemonDescription: some View { Text(model.descriptionText) .font(.callout) .foregroundColor(Color(hex: 0x666666)) .fixedSize(horizontal: false, vertical: true) } var body: some View { VStack(spacing: 20) { topIndicator Header(model: model) pokemonDescription Divider() AbilityList(model: model, abilityModels: abilities) } .padding( EdgeInsets( top: 12, leading: 30, bottom: 30, trailing: 30 ) ) // .background(.white) .blurBackground(style: .systemMaterial) .cornerRadius(20) .fixedSize(horizontal: false, vertical: true) } } struct PokemonInfoPanel_Previews: PreviewProvider { static var previews: some View { PokemonInfoPanel(model: .sample(id: 1)) } }
24.071429
63
0.571958
f9c5f6fd9b23432c5d943eef4585742fc560c9ac
512
// 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 // RUN: not %target-swift-frontend %s -parse enum a: String { protocol A : A.B { typealias h: (x) -> { var a):Any)" let i: b> U) -> { } public class b typealias A {
30.117647
78
0.708984
299116af7540b74022957df2bf3cb394ecd27f94
766
import UIKit import XCTest import RxBarcodeScanner class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.533333
111
0.608355
dbaa1fa302e173eb059e961c522c767da665645c
1,616
// // RoleViewController.swift // presteasymo // // Created by Pietro Russo on 07/04/17. // Copyright © 2017 Team 2.4. All rights reserved. // import UIKit class RoleViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{ @IBOutlet weak var picker: UIPickerView! var pickerData: [String] = ["Drums","Guitar","Singer","Bass","Keyboard","All"] let coredata = CoreDataController() override func viewDidLoad() { super.viewDidLoad() self.picker.delegate = self self.picker.dataSource = self } public func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerData.count } public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerData[row] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "detailUser" { let i = picker.selectedRow(inComponent: 0) let ruolo = pickerData[i] let utenti: [User] = coredata.cercaRoleUser(role: ruolo)! let nextWindow = segue.destination as! ResearchUserViewController nextWindow.utenti = utenti } } }
26.933333
118
0.629332
562cabad523f125361b9b39d8d524881e9efe7a4
3,269
// // Created by Tom Baranes on 13/08/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public class DropDownAnimator: NSObject, AnimatedPresenting { // MARK: - AnimatedPresenting public var transitionDuration: Duration = defaultTransitionDuration fileprivate var timingFunctions: [TimingFunctionType] = [.easeOut, .linear, .easeOut] fileprivate var completion: AnimatableCompletion? // MARK: - Life cycle public init(duration: Duration) { transitionDuration = duration super.init() } } // MARK: - Animator extension DropDownAnimator: UIViewControllerAnimatedTransitioning { public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return retrieveTransitionDuration(transitionContext: transitionContext) } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let (fromView, toView, tempContainerView) = retrieveViews(transitionContext: transitionContext) let isPresenting = self.isPresenting(transitionContext: transitionContext) guard let containerView = tempContainerView, let animatingView = isPresenting ? toView : fromView else { transitionContext.completeTransition(true) return } if isPresenting { containerView.addSubview(animatingView) } animateDropDown(animatingView: animatingView, isPresenting: isPresenting) { if !isPresenting { fromView?.removeFromSuperview() } transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } } // MARK: - Animation private extension DropDownAnimator { func animateDropDown(animatingView: UIView, isPresenting: Bool, completion: @escaping AnimatableCompletion) { if isPresenting { animatePresengingDropDown(animatingView: animatingView, completion: completion) } else { animateDismissingDropDown(animatingView: animatingView, completion: completion) } } func animatePresengingDropDown(animatingView: UIView, completion: @escaping AnimatableCompletion) { let y = animatingView.center.y let animation = CAKeyframeAnimation(keyPath: .positionY) animation.values = [y - UIScreen.main.bounds.height, y + 20, y - 10, y] animation.keyTimes = [0, 0.5, 0.75, 1] animation.timingFunctionsType = timingFunctions animation.duration = transitionDuration animation.delegate = self self.completion = completion animatingView.layer.add(animation, forKey: "dropdown") } func animateDismissingDropDown(animatingView: UIView, completion: @escaping AnimatableCompletion) { var point = animatingView.center let angle = CGFloat(arc4random_uniform(100)) - 50 point.y += UIScreen.main.bounds.height UIView.animate(withDuration: transitionDuration, animations: { animatingView.center = point animatingView.transform = CGAffineTransform(rotationAngle: angle / 100) }, completion: { _ in completion() }) } } // MARK: - CAAnimationDelegate extension DropDownAnimator: CAAnimationDelegate { public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if let completion = completion { completion() self.completion = nil } } }
32.366337
114
0.745794
0ad2ebdf3e259a370a6a8d910610ef2a304d9894
79,389
// // ViewController.swift // FSNotes // // Created by Oleksandr Glushchenko on 7/20/17. // Copyright © 2017 Oleksandr Glushchenko. All rights reserved. // import Cocoa import MASShortcut import FSNotesCore_macOS import WebKit import LocalAuthentication class ViewController: NSViewController, NSTextViewDelegate, NSTextFieldDelegate, NSSplitViewDelegate, NSOutlineViewDelegate, NSOutlineViewDataSource, WebFrameLoadDelegate, NSMenuItemValidation { // MARK: - Properties public var fsManager: FileSystemEventManager? private var projectSettingsViewController: ProjectSettingsViewController? let storage = Storage.sharedInstance() var filteredNoteList: [Note]? var alert: NSAlert? var refilled: Bool = false var timer = Timer() var sidebarTimer = Timer() var rowUpdaterTimer = Timer() let searchQueue = OperationQueue() var printWebView: WebView? /* Git */ public var snapshotsTimer = Timer() public var lastSnapshot: Int = 0 override var representedObject: Any? { didSet { } // Update the view, if already loaded. } // MARK: - IBOutlets @IBOutlet var emptyEditAreaImage: NSImageView! @IBOutlet weak var splitView: EditorSplitView! @IBOutlet var editArea: EditTextView! @IBOutlet weak var editAreaScroll: EditorScrollView! @IBOutlet weak var search: SearchTextField! @IBOutlet weak var notesTableView: NotesTableView! @IBOutlet var noteMenu: NSMenu! @IBOutlet weak var storageOutlineView: SidebarProjectView! @IBOutlet weak var sidebarSplitView: NSSplitView! @IBOutlet weak var notesListCustomView: NSView! @IBOutlet weak var searchTopConstraint: NSLayoutConstraint! @IBOutlet private weak var titleLabel: TitleTextField! { didSet { let clickGesture = NSClickGestureRecognizer() clickGesture.target = self clickGesture.numberOfClicksRequired = 2 clickGesture.buttonMask = 0x1 clickGesture.action = #selector(switchTitleToEditMode) titleLabel.addGestureRecognizer(clickGesture) } } @IBOutlet weak var shareButton: NSButton! @IBOutlet weak var sortByOutlet: NSMenuItem! @IBOutlet weak var titleBarAdditionalView: NSView! @IBOutlet weak var previewButton: NSButton! @IBOutlet weak var titleBarView: TitleBarView! { didSet { titleBarView.onMouseExitedClosure = { [weak self] in DispatchQueue.main.async { NSAnimationContext.runAnimationGroup({ context in context.duration = 0.25 self?.titleBarAdditionalView.isHidden = true }, completionHandler: nil) } } titleBarView.onMouseEnteredClosure = { [weak self] in DispatchQueue.main.async { if let note = EditTextView.note { if note.isUnlocked() { self?.lockUnlock.image = NSImage(named: NSImage.lockUnlockedTemplateName) } else { self?.lockUnlock.image = NSImage(named: NSImage.lockLockedTemplateName) } } self?.lockUnlock.isHidden = (EditTextView.note == nil) NSAnimationContext.runAnimationGroup({ context in context.duration = 0.25 self?.titleBarAdditionalView.isHidden = false }, completionHandler: nil) } } } } @IBOutlet weak var lockUnlock: NSButton! @IBOutlet weak var sidebarScrollView: NSScrollView! @IBOutlet weak var notesScrollView: NSScrollView! // MARK: - Overrides override func viewDidLoad() { scheduleSnapshots() self.configureShortcuts() self.configureDelegates() self.configureLayout() self.configureNotesList() self.configureEditor() self.fsManager = FileSystemEventManager(storage: storage, delegate: self) self.fsManager?.start() self.loadMoveMenu() self.loadSortBySetting() self.checkSidebarConstraint() #if CLOUDKIT self.registerKeyValueObserver() #endif searchQueue.maxConcurrentOperationCount = 1 notesTableView.loadingQueue.maxConcurrentOperationCount = 1 notesTableView.loadingQueue.qualityOfService = QualityOfService.userInteractive } override func viewDidAppear() { if UserDefaultsManagement.fullScreen { view.window?.toggleFullScreen(nil) } if let appDelegate = NSApplication.shared.delegate as? AppDelegate { if let urls = appDelegate.urls { appDelegate.importNotes(urls: urls) return } if let query = appDelegate.searchQuery { appDelegate.search(query: query) return } if nil != appDelegate.newName || nil != appDelegate.newContent { let name = appDelegate.newName ?? "" let content = appDelegate.newContent ?? "" appDelegate.create(name: name, content: content) } } } func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { guard let vc = ViewController.shared() else { return false} if let title = menuItem.menu?.identifier?.rawValue { switch title { case "fsnotesMenu": if menuItem.identifier?.rawValue == "emptyTrashMenu" { menuItem.keyEquivalentModifierMask = UserDefaultsManagement.focusInEditorOnNoteSelect ? [.command, .option, .shift] : [.command, .shift] return true } case "fileMenu": if menuItem.identifier?.rawValue == "fileMenu.delete" { menuItem.keyEquivalentModifierMask = UserDefaultsManagement.focusInEditorOnNoteSelect ? [.command, .option] : [.command] } if menuItem.identifier?.rawValue == "fileMenu.history" { if EditTextView.note != nil { return true } } if ["fileMenu.new", "fileMenu.newRtf", "fileMenu.searchAndCreate", "fileMenu.import"].contains(menuItem.identifier?.rawValue) { return true } if vc.notesTableView.selectedRow == -1 { return false } break case "folderMenu": if ["folderMenu.attachStorage"].contains(menuItem.identifier?.rawValue) { return true } guard let p = vc.getSidebarProject(), !p.isTrash else { return false } case "findMenu": if ["findMenu.find", "findMenu.findAndReplace", "findMenu.next", "findMenu.prev"].contains(menuItem.identifier?.rawValue), vc.notesTableView.selectedRow > -1 { return true } return vc.editAreaScroll.isFindBarVisible || vc.editArea.hasFocus() default: break } } return true } // MARK: - Initial configuration private func configureLayout() { updateTitle(newTitle: nil) DispatchQueue.main.async { self.editArea.updateTextContainerInset() } editArea.textContainerInset.height = 10 editArea.isEditable = false editArea.layoutManager?.allowsNonContiguousLayout = false if #available(OSX 10.13, *) {} else { self.editArea.backgroundColor = UserDefaultsManagement.bgColor } self.editArea.layoutManager?.defaultAttachmentScaling = .scaleProportionallyDown let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = CGFloat(UserDefaultsManagement.editorLineSpacing) self.editArea.defaultParagraphStyle = paragraphStyle self.editArea.typingAttributes[.paragraphStyle] = paragraphStyle self.editArea.font = UserDefaultsManagement.noteFont if (UserDefaultsManagement.horizontalOrientation) { self.splitView.isVertical = false } self.shareButton.sendAction(on: .leftMouseDown) self.setTableRowHeight() self.storageOutlineView.sidebarItems = Sidebar().getList() self.sidebarSplitView.autosaveName = "SidebarSplitView" self.splitView.autosaveName = "EditorSplitView" notesScrollView.scrollerStyle = .overlay sidebarScrollView.scrollerStyle = .overlay if UserDefaultsManagement.appearanceType == .Custom { titleBarView.wantsLayer = true titleBarView.layer?.backgroundColor = UserDefaultsManagement.bgColor.cgColor titleLabel.backgroundColor = UserDefaultsManagement.bgColor } NSWorkspace.shared.notificationCenter.addObserver( self, selector: #selector(onSleepNote(note:)), name: NSWorkspace.willSleepNotification, object: nil) NSWorkspace.shared.notificationCenter.addObserver( self, selector: #selector(onUserSwitch(note:)), name: NSWorkspace.sessionDidBecomeActiveNotification, object: nil) DistributedNotificationCenter.default().addObserver( self, selector: #selector(onScreenLocked(note:)), name: NSNotification.Name(rawValue: "com.apple.screenIsLocked"), object: nil ) } private func configureNotesList() { self.updateTable() { let lastSidebarItem = UserDefaultsManagement.lastProject if let items = self.storageOutlineView.sidebarItems, items.indices.contains(lastSidebarItem) { DispatchQueue.main.async { self.storageOutlineView.selectRowIndexes([lastSidebarItem], byExtendingSelection: false) } } } } private func configureEditor() { self.editArea.isGrammarCheckingEnabled = UserDefaultsManagement.grammarChecking self.editArea.isContinuousSpellCheckingEnabled = UserDefaultsManagement.continuousSpellChecking self.editArea.smartInsertDeleteEnabled = UserDefaultsManagement.smartInsertDelete self.editArea.isAutomaticSpellingCorrectionEnabled = UserDefaultsManagement.automaticSpellingCorrection self.editArea.isAutomaticQuoteSubstitutionEnabled = UserDefaultsManagement.automaticQuoteSubstitution self.editArea.isAutomaticDataDetectionEnabled = UserDefaultsManagement.automaticDataDetection self.editArea.isAutomaticLinkDetectionEnabled = UserDefaultsManagement.automaticLinkDetection self.editArea.isAutomaticTextReplacementEnabled = UserDefaultsManagement.automaticTextReplacement self.editArea.isAutomaticDashSubstitutionEnabled = UserDefaultsManagement.automaticDashSubstitution if UserDefaultsManagement.appearanceType != AppearanceType.Custom { if #available(OSX 10.13, *) { self.editArea?.linkTextAttributes = [ .foregroundColor: NSColor.init(named: "link")! ] } } self.editArea.usesFindBar = true self.editArea.isIncrementalSearchingEnabled = true self.editArea.textStorage?.delegate = self.editArea.textStorage self.editArea.viewDelegate = self } private func configureShortcuts() { MASShortcutMonitor.shared().register(UserDefaultsManagement.newNoteShortcut, withAction: { self.makeNoteShortcut() }) MASShortcutMonitor.shared().register(UserDefaultsManagement.searchNoteShortcut, withAction: { self.searchShortcut() }) NSEvent.addLocalMonitorForEvents(matching: NSEvent.EventTypeMask.flagsChanged) { return $0 } NSEvent.addLocalMonitorForEvents(matching: NSEvent.EventTypeMask.keyDown) { if self.keyDown(with: $0) { return $0 } //return NSEvent() return nil } } private func configureDelegates() { self.editArea.delegate = self self.search.vcDelegate = self self.search.delegate = self.search self.sidebarSplitView.delegate = self self.storageOutlineView.viewDelegate = self } // MARK: - Actions @IBAction func searchAndCreate(_ sender: Any) { guard let vc = ViewController.shared() else { return } let size = UserDefaultsManagement.horizontalOrientation ? vc.splitView.subviews[0].frame.height : vc.splitView.subviews[0].frame.width if size == 0 { toggleNoteList(self) } vc.search.window?.makeFirstResponder(vc.search) } @IBAction func sortBy(_ sender: NSMenuItem) { if let id = sender.identifier { let key = String(id.rawValue.dropFirst(3)) guard let sortBy = SortBy(rawValue: key) else { return } UserDefaultsManagement.sort = sortBy UserDefaultsManagement.sortDirection = !UserDefaultsManagement.sortDirection if let submenu = sortByOutlet.submenu { for item in submenu.items { item.state = NSControl.StateValue.off } } sender.state = NSControl.StateValue.on guard let controller = ViewController.shared() else { return } // Sort all notes storage.noteList = storage.sortNotes(noteList: storage.noteList, filter: controller.search.stringValue) // Sort notes in the current project if let filtered = controller.filteredNoteList { controller.notesTableView.noteList = storage.sortNotes(noteList: filtered, filter: controller.search.stringValue) } else { controller.notesTableView.noteList = storage.noteList } controller.notesTableView.reloadData() } } @objc func moveNote(_ sender: NSMenuItem) { let project = sender.representedObject as! Project guard let notes = notesTableView.getSelectedNotes() else { return } move(notes: notes, project: project) } public func move(notes: [Note], project: Project) { for note in notes { if note.project == project { continue } let destination = project.url.appendingPathComponent(note.name) if note.type == .Markdown && note.container == .none { let imagesMeta = note.getAllImages() for imageMeta in imagesMeta { move(note: note, from: imageMeta.url, imagePath: imageMeta.path, to: project) } note.save() } _ = note.move(to: destination, project: project) let show = isFit(note: note, shouldLoadMain: true) if !show { notesTableView.removeByNotes(notes: [note]) } note.invalidateCache() } editArea.clear() } private func move(note: Note, from imageURL: URL, imagePath: String, to project: Project, copy: Bool = false) { let dstPrefix = NotesTextProcessor.getAttachPrefix(url: imageURL) let dest = project.url.appendingPathComponent(dstPrefix) if !FileManager.default.fileExists(atPath: dest.path) { try? FileManager.default.createDirectory(at: dest, withIntermediateDirectories: false, attributes: nil) } do { if copy { try FileManager.default.copyItem(at: imageURL, to: dest) } else { try FileManager.default.moveItem(at: imageURL, to: dest) } } catch { if let fileName = ImagesProcessor.getFileName(from: imageURL, to: dest, ext: imageURL.pathExtension) { let dest = dest.appendingPathComponent(fileName) if copy { try? FileManager.default.copyItem(at: imageURL, to: dest) } else { try? FileManager.default.moveItem(at: imageURL, to: dest) } let prefix = "](" let postfix = ")" let find = prefix + imagePath + postfix let replace = prefix + dstPrefix + fileName + postfix guard find != replace else { return } while note.content.mutableString.contains(find) { let range = note.content.mutableString.range(of: find) note.content.replaceCharacters(in: range, with: replace) } } } } func splitViewDidResizeSubviews(_ notification: Notification) { guard let vc = ViewController.shared() else { return } vc.checkSidebarConstraint() if !refilled { self.refilled = true DispatchQueue.main.async() { self.refillEditArea(previewOnly: true) self.refilled = false } } } func reloadSideBar() { guard let outline = storageOutlineView else { return } sidebarTimer.invalidate() sidebarTimer = Timer.scheduledTimer(timeInterval: 1.2, target: outline, selector: #selector(outline.reloadSidebar), userInfo: nil, repeats: false) } func reloadView(note: Note? = nil) { let notesTable = self.notesTableView! let selectedNote = notesTable.getSelectedNote() let cursor = editArea.selectedRanges[0].rangeValue.location self.updateTable() { if let selected = selectedNote, let index = notesTable.getIndex(selected) { notesTable.selectRowIndexes([index], byExtendingSelection: false) self.refillEditArea(cursor: cursor) } } } func setTableRowHeight() { notesTableView.rowHeight = CGFloat(21 + UserDefaultsManagement.cellSpacing) notesTableView.reloadData() } func refillEditArea(cursor: Int? = nil, previewOnly: Bool = false, saveTyping: Bool = false) { DispatchQueue.main.async { [weak self] in self?.previewButton.state = UserDefaultsManagement.preview ? .on : .off } guard !previewOnly || previewOnly && UserDefaultsManagement.preview else { return } DispatchQueue.main.async { var location: Int = 0 if let unwrappedCursor = cursor { location = unwrappedCursor } else { location = self.editArea.selectedRanges[0].rangeValue.location } let selected = self.notesTableView.selectedRow if (selected > -1 && self.notesTableView.noteList.indices.contains(selected)) { if let note = self.notesTableView.getSelectedNote() { self.editArea.fill(note: note, saveTyping: saveTyping) self.editArea.setSelectedRange(NSRange.init(location: location, length: 0)) } } } } public func keyDown(with event: NSEvent) -> Bool { guard let mw = MainWindowController.shared() else { return false } guard self.alert == nil else { if event.keyCode == kVK_Escape, let unwrapped = alert { mw.endSheet(unwrapped.window) self.alert = nil } return true } if event.keyCode == kVK_Delete && event.modifierFlags.contains(.command) && editArea.hasFocus() { editArea.deleteToBeginningOfLine(nil) return false } // Return / Cmd + Return navigation if event.keyCode == kVK_Return { if let fr = NSApp.mainWindow?.firstResponder, self.alert == nil { if event.modifierFlags.contains(.command) { if fr.isKind(of: NotesTableView.self) { NSApp.mainWindow?.makeFirstResponder(self.storageOutlineView) return false } if fr.isKind(of: EditTextView.self) { NSApp.mainWindow?.makeFirstResponder(self.notesTableView) return false } } else { if fr.isKind(of: SidebarProjectView.self) { self.notesTableView.selectNext() NSApp.mainWindow?.makeFirstResponder(self.notesTableView) return false } if fr.isKind(of: NotesTableView.self) && !UserDefaultsManagement.preview { NSApp.mainWindow?.makeFirstResponder(self.editArea) return false } } } return true } // Tab / Control + Tab if event.keyCode == kVK_Tab { if event.modifierFlags.contains(.control) { self.notesTableView.window?.makeFirstResponder(self.notesTableView) return true } if let fr = NSApp.mainWindow?.firstResponder, fr.isKind(of: NotesTableView.self) { NSApp.mainWindow?.makeFirstResponder(self.notesTableView) return false } } // Focus search bar on ESC if ( ( event.keyCode == kVK_Escape || ( event.characters == "." && event.modifierFlags.contains(.command) ) ) && NSApplication.shared.mainWindow == NSApplication.shared.keyWindow ) { UserDataService.instance.resetLastSidebar() if let view = NSApplication.shared.mainWindow?.firstResponder as? NSTextView, let textField = view.superview?.superview, textField.isKind(of: NameTextField.self) { NSApp.mainWindow?.makeFirstResponder( self.notesTableView) return false } if self.editAreaScroll.isFindBarVisible { cancelTextSearch() return false } // Renaming is in progress if titleLabel.isEditable == true { titleLabel.isEditable = false titleLabel.window?.makeFirstResponder(nil) return true } UserDefaultsManagement.lastProject = 0 UserDefaultsManagement.lastSelectedURL = nil notesTableView.scroll(.zero) let hasSelectedNotes = notesTableView.selectedRow > -1 let hasSelectedBarItem = storageOutlineView.selectedRow > -1 if hasSelectedBarItem && hasSelectedNotes { UserDefaultsManagement.lastProject = 0 UserDataService.instance.isNotesTableEscape = true notesTableView.deselectAll(nil) NSApp.mainWindow?.makeFirstResponder(search) return false } storageOutlineView.deselectAll(nil) cleanSearchAndEditArea() return true } // Search cmd-f if (event.keyCode == kVK_ANSI_F && event.modifierFlags.contains(.command) && !event.modifierFlags.contains(.control)) { if self.notesTableView.getSelectedNote() != nil { //Turn off preview mode as text search works only in text editor disablePreview() return true } } // Pin note shortcut (cmd-8) if (event.keyCode == kVK_ANSI_8 && event.modifierFlags.contains(.command)) { pin(notesTableView.selectedRowIndexes) return true } // Next note (cmd-j) if ( event.keyCode == kVK_ANSI_J && event.modifierFlags.contains([.command]) && !event.modifierFlags.contains(.option) ) { notesTableView.selectNext() return true } // Prev note (cmd-k) if (event.keyCode == kVK_ANSI_K && event.modifierFlags.contains(.command)) { notesTableView.selectPrev() return true } // Toggle sidebar cmd+shift+control+b if event.modifierFlags.contains(.command) && event.modifierFlags.contains(.shift) && event.modifierFlags.contains(.control) && event.keyCode == kVK_ANSI_B { toggleSidebar("") return false } if let fr = mw.firstResponder, !fr.isKind(of: EditTextView.self), !fr.isKind(of: NSTextView.self), !event.modifierFlags.contains(.command), !event.modifierFlags.contains(.control) { if let char = event.characters { let newSet = CharacterSet(charactersIn: char) if newSet.isSubset(of: CharacterSet.alphanumerics) { self.search.becomeFirstResponder() } } } return true } func cancelTextSearch() { let menu = NSMenuItem(title: "", action: nil, keyEquivalent: "") menu.tag = NSTextFinder.Action.hideFindInterface.rawValue self.editArea.performTextFinderAction(menu) if !UserDefaultsManagement.preview { NSApp.mainWindow?.makeFirstResponder(self.editArea) } } @IBAction func makeNote(_ sender: SearchTextField) { guard let vc = ViewController.shared() else { return } if let type = vc.getSidebarType(), type == .Trash { vc.storageOutlineView.deselectAll(nil) } var value = sender.stringValue if let editor = sender.currentEditor() { let query = editor.string.prefix(editor.selectedRange.location) if query.count > 0 { value = String(query) sender.stringValue = String(query) } } if (value.count > 0) { search.stringValue = "" editArea.clear() createNote(name: value) } else { createNote() } } @IBAction func fileMenuNewNote(_ sender: Any) { guard let vc = ViewController.shared() else { return } if let type = vc.getSidebarType(), type == .Trash { vc.storageOutlineView.deselectAll(nil) } vc.createNote() } @IBAction func importNote(_ sender: NSMenuItem) { let panel = NSOpenPanel() panel.allowsMultipleSelection = true panel.canChooseDirectories = false panel.canChooseFiles = true panel.canCreateDirectories = false panel.begin { (result) -> Void in if result.rawValue == NSFileHandlingPanelOKButton { let urls = panel.urls let project = self.getSidebarProject() ?? self.storage.getMainProject() for url in urls { _ = self.copy(project: project, url: url) } } } } @IBAction func fileMenuNewRTF(_ sender: Any) { guard let vc = ViewController.shared() else { return } if let type = vc.getSidebarType(), type == .Trash { vc.storageOutlineView.deselectAll(nil) } vc.createNote(type: .RichText) } @IBAction func moveMenu(_ sender: Any) { guard let vc = ViewController.shared() else { return } if vc.notesTableView.selectedRow >= 0 { vc.loadMoveMenu() let moveTitle = NSLocalizedString("Move", comment: "Menu") let moveMenu = vc.noteMenu.item(withTitle: moveTitle) let view = vc.notesTableView.rect(ofRow: vc.notesTableView.selectedRow) let x = vc.splitView.subviews[0].frame.width + 5 let general = moveMenu?.submenu?.item(at: 0) moveMenu?.submenu?.popUp(positioning: general, at: NSPoint(x: x, y: view.origin.y + 8), in: vc.notesTableView) } } @IBAction func historyMenu(_ sender: Any) { guard let vc = ViewController.shared() else { return } if vc.notesTableView.selectedRow >= 0 { vc.loadHistory() let historyTitle = NSLocalizedString("History", comment: "Menu") let historyMenu = vc.noteMenu.item(withTitle: historyTitle) let view = vc.notesTableView.rect(ofRow: vc.notesTableView.selectedRow) let x = vc.splitView.subviews[0].frame.width + 5 let general = historyMenu?.submenu?.item(at: 0) historyMenu?.submenu?.popUp(positioning: general, at: NSPoint(x: x, y: view.origin.y + 8), in: vc.notesTableView) } } @IBAction func fileName(_ sender: NSTextField) { guard let note = notesTableView.getNoteFromSelectedRow() else { return } let value = sender.stringValue let url = note.url let newName = sender.stringValue + "." + note.url.pathExtension let isSoftRename = note.url.lastPathComponent.lowercased() == newName.lowercased() if note.project.fileExist(fileName: value, ext: note.url.pathExtension), !isSoftRename { self.alert = NSAlert() guard let alert = self.alert else { return } alert.messageText = "Hmm, something goes wrong 🙈" alert.informativeText = "Note with name \"\(value)\" already exists in selected storage." alert.runModal() note.parseURL() sender.stringValue = note.getTitleWithoutLabel() return } guard value.count > 0 else { sender.stringValue = note.getTitleWithoutLabel() return } sender.isEditable = false let newUrl = note.getNewURL(name: value) UserDataService.instance.focusOnImport = newUrl if note.url.path == newUrl.path { return } note.overwrite(url: newUrl) do { try FileManager.default.moveItem(at: url, to: newUrl) print("File moved from \"\(url.deletingPathExtension().lastPathComponent)\" to \"\(newUrl.deletingPathExtension().lastPathComponent)\"") } catch { note.overwrite(url: url) } } @IBAction func editorMenu(_ sender: Any) { for index in notesTableView.selectedRowIndexes { external(selectedRow: index) } } @IBAction func finderMenu(_ sender: NSMenuItem) { if let notes = notesTableView.getSelectedNotes() { var urls = [URL]() for note in notes { urls.append(note.url) } NSWorkspace.shared.activateFileViewerSelecting(urls) } } @IBAction func makeMenu(_ sender: Any) { guard let vc = ViewController.shared() else { return } if let type = vc.getSidebarType(), type == .Trash { vc.storageOutlineView.deselectAll(nil) } vc.createNote() } @IBAction func pinMenu(_ sender: Any) { guard let vc = ViewController.shared() else { return } vc.pin(vc.notesTableView.selectedRowIndexes) } @IBAction func renameMenu(_ sender: Any) { switchTitleToEditMode() } @objc func switchTitleToEditMode() { guard let vc = ViewController.shared() else { return } if vc.notesTableView.selectedRow > -1 { vc.titleLabel.isEditable = true vc.titleLabel.becomeFirstResponder() //vc.titleLabel. } } @IBAction func deleteNote(_ sender: Any) { guard let vc = ViewController.shared() else { return } guard let notes = vc.notesTableView.getSelectedNotes() else { return } if let si = vc.getSidebarItem(), si.isTrash() { removeForever() return } let selectedRow = vc.notesTableView.selectedRowIndexes.min() UserDataService.instance.searchTrigger = true vc.notesTableView.removeByNotes(notes: notes) vc.storage.removeNotes(notes: notes) { urls in vc.storageOutlineView.reloadSidebar() if let appd = NSApplication.shared.delegate as? AppDelegate, let md = appd.mainWindowController { let undoManager = md.notesListUndoManager if let ntv = vc.notesTableView { undoManager.registerUndo(withTarget: ntv, selector: #selector(ntv.unDelete), object: urls) undoManager.setActionName(NSLocalizedString("Delete", comment: "")) } if let i = selectedRow, i > -1 { vc.notesTableView.selectRow(i) } UserDataService.instance.searchTrigger = false } if UserDefaultsManagement.preview { vc.disablePreview() } vc.editArea.clear() } NSApp.mainWindow?.makeFirstResponder(vc.notesTableView) } @IBAction func archiveNote(_ sender: Any) { guard let vc = ViewController.shared() else { return } guard let notes = vc.notesTableView.getSelectedNotes() else { return } if let project = storage.getArchive() { for note in notes { let removed = note.removeAllTags() vc.storageOutlineView.removeTags(removed) } move(notes: notes, project: project) } } @IBAction func tagNote(_ sender: Any) { guard let vc = ViewController.shared() else { return } guard let notes = vc.notesTableView.getSelectedNotes() else { return } guard let note = notes.first else { return } guard let window = MainWindowController.shared() else { return } vc.alert = NSAlert() let field = NSTextField(frame: NSRect(x: 0, y: 0, width: 290, height: 20)) #if CLOUDKIT field.placeholderString = "fun, health, life" #else field.placeholderString = "sex, drugs, rock and roll" #endif field.stringValue = note.getCommaSeparatedTags() vc.alert?.messageText = NSLocalizedString("Tags", comment: "Menu") vc.alert?.informativeText = NSLocalizedString("Please enter tags (comma separated):", comment: "Menu") vc.alert?.accessoryView = field vc.alert?.alertStyle = .informational vc.alert?.addButton(withTitle: "OK") vc.alert?.beginSheetModal(for: window) { (returnCode: NSApplication.ModalResponse) -> Void in if returnCode == NSApplication.ModalResponse.alertFirstButtonReturn { if let tags = TagList(tags: field.stringValue).get() { var removed = [String]() var deselected = [String]() for note in notes { let r = note.saveTags(tags) removed = r.0 deselected = r.1 } vc.storageOutlineView.removeTags(removed) vc.storageOutlineView.deselectTags(deselected) vc.storageOutlineView.addTags(tags) vc.storageOutlineView.reloadSidebar() } } vc.alert = nil } field.becomeFirstResponder() } @IBAction func openInExternalEditor(_ sender: Any) { guard let vc = ViewController.shared() else { return } vc.external(selectedRow: vc.notesTableView.selectedRow) } @IBAction func toggleNoteList(_ sender: Any) { guard let vc = ViewController.shared() else { return } let size = UserDefaultsManagement.horizontalOrientation ? vc.splitView.subviews[0].frame.height : vc.splitView.subviews[0].frame.width if size == 0 { var size = UserDefaultsManagement.sidebarSize if UserDefaultsManagement.sidebarSize == 0 { size = 250 } vc.splitView.shouldHideDivider = false vc.splitView.setPosition(size, ofDividerAt: 0) } else if vc.splitView.shouldHideDivider { vc.splitView.shouldHideDivider = false vc.splitView.setPosition(UserDefaultsManagement.sidebarSize, ofDividerAt: 0) } else { UserDefaultsManagement.sidebarSize = size vc.splitView.shouldHideDivider = true vc.splitView.setPosition(0, ofDividerAt: 0) DispatchQueue.main.async { vc.splitView.setPosition(0, ofDividerAt: 0) } } vc.editArea.updateTextContainerInset() } @IBAction func toggleSidebar(_ sender: Any) { guard let vc = ViewController.shared() else { return } let size = Int(vc.sidebarSplitView.subviews[0].frame.width) if size != 0 { UserDefaultsManagement.realSidebarSize = size vc.sidebarSplitView.setPosition(0, ofDividerAt: 0) } else { vc.sidebarSplitView.setPosition(CGFloat(UserDefaultsManagement.realSidebarSize), ofDividerAt: 0) } vc.editArea.updateTextContainerInset() } @IBAction func emptyTrash(_ sender: NSMenuItem) { guard let vc = ViewController.shared() else { return } if let sidebarItem = vc.getSidebarItem(), sidebarItem.isTrash() { let indexSet = IndexSet(integersIn: 0..<vc.notesTableView.noteList.count) vc.notesTableView.removeRows(at: indexSet, withAnimation: .effectFade) } let notes = storage.getAllTrash() for note in notes { _ = note.removeFile() } NSSound(named: "Pop")?.play() } @IBAction func printNotes(_ sender: NSMenuItem) { if let note = EditTextView.note, note.isMarkdown() { self.printWebView = WebView() printMarkdownPreview(webView: self.printWebView) return } let pv = NSTextView(frame: NSMakeRect(0, 0, 528, 688)) pv.textStorage?.append(editArea.attributedString()) let printInfo = NSPrintInfo.shared printInfo.isHorizontallyCentered = false printInfo.isVerticallyCentered = false printInfo.scalingFactor = 1 printInfo.topMargin = 40 printInfo.leftMargin = 40 printInfo.rightMargin = 40 printInfo.bottomMargin = 40 let operation: NSPrintOperation = NSPrintOperation(view: pv, printInfo: printInfo) operation.printPanel.options.insert(NSPrintPanel.Options.showsPaperSize) operation.printPanel.options.insert(NSPrintPanel.Options.showsOrientation) operation.run() } @IBAction func toggleNotesLock(_ sender: Any) { guard let vc = ViewController.shared() else { return } guard var notes = vc.notesTableView.getSelectedNotes() else { return } notes = lockUnlocked(notes: notes) guard notes.count > 0 else { return } getMasterPassword() { password, isTypedByUser in guard password.count > 0 else { return } var isFirst = true for note in notes { var success = false if note.container == .encryptedTextPack { success = note.unLock(password: password) if success && isFirst { self.refillEditArea() } } else { success = note.encrypt(password: password) if success && isFirst { self.refillEditArea() self.focusTable() } } if success && isTypedByUser { self.save(password: password) } self.notesTableView.reloadRow(note: note) isFirst = false } } } @IBAction func removeNoteEncryption(_ sender: Any) { guard let vc = ViewController.shared() else { return } guard var notes = vc.notesTableView.getSelectedNotes() else { return } notes = decryptUnlocked(notes: notes) guard notes.count > 0 else { return } getMasterPassword() { password, isTypedByUser in var isFirst = true for note in notes { if note.container == .encryptedTextPack { let success = note.unEncrypt(password: password) if success && isFirst { self.refillEditArea() } } self.notesTableView.reloadRow(note: note) isFirst = false } } } @IBAction func openProjectViewSettings(_ sender: NSMenuItem) { guard let vc = ViewController.shared() else { return } if let controller = vc.storyboard?.instantiateController(withIdentifier: "ProjectSettingsViewController") as? ProjectSettingsViewController { self.projectSettingsViewController = controller if let project = vc.getSidebarProject() { vc.presentAsSheet(controller) controller.load(project: project) } } } @IBAction func lockAll(_ sender: Any) { let notes = storage.noteList.filter({ $0.isUnlocked() }) for note in notes { if note.lock() { notesTableView.reloadRow(note: note) } } editArea.clear() refillEditArea() } func controlTextDidEndEditing(_ obj: Notification) { guard let textField = obj.object as? NSTextField, textField == titleLabel else { return } if titleLabel.isEditable == true { titleLabel.isEditable = false fileName(titleLabel) view.window?.makeFirstResponder(notesTableView) } else { let currentNote = notesTableView.getSelectedNote() updateTitle(newTitle: currentNote?.getTitleWithoutLabel() ?? NSLocalizedString("Untitled Note", comment: "Untitled Note")) } } // Changed main edit view func textDidChange(_ notification: Notification) { timer.invalidate() timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(enableFSUpdates), userInfo: nil, repeats: false) UserDataService.instance.fsUpdatesDisabled = true let index = notesTableView.selectedRow if ( notesTableView.noteList.indices.contains(index) && index > -1 && !UserDefaultsManagement.preview && self.editArea.isEditable ) { editArea.removeHighlight() let note = notesTableView.noteList[index] editArea.saveImages() note.save(attributed: editArea.attributedString()) rowUpdaterTimer.invalidate() rowUpdaterTimer = Timer.scheduledTimer(timeInterval: 1.2, target: self, selector: #selector(updateCurrentRow), userInfo: nil, repeats: false) } } private func removeForever() { guard let vc = ViewController.shared() else { return } guard let notes = vc.notesTableView.getSelectedNotes() else { return } guard let window = MainWindowController.shared() else { return } vc.alert = NSAlert() guard let alert = vc.alert else { return } alert.messageText = String(format: NSLocalizedString("Are you sure you want to irretrievably delete %d note(s)?", comment: ""), notes.count) alert.informativeText = NSLocalizedString("This action cannot be undone.", comment: "") alert.addButton(withTitle: NSLocalizedString("Remove note(s)", comment: "")) alert.addButton(withTitle: NSLocalizedString("Cancel", comment: "")) alert.beginSheetModal(for: window) { (returnCode: NSApplication.ModalResponse) -> Void in if returnCode == NSApplication.ModalResponse.alertFirstButtonReturn { let selectedRow = vc.notesTableView.selectedRowIndexes.min() vc.editArea.clear() vc.storage.removeNotes(notes: notes) { _ in DispatchQueue.main.async { vc.storageOutlineView.reloadSidebar() vc.notesTableView.removeByNotes(notes: notes) if let i = selectedRow, i > -1 { vc.notesTableView.selectRow(i) } } } } else { self.alert = nil } } } @objc func enableFSUpdates() { UserDataService.instance.fsUpdatesDisabled = false } @objc private func updateCurrentRow() { let index = notesTableView.selectedRow if ( notesTableView.noteList.indices.contains(index) && index > -1 && !UserDefaultsManagement.preview && self.editArea.isEditable ) { if UserDefaultsManagement.sort == .modificationDate && UserDefaultsManagement.sortDirection == true { moveNoteToTop(note: index) } else { let note = notesTableView.noteList[index] notesTableView.reloadRow(note: note) } } } func getSidebarProject() -> Project? { if storageOutlineView.selectedRow < 0 { return nil } let sidebarItem = storageOutlineView.item(atRow: storageOutlineView.selectedRow) as? SidebarItem if let project = sidebarItem?.project { return project } return nil } func getSidebarType() -> SidebarItemType? { let sidebarItem = storageOutlineView.item(atRow: storageOutlineView.selectedRow) as? SidebarItem if let type = sidebarItem?.type { return type } return nil } func getSidebarItem() -> SidebarItem? { if let sidebarItem = storageOutlineView.item(atRow: storageOutlineView.selectedRow) as? SidebarItem { return sidebarItem } return nil } private var selectRowTimer = Timer() func updateTable(search: Bool = false, searchText: String? = nil, sidebarItem: SidebarItem? = nil, completion: @escaping () -> Void = {}) { let timestamp = Date().toMillis() self.search.timestamp = timestamp self.searchQueue.cancelAllOperations() var sidebarItem = sidebarItem if searchText == nil { sidebarItem = self.getSidebarItem() } let project = sidebarItem?.project let type = sidebarItem?.type var filter = searchText ?? self.search.stringValue let originalFilter = searchText ?? self.search.stringValue filter = originalFilter.lowercased() let operation = BlockOperation() operation.addExecutionBlock { [weak self] in guard let self = self else {return} var terms = filter.split(separator: " ") let source = self.storage.noteList var notes = [Note]() if let type = type, type == .Todo { terms.append("- [ ]") } for note in source { if operation.isCancelled { return } if (self.isFit(note: note, sidebarItem: sidebarItem, filter: filter, terms: terms)) { notes.append(note) } } self.filteredNoteList = notes self.notesTableView.noteList = self.storage.sortNotes(noteList: notes, filter: filter, project: project, operation: operation) if operation.isCancelled { completion() return } guard self.notesTableView.noteList.count > 0 else { DispatchQueue.main.async { self.editArea.clear() self.notesTableView.reloadData() completion() } return } let note = self.notesTableView.noteList[0] DispatchQueue.main.async { self.notesTableView.reloadData() if search { if (self.notesTableView.noteList.count > 0) { if !self.search.skipAutocomplete && self.search.timestamp == timestamp { self.search.suggestAutocomplete(note, filter: originalFilter) } if filter.count > 0 && (UserDefaultsManagement.textMatchAutoSelection || note.title.lowercased() == self.search.stringValue.lowercased()) { self.selectNullTableRow(timer: true) } else { self.editArea.clear() } } else { self.editArea.clear() } } completion() } } self.searchQueue.addOperation(operation) } private func isMatched(note: Note, terms: [Substring]) -> Bool { for term in terms { if note.name.range(of: term, options: .caseInsensitive, range: nil, locale: nil) != nil || note.content.string.range(of: term, options: .caseInsensitive, range: nil, locale: nil) != nil { continue } return false } return true } public func isFit(note: Note, sidebarItem: SidebarItem? = nil, filter: String = "", terms: [Substring]? = nil, shouldLoadMain: Bool = false) -> Bool { var filter = filter var sidebarItem = sidebarItem var terms = terms var sidebarName = sidebarItem?.name ?? "" var selectedProject = sidebarItem?.project var type = sidebarItem?.type ?? .Inbox // Global search if sidebar not checked if filter.count > 0 && sidebarItem == nil { type = .All } if shouldLoadMain { filter = search.stringValue sidebarItem = getSidebarItem() terms = search.stringValue.split(separator: " ") sidebarName = sidebarItem?.name ?? "" selectedProject = sidebarItem?.project type = sidebarItem?.type ?? .Inbox if type == .Todo { terms!.append("- [ ]") } } return !note.name.isEmpty && ( filter.isEmpty && type != .Todo || type == .Todo && ( self.isMatched(note: note, terms: ["- [ ]"]) || self.isMatched(note: note, terms: ["- [x]"]) ) || self.isMatched(note: note, terms: terms!) ) && ( type == .All && !note.project.isArchive && note.project.showInCommon || type == .Tag && note.tagNames.contains(sidebarName) || [.Category, .Label].contains(type) && selectedProject != nil && note.project == selectedProject || selectedProject != nil && selectedProject!.isRoot && note.project.parent == selectedProject && type != .Inbox || type == .Trash || type == .Todo || type == .Archive && note.project.isArchive || type == .Inbox && note.project.isRoot && note.project.isDefault ) && ( type == .Trash && note.isTrash() || type != .Trash && !note.isTrash() ) } @objc func selectNullTableRow(timer: Bool = false) { if timer { self.selectRowTimer.invalidate() self.selectRowTimer = Timer.scheduledTimer(timeInterval: TimeInterval(0.2), target: self, selector: #selector(self.selectRowInstant), userInfo: nil, repeats: false) return } selectRowInstant() } @objc private func selectRowInstant() { notesTableView.selectRowIndexes([0], byExtendingSelection: false) notesTableView.scrollRowToVisible(0) } func focusEditArea(firstResponder: NSResponder? = nil) { guard !UserDefaultsManagement.preview, EditTextView.note?.container != .encryptedTextPack else { return } var resp: NSResponder = self.editArea if let responder = firstResponder { resp = responder } if (self.notesTableView.selectedRow > -1) { DispatchQueue.main.async() { self.editArea.isEditable = true self.emptyEditAreaImage.isHidden = true self.editArea.window?.makeFirstResponder(resp) if UserDefaultsManagement.focusInEditorOnNoteSelect { //self.editArea.restoreCursorPosition() } } return } editArea.window?.makeFirstResponder(resp) } func focusTable() { DispatchQueue.main.async { let index = self.notesTableView.selectedRow > -1 ? self.notesTableView.selectedRow : 0 self.notesTableView.window?.makeFirstResponder(self.notesTableView) self.notesTableView.selectRowIndexes([index], byExtendingSelection: false) self.notesTableView.scrollRowToVisible(index) } } func cleanSearchAndEditArea() { search.stringValue = "" search.becomeFirstResponder() notesTableView.selectRowIndexes(IndexSet(), byExtendingSelection: false) editArea.clear() self.updateTable(searchText: "") } func makeNoteShortcut() { let clipboard = NSPasteboard.general.string(forType: NSPasteboard.PasteboardType.string) if (clipboard != nil) { let project = Storage.sharedInstance().getMainProject() createNote(content: clipboard!, project: project) let notification = NSUserNotification() notification.title = "FSNotes" notification.informativeText = "Clipboard successfully saved" notification.soundName = NSUserNotificationDefaultSoundName NSUserNotificationCenter.default.deliver(notification) } } func searchShortcut() { guard let mainWindow = MainWindowController.shared() else { return } if ( NSApplication.shared.isActive && !NSApplication.shared.isHidden && !mainWindow.isMiniaturized ) { NSApplication.shared.hide(nil) return } NSApp.activate(ignoringOtherApps: true) mainWindow.makeKeyAndOrderFront(self) guard let controller = mainWindow.contentViewController as? ViewController else { return } mainWindow.makeFirstResponder(controller.search) } func moveNoteToTop(note index: Int) { let isPinned = notesTableView.noteList[index].isPinned let position = isPinned ? 0 : notesTableView.countVisiblePinned() let note = notesTableView.noteList.remove(at: index) notesTableView.noteList.insert(note, at: position) notesTableView.reloadRow(note: note) notesTableView.moveRow(at: index, to: position) notesTableView.scrollRowToVisible(0) } func createNote(name: String = "", content: String = "", type: NoteType? = nil, project: Project? = nil) { guard let vc = ViewController.shared() else { return } var sidebarProject = project ?? getSidebarProject() var text = content if let type = vc.getSidebarType(), type == .Todo, content.count == 0 { text = "- [ ] " } if sidebarProject == nil { let projects = storage.getProjects() sidebarProject = projects.first } guard let project = sidebarProject else { return } disablePreview() notesTableView.deselectNotes() editArea.string = text let note = Note(name: name, project: project, type: type) note.content = NSMutableAttributedString(string: text) note.save() if let si = getSidebarItem(), si.type == .Tag { note.addTag(si.name) } self.search.stringValue.removeAll() updateTable() { DispatchQueue.main.async { if let index = self.notesTableView.getIndex(note) { self.notesTableView.selectRowIndexes([index], byExtendingSelection: false) self.notesTableView.scrollRowToVisible(index) } self.focusEditArea() } } } func pin(_ selectedRows: IndexSet) { guard !selectedRows.isEmpty, let notes = filteredNoteList, var state = filteredNoteList else { return } var updatedNotes = [(Int, Note)]() for row in selectedRows { guard let rowView = notesTableView.rowView(atRow: row, makeIfNecessary: false) as? NoteRowView, let cell = rowView.view(atColumn: 0) as? NoteCellView, let note = cell.objectValue as? Note else { continue } updatedNotes.append((row, note)) note.togglePin() cell.renderPin() } let resorted = storage.sortNotes(noteList: notes, filter: self.search.stringValue) let indexes = updatedNotes.compactMap({ _, note in resorted.firstIndex(where: { $0 === note }) }) let newIndexes = IndexSet(indexes) notesTableView.beginUpdates() let nowPinned = updatedNotes.filter { _, note in note.isPinned } for (row, note) in nowPinned { guard let newRow = resorted.firstIndex(where: { $0 === note }) else { continue } notesTableView.moveRow(at: row, to: newRow) let toMove = state.remove(at: row) state.insert(toMove, at: newRow) } let nowUnpinned = updatedNotes .filter({ (_, note) -> Bool in !note.isPinned }) .compactMap({ (_, note) -> (Int, Note)? in guard let curRow = state.firstIndex(where: { $0 === note }) else { return nil } return (curRow, note) }) for (row, note) in nowUnpinned.reversed() { guard let newRow = resorted.firstIndex(where: { $0 === note }) else { continue } notesTableView.moveRow(at: row, to: newRow) let toMove = state.remove(at: row) state.insert(toMove, at: newRow) } notesTableView.noteList = resorted notesTableView.reloadData(forRowIndexes: newIndexes, columnIndexes: [0]) notesTableView.selectRowIndexes(newIndexes, byExtendingSelection: false) notesTableView.endUpdates() filteredNoteList = resorted } func renameNote(selectedRow: Int) { guard notesTableView.noteList.indices.contains(selectedRow) else { return } guard let row = notesTableView.rowView(atRow: selectedRow, makeIfNecessary: true) as? NoteRowView else { return } guard let cell = row.view(atColumn: 0) as? NoteCellView else { return } guard let note = cell.objectValue as? Note else { return } cell.name.isEditable = true cell.name.becomeFirstResponder() cell.name.stringValue = note.getTitleWithoutLabel() if UserDefaultsManagement.appearanceType != AppearanceType.Custom, !UserDataService.instance.isDark, #available(OSX 10.13, *) { cell.name.textColor = NSColor.init(named: "reverseBackground") } let fileName = cell.name.currentEditor()!.string as NSString let fileNameLength = fileName.length cell.name.currentEditor()?.selectedRange = NSMakeRange(0, fileNameLength) } func external(selectedRow: Int) { if (notesTableView.noteList.indices.contains(selectedRow)) { let note = notesTableView.noteList[selectedRow] var path = note.url.path if note.isTextBundle() && !note.isUnlocked() { path = note.url.appendingPathComponent("text.markdown").absoluteURL.path } NSWorkspace.shared.openFile(path, withApplication: UserDefaultsManagement.externalEditor) } } func enablePreview() { //Preview mode doesn't support text search cancelTextSearch() guard let vc = ViewController.shared() else { return } vc.editArea.window?.makeFirstResponder(vc.notesTableView) self.view.window!.title = NSLocalizedString("FSNotes [preview]", comment: "") UserDefaultsManagement.preview = true refillEditArea() } func disablePreview() { self.view.window!.title = NSLocalizedString("FSNotes [edit]", comment: "") UserDefaultsManagement.preview = false editArea.markdownView?.removeFromSuperview() guard let editor = editArea else { return } editor.subviews.removeAll(where: { $0.isKind(of: MPreviewView.self) }) self.refillEditArea() } func togglePreview() { if (UserDefaultsManagement.preview) { disablePreview() } else { enablePreview() } } func loadMoveMenu() { guard let vc = ViewController.shared(), let note = vc.notesTableView.getSelectedNote() else { return } let moveTitle = NSLocalizedString("Move", comment: "Menu") if let prevMenu = noteMenu.item(withTitle: moveTitle) { noteMenu.removeItem(prevMenu) } let moveMenuItem = NSMenuItem() moveMenuItem.title = NSLocalizedString("Move", comment: "Menu") noteMenu.addItem(moveMenuItem) let moveMenu = NSMenu() if !note.isInArchive() { let archiveMenu = NSMenuItem() archiveMenu.title = NSLocalizedString("Archive", comment: "Sidebar label") archiveMenu.action = #selector(vc.archiveNote(_:)) moveMenu.addItem(archiveMenu) moveMenu.addItem(NSMenuItem.separator()) } if !note.isTrash() { let trashMenu = NSMenuItem() trashMenu.title = NSLocalizedString("Trash", comment: "Sidebar label") trashMenu.action = #selector(vc.deleteNote(_:)) trashMenu.tag = 555 moveMenu.addItem(trashMenu) moveMenu.addItem(NSMenuItem.separator()) } let projects = storage.getProjects() for item in projects { if note.project == item || item.isTrash || item.isArchive { continue } let menuItem = NSMenuItem() menuItem.title = item.getFullLabel() menuItem.representedObject = item menuItem.action = #selector(vc.moveNote(_:)) moveMenu.addItem(menuItem) } let personalSelection = [ "noteMove.print", "noteMove.copyTitle", "noteMove.copyUrl", "noteMove.rename" ] for menu in noteMenu.items { if let identifier = menu.identifier?.rawValue, personalSelection.contains(identifier) { menu.isHidden = (vc.notesTableView.selectedRowIndexes.count > 1) } } noteMenu.setSubmenu(moveMenu, for: moveMenuItem) loadHistory() } func loadSortBySetting() { let viewLabel = NSLocalizedString("View", comment: "Menu") let sortByLabel = NSLocalizedString("Sort by", comment: "View menu") guard let menu = NSApp.menu, let view = menu.item(withTitle: viewLabel), let submenu = view.submenu, let sortMenu = submenu.item(withTitle: sortByLabel), let sortItems = sortMenu.submenu else { return } let sort = UserDefaultsManagement.sort for item in sortItems.items { if let id = item.identifier, id.rawValue == "SB.\(sort.rawValue)" { item.state = NSControl.StateValue.on } } } func registerKeyValueObserver() { let keyStore = NSUbiquitousKeyValueStore() NotificationCenter.default.addObserver(self, selector: #selector(ViewController.ubiquitousKeyValueStoreDidChange), name: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: keyStore) keyStore.synchronize() } @objc func ubiquitousKeyValueStoreDidChange(notification: NSNotification) { if let keys = notification.userInfo?[NSUbiquitousKeyValueStoreChangedKeysKey] as? [String] { for key in keys { if key == "co.fluder.fsnotes.pins.shared" { let changedNotes = storage.restoreCloudPins() if let notes = changedNotes.added { for note in notes { if let i = notesTableView.getIndex(note) { self.moveNoteToTop(note: i) } } } if let notes = changedNotes.removed { for note in notes { if let i = notesTableView.getIndex(note) { notesTableView.reloadData(forRowIndexes: [i], columnIndexes: [0]) } } } } } } } func checkSidebarConstraint() { if sidebarSplitView.subviews[0].frame.width > 50 { searchTopConstraint.constant = 8 return } if UserDefaultsManagement.hideRealSidebar || sidebarSplitView.subviews[0].frame.width < 50 { searchTopConstraint.constant = CGFloat(25) return } searchTopConstraint.constant = 8 } @IBAction func duplicate(_ sender: Any) { if let notes = notesTableView.getSelectedNotes() { for note in notes { if note.isUnlocked() { } if note.isTextBundle() || note.isEncrypted() { note.duplicate() continue } guard let name = note.getDupeName() else { continue } let noteDupe = Note(name: name, project: note.project, type: note.type) noteDupe.content = NSMutableAttributedString(string: note.content.string) // Clone images if note.type == .Markdown && note.container == .none { let images = note.getAllImages() for image in images { move(note: noteDupe, from: image.url, imagePath: image.path, to: note.project, copy: true) } } noteDupe.save() storage.add(noteDupe) notesTableView.insertNew(note: noteDupe) } } } @IBAction func noteCopy(_ sender: Any) { guard let fr = self.view.window?.firstResponder else { return } if fr.isKind(of: EditTextView.self) { self.editArea.copy(sender) } if fr.isKind(of: NotesTableView.self) { self.saveTextAtClipboard() } } @IBAction func copyURL(_ sender: Any) { if let note = notesTableView.getSelectedNote(), let title = note.title.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { let name = "fsnotes://find/\(title)" let pasteboard = NSPasteboard.general pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil) pasteboard.setString(name, forType: NSPasteboard.PasteboardType.string) let notification = NSUserNotification() notification.title = "FSNotes" notification.informativeText = NSLocalizedString("URL has been copied to clipboard", comment: "") notification.soundName = NSUserNotificationDefaultSoundName NSUserNotificationCenter.default.deliver(notification) } } @IBAction func copyTitle(_ sender: Any) { if let note = notesTableView.getSelectedNote() { let pasteboard = NSPasteboard.general pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil) pasteboard.setString(note.title, forType: NSPasteboard.PasteboardType.string) } } func updateTitle(newTitle: String?) { let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? "FSNotes" let noteTitle: String = newTitle ?? appName var titleString = noteTitle if noteTitle.isValidUUID { titleString = String() } titleLabel.stringValue = titleString let title = newTitle != nil ? "\(appName) - \(noteTitle)" : appName MainWindowController.shared()?.title = title } //MARK: Share Service @IBAction func togglePreview(_ sender: NSButton) { togglePreview() } @IBAction func shareSheet(_ sender: NSButton) { if let note = notesTableView.getSelectedNote() { let sharingPicker = NSSharingServicePicker(items: [note.content]) sharingPicker.delegate = self sharingPicker.show(relativeTo: NSZeroRect, of: sender, preferredEdge: .minY) } } public func saveTextAtClipboard() { if let note = notesTableView.getSelectedNote() { let pasteboard = NSPasteboard.general pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil) pasteboard.setString(note.content.string, forType: NSPasteboard.PasteboardType.string) } } public func saveHtmlAtClipboard() { if let note = notesTableView.getSelectedNote() { if let render = renderMarkdownHTML(markdown: note.content.string) { let pasteboard = NSPasteboard.general pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil) pasteboard.setString(render, forType: NSPasteboard.PasteboardType.string) } } } @IBAction func textFinder(_ sender: NSMenuItem) { guard let vc = ViewController.shared() else { return } if !vc.editAreaScroll.isFindBarVisible, [NSFindPanelAction.next.rawValue, NSFindPanelAction.previous.rawValue].contains(UInt(sender.tag)) { if UserDefaultsManagement.preview && vc.notesTableView.selectedRow > -1 { vc.disablePreview() } let menu = NSMenuItem(title: "", action: nil, keyEquivalent: "") menu.tag = NSTextFinder.Action.showFindInterface.rawValue vc.editArea.performTextFinderAction(menu) } DispatchQueue.main.async { vc.editArea.performTextFinderAction(sender) } } func textView(_ view: NSTextView, menu: NSMenu, for event: NSEvent, at charIndex: Int) -> NSMenu? { for item in menu.items { if item.title == NSLocalizedString("Copy Link", comment: "") { item.action = #selector(NSText.copy(_:)) } } return menu } func splitViewWillResizeSubviews(_ notification: Notification) { editArea.updateTextContainerInset() } public static func shared() -> ViewController? { guard let delegate = NSApplication.shared.delegate as? AppDelegate else { return nil } return delegate.mainWindowController?.window?.contentViewController as? ViewController } public func copy(project: Project, url: URL) -> URL { let fileName = url.lastPathComponent do { let destination = project.url.appendingPathComponent(fileName) try FileManager.default.copyItem(at: url, to: destination) return destination } catch { var tempUrl = url let ext = tempUrl.pathExtension tempUrl.deletePathExtension() let name = tempUrl.lastPathComponent tempUrl.deleteLastPathComponent() let now = DateFormatter().formatForDuplicate(Date()) let baseUrl = project.url.appendingPathComponent(name + " " + now + "." + ext) try? FileManager.default.copyItem(at: url, to: baseUrl) return baseUrl } } public func unLock(notes: [Note]) { getMasterPassword() { password, isTypedByUser in guard password.count > 0 else { return } var i = 0 for note in notes { let success = note.unLock(password: password) if success, i == 0 { self.refillEditArea() if isTypedByUser { self.save(password: password) } } self.notesTableView.reloadRow(note: note) i = i + 1 } } } private func getMasterPassword(completion: @escaping (String, Bool) -> ()) { if #available(OSX 10.12.2, *), UserDefaultsManagement.allowTouchID { let context = LAContext() context.localizedFallbackTitle = NSLocalizedString("Enter Master Password", comment: "") guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) else { masterPasswordPrompt(completion: completion) return } context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "To access secure data") { (success, evaluateError) in if !success { self.masterPasswordPrompt(completion: completion) return } do { let item = KeychainPasswordItem(service: KeychainConfiguration.serviceName, account: "Master Password") let password = try item.readPassword() completion(password, false) return } catch { print(error) } self.masterPasswordPrompt(completion: completion) } } else { masterPasswordPrompt(completion: completion) } } private func masterPasswordPrompt(completion: @escaping (String, Bool) -> ()) { DispatchQueue.main.async { guard let window = MainWindowController.shared() else { return } self.alert = NSAlert() guard let alert = self.alert else { return } let field = NSSecureTextField(frame: NSRect(x: 0, y: 0, width: 290, height: 20)) alert.messageText = NSLocalizedString("Master password:", comment: "") alert.informativeText = NSLocalizedString("Please enter password for current note", comment: "") alert.accessoryView = field alert.alertStyle = .informational alert.addButton(withTitle: NSLocalizedString("OK", comment: "")) alert.addButton(withTitle: NSLocalizedString("Cancel", comment: "")) alert.beginSheetModal(for: window) { (returnCode: NSApplication.ModalResponse) -> Void in if returnCode == NSApplication.ModalResponse.alertFirstButtonReturn { completion(field.stringValue, true) } else { self.alert = nil } } field.becomeFirstResponder() } } private func save(password: String) { guard password.count > 0, UserDefaultsManagement.savePasswordInKeychain else { return } let item = KeychainPasswordItem(service: KeychainConfiguration.serviceName, account: "Master Password") do { let oldPassword = try item.readPassword() guard oldPassword.count == 0 else { return } try item.savePassword(password) } catch { print("Master password saving error: \(error)") } } private func lockUnlocked(notes: [Note]) -> [Note] { var notes = notes var isFirst = true for note in notes { if note.isUnlocked() && note.isEncrypted() { if note.lock() && isFirst { self.refillEditArea() } notes.removeAll { $0 === note } } isFirst = false self.notesTableView.reloadRow(note: note) } return notes } private func decryptUnlocked(notes: [Note]) -> [Note] { var notes = notes for note in notes { if note.isUnlocked() { if note.unEncryptUnlocked() { notes.removeAll { $0 === note } notesTableView.reloadRow(note: note) } } } return notes } @objc func onSleepNote(note: NSNotification) { if UserDefaultsManagement.lockOnSleep { lockAll(self) } } @objc func onScreenLocked(note: NSNotification) { if UserDefaultsManagement.lockOnScreenActivated{ lockAll(self) } } @objc func onUserSwitch(note: NSNotification) { if UserDefaultsManagement.lockOnUserSwitch { lockAll(self) } } }
36.053134
205
0.571868
09b9c0427002fb07d57667512a4d34c46fba5e3e
1,203
// // AppDelegate.swift // FloatingBrowser // // Created by Andrew Finke on 9/21/19. // Copyright © 2019 Andrew Finke. All rights reserved. // import Cocoa import SwiftUI @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var window: NSWindow! func applicationDidFinishLaunching(_ aNotification: Notification) { window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 480, height: 300), styleMask: [ .titled, .closable, .miniaturizable, .resizable, .fullSizeContentView ], backing: .buffered, defer: false) window.contentView = NSHostingView(rootView: ContentView()) window.makeKeyAndOrderFront(nil) window.level = .floating window.collectionBehavior = .canJoinAllSpaces window.alphaValue = 0.0 DispatchQueue.main.asyncAfter(deadline: .now() + 0.001) { self.window.center() self.window.alphaValue = 1.0 } } func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return true } }
25.0625
91
0.600998
16ba94313fc65fd17e2a2148497f13a5e7df0b27
1,445
@testable import Argo import XCTest final class TestChunk: XCTestCase { private var factory: Factory! private var split: Factory.Split! override func setUp() { factory = .init() split = .init() } override func tearDown() { try? FileManager.default.removeItem(at: Argonaut.url) try? FileManager.default.removeItem(at: Argonaut.temporal) } func testAdd() { split.data = .init("hello world".utf8) split.x = 87 split.y = 76 factory.chunk([split], z: 0) let data = try! Data(contentsOf: Argonaut.temporal) XCTAssertEqual(87, data.subdata(in: 1 ..< 5).withUnsafeBytes { $0.bindMemory(to: UInt32.self)[0] }) XCTAssertEqual(76, data.subdata(in: 5 ..< 9).withUnsafeBytes { $0.bindMemory(to: UInt32.self)[0] }) } func testWrap() { let expect = expectation(description: "") split.data = .init("hello world".utf8) split.x = 87 split.y = 76 factory.chunk([split], z: 3) split.data = .init("lorem ipsum".utf8) split.x = 34 split.y = 12 factory.chunk([split], z: 4) Argonaut.save(factory) let cart = Argonaut.load(factory.item).1 XCTAssertEqual(2, cart.map.keys.count) cart.tile(87, 76, 3) { XCTAssertNotNil($0) expect.fulfill() } waitForExpectations(timeout: 1) } }
30.104167
107
0.574394
29aa5ab93d49ace99fc06c69ff519e884ac78754
1,455
// // XDataRefreshProtocol.swift // XFoundation // // Created by sckj on 2020/8/13. // Copyright © 2020 com.learn. All rights reserved. // import Foundation import RxSwift protocol XDataRefreshProtocol : NSObject { associatedtype Data var dataList : [Data] { get set } var page : Int { get set } var pageSize : Int { get set } /// 是否有数据没有加载 var hasMoreData : Bool { get set } /// 刷新数据完成,通知视图刷新 var didRefreshSubject: PublishSubject<()> { get } /// 加载更多完成,通知视图刷新 var didLoadMoreSubject: PublishSubject<Range<Int>> { get } /// 请求完成了,不区分是刷新还是加载更多 var requestFinishSubject: PublishSubject<()> { get } func requestData() -> Single<XResponseModel<[Data]>> } extension XDataRefreshProtocol { /// 默认一页30条数据 var pageSize : Int { 30 } func refreshData() { self.page = 1 sendRequest() } func sendRequest() { let request = requestData() request.subscribe(onSuccess: { [weak self] (resp) in guard let strongSelf = self else { return } if strongSelf.page == 1 { strongSelf.dataList.removeAll() } let list = resp.data ?? [] strongSelf.dataList.append(contentsOf: list) // strongSelf.hasMoreData = list.count > }) { (error) in }.disposed(by: self.disposeBag) } }
23.095238
62
0.567698
2104ba2505102631f016b31b09525163c693bdb5
6,177
// // ParameterServer.swift // rosmaster // // Created by Thomas Gustafsson on 2019-04-04. // import Foundation import Logging import rpcobject fileprivate let logger = Logger(label: "params") struct Update<Value: ArrayContructable> { let subscriber: Caller let key: String let value: Value? init(_ subscriber: Caller, _ key: String, _ value: Value? = nil) { self.subscriber = subscriber self.key = key self.value = value } } final class ParameterServer<Value: ArrayContructable> { typealias ParameterValue = Root<Value> let registrationManager: RegistrationManager let parameters = RadixTree<Value>() init(reg_manager: RegistrationManager) { self.registrationManager = reg_manager } func getAllNames() -> [String] { return parameters.getNames() } func getValueFor(param: String) -> ParameterValue? { return parameters.get(param) } func has(parameter: String) -> Bool { return parameters.find(parameter) } func search(namespace: String, param: String) -> String? { if param.isEmpty || isPrivate(param) { logger.error("invalid key [\(param) in search_parameter") return nil } if !isGlobal(namespace) { logger.error("namespace [\(namespace) must be global in search_parameter") return nil } if isGlobal(param) { if has(parameter: param) { return param } else { return nil } } // - we only search for the first namespace in the key to check for a match let key_namespaces = param.split(separator: "/") let key_ns = String(key_namespaces[0]) let namespaces = namespace.split(separator: "/") for i in 0...namespaces.count { let namespace = namespaces.dropLast(i).joined(separator: "/") let search_key = "/" + join(namespace: namespace, name: key_ns) if has(parameter: search_key) { return "/" + join(namespace: namespace, name: param) } } return nil } func delete(param: String, notfiy: ([Update<Value>]) -> Void) -> Bool { if param == "/" || param.isEmpty { logger.error("cannot delete root of parameter tree") return false } if let removed = parameters.remove(param) { let updates = computeUpdates(key: removed) notfiy(updates) return true } return false } public func set(param: String, value: Value) -> Edge<Value>? { if param == "/" && value.count <= 1 { logger.error("cannot set root of parameter tree to non-dictionary") return nil } let name = canonicalize(name: param) // Split dictionary into children values if let dict = value.dictionary { for (key, val) in dict { let n = join(namespace: name, name: key) let _ = set(param: n, value: val) } return parameters.get(name) as? Edge<Value> } var par = parameters.get(name) as? Edge<Value> if let par = par { par.value = value par.children.removeAll() } else { par = parameters.insert(name, value: value) } guard let parameter = par else { logger.error("could not set/create parameter \(name) with value \(value)") return nil } return parameter } public func set(param: String, value: Value, notfiy: ([Update<Value>]) -> Void) { guard let parameter = set(param: param, value: value) else { return } let updates = computeUpdates(key: parameter, param_value: value) notfiy(updates) } func subscribe(parameter: String, node: Caller) -> ParameterValue? { let key = canonicalize(name: parameter) let val = getValueFor(param: key) registrationManager.register(parameterSubscriber: node, parameter: key) return val } func unsubscribe(parameter: String, node: Caller) -> Result<String,ErrorMessage> { let key = canonicalize(name: parameter) return registrationManager.unregisterParameterSubscriber(key: key, node: node) } func computeUpdates(key: Edge<Value>, param_value: Value? = nil) -> [Update<Value>] { if registrationManager.paramSubscribers.isEmpty { return [] } var updates = [Update<Value>]() var all_keys = [String]() key.getNames(&all_keys) logger.debug("\(all_keys) has changed") for (sub_key, sub_caller) in registrationManager.paramSubscribers.providers { let ns_key = sub_key.hasSuffix("/") ? sub_key : sub_key + "/" if key.fullName.hasPrefix(ns_key) { updates.append(Update<Value>(sub_caller, key.fullName, param_value )) } else if ns_key.hasPrefix(key.fullName) && !all_keys.contains(sub_key) { // parameter was deleted updates.append(Update<Value>(sub_caller, sub_key)) } } // add updates for exact matches within tree for key in all_keys { for s in registrationManager.paramSubscribers.getCallers(key: key) { if let par = parameters.get(key) as? Edge<Value> { updates.append(Update(s, key, par.values )) } else { logger.error("Could not find parameter \(key)") } } } return updates } func computeAllKeys(param: String, value: XmlRpcValue, all_keys: inout [String] ) { guard let vs = value.dictionary else { return } for (k, value) in vs { let newKey = join(namespace: param, name: k) + "/" all_keys.append(newKey) if let _ = value.dictionary { computeAllKeys(param: newKey, value: value, all_keys: &all_keys) } } } }
29.414286
89
0.570342
219663e6127b2eef3dbaacc0cbffe88147125d8b
551
// // DetailRouter.swift // ViperTaskManager // // Created by Aaron Lee on 19/11/16. // Copyright © 2016 One Fat Giraffe. All rights reserved. // import UIKit import Swinject protocol DetailRouterInputProtocol: class { func dismissDetailViewController(viewController: UIViewController) } protocol DetailParentRouterProtocol: class { } class DetailRouter: DetailRouterInputProtocol { func dismissDetailViewController(viewController: UIViewController) { viewController.dismiss(animated: true, completion: nil) } }
20.407407
72
0.749546
91f4db24457b851f8f1c87c52e5a36cd3f56a271
352
// // Cart.swift // NavigationDrawer // // Created by recherst on 2021/8/28. // import SwiftUI struct Cart: View { var body: some View { NavigationView { Text("") .navigationTitle("Cart") } } } struct Cart_Previews: PreviewProvider { static var previews: some View { Cart() } }
14.666667
40
0.548295
2109a12dda8178cc4f3cee10ebfef3168316fa57
336
// swift-tools-version:5.0 import PackageDescription let package = Package( name: "DTPagerController", products: [ .library(name: "DTPagerController", targets: ["DTPagerController"]), ], targets: [ .target( name: "DTPagerController", path: "DTPagerController/Classes"), ] )
21
76
0.604167
d94b1e047a354f05edd96090331f6a46ff3ef0aa
257
// // DifferentNameView.swift // UIKitExtensionsExample // // Created by 张鹏 on 2019/8/8. // Copyright © 2019 [email protected]. All rights reserved. // import UIKit class DifferentNameView: UIView { @IBOutlet weak var textLabel: UILabel! }
17.133333
66
0.715953
2995b481cbba69cb80c68f6da061f57b664c7a92
3,235
// // WriteExperienceViewController.swift // ReceptApp // // In the WriteExperienceViewController users are able to write an experience about the chosen recipe. If the user submits the experience, the experience is added to the database. // // Created by Gavin Schipper on 24-01-18. // Copyright © 2018 Gavin Schipper. All rights reserved. // import UIKit import Firebase class WriteExperienceViewController: UIViewController { // MARK: Properties var chosenRecipe: recipe! var username: String = "" let userID = Auth.auth().currentUser?.uid let ref: DatabaseReference! = Database.database().reference() // MARK: Outlets @IBOutlet weak var recipeNameLabel: UILabel! @IBOutlet weak var storyTextView: UITextView! @IBOutlet weak var saveButton: UIButton! // MARK: Actions /// checks if the textView is empty and possibly shows an alert. Otherwise the experience is added to the database and shows an alert from where the user can go back to the ExperienceViewController. @IBAction func saveButtonPressed(_ sender: Any) { if storyTextView.text == "" { showAlert(title: "Error", message: "You didn't write any experiences to be added.") } else { let expReference = ref.child("experiences").child(chosenRecipe.recipeID) let expID = ref.childByAutoId().key expReference.child(expID).setValue(["userID": userID!, "username": username, "experienceText": storyTextView.text!]) storyTextView.text = "" let alert = UIAlertController(title: "Thanks!", message: "Your experience with this recipe was added and is now accessible for others.", preferredStyle: UIAlertControllerStyle.alert) // Go back to the ExperienceViewController when 'OK' is tapped alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { action in self.navigationController?.popViewController(animated: true) })) self.present(alert, animated: true, completion: nil) } } // MARK: Functions /// gives the outlets the right values, gives the textview a border and retrieves the username of the current user override func viewDidLoad() { super.viewDidLoad() recipeNameLabel.text = chosenRecipe.title storyTextView.layer.borderWidth = 3.0 let appRed = UIColor(red: 204/255, green: 83/255, blue: 67/255, alpha: 1) storyTextView.layer.borderColor = appRed.cgColor retrieveUsername() } /// Retrieves the username of the current user from the database func retrieveUsername() { ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in let value = snapshot.value as? NSDictionary self.username = value?["username"] as? String ?? "" }) } // Closes the keyboard when the screen is pressed anywhere but the keyboard override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } }
38.975904
202
0.650696
3a54d2a704be009d6b746737f9c3653999e8c910
9,951
/* SwiftVideo, Copyright 2019 Unpause SAS 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 VectorMath import Foundation // swiftlint:disable identifier_name enum ComputeError: Error { case invalidPlatform case invalidDevice case invalidOperation case invalidValue case invalidProgram case invalidContext case deviceNotAvailable case outOfMemory case compilerNotAvailable case computeKernelNotFound(ComputeKernel) case badTarget case badInputData(description: String) case badContextState(description: String) case compilerError(description: String) case unknownError case notImplemented } public enum ComputeDeviceType { case GPU case CPU case Accelerator case Default } // operation_infmt_outfmt enum ComputeKernel { // basic compositing and format conversion case img_nv12_nv12 case img_bgra_nv12 case img_rgba_nv12 case img_bgra_bgra case img_y420p_y420p case img_y420p_nv12 case img_clear_nv12 // clear the texture provided as target case img_clear_yuvs case img_clear_bgra case img_clear_y420p case img_clear_rgba case img_rgba_y420p case img_bgra_y420p // audio case snd_s16i_s16i // motion estimation case me_fullsearch // user-defined case custom(name: String) } struct ImageUniforms { let transform: Matrix4 let textureTransform: Matrix4 let borderMatrix: Matrix4 let fillColor: Vector4 let inputSize: Vector2 let outputSize: Vector2 let opacity: Float let imageTime: Float let targetTime: Float } // Find a default compute kernel // Throws ComputeError.invalidValue if not found func defaultComputeKernelFromString(_ str: String) throws -> ComputeKernel { let kernelMap: [String: ComputeKernel] = [ "img_nv12_nv12": .img_nv12_nv12, "img_bgra_nv12": .img_bgra_nv12, "img_rgba_nv12": .img_rgba_nv12, "img_bgra_bgra": .img_bgra_bgra, "img_y420p_y420p": .img_y420p_y420p, "img_y420p_nv12": .img_y420p_nv12, "img_clear_nv12": .img_clear_nv12, "img_clear_yuvs": .img_clear_yuvs, "img_clear_bgra": .img_clear_bgra, "img_clear_rgba": .img_clear_bgra, "img_rgba_y420p": .img_rgba_y420p, "img_bgra_y420p": .img_bgra_y420p, "img_clear_y420p": .img_clear_y420p ] guard let kernel = kernelMap[str] else { throw ComputeError.invalidValue } return kernel } public func hasAvailableComputeDevices(forType search: ComputeDeviceType) -> Bool { availableComputeDevices().filter { guard let type = $0.deviceType, type == search && $0.available else { return false } return true }.count > 0 } public func makeComputeContext(forType search: ComputeDeviceType) throws -> ComputeContext { let devices = availableComputeDevices().filter { ($0.deviceType <??> { $0 == search } <|> false) && $0.available } if let device = devices.first, let context = try createComputeContext(device) { return context } else { throw ComputeError.deviceNotAvailable } } func usingContext(_ context: ComputeContext, _ fun: (ComputeContext) throws -> ComputeContext) rethrows -> ComputeContext { endComputePass(try fun(beginComputePass(context)), true) } // applyComputeImage is a convenience function used for typical image compositing operations and // format conversion. This has a standard set of useful uniforms for those // operations. If you want to do something more custom, use runComputeKernel instead. // Throws ComputeError: // - badContextState // - computeKernelNotFound // - badInputData // - badTarget // Can throw additional errors from MTLDevice.makeComputePipelineState func applyComputeImage(_ context: ComputeContext, image: PictureSample, target: PictureSample, kernel: ComputeKernel) throws -> ComputeContext { let inputSize = Vector2([image.size().x, image.size().y]) let outputSize = Vector2([target.size().x, target.size().y]) let matrix = image.matrix().inverse.transpose let textureMatrix = image.textureMatrix().inverse.transpose let uniforms = ImageUniforms(transform: matrix, textureTransform: textureMatrix, borderMatrix: image.borderMatrix().inverse.transpose, fillColor: image.fillColor(), inputSize: inputSize, outputSize: outputSize, opacity: image.opacity(), imageTime: seconds(image.time()), targetTime: seconds(target.time())) return try runComputeKernel(context, images: [image], target: target, kernel: kernel, maxPlanes: 3, uniforms: uniforms, blends: true) } // // Place in a pipeline to upload textures to the GPU // public class GPUBarrierUpload: Tx<PictureSample, PictureSample> { public init(_ context: ComputeContext, retainCpuBuffer: Bool = true) { self.context = createComputeContext(sharing: context) super.init() super.set { [weak self] in guard let strongSelf = self, let context = strongSelf.context else { return .gone } if $0.bufferType() == .cpu { do { $0.info()?.startTimer("gpu.upload") let sample = try uploadComputePicture(context, pict: $0, retainCpuBuffer: retainCpuBuffer) $0.info()?.endTimer("gpu.upload") return .just(sample) } catch let error { return .error(EventError("barrier.upload", -1, "\(error)", assetId: $0.assetId())) } } else { return .just($0) } } } let context: ComputeContext? } /* public class GPUBarrierAudioUpload: Tx<AudioSample, AudioSample> { public init(_ context: ComputeContext) { self.context = createComputeContext(sharing: context) self.peak = 0 super.init() super.set { [weak self] sample in guard let strongSelf = self, let context = strongSelf.context else { return .gone } if sample.bufferType() == .cpu { do { let buffers = try sample.data().enumerated().map { (idx, element) in return try uploadComputeBuffer(context, src: element, dst: sample.computeData()[safe: idx]) } return .just(AudioSample(sample, bufferType: .gpu, computeBuffers: buffers)) } catch (let error) { print("caught download error \(error)") return .error(EventError("barrier.upload", -1, "\(error)")) } } return .just(sample) } } let context: ComputeContext? var peak: Double }*/ // // Place in a pipeline to download textures from the GPU // public class GPUBarrierDownload: Tx<PictureSample, PictureSample> { public init(_ context: ComputeContext, retainGpuBuffer: Bool = true) { self.context = createComputeContext(sharing: context) super.init() super.set { [weak self] in guard let strongSelf = self, let context = strongSelf.context else { return .gone } if $0.bufferType() == .gpu { do { $0.info()?.startTimer("gpu.download") let sample = try downloadComputePicture(context, pict: $0, retainGpuBuffer: retainGpuBuffer) $0.info()?.endTimer("gpu.download") return .just(sample) } catch let error { return .error(EventError("barrier.download", -1, "\(error)", assetId: $0.assetId())) } } else { return .just($0) } } } let context: ComputeContext? } /* public class GPUBarrierAudioDownload: Tx<AudioSample, AudioSample> { public init(_ context: ComputeContext) { self.context = createComputeContext(sharing: context) self.peak = 0 super.init() super.set { [weak self] sample in guard let strongSelf = self, let context = strongSelf.context else { return .gone } if sample.bufferType() == .cpu { do { let buffers = try sample.computeData().enumerated().map { (idx, element) in return try downloadComputeBuffer(context, src: element, dst: sample.data()[safe: idx]) } return .just(AudioSample(sample, bufferType: .cpu, buffers: buffers)) } catch (let error) { return .error(EventError("barrier.download", -1, "\(error)")) } } return .just(sample) } } let context: ComputeContext? var peak: Double }*/
35.162544
118
0.598432
d54ecb230d5b9c9b09eac24c030d26f54c81605b
1,396
import Critic import Informant #if canImport(Darwin) import Darwin #else import Glibc #endif import Foundation enum ExplainError: Error, LocalizedError { case unrecognizedID(String) var errorDescription: String? { switch self { case .unrecognizedID(let summary): return summary } } } public func explain(_ arguments: [String]) throws { var unrecognizedIDs = [String]() for id in arguments { if let explainer = Explainer.all[id.uppercased()] ?? guessID(id).flatMap({ Explainer.all[$0] }) { print(plainText(for: explainer)) } else { unrecognizedIDs.append(id) } } if !unrecognizedIDs.isEmpty { throw ExplainError.unrecognizedID( "Unrecgonized ID\(unrecognizedIDs.count > 1 ? "s" : ""): \(unrecognizedIDs.joined(separator: ", ")). " + "Please choose from: \(Explainer.all.keys.sorted().joined(separator: ", "))" ) } } private func guessID(_ badID: String) -> String? { let maybeNumber: String if badID.uppercased().first == "E" { maybeNumber = String(badID.dropFirst()) } else { maybeNumber = badID } guard let n = Int(maybeNumber) else { return nil } if n < 10 { return "E00\(n)" } else if n < 100 { return "E0\(n)" } else { return "E\(n)" } }
22.516129
116
0.581662
4806f2ac3c367bc126a3e4690b49609d8cf19196
8,872
// // ContentView.swift // TestDecimilKeyboard WatchKit Extension // // Created by Ian Applebaum on 2/2/21. // import SwiftUI #if os(watchOS) @available(watchOS 6.0, *) public struct DigiTextView: View { var style: KeyboardStyle var placeholder: String @Binding public var text: String @State public var presentingModal: Bool var align: TextViewAlignment public init( placeholder: String, text: Binding<String>, presentingModal:Bool, alignment: TextViewAlignment = .center,style: KeyboardStyle = .numbers){ _text = text _presentingModal = State(initialValue: presentingModal) self.align = alignment self.placeholder = placeholder self.style = style } public var body: some View { Button(action: { presentingModal.toggle() }) { if text != ""{ Text(text) } else{ Text(placeholder) .lineLimit(1) .opacity(0.5) } }.buttonStyle(TextViewStyle(alignment: align)) .sheet(isPresented: $presentingModal, content: { EnteredText(text: $text, presentedAsModal: $presentingModal, style: self.style) }) } } @available(watchOS 6.0, *) public struct EnteredText: View { @Binding var text:String @Binding var presentedAsModal: Bool var style: KeyboardStyle var watchOSDimensions: CGRect? public init(text: Binding<String>, presentedAsModal: Binding<Bool>, style: KeyboardStyle){ _text = text _presentedAsModal = presentedAsModal self.style = style let device = WKInterfaceDevice.current() watchOSDimensions = device.screenBounds } public var body: some View{ VStack(alignment: .trailing) { Button(action:{ presentedAsModal.toggle() }){ ZStack(content: { Text("1") .font(.title2) .foregroundColor(.clear ) }) Text(text) .font(.title2) .frame(height: watchOSDimensions!.height * 0.15, alignment: .trailing) } .buttonStyle(PlainButtonStyle()) .multilineTextAlignment(.trailing) .lineLimit(1) DigetPadView(text: $text, style: style) .edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/) } .toolbar(content: { ToolbarItem(placement: .cancellationAction){ Button("Done"){ presentedAsModal.toggle() } } }) } } @available(iOS 13.0, watchOS 6.0, *) public struct DigetPadView: View { public var widthSpace: CGFloat = 1.0 @Binding var text:String var style: KeyboardStyle @State var scrollAmount = 0.0 public init(text: Binding<String>, style: KeyboardStyle){ _text = text self.style = style } public var body: some View { VStack(spacing: 1) { HStack(spacing: widthSpace){ Button(action: { text.append("1") }) { Text("1") .padding(0) } .digitKeyFrame() Button(action: { text.append("2") }) { Text("2") }.digitKeyFrame() Button(action: { text.append("3") }) { Text("3") }.digitKeyFrame() } HStack(spacing:widthSpace){ Button(action: { text.append("4") }) { Text("4") }.digitKeyFrame() Button(action: { text.append("5") }) { Text("5") }.digitKeyFrame() Button(action: { text.append("6") }) { Text("6") }.digitKeyFrame() } HStack(spacing:widthSpace){ Button(action: { text.append("7") }) { Text("7") }.digitKeyFrame() Button(action: { text.append("8") }) { Text("8") }.digitKeyFrame() Button(action: { text.append("9") }) { Text("9") } .digitKeyFrame() } HStack(spacing:widthSpace) { if style == .decimal { Button(action: { if !(text.contains(".")){ if text == ""{ text.append("0.") }else{ text.append(".") } } }) { Text("•") } .digitKeyFrame() } else { Spacer() .padding(1) } Button(action: { text.append("0") }) { Text("0") } .digitKeyFrame() Button(action: { if let last = text.indices.last{ text.remove(at: last) } }) { Image(systemName: "delete.left") } .digitKeyFrame() } } .font(.title2) .focusable(true) .digitalCrownRotation($scrollAmount, from: -1, through: 1) .onChange(of: scrollAmount){newValue in print(newValue) if (newValue == 1){ scrollAmount = 0 text = String((Int(text) ?? 0) + 1) print(text) }else if (newValue == -1){ scrollAmount = 0 text = String((Int(text) ?? 0) - 1) print(text) } } } } #endif #if DEBUG #if os(watchOS) struct EnteredText_Previews: PreviewProvider { static var previews: some View { EnteredText( text: .constant(""), presentedAsModal: .constant(true), style: .numbers) Group { EnteredText( text: .constant(""), presentedAsModal: .constant(true), style: .decimal) EnteredText( text: .constant(""), presentedAsModal: .constant(true), style: .decimal) .environment(\.sizeCategory, .accessibilityExtraExtraExtraLarge) EnteredText( text: .constant(""), presentedAsModal: .constant(true), style: .decimal) .environment(\.sizeCategory, .accessibilityExtraExtraExtraLarge) .accessibilityElement(children: /*@START_MENU_TOKEN@*/.contain/*@END_MENU_TOKEN@*/) } EnteredText( text: .constant(""), presentedAsModal: .constant(true), style: .decimal).previewDevice("Apple Watch Series 6 - 40mm") Group { EnteredText( text: .constant(""), presentedAsModal: .constant(true), style: .numbers).previewDevice("Apple Watch Series 3 - 38mm") EnteredText( text: .constant(""), presentedAsModal: .constant(true), style: .numbers).environment(\.sizeCategory, .accessibilityExtraExtraExtraLarge).previewDevice("Apple Watch Series 3 - 38mm") } EnteredText( text: .constant(""), presentedAsModal: .constant(true), style: .decimal).previewDevice("Apple Watch Series 3 - 42mm") } } struct Content_View_Previews: PreviewProvider { static var previews: some View{ ScrollView { ForEach(0 ..< 4) { item in DigiTextView(placeholder: "Placeholder", text: .constant(""), presentingModal: false, alignment: .leading) } Button(action: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Action@*/{}/*@END_MENU_TOKEN@*/) { /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Content@*/Text("Button")/*@END_MENU_TOKEN@*/ } } } } struct memeView: View{ @State var text = "0" var body: some View{ DigiTextView(placeholder: "Placeholder", text: $text, presentingModal: false, alignment: .leading) } } struct PP_Previews: PreviewProvider { static var previews: some View{ memeView() } } struct TextField_Previews: PreviewProvider { static var previews: some View{ ScrollView{ ForEach(0 ..< 4){ item in TextField(/*@START_MENU_TOKEN@*/"Placeholder"/*@END_MENU_TOKEN@*/, text: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Value@*/.constant("")/*@END_MENU_TOKEN@*/) } Button(action: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Action@*/{}/*@END_MENU_TOKEN@*/) { /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Content@*/Text("Button")/*@END_MENU_TOKEN@*/ } } } } #endif #endif #if os(watchOS) @available(iOS 13.0, watchOS 6.0, *) struct TextViewStyle: ButtonStyle { init(alignment: TextViewAlignment = .center) { self.align = alignment } var align: TextViewAlignment func makeBody(configuration: Configuration) -> some View { HStack { if align == .center || align == .trailing{ Spacer() } configuration.label .font(/*@START_MENU_TOKEN@*/.body/*@END_MENU_TOKEN@*/) .padding(.vertical, 11.0) .padding(.horizontal) if align == .center || align == .leading{ Spacer() } } .background( GeometryReader { geometry in ZStack{ RoundedRectangle(cornerRadius: 7, style: .continuous) .fill(configuration.isPressed ? Color.gray.opacity(0.1): Color.gray.opacity(0.2)) } }) } } #endif
28.527331
206
0.560866
5d14633c5c3919f230d5e75989ec8da5b95cd99b
297
/* See LICENSE folder for this sample’s licensing information. Abstract: A utility type that generates sloths. */ /// A type that generates sloths. public protocol SlothGenerator { /// Generates a sloth in the specified habitat. func generateSloth(in habitat: Habitat) throws -> Sloth }
22.846154
59
0.744108
f53146bbf043fa5b35fbde4101b96509eeed9dc5
1,436
// // ChangeCityViewController.swift // WeatherApp // // Created by Angela Yu on 23/08/2015. // Copyright (c) 2015 London App Brewery. All rights reserved. // import UIKit //Write the protocol declaration here: protocol ChangeCityDelegate { func userEnteredANewCityName(city: String) } class ChangeCityViewController: UIViewController { //Declare the delegate variable here: var delegate : ChangeCityDelegate? //This is the pre-linked IBOutlets to the text field: @IBOutlet weak var changeCityTextField: UITextField! //This is the IBAction that gets called when the user taps on the "Get Weather" button: @IBAction func getWeatherPressed(_ sender: AnyObject) { //1 Get the city name the user entered in the text field let cityName = changeCityTextField.text! //2 If we have a delegate set, call the method userEnteredANewCityName delegate?.userEnteredANewCityName(city: cityName) //3 dismiss the Change City View Controller to go back to the WeatherViewController self.dismiss(animated: true, completion: nil) } //This is the IBAction that gets called when the user taps the back button. It dismisses the ChangeCityViewController. @IBAction func backButtonPressed(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } }
27.09434
122
0.682451
617ab446ce6dc30c512301ff968269f17eafaab4
531
// // Node.swift // AmaranthineQueue // // Created by Instructor Amaranthine on 02/09/21. // import Foundation /** Node<Element> class represents a single node. *Parameters* __________ `data` Represents the data stored in the Node. `nextNode` Represents the next node in the queue. - Author: Arun Patwardhan - Version: 1.0 */ final class Node<Element> { var data : Element? var nextNode : Node<Element>? init(with newData : Element) { data = newData } }
17.129032
56
0.621469
2651e2d040d49db4cdd4730958405fc07b2929c7
259
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func a { case c, [k<D> Void>() { class c : C { struct B<h : C { var e: A? { class case c,
18.5
87
0.687259
7a9e1f73c776a8279fcd47ceea9a18e99e4cbe43
1,998
// // Modified MIT License // // Copyright (c) 2010-2018 Kite Tech Ltd. https://www.kite.ly // // 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 software MAY ONLY be used with the Kite Tech Ltd platform and MAY NOT be modified // to be used with any competitor platforms. This means the software MAY NOT be modified // to place orders with any competitors to Kite Tech Ltd, all orders MUST go through the // Kite Tech Ltd platform servers. // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class DeliveryAddressTableViewCell: UITableViewCell { static let reuseIdentifier = NSStringFromClass(DeliveryAddressTableViewCell.self).components(separatedBy: ".").last! @IBOutlet weak var topSeparator: UIView! @IBOutlet private weak var separator: UIView! @IBOutlet weak var topLabel: UILabel! { didSet { topLabel.scaleFont() } } @IBOutlet weak var bottomLabel: UILabel! { didSet { bottomLabel.scaleFont() } } @IBOutlet weak var checkmark: UIImageView! }
47.571429
120
0.748248
72f960b33955cba7d9cacca13391f879c3632907
3,280
// // The MIT License (MIT) // // Copyright (c) 2015-present Badoo Trading Limited. // // 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 HyperLabel final class LabelExample { let title: String let factory: () -> UIView init(title: String, factory: @escaping () -> UIView) { self.title = title self.factory = factory } } extension Array where Element == LabelExample { static func makeExamples() -> [LabelExample] { return [ LabelExample(title: "Exact touchable area") { HLHyperLabel.makeDemoLabel(extendLinkTouchArea: false) }, LabelExample(title: "Extended touchable area") { HLHyperLabel.makeDemoLabel(extendLinkTouchArea: true) }, ] } } // MARK: - HyperLabel example private extension HLHyperLabel { static func makeDemoLabel(extendLinkTouchArea: Bool) -> HLHyperLabel { let label = HLHyperLabel() label.numberOfLines = 0 label.extendsLinkTouchArea = extendLinkTouchArea label.additionalLinkAttributes = [ NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue ] let text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." label.text = text let nsString = text as NSString let firstLinkRange = nsString.range(of: "consectetur adipiscing elit") label.addLink(withRange: firstLinkRange, accessibilityIdentifier: "first-link") { print("first link pressed") } let secondLinkRange = nsString.range(of: "minim veniam") label.addLink(withRange: secondLinkRange, accessibilityIdentifier: "second-link") { print("second link pressed") } return label } }
42.051282
466
0.704878
5d79735a6764ac71315297b102da7f8975e364b8
2,077
// // AddressScreenDelegate.swift // Karhoo // // // Copyright © 2020 Karhoo All rights reserved. // import UIKit class TableDelegate<T>: NSObject, UITableViewDelegate { typealias SelectionCallback = (T) -> Void typealias ReachedBottomCallback = (Bool) -> Void private let estimatedFooterHeight: CGFloat = 50 private let tableData: TableData<T> private var selectionCallback: SelectionCallback? private var bottomCallback: ReachedBottomCallback? private var footerView: UIView? private var paginationEnabled: Bool init(tableData: TableData<T> = TableData<T>(), paginationEnabled: Bool = false) { self.paginationEnabled = paginationEnabled self.tableData = tableData } func setSection(key: String, to items: [T]) { tableData.setSection(key: key, to: items) } func set(selectionCallback: SelectionCallback?) { self.selectionCallback = selectionCallback } func set(reachedBottom: ReachedBottomCallback?) { self.bottomCallback = reachedBottom } func set(footerView: UIView) { self.footerView = footerView } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let item = tableData.getItem(indexPath: indexPath) else { return } selectionCallback?(item) } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return footerView } func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat { guard footerView != nil else { return 0 } return estimatedFooterHeight } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if paginationEnabled { if tableView.numberOfRows(inSection: 0) - indexPath.row == 1 { bottomCallback?(true) } } } }
28.452055
112
0.662494
f567d7345629d3a9d83fc527d99be5302e0dbcf6
593
// // EpisodeCell.swift // GameOfThrones // // Created by Maitree Bain on 11/19/19. // Copyright © 2019 Pursuit. All rights reserved. // import UIKit class EpisodeCell: UITableViewCell { @IBOutlet weak var episodeImageView: UIImageView! @IBOutlet weak var episodeNameLabel: UILabel! @IBOutlet weak var seasonEpLabel: UILabel! func configueCell(for episode: GOTEpisode) { episodeImageView.image = UIImage(named: episode.mediumImageID) episodeNameLabel.text = episode.name seasonEpLabel.text = episode.season.description } }
23.72
70
0.694772
6a7bbc5e7806f51f329d380251ab09959bf42357
5,875
//// // 🦠 Corona-Warn-App // import UIKit import OpenCombine class DiaryOverviewTableViewController: UITableViewController { // MARK: - Init init( viewModel: DiaryOverviewViewModel, onCellSelection: @escaping (DiaryDay) -> Void, onInfoButtonTap: @escaping () -> Void, onExportButtonTap: @escaping () -> Void, onEditContactPersonsButtonTap: @escaping () -> Void, onEditLocationsButtonTap: @escaping () -> Void ) { self.viewModel = viewModel self.onCellSelection = onCellSelection self.onInfoButtonTap = onInfoButtonTap self.onExportButtonTap = onExportButtonTap self.onEditContactPersonsButtonTap = onEditContactPersonsButtonTap self.onEditLocationsButtonTap = onEditLocationsButtonTap super.init(style: .plain) self.viewModel.refreshTableView = { [weak self] in self?.tableView.reloadData() } } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Overrides override func viewDidLoad() { super.viewDidLoad() setupTableView() navigationItem.largeTitleDisplayMode = .always navigationItem.title = AppStrings.ContactDiary.Overview.title view.backgroundColor = .enaColor(for: .darkBackground) let moreImage = UIImage(named: "Icons_More_Circle") let rightBarButton = UIBarButtonItem(image: moreImage, style: .plain, target: self, action: #selector(onMore)) rightBarButton.accessibilityLabel = AppStrings.ContactDiary.Overview.menuButtonTitle rightBarButton.tintColor = .enaColor(for: .tint) self.navigationItem.setRightBarButton(rightBarButton, animated: false) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // navigationbar is a shared property - so we need to trigger a resizing because others could have set it to false navigationController?.navigationBar.prefersLargeTitles = true navigationController?.navigationBar.sizeToFit() } // MARK: - Protocol UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return viewModel.numberOfSections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { viewModel.numberOfRows(in: section) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch DiaryOverviewViewModel.Section(rawValue: indexPath.section) { case .description: return descriptionCell(forRowAt: indexPath) case .days: return dayCell(forRowAt: indexPath) default: fatalError("Invalid section") } } // MARK: - Protocol UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard indexPath.section == 1 else { return } onCellSelection(viewModel.day(by: indexPath)) } // MARK: - Private private let viewModel: DiaryOverviewViewModel private let onCellSelection: (DiaryDay) -> Void private let onInfoButtonTap: () -> Void private let onExportButtonTap: () -> Void private let onEditContactPersonsButtonTap: () -> Void private let onEditLocationsButtonTap: () -> Void private var subscriptions = [AnyCancellable]() private func setupTableView() { tableView.register( UINib(nibName: String(describing: DiaryOverviewDescriptionTableViewCell.self), bundle: nil), forCellReuseIdentifier: String(describing: DiaryOverviewDescriptionTableViewCell.self) ) tableView.register( UINib(nibName: String(describing: DiaryOverviewDayTableViewCell.self), bundle: nil), forCellReuseIdentifier: String(describing: DiaryOverviewDayTableViewCell.self) ) tableView.separatorStyle = .none tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 60 tableView.accessibilityIdentifier = AccessibilityIdentifiers.ContactDiaryInformation.Overview.tableView } private func descriptionCell(forRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: DiaryOverviewDescriptionTableViewCell.self), for: indexPath) as? DiaryOverviewDescriptionTableViewCell else { fatalError("Could not dequeue DiaryOverviewDescriptionTableViewCell") } return cell } private func dayCell(forRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: DiaryOverviewDayTableViewCell.self), for: indexPath) as? DiaryOverviewDayTableViewCell else { fatalError("Could not dequeue DiaryOverviewDayTableViewCell") } cell.configure(cellViewModel: viewModel.cellModel(for: indexPath)) return cell } @objc private func onMore() { let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let infoAction = UIAlertAction(title: AppStrings.ContactDiary.Overview.ActionSheet.infoActionTitle, style: .default, handler: { [weak self] _ in self?.onInfoButtonTap() }) actionSheet.addAction(infoAction) let exportAction = UIAlertAction(title: AppStrings.ContactDiary.Overview.ActionSheet.exportActionTitle, style: .default, handler: { [weak self] _ in self?.onExportButtonTap() }) actionSheet.addAction(exportAction) let editPerson = UIAlertAction(title: AppStrings.ContactDiary.Overview.ActionSheet.editPersonTitle, style: .default, handler: { [weak self] _ in self?.onEditContactPersonsButtonTap() }) actionSheet.addAction(editPerson) let editLocation = UIAlertAction(title: AppStrings.ContactDiary.Overview.ActionSheet.editLocationTitle, style: .default, handler: { [weak self] _ in self?.onEditLocationsButtonTap() }) actionSheet.addAction(editLocation) let cancelAction = UIAlertAction(title: AppStrings.Common.alertActionCancel, style: .cancel, handler: nil) actionSheet.addAction(cancelAction) present(actionSheet, animated: true, completion: nil) } }
34.356725
193
0.77617
fcd217a0c09210dd4d53076377e03a33dd748a14
2,201
// // UIView+Swifty.swift // Swifty // // Created by 王荣庆 on 2019/9/14. // Copyright © 2019 RyukieSama. All rights reserved. // import UIKit extension UIView: SwiftyCompatible {} public extension Swifty where Base: UIView { var x: CGFloat { return base.frame.origin.x } var y: CGFloat { return base.frame.origin.y } var width: CGFloat { return base.frame.size.width } var height: CGFloat { return base.frame.size.height } func setX(x: CGFloat) { base.frame = CGRect(x: x, y: base.frame.origin.y, width: base.frame.size.width, height: base.frame.size.height) } func setY(y: CGFloat) { base.frame = CGRect(x: base.frame.origin.x, y: y, width: base.frame.size.width, height: base.frame.size.height) } func setWidth(width: CGFloat) { base.frame = CGRect(x: base.frame.origin.x, y: base.frame.origin.y, width: width, height: base.frame.size.height) } func setHeight(height: CGFloat) { base.frame = CGRect(x: base.frame.origin.x, y: base.frame.origin.y, width: base.frame.size.width, height: height) } } public extension UIView { func shake() { let animation = CAKeyframeAnimation() animation.keyPath = "transform.rotation.z" animation.values = [(-2.0 / 180 * M_PI), (2.0 / 180 * M_PI), (-2.0 / 180 * M_PI)] animation.duration = 0.5 animation.repeatCount = MAXFLOAT animation.isRemovedOnCompletion = false animation.fillMode = .forwards layer.add(animation, forKey: "swifty_shake") } } public extension UIView { public class func initFromNib<T>() -> T? { let nibName = "\(T.self)" return Bundle.main.loadNibNamed(nibName, owner: nil, options: nil)?.first as? T /// 不用last 如果用last添加手势的话会拿到手势 } } @available(iOSApplicationExtension, unavailable) public extension UIDevice { @objc public func isiPhoneXMore() -> Bool { var isMore:Bool = false if #available(iOS 11.0, *) { isMore = UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0.0 > CGFloat(0.0) } return isMore } }
27.860759
121
0.617447
e2ffaae5156722055f787e70d3390e4dd6de177c
5,926
// Copyright 2019 Algorand, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // LedgerDeviceListView.swift import UIKit class LedgerDeviceListView: BaseView { private let layout = Layout<LayoutConstants>() weak var delegate: LedgerDeviceListViewDelegate? private(set) lazy var devicesCollectionView: UICollectionView = { let flowLayout = UICollectionViewFlowLayout() flowLayout.scrollDirection = .vertical flowLayout.minimumLineSpacing = 4.0 let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout) collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.bounces = false collectionView.isScrollEnabled = false collectionView.backgroundColor = Colors.Background.primary collectionView.contentInset = layout.current.listContentInset collectionView.register(LedgerDeviceCell.self, forCellWithReuseIdentifier: LedgerDeviceCell.reusableIdentifier) return collectionView }() private lazy var searchingDevicesLabel: UILabel = { UILabel() .withFont(UIFont.font(withWeight: .regular(size: 14.0))) .withTextColor(Colors.Text.primary) .withLine(.single) .withAlignment(.left) .withText("ledger-device-list-looking".localized) }() private lazy var searchingSpinnerView = LoadingSpinnerView() private lazy var troubleshootButton: AlignedButton = { let button = AlignedButton(.imageAtLeft(spacing: 8.0)) button.setImage(img("img-question-24"), for: .normal) button.setTitle("ledger-device-list-troubleshoot".localized, for: .normal) button.setTitleColor(Colors.Main.white, for: .normal) button.titleLabel?.font = UIFont.font(withWeight: .semiBold(size: 16.0)) button.setBackgroundImage(img("bg-gray-600-button"), for: .normal) button.titleLabel?.textAlignment = .center return button }() override func setListeners() { troubleshootButton.addTarget(self, action: #selector(notifyDelegateToOpenTrobuleshooting), for: .touchUpInside) } override func prepareLayout() { setupTroubleshootButtonLayout() setupDevicesCollectionViewLayout() setupSearchingDevicesLabelLayout() setupSearchingSpinnerViewLayout() } } extension LedgerDeviceListView { @objc func notifyDelegateToOpenTrobuleshooting() { delegate?.ledgerDeviceListViewDidTapTroubleshootButton(self) } } extension LedgerDeviceListView { private func setupTroubleshootButtonLayout() { addSubview(troubleshootButton) troubleshootButton.snp.makeConstraints { make in make.centerX.equalToSuperview() make.leading.trailing.equalToSuperview().inset(layout.current.horizontalInset) make.bottom.equalToSuperview().inset(layout.current.buttonBottomInset) } } private func setupDevicesCollectionViewLayout() { addSubview(devicesCollectionView) devicesCollectionView.snp.makeConstraints { make in make.leading.trailing.equalToSuperview() make.top.equalToSuperview() make.height.equalTo(layout.current.collectionViewHeight) } } private func setupSearchingDevicesLabelLayout() { addSubview(searchingDevicesLabel) searchingDevicesLabel.snp.makeConstraints { make in make.top.equalTo(devicesCollectionView.snp.bottom).offset(layout.current.devicesLabelTopOffset) make.leading.equalToSuperview().inset(layout.current.horizontalInset) } } private func setupSearchingSpinnerViewLayout() { addSubview(searchingSpinnerView) searchingSpinnerView.snp.makeConstraints { make in make.centerY.equalTo(searchingDevicesLabel) make.leading.equalTo(searchingDevicesLabel.snp.trailing).offset(layout.current.spinnerLeadingInset) make.size.equalTo(layout.current.spinnerSize) } } } extension LedgerDeviceListView { func startSearchSpinner() { searchingSpinnerView.show() } func stopSearchSpinner() { searchingSpinnerView.stop() } func setSearchSpinner(visible isVisible: Bool) { searchingDevicesLabel.isHidden = !isVisible searchingSpinnerView.isHidden = !isVisible } func invalidateContentSize(by size: Int) { devicesCollectionView.snp.updateConstraints { make in make.height.equalTo(size * layout.current.deviceItemTotalSize) } } } extension LedgerDeviceListView { private struct LayoutConstants: AdaptiveLayoutConstants { let deviceItemTotalSize = 64 let buttonBottomInset: CGFloat = 60.0 let listContentInset = UIEdgeInsets(top: 10.0, left: 0.0, bottom: 0.0, right: 0.0) let horizontalInset: CGFloat = 20.0 let spinnerLeadingInset: CGFloat = 13.0 let devicesLabelTopOffset: CGFloat = 12.0 let collectionViewHeight: CGFloat = 0.0 let spinnerSize = CGSize(width: 17.5, height: 17.5) } } protocol LedgerDeviceListViewDelegate: AnyObject { func ledgerDeviceListViewDidTapTroubleshootButton(_ ledgerDeviceListView: LedgerDeviceListView) }
37.0375
119
0.700304
9c8719efc9b642b8b4965a814e48fb761ce5200c
6,181
// // Oep4TxBuilder.swift // OntSwift // // Created by hsiaosiyuan on 2018/12/8. // Copyright © 2018 hsiaosiyuan. All rights reserved. // import Foundation public class Oep4TxBuilder { public let contract: Address public init(contract: Address) { self.contract = contract } public func makeInitTx(gasPrice: String, gasLimit: String, payer: Address? = nil) throws -> Transaction { let b = TransactionBuilder() let fn = Oep4TxBuilder.Method.Init.rawValue return try b.makeInvokeTransaction( fnName: fn, params: [], contract: contract, gasPrice: gasPrice, gasLimit: gasLimit, payer: payer ) } public func makeTransferTx( from: Address, to: Address, amount: BigInt, gasPrice: String, gasLimit: String, payer: Address ) throws -> Transaction { let b = TransactionBuilder() let fn = Oep4TxBuilder.Method.transfer.rawValue let v1 = Data.from(hex: from.serialize())! let v2 = Data.from(hex: to.serialize())! let v3 = amount let p1 = AbiParameter(name: "from", type: .byteArray, value: AbiParameter.Value.bytes(v1)) let p2 = AbiParameter(name: "to", type: .byteArray, value: AbiParameter.Value.bytes(v2)) let p3 = AbiParameter(name: "value", type: .long, value: AbiParameter.Value.long(v3)) return try b.makeInvokeTransaction( fnName: fn, params: [p1, p2, p3], contract: contract, gasPrice: gasPrice, gasLimit: gasLimit, payer: payer ) } public func makeTransferMultiTx( states: [OepState], gasPrice: String, gasLimit: String, payer: Address ) throws -> Transaction { let fn = Oep4TxBuilder.Method.transferMulti.rawValue var list: [Any] = [fn.data(using: .utf8)!] var args: [Any] = [] states.forEach { args.append([$0.from, $0.to, $0.amount]) } list.append(args) let pb = NativeVmParamsBuilder() let params = try pb.pushCodeParams(objs: list).buf let txb = TransactionBuilder() return try txb.makeInvokeTransaction( params: params, contract: contract, gasPrice: gasPrice, gasLimit: gasLimit, payer: payer ) } public func makeApproveTx( owner: Address, spender: Address, amount: BigInt, gasPrice: String, gasLimit: String, payer: Address ) throws -> Transaction { let fn = Oep4TxBuilder.Method.approve.rawValue let v1 = Data.from(hex: owner.serialize())! let v2 = Data.from(hex: spender.serialize())! let v3 = amount let p1 = AbiParameter(name: "owner", type: .byteArray, value: AbiParameter.Value.bytes(v1)) let p2 = AbiParameter(name: "spender", type: .byteArray, value: AbiParameter.Value.bytes(v2)) let p3 = AbiParameter(name: "amount", type: .long, value: AbiParameter.Value.long(v3)) let b = TransactionBuilder() return try b.makeInvokeTransaction( fnName: fn, params: [p1, p2, p3], contract: contract, gasPrice: gasPrice, gasLimit: gasLimit, payer: payer ) } public func makeTransferFromTx( spender: Address, from: Address, to: Address, amount: BigInt, gasPrice: String, gasLimit: String, payer: Address ) throws -> Transaction { let fn = Oep4TxBuilder.Method.transferFrom.rawValue let v1 = Data.from(hex: spender.serialize())! let v2 = Data.from(hex: from.serialize())! let v3 = Data.from(hex: to.serialize())! let v4 = amount let b = TransactionBuilder() let params: [AbiParameter] = [ AbiParameter(name: "spender", type: .byteArray, value: AbiParameter.Value.bytes(v1)), AbiParameter(name: "from", type: .byteArray, value: AbiParameter.Value.bytes(v2)), AbiParameter(name: "to", type: .byteArray, value: AbiParameter.Value.bytes(v3)), AbiParameter(name: "amount", type: .long, value: AbiParameter.Value.long(v4)), ] return try b.makeInvokeTransaction( fnName: fn, params: params, contract: contract, gasPrice: gasPrice, gasLimit: gasLimit, payer: payer ) } public func makeQueryAllowanceTx(owner: Address, spender: Address) throws -> Transaction { let fn = Oep4TxBuilder.Method.allowance.rawValue let v1 = Data.from(hex: owner.serialize())! let v2 = Data.from(hex: spender.serialize())! let params: [AbiParameter] = [ AbiParameter(name: "owner", type: .byteArray, value: AbiParameter.Value.bytes(v1)), AbiParameter(name: "spender", type: .byteArray, value: AbiParameter.Value.bytes(v2)), ] let b = TransactionBuilder() return try b.makeInvokeTransaction(fnName: fn, params: params, contract: contract) } public func makeQueryBalanceOfTx(addr: Address) throws -> Transaction { let fn = Oep4TxBuilder.Method.balanceOf.rawValue let v = Data.from(hex: addr.serialize())! let p = AbiParameter(name: "from", type: .byteArray, value: AbiParameter.Value.bytes(v)) let b = TransactionBuilder() return try b.makeInvokeTransaction(fnName: fn, params: [p], contract: contract) } public func makeQueryTotalSupplyTx() throws -> Transaction { let fn = Oep4TxBuilder.Method.totalSupply.rawValue let b = TransactionBuilder() return try b.makeInvokeTransaction(fnName: fn, params: [], contract: contract) } public func makeQueryDecimalsTx() throws -> Transaction { let fn = Oep4TxBuilder.Method.decimals.rawValue let b = TransactionBuilder() return try b.makeInvokeTransaction(fnName: fn, params: [], contract: contract) } public func makeQuerySymbolTx() throws -> Transaction { let fn = Oep4TxBuilder.Method.symbol.rawValue let b = TransactionBuilder() return try b.makeInvokeTransaction(fnName: fn, params: [], contract: contract) } public func makeQueryNameTx() throws -> Transaction { let fn = Oep4TxBuilder.Method.name.rawValue let b = TransactionBuilder() return try b.makeInvokeTransaction(fnName: fn, params: [], contract: contract) } public enum Method: String { case Init = "init" case transfer, transferMulti, approve case transferFrom, allowance, balanceOf case totalSupply, symbol, decimals, name } }
32.531579
107
0.669956
d66b97865787b22381491e11b5e2b76b51dbb630
741
import XCTest @testable import FXSwifter final class FXSwifterTakeWhileTests: XCTestCase { let arr: Array<Int> = [1, 2, 3] func testLess() { var takeArr = arr.takeWhile(closure: { $0 > 3 }) XCTAssert(takeArr.next() == nil) } func testEquatal() { var takeArr = arr.takeWhile(closure: { $0 <= 3 }) XCTAssert(takeArr.next() == 1) XCTAssert(takeArr.next() == 2) XCTAssert(takeArr.next() == 3) XCTAssert(takeArr.next() == nil) } func testMore() { var takeArr = arr.takeWhile(closure: { $0 <= 2 }) XCTAssert(takeArr.next() == 1) XCTAssert(takeArr.next() == 2) XCTAssert(takeArr.next() == nil) } }
25.551724
57
0.541161
f80301ac1bcda2b3b841524da64e62f8677e3211
117,190
import CoreFoundation import Foundation import OrderedCollections /// A marker protocol used to determine whether a value is a `String`-keyed `OrderedDictionary` /// containing `Encodable` values (in which case it should be exempt from key conversion strategies). /// fileprivate protocol _MapStringDictionaryEncodableMarker { } extension OrderedDictionary : _MapStringDictionaryEncodableMarker where Key == String, Value: Encodable { } /// A marker protocol used to determine whether a value is a `String`-keyed `OrderedDictionary` /// containing `Decodable` values (in which case it should be exempt from key conversion strategies). /// /// The marker protocol also provides access to the type of the `Decodable` values, /// which is needed for the implementation of the key conversion strategy exemption. /// fileprivate protocol _MapStringDictionaryDecodableMarker { static var elementType: Decodable.Type { get } } extension OrderedDictionary : _MapStringDictionaryDecodableMarker where Key == String, Value: Decodable { static var elementType: Decodable.Type { return Value.self } } //===----------------------------------------------------------------------===// // Map Encoder //===----------------------------------------------------------------------===// /// `MapEncoder` facilitates the encoding of `Encodable` values into Map. open class MapEncoder { // MARK: Options /// The formatting of the output Map data. public struct OutputFormatting : OptionSet { /// The format's default value. public let rawValue: UInt /// Creates an OutputFormatting value with the given raw value. public init(rawValue: UInt) { self.rawValue = rawValue } /// Produce human-readable Map with indented output. public static let prettyPrinted = OutputFormatting(rawValue: 1 << 0) /// Produce Map with dictionary keys sorted in lexicographic order. @available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) public static let sortedKeys = OutputFormatting(rawValue: 1 << 1) } /// The strategy to use for encoding `Date` values. public enum DateEncodingStrategy { /// Defer to `Date` for choosing an encoding. This is the default strategy. case deferredToDate /// Encode the `Date` as a UNIX timestamp (as a Map number). case secondsSince1970 /// Encode the `Date` as UNIX millisecond timestamp (as a Map number). case millisecondsSince1970 /// Encode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Encode the `Date` as a string formatted by the given formatter. case formatted(DateFormatter) /// Encode the `Date` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Date, Encoder) throws -> Void) } /// The strategy to use for encoding `Data` values. public enum DataEncodingStrategy { /// Defer to `Data` for choosing an encoding. case deferredToData /// Encoded the `Data` as a Base64-encoded string. This is the default strategy. case base64 /// Encode the `Data` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Data, Encoder) throws -> Void) } /// The strategy to use for non-Map-conforming floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloatEncodingStrategy { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Encode the values using the given representation strings. case convertToString(positiveInfinity: String, negativeInfinity: String, nan: String) } /// The strategy to use for automatically changing the value of keys before encoding. public enum KeyEncodingStrategy { /// Use the keys specified by each type. This is the default strategy. case useDefaultKeys /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key to Map payload. /// /// Capital characters are determined by testing membership in `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` (Unicode General Categories Lu and Lt). /// The conversion to lower case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences. /// /// Converting from camel case to snake case: /// 1. Splits words at the boundary of lower-case to upper-case /// 2. Inserts `_` between words /// 3. Lowercases the entire string /// 4. Preserves starting and ending `_`. /// /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`. /// /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. case convertToSnakeCase /// Provide a custom conversion to the key in the encoded Map from the keys specified by the encoded types. /// The full path to the current encoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before encoding. /// If the result of the conversion is a duplicate key, then only one value will be present in the result. case custom((_ codingPath: [CodingKey]) -> CodingKey) fileprivate static func _convertToSnakeCase(_ stringKey: String) -> String { guard !stringKey.isEmpty else { return stringKey } var words : [Range<String.Index>] = [] // The general idea of this algorithm is to split words on transition from lower to upper case, then on transition of >1 upper case characters to lowercase // // myProperty -> my_property // myURLProperty -> my_url_property // // We assume, per Swift naming conventions, that the first character of the key is lowercase. var wordStart = stringKey.startIndex var searchRange = stringKey.index(after: wordStart)..<stringKey.endIndex // Find next uppercase character while let upperCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.uppercaseLetters, options: [], range: searchRange) { let untilUpperCase = wordStart..<upperCaseRange.lowerBound words.append(untilUpperCase) // Find next lowercase character searchRange = upperCaseRange.lowerBound..<searchRange.upperBound guard let lowerCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.lowercaseLetters, options: [], range: searchRange) else { // There are no more lower case letters. Just end here. wordStart = searchRange.lowerBound break } // Is the next lowercase letter more than 1 after the uppercase? If so, we encountered a group of uppercase letters that we should treat as its own word let nextCharacterAfterCapital = stringKey.index(after: upperCaseRange.lowerBound) if lowerCaseRange.lowerBound == nextCharacterAfterCapital { // The next character after capital is a lower case character and therefore not a word boundary. // Continue searching for the next upper case for the boundary. wordStart = upperCaseRange.lowerBound } else { // There was a range of >1 capital letters. Turn those into a word, stopping at the capital before the lower case character. let beforeLowerIndex = stringKey.index(before: lowerCaseRange.lowerBound) words.append(upperCaseRange.lowerBound..<beforeLowerIndex) // Next word starts at the capital before the lowercase we just found wordStart = beforeLowerIndex } searchRange = lowerCaseRange.upperBound..<searchRange.upperBound } words.append(wordStart..<searchRange.upperBound) let result = words.map({ (range) in return stringKey[range].lowercased() }).joined(separator: "_") return result } } /// The output format to produce. Defaults to `[]`. open var outputFormatting: OutputFormatting = [] /// The strategy to use in encoding dates. Defaults to `.deferredToDate`. open var dateEncodingStrategy: DateEncodingStrategy = .deferredToDate /// The strategy to use in encoding binary data. Defaults to `.base64`. open var dataEncodingStrategy: DataEncodingStrategy = .base64 /// The strategy to use in encoding non-conforming numbers. Defaults to `.throw`. open var nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy = .throw /// The strategy to use for encoding keys. Defaults to `.useDefaultKeys`. open var keyEncodingStrategy: KeyEncodingStrategy = .useDefaultKeys /// Contextual user-provided information for use during encoding. open var userInfo: [CodingUserInfoKey : Any] = [:] /// Options set on the top-level encoder to pass down the encoding hierarchy. fileprivate struct _Options { let dateEncodingStrategy: DateEncodingStrategy let dataEncodingStrategy: DataEncodingStrategy let nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy let keyEncodingStrategy: KeyEncodingStrategy let userInfo: [CodingUserInfoKey : Any] } /// The options set on the top-level encoder. fileprivate var options: _Options { return _Options(dateEncodingStrategy: dateEncodingStrategy, dataEncodingStrategy: dataEncodingStrategy, nonConformingFloatEncodingStrategy: nonConformingFloatEncodingStrategy, keyEncodingStrategy: keyEncodingStrategy, userInfo: userInfo) } // MARK: - Constructing a Map Encoder /// Initializes `self` with default strategies. public init() {} // MARK: - Encoding Values /// Encodes the given top-level value and returns its Map representation. /// /// - parameter value: The value to encode. /// - returns: A new `Data` value containing the encoded Map data. /// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`. /// - throws: An error if any value throws an error during encoding. open func encode<T : Encodable>(_ value: T) throws -> Map { let encoder = _MapEncoder(options: self.options) guard let topLevel = try encoder.box_(value) else { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) did not encode any values.")) } return try MapSerialization.map(with: topLevel) } } // MARK: - _MapEncoder fileprivate class _MapEncoder : Encoder { // MARK: Properties /// The encoder's storage. fileprivate var storage: _MapEncodingStorage /// Options set on the top-level encoder. fileprivate let options: MapEncoder._Options /// The path to the current point in encoding. public var codingPath: [CodingKey] /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level encoder options. fileprivate init(options: MapEncoder._Options, codingPath: [CodingKey] = []) { self.options = options self.storage = _MapEncodingStorage() self.codingPath = codingPath } /// Returns whether a new element can be encoded at this coding path. /// /// `true` if an element has not yet been encoded at this coding path; `false` otherwise. fileprivate var canEncodeNewValue: Bool { // Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container). // At the same time, every time a container is requested, a new value gets pushed onto the storage stack. // If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition. // // This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path. // Things which will not request containers do not need to have the coding path extended for them (but it doesn't matter if it is, because they will not reach here). return self.storage.count == self.codingPath.count } // MARK: - Encoder Methods public func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> { // If an existing keyed container was already requested, return that one. let topContainer: NSMutableDictionary if self.canEncodeNewValue { // We haven't yet pushed a container at this level; do so here. topContainer = self.storage.pushKeyedContainer() } else { guard let container = self.storage.containers.last as? NSMutableDictionary else { preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.") } topContainer = container } let container = _MapKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer) return KeyedEncodingContainer(container) } public func unkeyedContainer() -> UnkeyedEncodingContainer { // If an existing unkeyed container was already requested, return that one. let topContainer: NSMutableArray if self.canEncodeNewValue { // We haven't yet pushed a container at this level; do so here. topContainer = self.storage.pushUnkeyedContainer() } else { guard let container = self.storage.containers.last as? NSMutableArray else { preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.") } topContainer = container } return _MapUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer) } public func singleValueContainer() -> SingleValueEncodingContainer { return self } } // MARK: - Encoding Storage and Containers fileprivate struct _MapEncodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the Map types (NSNull, NSNumber, NSString, NSArray, NSDictionary). private(set) fileprivate var containers: [NSObject] = [] // MARK: - Initialization /// Initializes `self` with no containers. fileprivate init() {} // MARK: - Modifying the Stack fileprivate var count: Int { return self.containers.count } fileprivate mutating func pushKeyedContainer() -> NSMutableDictionary { let dictionary = NSMutableDictionary() self.containers.append(dictionary) return dictionary } fileprivate mutating func pushUnkeyedContainer() -> NSMutableArray { let array = NSMutableArray() self.containers.append(array) return array } fileprivate mutating func push(container: NSObject) { self.containers.append(container) } fileprivate mutating func popContainer() -> NSObject { precondition(!self.containers.isEmpty, "Empty container stack.") return self.containers.popLast()! } } // MARK: - Encoding Containers fileprivate struct _MapKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the encoder we're writing to. private let encoder: _MapEncoder /// A reference to the container we're writing to. private let container: NSMutableDictionary /// The path of coding keys taken to get to this point in encoding. private(set) public var codingPath: [CodingKey] // MARK: - Initialization /// Initializes `self` with the given references. fileprivate init(referencing encoder: _MapEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - Coding Path Operations private func _converted(_ key: CodingKey) -> CodingKey { switch encoder.options.keyEncodingStrategy { case .useDefaultKeys: return key case .convertToSnakeCase: let newKeyString = MapEncoder.KeyEncodingStrategy._convertToSnakeCase(key.stringValue) return _MapKey(stringValue: newKeyString, intValue: key.intValue) case .custom(let converter): return converter(codingPath + [key]) } } // MARK: - KeyedEncodingContainerProtocol Methods public mutating func encodeNil(forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = NSNull() } public mutating func encode(_ value: Bool, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Int, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Int8, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Int16, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Int32, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Int64, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: UInt, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: UInt8, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: UInt16, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: UInt32, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: UInt64, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: String, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Float, forKey key: Key) throws { // Since the float may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } #if DEPLOYMENT_RUNTIME_SWIFT self.container[_converted(key).stringValue._bridgeToObjectiveC()] = try self.encoder.box(value) #else self.container[_converted(key).stringValue] = try self.encoder.box(value) #endif } public mutating func encode(_ value: Double, forKey key: Key) throws { // Since the double may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } #if DEPLOYMENT_RUNTIME_SWIFT self.container[_converted(key).stringValue._bridgeToObjectiveC()] = try self.encoder.box(value) #else self.container[_converted(key).stringValue] = try self.encoder.box(value) #endif } public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws { self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } #if DEPLOYMENT_RUNTIME_SWIFT self.container[_converted(key).stringValue._bridgeToObjectiveC()] = try self.encoder.box(value) #else self.container[_converted(key).stringValue] = try self.encoder.box(value) #endif } public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { let dictionary = NSMutableDictionary() #if DEPLOYMENT_RUNTIME_SWIFT self.container[_converted(key).stringValue._bridgeToObjectiveC()] = dictionary #else self.container[_converted(key).stringValue] = dictionary #endif self.codingPath.append(key) defer { self.codingPath.removeLast() } let container = _MapKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { let array = NSMutableArray() #if DEPLOYMENT_RUNTIME_SWIFT self.container[_converted(key).stringValue._bridgeToObjectiveC()] = array #else self.container[_converted(key).stringValue] = array #endif self.codingPath.append(key) defer { self.codingPath.removeLast() } return _MapUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array) } public mutating func superEncoder() -> Encoder { return _MapReferencingEncoder(referencing: self.encoder, at: _MapKey.super, wrapping: self.container) } public mutating func superEncoder(forKey key: Key) -> Encoder { return _MapReferencingEncoder(referencing: self.encoder, at: key, wrapping: self.container) } } fileprivate struct _MapUnkeyedEncodingContainer : UnkeyedEncodingContainer { // MARK: Properties /// A reference to the encoder we're writing to. private let encoder: _MapEncoder /// A reference to the container we're writing to. private let container: NSMutableArray /// The path of coding keys taken to get to this point in encoding. private(set) public var codingPath: [CodingKey] /// The number of elements encoded into the container. public var count: Int { return self.container.count } // MARK: - Initialization /// Initializes `self` with the given references. fileprivate init(referencing encoder: _MapEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - UnkeyedEncodingContainer Methods public mutating func encodeNil() throws { self.container.add(NSNull()) } public mutating func encode(_ value: Bool) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int8) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int16) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int32) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int64) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt8) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt16) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt32) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt64) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: String) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Float) throws { // Since the float may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(_MapKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.container.add(try self.encoder.box(value)) } public mutating func encode(_ value: Double) throws { // Since the double may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(_MapKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.container.add(try self.encoder.box(value)) } public mutating func encode<T : Encodable>(_ value: T) throws { self.encoder.codingPath.append(_MapKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.container.add(try self.encoder.box(value)) } public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> { self.codingPath.append(_MapKey(index: self.count)) defer { self.codingPath.removeLast() } let dictionary = NSMutableDictionary() self.container.add(dictionary) let container = _MapKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } public mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self.codingPath.append(_MapKey(index: self.count)) defer { self.codingPath.removeLast() } let array = NSMutableArray() self.container.add(array) return _MapUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array) } public mutating func superEncoder() -> Encoder { return _MapReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container) } } extension _MapEncoder : SingleValueEncodingContainer { // MARK: - SingleValueEncodingContainer Methods fileprivate func assertCanEncodeNewValue() { precondition(self.canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.") } public func encodeNil() throws { assertCanEncodeNewValue() self.storage.push(container: NSNull()) } public func encode(_ value: Bool) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int8) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int16) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int32) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int64) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt8) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt16) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt32) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt64) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: String) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Float) throws { assertCanEncodeNewValue() try self.storage.push(container: self.box(value)) } public func encode(_ value: Double) throws { assertCanEncodeNewValue() try self.storage.push(container: self.box(value)) } public func encode<T : Encodable>(_ value: T) throws { assertCanEncodeNewValue() try self.storage.push(container: self.box(value)) } } // MARK: - Concrete Value Representations extension _MapEncoder { /// Returns the given value boxed in a container appropriate for pushing onto the container stack. fileprivate func box(_ value: Bool) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: String) -> NSObject { return NSString(string: value) } fileprivate func box(_ float: Float) throws -> NSObject { guard !float.isInfinite && !float.isNaN else { guard case let .convertToString(positiveInfinity: posInfString, negativeInfinity: negInfString, nan: nanString) = self.options.nonConformingFloatEncodingStrategy else { throw EncodingError._invalidFloatingPointValue(float, at: codingPath) } if float == Float.infinity { return NSString(string: posInfString) } else if float == -Float.infinity { return NSString(string: negInfString) } else { return NSString(string: nanString) } } return NSNumber(value: float) } fileprivate func box(_ double: Double) throws -> NSObject { guard !double.isInfinite && !double.isNaN else { guard case let .convertToString(positiveInfinity: posInfString, negativeInfinity: negInfString, nan: nanString) = self.options.nonConformingFloatEncodingStrategy else { throw EncodingError._invalidFloatingPointValue(double, at: codingPath) } if double == Double.infinity { return NSString(string: posInfString) } else if double == -Double.infinity { return NSString(string: negInfString) } else { return NSString(string: nanString) } } return NSNumber(value: double) } fileprivate func box(_ date: Date) throws -> NSObject { switch self.options.dateEncodingStrategy { case .deferredToDate: // Must be called with a surrounding with(pushedKey:) call. // Dates encode as single-value objects; this can't both throw and push a container, so no need to catch the error. try date.encode(to: self) return self.storage.popContainer() case .secondsSince1970: return NSNumber(value: date.timeIntervalSince1970) case .millisecondsSince1970: return NSNumber(value: 1000.0 * date.timeIntervalSince1970) case .iso8601: if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { return NSString(string: _iso8601Formatter.string(from: date)) } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): return NSString(string: formatter.string(from: date)) case .custom(let closure): let depth = self.storage.count do { try closure(date, self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } guard self.storage.count > depth else { // The closure didn't encode anything. Return the default keyed container. return NSDictionary() } // We can pop because the closure encoded something. return self.storage.popContainer() } } fileprivate func box(_ data: Data) throws -> NSObject { switch self.options.dataEncodingStrategy { case .deferredToData: // Must be called with a surrounding with(pushedKey:) call. let depth = self.storage.count do { try data.encode(to: self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. // This shouldn't be possible for Data (which encodes as an array of bytes), but it can't hurt to catch a failure. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } return self.storage.popContainer() case .base64: return NSString(string: data.base64EncodedString()) case .custom(let closure): let depth = self.storage.count do { try closure(data, self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } guard self.storage.count > depth else { // The closure didn't encode anything. Return the default keyed container. return NSDictionary() } // We can pop because the closure encoded something. return self.storage.popContainer() } } fileprivate func box(_ dict: OrderedDictionary<String, Encodable>) throws -> NSObject? { let depth = self.storage.count let result = self.storage.pushKeyedContainer() do { for (key, value) in dict { self.codingPath.append(_MapKey(stringValue: key, intValue: nil)) defer { self.codingPath.removeLast() } result[key] = try box(value) } } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } // The top container should be a new container. guard self.storage.count > depth else { return nil } return self.storage.popContainer() } fileprivate func box(_ value: Encodable) throws -> NSObject { return try self.box_(value) ?? NSDictionary() } // This method is called "box_" instead of "box" to disambiguate it from the overloads. Because the return type here is different from all of the "box" overloads (and is more general), any "box" calls in here would call back into "box" recursively instead of calling the appropriate overload, which is not what we want. fileprivate func box_(_ value: Encodable) throws -> NSObject? { let type = Swift.type(of: value) #if DEPLOYMENT_RUNTIME_SWIFT if type == Date.self { // Respect Date encoding strategy return try self.box((value as! Date)) } else if type == Data.self { // Respect Data encoding strategy return try self.box((value as! Data)) } else if type == URL.self { // Encode URLs as single strings. return self.box((value as! URL).absoluteString) } else if type == Decimal.self { // MapSerialization can consume NSDecimalNumber values. return NSDecimalNumber(decimal: value as! Decimal) } else if value is _MapStringDictionaryEncodableMarker { return try box((value as Any) as! OrderedDictionary<String, Encodable>) } #else if type == Date.self || type == NSDate.self { // Respect Date encoding strategy return try self.box((value as! Date)) } else if type == Data.self || type == NSData.self { // Respect Data encoding strategy return try self.box((value as! Data)) } else if type == URL.self || type == NSURL.self { // Encode URLs as single strings. return self.box((value as! URL).absoluteString) } else if type == Decimal.self { // MapSerialization can consume NSDecimalNumber values. return NSDecimalNumber(decimal: value as! Decimal) } else if value is _MapStringDictionaryEncodableMarker { return try box((value as Any) as! OrderedDictionary<String, Encodable>) } #endif // The value should request a container from the _MapEncoder. let depth = self.storage.count do { try value.encode(to: self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } // The top container should be a new container. guard self.storage.count > depth else { return nil } return self.storage.popContainer() } } // MARK: - _MapReferencingEncoder /// _MapReferencingEncoder is a special subclass of _MapEncoder which has its own storage, but references the contents of a different encoder. /// It's used in superEncoder(), which returns a new encoder for encoding a superclass -- the lifetime of the encoder should not escape the scope it's created in, but it doesn't necessarily know when it's done being used (to write to the original container). fileprivate class _MapReferencingEncoder : _MapEncoder { // MARK: Reference types. /// The type of container we're referencing. private enum Reference { /// Referencing a specific index in an array container. case array(NSMutableArray, Int) /// Referencing a specific key in a dictionary container. case dictionary(NSMutableDictionary, String) } // MARK: - Properties /// The encoder we're referencing. fileprivate let encoder: _MapEncoder /// The container reference itself. private let reference: Reference // MARK: - Initialization /// Initializes `self` by referencing the given array container in the given encoder. fileprivate init(referencing encoder: _MapEncoder, at index: Int, wrapping array: NSMutableArray) { self.encoder = encoder self.reference = .array(array, index) super.init(options: encoder.options, codingPath: encoder.codingPath) self.codingPath.append(_MapKey(index: index)) } /// Initializes `self` by referencing the given dictionary container in the given encoder. fileprivate init(referencing encoder: _MapEncoder, at key: CodingKey, wrapping dictionary: NSMutableDictionary) { self.encoder = encoder self.reference = .dictionary(dictionary, key.stringValue) super.init(options: encoder.options, codingPath: encoder.codingPath) self.codingPath.append(key) } // MARK: - Coding Path Operations fileprivate override var canEncodeNewValue: Bool { // With a regular encoder, the storage and coding path grow together. // A referencing encoder, however, inherits its parents coding path, as well as the key it was created for. // We have to take this into account. return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1 } // MARK: - Deinitialization // Finalizes `self` by writing the contents of our storage to the referenced encoder's storage. deinit { let value: Any switch self.storage.count { case 0: value = NSDictionary() case 1: value = self.storage.popContainer() default: fatalError("Referencing encoder deallocated with multiple containers on stack.") } switch self.reference { case .array(let array, let index): array.insert(value, at: index) case .dictionary(let dictionary, let key): dictionary[NSString(string: key)] = value } } } //===----------------------------------------------------------------------===// // Map Decoder //===----------------------------------------------------------------------===// /// `MapDecoder` facilitates the decoding of Map into semantic `Decodable` types. open class MapDecoder { // MARK: Options /// The strategy to use for decoding `Date` values. public enum DateDecodingStrategy { /// Defer to `Date` for decoding. This is the default strategy. case deferredToDate /// Decode the `Date` as a UNIX timestamp from a Map number. case secondsSince1970 /// Decode the `Date` as UNIX millisecond timestamp from a Map number. case millisecondsSince1970 /// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Decode the `Date` as a string parsed by the given formatter. case formatted(DateFormatter) /// Decode the `Date` as a custom value decoded by the given closure. case custom((_ decoder: Decoder) throws -> Date) } /// The strategy to use for decoding `Data` values. public enum DataDecodingStrategy { /// Defer to `Data` for decoding. case deferredToData /// Decode the `Data` from a Base64-encoded string. This is the default strategy. case base64 /// Decode the `Data` as a custom value decoded by the given closure. case custom((_ decoder: Decoder) throws -> Data) } /// The strategy to use for non-Map-conforming floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloatDecodingStrategy { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Decode the values from the given representation strings. case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String) } /// The strategy to use for automatically changing the value of keys before decoding. public enum KeyDecodingStrategy { /// Use the keys specified by each type. This is the default strategy. case useDefaultKeys /// Convert from "snake_case_keys" to "camelCaseKeys" before attempting to match a key with the one specified by each type. /// /// The conversion to upper case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences. /// /// Converting from snake case to camel case: /// 1. Capitalizes the word starting after each `_` /// 2. Removes all `_` /// 3. Preserves starting and ending `_` (as these are often used to indicate private variables or other metadata). /// For example, `one_two_three` becomes `oneTwoThree`. `_one_two_three_` becomes `_oneTwoThree_`. /// /// - Note: Using a key decoding strategy has a nominal performance cost, as each string key has to be inspected for the `_` character. case convertFromSnakeCase /// Provide a custom conversion from the key in the encoded Map to the keys specified by the decoded types. /// The full path to the current decoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before decoding. /// If the result of the conversion is a duplicate key, then only one value will be present in the container for the type to decode from. case custom((_ codingPath: [CodingKey]) -> CodingKey) fileprivate static func _convertFromSnakeCase(_ stringKey: String) -> String { guard !stringKey.isEmpty else { return stringKey } // Find the first non-underscore character guard let firstNonUnderscore = stringKey.firstIndex(where: { $0 != "_" }) else { // Reached the end without finding an _ return stringKey } // Find the last non-underscore character var lastNonUnderscore = stringKey.index(before: stringKey.endIndex) while lastNonUnderscore > firstNonUnderscore && stringKey[lastNonUnderscore] == "_" { stringKey.formIndex(before: &lastNonUnderscore) } let keyRange = firstNonUnderscore...lastNonUnderscore let leadingUnderscoreRange = stringKey.startIndex..<firstNonUnderscore let trailingUnderscoreRange = stringKey.index(after: lastNonUnderscore)..<stringKey.endIndex let components = stringKey[keyRange].split(separator: "_") let joinedString : String if components.count == 1 { // No underscores in key, leave the word as is - maybe already camel cased joinedString = String(stringKey[keyRange]) } else { joinedString = ([components[0].lowercased()] + components[1...].map { $0.capitalized }).joined() } // Do a cheap isEmpty check before creating and appending potentially empty strings let result : String if (leadingUnderscoreRange.isEmpty && trailingUnderscoreRange.isEmpty) { result = joinedString } else if (!leadingUnderscoreRange.isEmpty && !trailingUnderscoreRange.isEmpty) { // Both leading and trailing underscores result = String(stringKey[leadingUnderscoreRange]) + joinedString + String(stringKey[trailingUnderscoreRange]) } else if (!leadingUnderscoreRange.isEmpty) { // Just leading result = String(stringKey[leadingUnderscoreRange]) + joinedString } else { // Just trailing result = joinedString + String(stringKey[trailingUnderscoreRange]) } return result } } /// The strategy to use in decoding dates. Defaults to `.deferredToDate`. open var dateDecodingStrategy: DateDecodingStrategy = .deferredToDate /// The strategy to use in decoding binary data. Defaults to `.base64`. open var dataDecodingStrategy: DataDecodingStrategy = .base64 /// The strategy to use in decoding non-conforming numbers. Defaults to `.throw`. open var nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy = .throw /// The strategy to use for decoding keys. Defaults to `.useDefaultKeys`. open var keyDecodingStrategy: KeyDecodingStrategy = .useDefaultKeys /// Contextual user-provided information for use during decoding. open var userInfo: [CodingUserInfoKey : Any] = [:] /// Options set on the top-level encoder to pass down the decoding hierarchy. fileprivate struct _Options { let dateDecodingStrategy: DateDecodingStrategy let dataDecodingStrategy: DataDecodingStrategy let nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy let keyDecodingStrategy: KeyDecodingStrategy let userInfo: [CodingUserInfoKey : Any] } /// The options set on the top-level decoder. fileprivate var options: _Options { return _Options(dateDecodingStrategy: dateDecodingStrategy, dataDecodingStrategy: dataDecodingStrategy, nonConformingFloatDecodingStrategy: nonConformingFloatDecodingStrategy, keyDecodingStrategy: keyDecodingStrategy, userInfo: userInfo) } // MARK: - Constructing a Map Decoder /// Initializes `self` with default strategies. public init() {} // MARK: - Decoding Values /// Decodes a top-level value of the given type from the given Map representation. /// /// - parameter type: The type of the value to decode. /// - parameter map: The map to decode from. /// - returns: A value of the requested type. /// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not valid Map. /// - throws: An error if any value throws an error during decoding. open func decode<T : Decodable>(_ type: T.Type, from map: Map) throws -> T { let topLevel = try MapSerialization.object(with: map) let decoder = _MapDecoder(referencing: topLevel, options: self.options) guard let value = try decoder.unbox(topLevel, as: type) else { throw DecodingError.valueNotFound( type, DecodingError.Context( codingPath: [], debugDescription: "The given data did not contain a top-level value." ) ) } return value } } // MARK: - _MapDecoder fileprivate class _MapDecoder : Decoder { // MARK: Properties /// The decoder's storage. fileprivate var storage: _MapDecodingStorage /// Options set on the top-level decoder. fileprivate let options: MapDecoder._Options /// The path to the current point in encoding. fileprivate(set) public var codingPath: [CodingKey] /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level container and options. fileprivate init(referencing container: Any, at codingPath: [CodingKey] = [], options: MapDecoder._Options) { self.storage = _MapDecodingStorage() self.storage.push(container: container) self.codingPath = codingPath self.options = options } // MARK: - Decoder Methods public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let topContainer = self.storage.topContainer as? [String : Any] else { throw DecodingError._typeMismatch( at: self.codingPath, expectation: [String : Any].self, reality: self.storage.topContainer ) } let container = _MapKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer) return KeyedDecodingContainer(container) } public func unkeyedContainer() throws -> UnkeyedDecodingContainer { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get unkeyed decoding container -- found null value instead.")) } guard let topContainer = self.storage.topContainer as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: self.storage.topContainer) } return _MapUnkeyedDecodingContainer(referencing: self, wrapping: topContainer) } public func singleValueContainer() throws -> SingleValueDecodingContainer { return self } } // MARK: - Decoding Storage fileprivate struct _MapDecodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the Map types (NSNull, NSNumber, String, Array, [String : Any]). private(set) fileprivate var containers: [Any] = [] // MARK: - Initialization /// Initializes `self` with no containers. fileprivate init() {} // MARK: - Modifying the Stack fileprivate var count: Int { return self.containers.count } fileprivate var topContainer: Any { precondition(!self.containers.isEmpty, "Empty container stack.") return self.containers.last! } fileprivate mutating func push(container: Any) { self.containers.append(container) } fileprivate mutating func popContainer() { precondition(!self.containers.isEmpty, "Empty container stack.") self.containers.removeLast() } } // MARK: Decoding Containers fileprivate struct _MapKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the decoder we're reading from. private let decoder: _MapDecoder /// A reference to the container we're reading from. private let container: [String : Any] /// The path of coding keys taken to get to this point in decoding. private(set) public var codingPath: [CodingKey] // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. fileprivate init(referencing decoder: _MapDecoder, wrapping container: [String : Any]) { self.decoder = decoder switch decoder.options.keyDecodingStrategy { case .useDefaultKeys: self.container = container case .convertFromSnakeCase: // Convert the snake case keys in the container to camel case. // If we hit a duplicate key after conversion, then we'll use the first one we saw. Effectively an undefined behavior with Map dictionaries. self.container = Dictionary(container.map { key, value in (MapDecoder.KeyDecodingStrategy._convertFromSnakeCase(key), value) }, uniquingKeysWith: { (first, _) in first }) case .custom(let converter): self.container = Dictionary(container.map { key, value in (converter(decoder.codingPath + [_MapKey(stringValue: key, intValue: nil)]).stringValue, value) }, uniquingKeysWith: { (first, _) in first }) } self.codingPath = decoder.codingPath } // MARK: - KeyedDecodingContainerProtocol Methods public var allKeys: [Key] { return self.container.keys.compactMap { Key(stringValue: $0) } } public func contains(_ key: Key) -> Bool { return self.container[key.stringValue] != nil } private func _errorDescription(of key: CodingKey) -> String { switch decoder.options.keyDecodingStrategy { case .convertFromSnakeCase: // In this case we can attempt to recover the original value by reversing the transform let original = key.stringValue let converted = MapEncoder.KeyEncodingStrategy._convertToSnakeCase(original) if converted == original { return "\(key) (\"\(original)\")" } else { return "\(key) (\"\(original)\"), converted to \(converted)" } default: // Otherwise, just report the converted string return "\(key) (\"\(key.stringValue)\")" } } public func decodeNil(forKey key: Key) throws -> Bool { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } return entry is NSNull } public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Bool.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int.Type, forKey key: Key) throws -> Int { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Float.Type, forKey key: Key) throws -> Float { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Float.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Double.Type, forKey key: Key) throws -> Double { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Double.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: String.Type, forKey key: Key) throws -> String { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: String.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: type) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get \(KeyedDecodingContainer<NestedKey>.self) -- no value found for key \(_errorDescription(of: key))")) } guard let dictionary = value as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value) } let container = _MapKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get UnkeyedDecodingContainer -- no value found for key \(_errorDescription(of: key))")) } guard let array = value as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value) } return _MapUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } private func _superDecoder(forKey key: CodingKey) throws -> Decoder { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } let value: Any = self.container[key.stringValue] ?? NSNull() return _MapDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options) } public func superDecoder() throws -> Decoder { return try _superDecoder(forKey: _MapKey.super) } public func superDecoder(forKey key: Key) throws -> Decoder { return try _superDecoder(forKey: key) } } fileprivate struct _MapUnkeyedDecodingContainer : UnkeyedDecodingContainer { // MARK: Properties /// A reference to the decoder we're reading from. private let decoder: _MapDecoder /// A reference to the container we're reading from. private let container: [Any] /// The path of coding keys taken to get to this point in decoding. private(set) public var codingPath: [CodingKey] /// The index of the element we're about to decode. private(set) public var currentIndex: Int // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. fileprivate init(referencing decoder: _MapDecoder, wrapping container: [Any]) { self.decoder = decoder self.container = container self.codingPath = decoder.codingPath self.currentIndex = 0 } // MARK: - UnkeyedDecodingContainer Methods public var count: Int? { return self.container.count } public var isAtEnd: Bool { return self.currentIndex >= self.count! } public mutating func decodeNil() throws -> Bool { guard !self.isAtEnd else { throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } if self.container[self.currentIndex] is NSNull { self.currentIndex += 1 return true } else { return false } } public mutating func decode(_ type: Bool.Type) throws -> Bool { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Bool.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int.Type) throws -> Int { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int8.Type) throws -> Int8 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int16.Type) throws -> Int16 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int32.Type) throws -> Int32 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int64.Type) throws -> Int64 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt.Type) throws -> UInt { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt8.Type) throws -> UInt8 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt16.Type) throws -> UInt16 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt32.Type) throws -> UInt32 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt64.Type) throws -> UInt64 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Float.Type) throws -> Float { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Float.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Double.Type) throws -> Double { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Double.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: String.Type) throws -> String { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: String.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode<T : Decodable>(_ type: T.Type) throws -> T { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: type) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_MapKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> { self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let dictionary = value as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value) } self.currentIndex += 1 let container = _MapKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let array = value as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value) } self.currentIndex += 1 return _MapUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } public mutating func superDecoder() throws -> Decoder { self.decoder.codingPath.append(_MapKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(Decoder.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get superDecoder() -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] self.currentIndex += 1 return _MapDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options) } } extension _MapDecoder : SingleValueDecodingContainer { // MARK: SingleValueDecodingContainer Methods private func expectNonNull<T>(_ type: T.Type) throws { guard !self.decodeNil() else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected \(type) but found null value instead.")) } } public func decodeNil() -> Bool { return self.storage.topContainer is NSNull } public func decode(_ type: Bool.Type) throws -> Bool { try expectNonNull(Bool.self) return try self.unbox(self.storage.topContainer, as: Bool.self)! } public func decode(_ type: Int.Type) throws -> Int { try expectNonNull(Int.self) return try self.unbox(self.storage.topContainer, as: Int.self)! } public func decode(_ type: Int8.Type) throws -> Int8 { try expectNonNull(Int8.self) return try self.unbox(self.storage.topContainer, as: Int8.self)! } public func decode(_ type: Int16.Type) throws -> Int16 { try expectNonNull(Int16.self) return try self.unbox(self.storage.topContainer, as: Int16.self)! } public func decode(_ type: Int32.Type) throws -> Int32 { try expectNonNull(Int32.self) return try self.unbox(self.storage.topContainer, as: Int32.self)! } public func decode(_ type: Int64.Type) throws -> Int64 { try expectNonNull(Int64.self) return try self.unbox(self.storage.topContainer, as: Int64.self)! } public func decode(_ type: UInt.Type) throws -> UInt { try expectNonNull(UInt.self) return try self.unbox(self.storage.topContainer, as: UInt.self)! } public func decode(_ type: UInt8.Type) throws -> UInt8 { try expectNonNull(UInt8.self) return try self.unbox(self.storage.topContainer, as: UInt8.self)! } public func decode(_ type: UInt16.Type) throws -> UInt16 { try expectNonNull(UInt16.self) return try self.unbox(self.storage.topContainer, as: UInt16.self)! } public func decode(_ type: UInt32.Type) throws -> UInt32 { try expectNonNull(UInt32.self) return try self.unbox(self.storage.topContainer, as: UInt32.self)! } public func decode(_ type: UInt64.Type) throws -> UInt64 { try expectNonNull(UInt64.self) return try self.unbox(self.storage.topContainer, as: UInt64.self)! } public func decode(_ type: Float.Type) throws -> Float { try expectNonNull(Float.self) return try self.unbox(self.storage.topContainer, as: Float.self)! } public func decode(_ type: Double.Type) throws -> Double { try expectNonNull(Double.self) return try self.unbox(self.storage.topContainer, as: Double.self)! } public func decode(_ type: String.Type) throws -> String { try expectNonNull(String.self) return try self.unbox(self.storage.topContainer, as: String.self)! } public func decode<T : Decodable>(_ type: T.Type) throws -> T { try expectNonNull(type) return try self.unbox(self.storage.topContainer, as: type)! } } // MARK: - Concrete Value Representations extension _MapDecoder { /// Returns the given value unboxed from a container. fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? { guard !(value is NSNull) else { return nil } #if DEPLOYMENT_RUNTIME_SWIFT || os(Linux) // Bridging differences require us to split implementations here guard let number = __SwiftValue.store(value) as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } // TODO: Add a flag to coerce non-boolean numbers into Bools? guard CFGetTypeID(number) == CFBooleanGetTypeID() else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } return number.boolValue #else if let number = value as? NSNumber { // TODO: Add a flag to coerce non-boolean numbers into Bools? if number === kCFBooleanTrue as NSNumber { return true } else if number === kCFBooleanFalse as NSNumber { return false } /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let bool = value as? Bool { return bool */ } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) #endif } fileprivate func unbox(_ value: Any, as type: Int.Type) throws -> Int? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int = number.intValue guard NSNumber(value: int) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed Map number <\(number)> does not fit in \(type).")) } return int } fileprivate func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int8 = number.int8Value guard NSNumber(value: int8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed Map number <\(number)> does not fit in \(type).")) } return int8 } fileprivate func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int16 = number.int16Value guard NSNumber(value: int16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed Map number <\(number)> does not fit in \(type).")) } return int16 } fileprivate func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int32 = number.int32Value guard NSNumber(value: int32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed Map number <\(number)> does not fit in \(type).")) } return int32 } fileprivate func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int64 = number.int64Value guard NSNumber(value: int64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed Map number <\(number)> does not fit in \(type).")) } return int64 } fileprivate func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint = number.uintValue guard NSNumber(value: uint) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed Map number <\(number)> does not fit in \(type).")) } return uint } fileprivate func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint8 = number.uint8Value guard NSNumber(value: uint8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed Map number <\(number)> does not fit in \(type).")) } return uint8 } fileprivate func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint16 = number.uint16Value guard NSNumber(value: uint16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed Map number <\(number)> does not fit in \(type).")) } return uint16 } fileprivate func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint32 = number.uint32Value guard NSNumber(value: uint32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed Map number <\(number)> does not fit in \(type).")) } return uint32 } fileprivate func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint64 = number.uint64Value guard NSNumber(value: uint64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed Map number <\(number)> does not fit in \(type).")) } return uint64 } fileprivate func unbox(_ value: Any, as type: Float.Type) throws -> Float? { guard !(value is NSNull) else { return nil } if let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse { // We are willing to return a Float by losing precision: // * If the original value was integral, // * and the integral value was > Float.greatestFiniteMagnitude, we will fail // * and the integral value was <= Float.greatestFiniteMagnitude, we are willing to lose precision past 2^24 // * If it was a Float, you will get back the precise value // * If it was a Double or Decimal, you will get back the nearest approximation if it will fit let double = number.doubleValue guard abs(double) <= Double(Float.greatestFiniteMagnitude) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed Map number \(number) does not fit in \(type).")) } return Float(double) /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let double = value as? Double { if abs(double) <= Double(Float.max) { return Float(double) } overflow = true } else if let int = value as? Int { if let float = Float(exactly: int) { return float } overflow = true */ } else if let string = value as? String, case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy { if string == posInfString { return Float.infinity } else if string == negInfString { return -Float.infinity } else if string == nanString { return Float.nan } } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func unbox(_ value: Any, as type: Double.Type) throws -> Double? { guard !(value is NSNull) else { return nil } if let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse { // We are always willing to return the number as a Double: // * If the original value was integral, it is guaranteed to fit in a Double; we are willing to lose precision past 2^53 if you encoded a UInt64 but requested a Double // * If it was a Float or Double, you will get back the precise value // * If it was Decimal, you will get back the nearest approximation return number.doubleValue /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let double = value as? Double { return double } else if let int = value as? Int { if let double = Double(exactly: int) { return double } overflow = true */ } else if let string = value as? String, case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy { if string == posInfString { return Double.infinity } else if string == negInfString { return -Double.infinity } else if string == nanString { return Double.nan } } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func unbox(_ value: Any, as type: String.Type) throws -> String? { guard !(value is NSNull) else { return nil } guard let string = value as? String else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } return string } fileprivate func unbox(_ value: Any, as type: Date.Type) throws -> Date? { guard !(value is NSNull) else { return nil } switch self.options.dateDecodingStrategy { case .deferredToDate: self.storage.push(container: value) defer { self.storage.popContainer() } return try Date(from: self) case .secondsSince1970: let double = try self.unbox(value, as: Double.self)! return Date(timeIntervalSince1970: double) case .millisecondsSince1970: let double = try self.unbox(value, as: Double.self)! return Date(timeIntervalSince1970: double / 1000.0) case .iso8601: if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { let string = try self.unbox(value, as: String.self)! guard let date = _iso8601Formatter.date(from: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected date string to be ISO8601-formatted.")) } return date } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): let string = try self.unbox(value, as: String.self)! guard let date = formatter.date(from: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Date string does not match format expected by formatter.")) } return date case .custom(let closure): self.storage.push(container: value) defer { self.storage.popContainer() } return try closure(self) } } fileprivate func unbox(_ value: Any, as type: Data.Type) throws -> Data? { guard !(value is NSNull) else { return nil } switch self.options.dataDecodingStrategy { case .deferredToData: self.storage.push(container: value) defer { self.storage.popContainer() } return try Data(from: self) case .base64: guard let string = value as? String else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } guard let data = Data(base64Encoded: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Encountered Data is not valid Base64.")) } return data case .custom(let closure): self.storage.push(container: value) defer { self.storage.popContainer() } return try closure(self) } } fileprivate func unbox(_ value: Any, as type: Decimal.Type) throws -> Decimal? { guard !(value is NSNull) else { return nil } // Attempt to bridge from NSDecimalNumber. if let decimal = value as? Decimal { return decimal } else { let doubleValue = try self.unbox(value, as: Double.self)! return Decimal(doubleValue) } } fileprivate func unbox<T>(_ value: Any, as type: _MapStringDictionaryDecodableMarker.Type) throws -> T? { guard !(value is NSNull) else { return nil } var result: OrderedDictionary<String, Any> = [:] guard let dict = value as? NSDictionary else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let elementType = type.elementType for (key, value) in dict { let key = key as! String self.codingPath.append(_MapKey(stringValue: key, intValue: nil)) defer { self.codingPath.removeLast() } result[key] = try unbox_(value, as: elementType) } return result as? T } fileprivate func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? { return try unbox_(value, as: type) as? T } fileprivate func unbox_(_ value: Any, as type: Decodable.Type) throws -> Any? { #if DEPLOYMENT_RUNTIME_SWIFT // Bridging differences require us to split implementations here if type == Date.self { guard let date = try self.unbox(value, as: Date.self) else { return nil } return date } else if type == Data.self { guard let data = try self.unbox(value, as: Data.self) else { return nil } return data } else if type == URL.self { guard let urlString = try self.unbox(value, as: String.self) else { return nil } guard let url = URL(string: urlString) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Invalid URL string.")) } return url } else if type == Decimal.self { guard let decimal = try self.unbox(value, as: Decimal.self) else { return nil } return decimal } else if let stringKeyedDictType = type as? _MapStringDictionaryDecodableMarker.Type { return try self.unbox(value, as: stringKeyedDictType) } else { self.storage.push(container: value) defer { self.storage.popContainer() } return try type.init(from: self) } #else if type == Date.self || type == NSDate.self { return try self.unbox(value, as: Date.self) } else if type == Data.self || type == NSData.self { return try self.unbox(value, as: Data.self) } else if type == URL.self || type == NSURL.self { guard let urlString = try self.unbox(value, as: String.self) else { return nil } guard let url = URL(string: urlString) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Invalid URL string.")) } return url } else if type == Decimal.self || type == NSDecimalNumber.self { return try self.unbox(value, as: Decimal.self) } else if let stringKeyedDictType = type as? _MapStringDictionaryDecodableMarker.Type { return try self.unbox(value, as: stringKeyedDictType) } else { self.storage.push(container: value) defer { self.storage.popContainer() } return try type.init(from: self) } #endif } } //===----------------------------------------------------------------------===// // Shared Key Types //===----------------------------------------------------------------------===// fileprivate struct _MapKey : CodingKey { public var stringValue: String public var intValue: Int? public init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } public init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } public init(stringValue: String, intValue: Int?) { self.stringValue = stringValue self.intValue = intValue } fileprivate init(index: Int) { self.stringValue = "Index \(index)" self.intValue = index } fileprivate static let `super` = _MapKey(stringValue: "super")! } //===----------------------------------------------------------------------===// // Shared ISO8601 Date Formatter //===----------------------------------------------------------------------===// // NOTE: This value is implicitly lazy and _must_ be lazy. We're compiled against the latest SDK (w/ ISO8601DateFormatter), but linked against whichever Foundation the user has. ISO8601DateFormatter might not exist, so we better not hit this code path on an older OS. @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) fileprivate var _iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter }() //===----------------------------------------------------------------------===// // Error Utilities //===----------------------------------------------------------------------===// extension EncodingError { /// Returns a `.invalidValue` error describing the given invalid floating-point value. /// /// /// - parameter value: The value that was invalid to encode. /// - parameter path: The path of `CodingKey`s taken to encode this value. /// - returns: An `EncodingError` with the appropriate path and debug description. fileprivate static func _invalidFloatingPointValue<T : FloatingPoint>(_ value: T, at codingPath: [CodingKey]) -> EncodingError { let valueDescription: String if value == T.infinity { valueDescription = "\(T.self).infinity" } else if value == -T.infinity { valueDescription = "-\(T.self).infinity" } else { valueDescription = "\(T.self).nan" } let debugDescription = "Unable to encode \(valueDescription) directly in Map. Use MapEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded." return .invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: debugDescription)) } } extension DecodingError { /// Returns a `.typeMismatch` error describing the expected type. /// /// - parameter path: The path of `CodingKey`s taken to decode a value of this type. /// - parameter expectation: The type expected to be encountered. /// - parameter reality: The value that was encountered instead of the expected type. /// - returns: A `DecodingError` with the appropriate path and debug description. internal static func _typeMismatch( at path: [CodingKey], expectation: Any.Type, reality: Any ) -> DecodingError { let description = "Expected to decode \(expectation) but found \(_typeDescription(of: reality)) instead." return .typeMismatch(expectation, Context(codingPath: path, debugDescription: description)) } /// Returns a description of the type of `value` appropriate for an error message. /// /// - parameter value: The value whose type to describe. /// - returns: A string describing `value`. /// - precondition: `value` is one of the types below. private static func _typeDescription(of value: Any) -> String { if value is NSNull { return "a null value" } else if value is NSNumber /* FIXME: If swift-corelibs-foundation isn't updated to use NSNumber, this check will be necessary: || value is Int || value is Double */ { return "a number" } else if value is String { return "a string/data" } else if value is [Any] { return "an array" } else if value is [String : Any] { return "a dictionary" } else { return "\(type(of: value))" } } } private struct __SwiftValue { fileprivate static func store(_ any: Any) -> Any { return any } }
45.021129
323
0.649279
dd53bce785eb462a5949ea5e705489a2239878e3
1,248
// // AppDelegate.swift // LightShow // // Created by Guido Westenberg on 11/9/20. // import Cocoa import SwiftUI @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var window: NSWindow! var store: PatternStore! func applicationDidFinishLaunching(_ aNotification: Notification) { // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Create the window and set the content view. window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 480, height: 300), styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing: .buffered, defer: false) window.isReleasedWhenClosed = false window.center() window.setFrameAutosaveName("Main Window") window.contentView = NSHostingView(rootView: contentView) window.makeKeyAndOrderFront(nil) } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } lazy var patterns : [LightShow.Pattern] = { store = PatternStore() store.loadPatterns() return store.patterns }() }
27.733333
95
0.659455
6a838d92356b79df2df176bff94f781adb49ba6a
264
import Foundation struct Day07: Day { static func test() throws { // Use precondition or assert to tests things } static func run(input: String) throws { // TODO: Implement Day 7 print("Day 7 is not yet implemented") } }
18.857143
53
0.609848
1c13beea597a8891f61d60838ad5435084440f18
24,502
// Copyright © 2014-2018 the Surge contributors // // 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 Accelerate public enum MatrixAxies { case row case column } public struct Matrix<Scalar> where Scalar: FloatingPoint, Scalar: ExpressibleByFloatLiteral { public let rows: Int public let columns: Int var grid: [Scalar] public init(rows: Int, columns: Int, repeatedValue: Scalar) { self.rows = rows self.columns = columns self.grid = [Scalar](repeating: repeatedValue, count: rows * columns) } public init<T: Collection, U: Collection>(_ contents: T) where T.Element == U, U.Element == Scalar { self.init(rows: contents.count, columns: contents.first!.count, repeatedValue: 0.0) for (i, row) in contents.enumerated() { precondition(row.count == columns, "All rows should have the same number of columns") grid.replaceSubrange(i*columns ..< (i + 1)*columns, with: row) } } public init(row: [Scalar]) { self.init(rows: 1, columns: row.count, grid: row) } public init(column: [Scalar]) { self.init(rows: column.count, columns: 1, grid: column) } public init(rows: Int, columns: Int, grid: [Scalar]) { precondition(grid.count == rows * columns) self.rows = rows self.columns = columns self.grid = grid } public subscript(row: Int, column: Int) -> Scalar { get { assert(indexIsValidForRow(row, column: column)) return grid[(row * columns) + column] } set { assert(indexIsValidForRow(row, column: column)) grid[(row * columns) + column] = newValue } } public subscript(row row: Int) -> [Scalar] { get { assert(row < rows) let startIndex = row * columns let endIndex = row * columns + columns return Array(grid[startIndex..<endIndex]) } set { assert(row < rows) assert(newValue.count == columns) let startIndex = row * columns let endIndex = row * columns + columns grid.replaceSubrange(startIndex..<endIndex, with: newValue) } } public subscript(column column: Int) -> [Scalar] { get { var result = [Scalar](repeating: 0.0, count: rows) for i in 0..<rows { let index = i * columns + column result[i] = self.grid[index] } return result } set { assert(column < columns) assert(newValue.count == rows) for i in 0..<rows { let index = i * columns + column grid[index] = newValue[i] } } } private func indexIsValidForRow(_ row: Int, column: Int) -> Bool { return row >= 0 && row < rows && column >= 0 && column < columns } } /// Holds the result of eigendecomposition. The (Scalar, Scalar) used /// in the property types represents a complex number with (real, imaginary) parts. public struct MatrixEigenDecompositionResult<Scalar> where Scalar: FloatingPoint, Scalar: ExpressibleByFloatLiteral { let eigenValues: [(Scalar, Scalar)] let leftEigenVectors: [[(Scalar, Scalar)]] let rightEigenVectors: [[(Scalar, Scalar)]] public init(eigenValues: [(Scalar, Scalar)], leftEigenVectors: [[(Scalar, Scalar)]], rightEigenVectors: [[(Scalar, Scalar)]]) { self.eigenValues = eigenValues self.leftEigenVectors = leftEigenVectors self.rightEigenVectors = rightEigenVectors } public init(rowCount: Int, eigenValueRealParts: [Scalar], eigenValueImaginaryParts: [Scalar], leftEigenVectorWork: [Scalar], rightEigenVectorWork: [Scalar]) { // The eigenvalues are an array of (real, imaginary) results from dgeev self.eigenValues = Array(zip(eigenValueRealParts, eigenValueImaginaryParts)) // Build the left and right eigenvectors let emptyVector = [(Scalar, Scalar)](repeating: (0, 0), count: rowCount) var leftEigenVectors = [[(Scalar, Scalar)]](repeating: emptyVector, count: rowCount) buildEigenVector(eigenValueImaginaryParts: eigenValueImaginaryParts, eigenVectorWork: leftEigenVectorWork, result: &leftEigenVectors) var rightEigenVectors = [[(Scalar, Scalar)]](repeating: emptyVector, count: rowCount) buildEigenVector(eigenValueImaginaryParts: eigenValueImaginaryParts, eigenVectorWork: rightEigenVectorWork, result: &rightEigenVectors) self.leftEigenVectors = leftEigenVectors self.rightEigenVectors = rightEigenVectors } } /// Errors thrown when a matrix cannot be decomposed. public enum EigenDecompositionError: Error { case matrixNotSquare case matrixNotDecomposable } // MARK: - Printable extension Matrix: CustomStringConvertible { public var description: String { var description = "" for i in 0..<rows { let contents = (0..<columns).map({ "\(self[i, $0])" }).joined(separator: "\t") switch (i, rows) { case (0, 1): description += "(\t\(contents)\t)" case (0, _): description += "⎛\t\(contents)\t⎞" case (rows - 1, _): description += "⎝\t\(contents)\t⎠" default: description += "⎜\t\(contents)\t⎥" } description += "\n" } return description } } // MARK: - SequenceType extension Matrix: Sequence { public func makeIterator() -> AnyIterator<ArraySlice<Scalar>> { let endIndex = rows * columns var nextRowStartIndex = 0 return AnyIterator { if nextRowStartIndex == endIndex { return nil } let currentRowStartIndex = nextRowStartIndex nextRowStartIndex += self.columns return self.grid[currentRowStartIndex..<nextRowStartIndex] } } } extension Matrix: Equatable {} public func ==<T> (lhs: Matrix<T>, rhs: Matrix<T>) -> Bool { return lhs.rows == rhs.rows && lhs.columns == rhs.columns && lhs.grid == rhs.grid } // MARK: - public func add(_ x: Matrix<Float>, _ y: Matrix<Float>) -> Matrix<Float> { precondition(x.rows == y.rows && x.columns == y.columns, "Matrix dimensions not compatible with addition") var results = y results.grid.withUnsafeMutableBufferPointer { pointer in cblas_saxpy(Int32(x.grid.count), 1.0, x.grid, 1, pointer.baseAddress!, 1) } return results } public func add(_ x: Matrix<Double>, _ y: Matrix<Double>) -> Matrix<Double> { precondition(x.rows == y.rows && x.columns == y.columns, "Matrix dimensions not compatible with addition") var results = y results.grid.withUnsafeMutableBufferPointer { pointer in cblas_daxpy(Int32(x.grid.count), 1.0, x.grid, 1, pointer.baseAddress!, 1) } return results } public func sub(_ x: Matrix<Float>, _ y: Matrix<Float>) -> Matrix<Float> { precondition(x.rows == y.rows && x.columns == y.columns, "Matrix dimensions not compatible with subtraction") var results = y results.grid.withUnsafeMutableBufferPointer { pointer in catlas_saxpby(Int32(x.grid.count), 1.0, x.grid, 1, -1, pointer.baseAddress!, 1) } return results } public func sub(_ x: Matrix<Double>, _ y: Matrix<Double>) -> Matrix<Double> { precondition(x.rows == y.rows && x.columns == y.columns, "Matrix dimensions not compatible with subtraction") var results = y results.grid.withUnsafeMutableBufferPointer { pointer in catlas_daxpby(Int32(x.grid.count), 1.0, x.grid, 1, -1, pointer.baseAddress!, 1) } return results } public func mul(_ alpha: Float, _ x: Matrix<Float>) -> Matrix<Float> { var results = x results.grid.withUnsafeMutableBufferPointer { pointer in cblas_sscal(Int32(x.grid.count), alpha, pointer.baseAddress!, 1) } return results } public func mul(_ alpha: Double, _ x: Matrix<Double>) -> Matrix<Double> { var results = x results.grid.withUnsafeMutableBufferPointer { pointer in cblas_dscal(Int32(x.grid.count), alpha, pointer.baseAddress!, 1) } return results } public func mul(_ x: Matrix<Float>, _ y: Matrix<Float>) -> Matrix<Float> { precondition(x.columns == y.rows, "Matrix dimensions not compatible with multiplication") if x.rows == 0 || x.columns == 0 || y.columns == 0 { return Matrix<Float>(rows: x.rows, columns: y.columns, repeatedValue: 0.0) } var results = Matrix<Float>(rows: x.rows, columns: y.columns, repeatedValue: 0.0) results.grid.withUnsafeMutableBufferPointer { pointer in cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, Int32(x.rows), Int32(y.columns), Int32(x.columns), 1.0, x.grid, Int32(x.columns), y.grid, Int32(y.columns), 0.0, pointer.baseAddress!, Int32(y.columns)) } return results } public func mul(_ x: Matrix<Double>, _ y: Matrix<Double>) -> Matrix<Double> { precondition(x.columns == y.rows, "Matrix dimensions not compatible with multiplication") if x.rows == 0 || x.columns == 0 || y.columns == 0 { return Matrix<Double>(rows: x.rows, columns: y.columns, repeatedValue: 0.0) } var results = Matrix<Double>(rows: x.rows, columns: y.columns, repeatedValue: 0.0) results.grid.withUnsafeMutableBufferPointer { pointer in cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, Int32(x.rows), Int32(y.columns), Int32(x.columns), 1.0, x.grid, Int32(x.columns), y.grid, Int32(y.columns), 0.0, pointer.baseAddress!, Int32(y.columns)) } return results } public func elmul(_ x: Matrix<Double>, _ y: Matrix<Double>) -> Matrix<Double> { precondition(x.rows == y.rows && x.columns == y.columns, "Matrix must have the same dimensions") var result = Matrix<Double>(rows: x.rows, columns: x.columns, repeatedValue: 0.0) result.grid = x.grid .* y.grid return result } public func elmul(_ x: Matrix<Float>, _ y: Matrix<Float>) -> Matrix<Float> { precondition(x.rows == y.rows && x.columns == y.columns, "Matrix must have the same dimensions") var result = Matrix<Float>(rows: x.rows, columns: x.columns, repeatedValue: 0.0) result.grid = x.grid .* y.grid return result } public func div(_ x: Matrix<Double>, _ y: Matrix<Double>) -> Matrix<Double> { let yInv = inv(y) precondition(x.columns == yInv.rows, "Matrix dimensions not compatible") return mul(x, yInv) } public func div(_ x: Matrix<Float>, _ y: Matrix<Float>) -> Matrix<Float> { let yInv = inv(y) precondition(x.columns == yInv.rows, "Matrix dimensions not compatible") return mul(x, yInv) } public func pow(_ x: Matrix<Double>, _ y: Double) -> Matrix<Double> { var result = Matrix<Double>(rows: x.rows, columns: x.columns, repeatedValue: 0.0) result.grid = pow(x.grid, y) return result } public func pow(_ x: Matrix<Float>, _ y: Float) -> Matrix<Float> { var result = Matrix<Float>(rows: x.rows, columns: x.columns, repeatedValue: 0.0) result.grid = pow(x.grid, y) return result } public func exp(_ x: Matrix<Double>) -> Matrix<Double> { var result = Matrix<Double>(rows: x.rows, columns: x.columns, repeatedValue: 0.0) result.grid = exp(x.grid) return result } public func exp(_ x: Matrix<Float>) -> Matrix<Float> { var result = Matrix<Float>(rows: x.rows, columns: x.columns, repeatedValue: 0.0) result.grid = exp(x.grid) return result } public func sum(_ x: Matrix<Double>, axies: MatrixAxies = .column) -> Matrix<Double> { switch axies { case .column: var result = Matrix<Double>(rows: 1, columns: x.columns, repeatedValue: 0.0) for i in 0..<x.columns { result.grid[i] = sum(x[column: i]) } return result case .row: var result = Matrix<Double>(rows: x.rows, columns: 1, repeatedValue: 0.0) for i in 0..<x.rows { result.grid[i] = sum(x[row: i]) } return result } } public func sum(_ x: Matrix<Float>, axies: MatrixAxies = .column) -> Matrix<Float> { switch axies { case .column: var result = Matrix<Float>(rows: 1, columns: x.columns, repeatedValue: 0.0) for i in 0..<x.columns { result.grid[i] = sum(x[column: i]) } return result case .row: var result = Matrix<Float>(rows: x.rows, columns: 1, repeatedValue: 0.0) for i in 0..<x.rows { result.grid[i] = sum(x[row: i]) } return result } } public func inv(_ x: Matrix<Float>) -> Matrix<Float> { precondition(x.rows == x.columns, "Matrix must be square") var results = x var ipiv = [__CLPK_integer](repeating: 0, count: x.rows * x.rows) var lwork = __CLPK_integer(x.columns * x.columns) var work = [CFloat](repeating: 0.0, count: Int(lwork)) var error: __CLPK_integer = 0 var nc = __CLPK_integer(x.columns) withUnsafeMutablePointers(&nc, &lwork, &error) { nc, lwork, error in withUnsafeMutableMemory(&ipiv, &work, &(results.grid)) { ipiv, work, grid in sgetrf_(nc, nc, grid.pointer, nc, ipiv.pointer, error) sgetri_(nc, grid.pointer, nc, ipiv.pointer, work.pointer, lwork, error) } } assert(error == 0, "Matrix not invertible") return results } public func inv(_ x: Matrix<Double>) -> Matrix<Double> { precondition(x.rows == x.columns, "Matrix must be square") var results = x var ipiv = [__CLPK_integer](repeating: 0, count: x.rows * x.rows) var lwork = __CLPK_integer(x.columns * x.columns) var work = [CDouble](repeating: 0.0, count: Int(lwork)) var error: __CLPK_integer = 0 var nc = __CLPK_integer(x.columns) withUnsafeMutablePointers(&nc, &lwork, &error) { nc, lwork, error in withUnsafeMutableMemory(&ipiv, &work, &(results.grid)) { ipiv, work, grid in dgetrf_(nc, nc, grid.pointer, nc, ipiv.pointer, error) dgetri_(nc, grid.pointer, nc, ipiv.pointer, work.pointer, lwork, error) } } assert(error == 0, "Matrix not invertible") return results } public func transpose(_ x: Matrix<Float>) -> Matrix<Float> { var results = Matrix<Float>(rows: x.columns, columns: x.rows, repeatedValue: 0.0) results.grid.withUnsafeMutableBufferPointer { pointer in vDSP_mtrans(x.grid, 1, pointer.baseAddress!, 1, vDSP_Length(x.columns), vDSP_Length(x.rows)) } return results } public func transpose(_ x: Matrix<Double>) -> Matrix<Double> { var results = Matrix<Double>(rows: x.columns, columns: x.rows, repeatedValue: 0.0) results.grid.withUnsafeMutableBufferPointer { pointer in vDSP_mtransD(x.grid, 1, pointer.baseAddress!, 1, vDSP_Length(x.columns), vDSP_Length(x.rows)) } return results } /// Computes the matrix determinant. public func det(_ x: Matrix<Float>) -> Float? { var decomposed = x var pivots = [__CLPK_integer](repeating: 0, count: min(x.rows, x.columns)) var info = __CLPK_integer() var m = __CLPK_integer(x.rows) var n = __CLPK_integer(x.columns) _ = withUnsafeMutableMemory(&pivots, &(decomposed.grid)) { ipiv, grid in withUnsafeMutablePointers(&m, &n, &info) { m, n, info in sgetrf_(m, n, grid.pointer, m, ipiv.pointer, info) } } if info != 0 { return nil } var det = 1 as Float for (i, p) in zip(pivots.indices, pivots) { if p != i + 1 { det = -det * decomposed[i, i] } else { det = det * decomposed[i, i] } } return det } /// Computes the matrix determinant. public func det(_ x: Matrix<Double>) -> Double? { var decomposed = x var pivots = [__CLPK_integer](repeating: 0, count: min(x.rows, x.columns)) var info = __CLPK_integer() var m = __CLPK_integer(x.rows) var n = __CLPK_integer(x.columns) _ = withUnsafeMutableMemory(&pivots, &(decomposed.grid)) { ipiv, grid in withUnsafeMutablePointers(&m, &n, &info) { m, n, info in dgetrf_(m, n, grid.pointer, m, ipiv.pointer, info) } } if info != 0 { return nil } var det = 1 as Double for (i, p) in zip(pivots.indices, pivots) { if p != i + 1 { det = -det * decomposed[i, i] } else { det = det * decomposed[i, i] } } return det } // Convert the result of dgeev into an array of complex numbers // See Intel's documentation on column-major results for sample code that this // is based on: // https://software.intel.com/sites/products/documentation/doclib/mkl_sa/11/mkl_lapack_examples/dgeev.htm private func buildEigenVector<Scalar: FloatingPoint & ExpressibleByFloatLiteral>(eigenValueImaginaryParts: [Scalar], eigenVectorWork: [Scalar], result: inout [[(Scalar, Scalar)]]) { // row and col count are the same because result must be square. let rowColCount = result.count for row in 0..<rowColCount { var col = 0 while col < rowColCount { if eigenValueImaginaryParts[col] == 0.0 { // v is column-major result[row][col] = (eigenVectorWork[row+rowColCount*col], 0.0) col += 1 } else { // v is column-major result[row][col] = (eigenVectorWork[row+col*rowColCount], eigenVectorWork[row+rowColCount*(col+1)]) result[row][col+1] = (eigenVectorWork[row+col*rowColCount], -eigenVectorWork[row+rowColCount*(col+1)]) col += 2 } } } } /// Decomposes a square matrix into its eigenvalues and left and right eigenvectors. /// The decomposition may result in complex numbers, represented by (Float, Float), which /// are the (real, imaginary) parts of the complex number. /// - Parameters: /// - x: a square matrix /// - Returns: a struct with the eigen values and left and right eigen vectors using (Float, Float) /// to represent a complex number. public func eigenDecompose(_ x: Matrix<Float>) throws -> MatrixEigenDecompositionResult<Float> { var input = Matrix<Double>(rows: x.rows, columns: x.columns, repeatedValue: 0.0) input.grid = x.grid.map { Double($0) } let decomposition = try eigenDecompose(input) return MatrixEigenDecompositionResult<Float>( eigenValues: decomposition.eigenValues.map { (Float($0.0), Float($0.1)) }, leftEigenVectors: decomposition.leftEigenVectors.map { $0.map { (Float($0.0), Float($0.1)) } }, rightEigenVectors: decomposition.rightEigenVectors.map { $0.map { (Float($0.0), Float($0.1)) } } ) } /// Decomposes a square matrix into its eigenvalues and left and right eigenvectors. /// The decomposition may result in complex numbers, represented by (Double, Double), which /// are the (real, imaginary) parts of the complex number. /// - Parameters: /// - x: a square matrix /// - Returns: a struct with the eigen values and left and right eigen vectors using (Double, Double) /// to represent a complex number. public func eigenDecompose(_ x: Matrix<Double>) throws -> MatrixEigenDecompositionResult<Double> { guard x.rows == x.columns else { throw EigenDecompositionError.matrixNotSquare } // dgeev_ needs column-major matrices, so transpose x. var matrixGrid: [__CLPK_doublereal] = transpose(x).grid var matrixRowCount = __CLPK_integer(x.rows) let matrixColCount = matrixRowCount var eigenValueCount = matrixRowCount var leftEigenVectorCount = matrixRowCount var rightEigenVectorCount = matrixRowCount var workspaceQuery: Double = 0.0 var workspaceSize = __CLPK_integer(-1) var error: __CLPK_integer = 0 var eigenValueRealParts = [Double](repeating: 0, count: Int(eigenValueCount)) var eigenValueImaginaryParts = [Double](repeating: 0, count: Int(eigenValueCount)) var leftEigenVectorWork = [Double](repeating: 0, count: Int(leftEigenVectorCount * matrixColCount)) var rightEigenVectorWork = [Double](repeating: 0, count: Int(rightEigenVectorCount * matrixColCount)) let decompositionJobV = UnsafeMutablePointer<Int8>(mutating: ("V" as NSString).utf8String) // Call dgeev to find out how much workspace to allocate dgeev_(decompositionJobV, decompositionJobV, &matrixRowCount, &matrixGrid, &eigenValueCount, &eigenValueRealParts, &eigenValueImaginaryParts, &leftEigenVectorWork, &leftEigenVectorCount, &rightEigenVectorWork, &rightEigenVectorCount, &workspaceQuery, &workspaceSize, &error) if error != 0 { throw EigenDecompositionError.matrixNotDecomposable } // Allocate the workspace and call dgeev again to do the actual decomposition var workspace = [Double](repeating: 0.0, count: Int(workspaceQuery)) workspaceSize = __CLPK_integer(workspaceQuery) dgeev_(decompositionJobV, decompositionJobV, &matrixRowCount, &matrixGrid, &eigenValueCount, &eigenValueRealParts, &eigenValueImaginaryParts, &leftEigenVectorWork, &leftEigenVectorCount, &rightEigenVectorWork, &rightEigenVectorCount, &workspace, &workspaceSize, &error) if error != 0 { throw EigenDecompositionError.matrixNotDecomposable } return MatrixEigenDecompositionResult<Double>(rowCount: x.rows, eigenValueRealParts: eigenValueRealParts, eigenValueImaginaryParts: eigenValueImaginaryParts, leftEigenVectorWork: leftEigenVectorWork, rightEigenVectorWork: rightEigenVectorWork) } // MARK: - Operators public func + (lhs: Matrix<Float>, rhs: Matrix<Float>) -> Matrix<Float> { return add(lhs, rhs) } public func + (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> { return add(lhs, rhs) } public func - (lhs: Matrix<Float>, rhs: Matrix<Float>) -> Matrix<Float> { return sub(lhs, rhs) } public func - (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> { return sub(lhs, rhs) } public func + (lhs: Matrix<Float>, rhs: Float) -> Matrix<Float> { return Matrix(rows: lhs.rows, columns: lhs.columns, grid: lhs.grid + rhs) } public func + (lhs: Matrix<Double>, rhs: Double) -> Matrix<Double> { return Matrix(rows: lhs.rows, columns: lhs.columns, grid: lhs.grid + rhs) } public func * (lhs: Float, rhs: Matrix<Float>) -> Matrix<Float> { return mul(lhs, rhs) } public func * (lhs: Double, rhs: Matrix<Double>) -> Matrix<Double> { return mul(lhs, rhs) } public func * (lhs: Matrix<Float>, rhs: Matrix<Float>) -> Matrix<Float> { return mul(lhs, rhs) } public func * (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> { return mul(lhs, rhs) } public func / (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> { return div(lhs, rhs) } public func / (lhs: Matrix<Float>, rhs: Matrix<Float>) -> Matrix<Float> { return div(lhs, rhs) } public func / (lhs: Matrix<Double>, rhs: Double) -> Matrix<Double> { var result = Matrix<Double>(rows: lhs.rows, columns: lhs.columns, repeatedValue: 0.0) result.grid = lhs.grid / rhs return result } public func / (lhs: Matrix<Float>, rhs: Float) -> Matrix<Float> { var result = Matrix<Float>(rows: lhs.rows, columns: lhs.columns, repeatedValue: 0.0) result.grid = lhs.grid / rhs return result } postfix operator ′ public postfix func ′ (value: Matrix<Float>) -> Matrix<Float> { return transpose(value) } public postfix func ′ (value: Matrix<Double>) -> Matrix<Double> { return transpose(value) }
36.624813
278
0.652437
8709fcc8de6163cf588270376b9d95b8f4686f6a
2,920
// // TableSectionConverter.swift // IngenicoConnectExample // // Created for Ingenico ePayments on 15/12/2016. // Copyright © 2016 Global Collect Services. All rights reserved. // import Foundation import IngenicoConnectKit class TableSectionConverter { static func paymentProductsTableSectionFromAccounts(onFile accountsOnFile: [AccountOnFile], paymentItems: PaymentItems) -> PaymentProductsTableSection { let section = PaymentProductsTableSection() section.type = .gcAccountOnFileType for accountOnFile in accountsOnFile.sorted(by: { (a, b) -> Bool in return paymentItems.paymentItem(withIdentifier:a.paymentProductIdentifier)?.displayHints.displayOrder ?? Int.max < paymentItems.paymentItem(withIdentifier:b.paymentProductIdentifier)?.displayHints.displayOrder ?? Int.max; }) { if let product = paymentItems.paymentItem(withIdentifier: accountOnFile.paymentProductIdentifier) { let row = PaymentProductsTableRow() let displayName = accountOnFile.label row.name = displayName row.accountOnFileIdentifier = accountOnFile.identifier row.paymentProductIdentifier = accountOnFile.paymentProductIdentifier row.logo = product.displayHints.logoImage section.rows.append(row) } } return section } static func paymentProductsTableSection(from paymentItems: PaymentItems) -> PaymentProductsTableSection { let section = PaymentProductsTableSection() for paymentItem in paymentItems.paymentItems.sorted(by: { (a, b) -> Bool in return a.displayHints.displayOrder ?? Int.max < b.displayHints.displayOrder ?? Int.max }) { section.type = .gcPaymentProductType let row = PaymentProductsTableRow() let paymentProductKey = localizationKey(with: paymentItem) let paymentProductValue = NSLocalizedString(paymentProductKey, tableName: SDKConstants.kSDKLocalizable, bundle: AppConstants.sdkBundle, value: "", comment: "") row.name = paymentProductValue row.accountOnFileIdentifier = "" row.paymentProductIdentifier = paymentItem.identifier row.logo = paymentItem.displayHints.logoImage section.rows.append(row) } return section } static func localizationKey(with paymentItem: BasicPaymentItem) -> String { switch paymentItem { case is BasicPaymentProduct: return "gc.general.paymentProducts.\(paymentItem.identifier).name" case is BasicPaymentProductGroup: return "gc.general.paymentProductGroups.\(paymentItem.identifier).name" default: return "" } } }
41.126761
233
0.655479
564448490b08e077696275308949c2ed965965e0
1,083
import Foundation /** AeroGear Services Security SDK SDK provides a way for the developer to perform security checks on the device their code is running on */ public class AgsSecurity { /** The initialise method of AgsSecurity */ public init() {} /** - Perform a security check on a device. - Parameter check: The security check to be performed - Returns: A SecurityCheckResult with a true or false property 'passed' */ public func check(_ check: SecurityCheck) -> SecurityCheckResult { return check.check() } /** - Perform multiple security checks on a device - Parameter checks: The security checks to be performed - Returns: An array of type SecurityCheckResult with a true or false property 'passed' for each result */ public func checkMany(_ checks: [SecurityCheck]) -> [SecurityCheckResult] { var completedChecks: [SecurityCheckResult] = [] for value in checks { completedChecks.append(check(value)) } return completedChecks } }
27.075
107
0.662973
c167967608556fc70a428f7805af16efd955d27a
4,172
// // ViewController.swift // Demo // // Created by Jawad Ali on 06/10/2021. // import UIKit import JDAnimatedField class ViewController: UIViewController { private lazy var fieldCenter: JDAnimatedTextField = { let field = JDAnimatedTextField() field.translatesAutoresizingMaskIntoConstraints = false field.placeholder = "search" field.textFieldColor = #colorLiteral(red: 1, green: 0.2591625452, blue: 0.3741788268, alpha: 1) field.delegate = self field.spellCheckingType = .no field.textAlignment = .center return field }() private lazy var fieldRight: JDAnimatedTextField = { let field = JDAnimatedTextField() field.translatesAutoresizingMaskIntoConstraints = false field.placeholder = "Right" field.textFieldColor = #colorLiteral(red: 0.3220693469, green: 0.01451195218, blue: 0.5633357763, alpha: 1) field.placeHolderFont = UIFont.boldSystemFont(ofSize: 14) field.delegate = self field.lineWidth = 1 field.spellCheckingType = .no field.textAlignment = .right return field }() private lazy var fieldSmall: JDAnimatedTextField = { let field = JDAnimatedTextField() field.translatesAutoresizingMaskIntoConstraints = false field.placeholder = "Small" field.textFieldColor = #colorLiteral(red: 0.6679978967, green: 0.4751212597, blue: 0.2586010993, alpha: 1) field.placeHolderFont = UIFont.systemFont(ofSize: 14) field.delegate = self field.lineWidth = 0.5 field.spellCheckingType = .no field.textAlignment = .center return field }() private lazy var fieldMid: JDAnimatedTextField = { let field = JDAnimatedTextField() field.translatesAutoresizingMaskIntoConstraints = false field.placeholder = "Medium" field.textFieldColor = #colorLiteral(red: 1, green: 0.6235294118, blue: 0.03921568627, alpha: 1) field.delegate = self field.placeHolderFont = UIFont.systemFont(ofSize: 16) field.lineWidth = 5 field.spellCheckingType = .no field.textAlignment = .left return field }() private lazy var fieldLeft: JDAnimatedTextField = { let field = JDAnimatedTextField() field.translatesAutoresizingMaskIntoConstraints = false field.placeholder = "Left" field.textFieldColor = #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1) field.lineWidth = 2 field.placeHolderFont = UIFont.systemFont(ofSize: 20) field.delegate = self field.spellCheckingType = .no field.textAlignment = .left return field }() private lazy var stack: UIStackView = { let stack = UIStackView() stack.alignment = .center stack.axis = .vertical stack.spacing = 50 stack.distribution = .fillEqually stack.translatesAutoresizingMaskIntoConstraints = false return stack }() override func viewDidLoad() { super.viewDidLoad() setupView() setupConstraints() } } extension ViewController: UITextFieldDelegate { public func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() if textField == fieldMid { fieldMid.showError(with: "Error message here") } return true } open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { false } } private extension ViewController { func setupView() { [fieldCenter, fieldLeft, fieldRight, fieldSmall, fieldMid].forEach(stack.addArrangedSubview) view.addSubview(stack) } func setupConstraints() { NSLayoutConstraint.activate([ stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50), stack.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20), stack.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20), fieldSmall.widthAnchor.constraint(equalToConstant: 200), fieldMid.widthAnchor.constraint(equalToConstant: 260), fieldCenter.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -40), fieldRight.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -40), fieldLeft.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -40) ]) } }
33.376
111
0.722435
fb19f30115ad5f1e2d9cea151939e13b9ad263a9
3,239
import UIKit import Accounts import EventBox import KeyClip import TwitterAPI import OAuthSwift import SwiftyJSON import Async import Reachability class TwitterSearchStreaming { var request: StreamingRequest? let account: Account let receiveStatus: ((TwitterStatus) -> Void) let connected: (() -> Void) let disconnected: (() -> Void) var status = Twitter.ConnectionStatus.disconnected init(account: Account, receiveStatus: @escaping ((TwitterStatus) -> Void), connected: @escaping (() -> Void), disconnected: @escaping (() -> Void)) { self.account = account self.receiveStatus = receiveStatus self.connected = connected self.disconnected = disconnected } func start(_ track: String) -> TwitterSearchStreaming { NSLog("TwitterSearchStreaming: start") request = account.client .streaming("https://stream.twitter.com/1.1/statuses/filter.json", parameters: ["track": track]) .progress(progress) .completion(completion) .start() status = .connecting return self } func stop() { NSLog("TwitterSearchStreaming: stop") status = .disconnecting request?.stop() } func progress(_ data: Data) { if self.status != .connected { self.status = .connected Async.main { self.connected() } } let responce = JSON(data: data) if responce["text"] == nil { return } let sourceUserID = account.userID let status = TwitterStatus(responce, connectionID: "") let quotedUserID = status.quotedStatus?.user.userID let retweetUserID = status.actionedBy != nil && status.type != .favorite ? status.actionedBy?.userID : nil Relationship.check(sourceUserID, targetUserID: status.user.userID, retweetUserID: retweetUserID, quotedUserID: quotedUserID) { (blocking, muting, noRetweets) -> Void in if blocking || muting || noRetweets { NSLog("skip blocking:\(blocking) muting:\(muting) noRetweets:\(noRetweets) text:\(status.text)") return } Async.main { self.receiveStatus(status) } } } func completion(_ responseData: Data?, response: URLResponse?, error: NSError?) { status = .disconnected Async.main { self.disconnected() } if let response = response as? HTTPURLResponse { NSLog("TwitterSearchStreaming [connectionDidFinishLoading] code:\(response.statusCode) data:\(NSString(data: responseData!, encoding: String.Encoding.utf8.rawValue))") if response.statusCode == 420 { // Rate Limited // The client has connected too frequently. For example, an endpoint returns this status if: // - A client makes too many login attempts in a short period of time. // - Too many copies of an application attempt to authenticate with the same credentials. ErrorAlert.show("Streaming API Rate Limited", message: "The client has connected too frequently.") } } } }
37.229885
179
0.614696
16105d329fde25c128756abe20256fc1e351dec7
19,130
// // AerialView.swift // Aerial // // Created by John Coates on 10/22/15. // Copyright © 2015 John Coates. All rights reserved. // import Foundation import ScreenSaver import AVFoundation import AVKit @objc(AerialView) // swiftlint:disable:next type_body_length final class AerialView: ScreenSaverView, CAAnimationDelegate { var layerManager: LayerManager var playerLayer: AVPlayerLayer! static var players: [AVPlayer] = [AVPlayer]() static var previewPlayer: AVPlayer? static var previewView: AerialView? var player: AVPlayer? var currentVideo: AerialVideo? var preferencesController: PreferencesWindowController? var observerWasSet = false var hasStartedPlaying = false var wasStopped = false var isDisabled = false var isQuickFading = false var brightnessToRestore: Float? // We use this for tentative Catalina bug workaround var originalWidth, originalHeight: CGFloat // Tentative improvement when only one video in playlist var shouldLoop = false static var shouldFade: Bool { return (PrefsVideos.fadeMode != .disabled) } static var fadeDuration: Double { switch PrefsVideos.fadeMode { case .t0_5: return 0.5 case .t1: return 1 case .t2: return 2 default: return 0.10 } } static var textFadeDuration: Double { switch PrefsInfo.fadeModeText { case .t0_5: return 0.5 case .t1: return 1 case .t2: return 2 default: return 0.10 } } // Mirrored/cloned viewing mode and Spanned viewing mode share the same player for sync & ressource saving static var sharingPlayers: Bool { switch PrefsDisplays.viewingMode { case .cloned, .mirrored, .spanned: return true default: return false } } static var sharedViews: [AerialView] = [] // Because of lifecycle in Preview, we may pile up old/no longer // shared instanciated views that we need to track to not reuse static var instanciatedViews: [AerialView] = [] // MARK: - Shared Player static var singlePlayerAlreadySetup: Bool = false static var sharedPlayerIndex: Int? static var didSkipMain: Bool = false class var sharedPlayer: AVPlayer { struct Static { static let instance: AVPlayer = AVPlayer() // swiftlint:disable:next identifier_name static var _player: AVPlayer? static var player: AVPlayer { if let activePlayer = _player { return activePlayer } _player = AVPlayer() return _player! } } return Static.player } // MARK: - Init / Setup // This is the one used by System Preferences/ScreenSaverEngine override init?(frame: NSRect, isPreview: Bool) { // legacyScreenSaver always return true for isPreview on Catalina // We need to detect and override ourselves var preview = false self.originalWidth = frame.width self.originalHeight = frame.height if frame.width < 400 && frame.height < 300 { preview = true } // This is where we manage our location info layers, clock, etc self.layerManager = LayerManager(isPreview: preview) super.init(frame: frame, isPreview: preview) debugLog("avInit .saver \(frame) p: \(isPreview) o: \(preview)") self.animationTimeInterval = 1.0 / 30.0 setup() } // This is the one used by our App target used for debugging required init?(coder: NSCoder) { self.layerManager = LayerManager(isPreview: false) // ... self.originalWidth = 0 self.originalHeight = 0 super.init(coder: coder) self.originalWidth = frame.width self.originalHeight = frame.height debugLog("avInit .app") setup() } deinit { debugLog("\(self.description) deinit AerialView") NotificationCenter.default.removeObserver(self) // set player item to nil if not preview player if player != AerialView.previewPlayer { player?.rate = 0 player?.replaceCurrentItem(with: nil) } guard let player = self.player else { return } // Remove from player index let indexMaybe = AerialView.players.firstIndex(of: player) guard let index = indexMaybe else { return } AerialView.players.remove(at: index) } // swiftlint:disable:next cyclomatic_complexity func setup() { if let version = Bundle(identifier: "hu.czo.Aerial")?.infoDictionary?["CFBundleShortVersionString"] as? String { debugLog("\(self.description) AerialView setup init (V\(version)) preview: \(self.isPreview)") } let preferences = Preferences.sharedInstance // Check early if we need to enable power saver mode, // black screen with minimal brightness if !isPreview { if (PrefsVideos.onBatteryMode == .alwaysDisabled && Battery.isUnplugged()) || (PrefsVideos.onBatteryMode == .disableOnLow && Battery.isLow()) { debugLog("Engaging power saving mode") isDisabled = true return } } // Shared views can get stuck, we may need to clean them up here cleanupSharedViews() // We look for the screen in our detected list. // In case of preview or unknown screen result will be nil let displayDetection = DisplayDetection.sharedInstance let thisScreen = displayDetection.findScreenWith(frame: self.frame) var localPlayer: AVPlayer? debugLog("Using : \(String(describing: thisScreen))") // Is the current screen disabled by user ? if !isPreview { // If it's an unknown screen, we leave it enabled if let screen = thisScreen { if !displayDetection.isScreenActive(id: screen.id) { // Then we disable and exit debugLog("This display is not active, disabling") isDisabled = true return } } } else { AerialView.previewView = self } // Track which views are sharing the sharedPlayer if AerialView.sharingPlayers { AerialView.sharedViews.append(self) } // We track all instanciated views here, independand of their shared status AerialView.instanciatedViews.append(self) // Setup the AVPlayer if AerialView.sharingPlayers { localPlayer = AerialView.sharedPlayer } else { localPlayer = AVPlayer() } guard let player = localPlayer else { errorLog("\(self.description) Couldn't create AVPlayer!") return } self.player = player if isPreview { AerialView.previewPlayer = player } else if !AerialView.sharingPlayers { // add to player list AerialView.players.append(player) } setupPlayerLayer(withPlayer: player) // In mirror mode we use the main instance player if AerialView.sharingPlayers && AerialView.singlePlayerAlreadySetup { self.playerLayer.player = AerialView.instanciatedViews[AerialView.sharedPlayerIndex!].player self.playerLayer.opacity = 0 return } // We're never sharing the preview ! if !isPreview { AerialView.singlePlayerAlreadySetup = true AerialView.sharedPlayerIndex = AerialView.instanciatedViews.count-1 } ManifestLoader.instance.addCallback { _ in self.playNextVideo() } } override func viewDidChangeBackingProperties() { //swiftlint:disable:next line_length debugLog("\(self.description) backing change \((self.window?.backingScaleFactor) ?? 1.0) isDisabled: \(isDisabled) frame: \(self.frame) preview: \(self.isPreview)") // Tentative workaround for a Catalina bug if self.frame.width < 300 && !isPreview { debugLog("*** Frame size bug, trying to override to \(originalWidth)x\(originalHeight)!") self.frame = CGRect(x: 0, y: 0, width: originalWidth, height: originalHeight) } if !isDisabled { self.layer!.contentsScale = (self.window?.backingScaleFactor) ?? 1.0 self.playerLayer.contentsScale = (self.window?.backingScaleFactor) ?? 1.0 // And our additional layers layerManager.setContentScale(scale: (self.window?.backingScaleFactor) ?? 1.0) } /* // TMP TEST if self.window?.backingScaleFactor == 1.0 { debugLog("*** Forcing retina 2.0") self.layer!.contentsScale = 2.0 self.playerLayer.contentsScale = 2.0 // And our additional layers layerManager.setContentScale(scale: 2.0) } */ } // On previews, it's possible that our shared player was stopped and is not reusable func cleanupSharedViews() { if AerialView.singlePlayerAlreadySetup { if AerialView.instanciatedViews[AerialView.sharedPlayerIndex!].wasStopped { AerialView.singlePlayerAlreadySetup = false AerialView.sharedPlayerIndex = nil AerialView.instanciatedViews = [AerialView]() // Clear the list of instanciated stuff AerialView.sharedViews = [AerialView]() // And the list of sharedViews } } } // MARK: - Lifecycle stuff override func startAnimation() { super.startAnimation() debugLog("\(self.description) startAnimation frame \(self.frame) bounds \(self.bounds)") if !isDisabled { // Previews may be restarted, but our layer will get hidden (somehow) so show it back if isPreview && player?.currentTime() != CMTime.zero { debugLog("restarting playback") playerLayer.opacity = 1 player?.play() } } } override func stopAnimation() { super.stopAnimation() wasStopped = true debugLog("\(self.description) stopAnimation") if !isDisabled { player?.pause() } let preferences = Preferences.sharedInstance } // Wait for the player to be ready // swiftlint:disable:next block_based_kvo internal override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { debugLog("\(self.description) observeValue \(String(describing: keyPath)) \(self.playerLayer.isReadyForDisplay) \(self.frame)") if self.playerLayer.isReadyForDisplay { self.player!.play() hasStartedPlaying = true debugLog("start playback: \(self.frame) \(self.bounds)") // If we share a player, we need to add the fades and the text to all the // instanciated views using it (eg: in mirrored mode) if AerialView.sharingPlayers { for view in AerialView.sharedViews { self.addPlayerFades(view: view, player: self.player!, video: self.currentVideo!) view.layerManager.setupLayersForVideo(video: self.currentVideo!, player: self.player!) } } else { self.addPlayerFades(view: self, player: self.player!, video: self.currentVideo!) self.layerManager.setupLayersForVideo(video: self.currentVideo!, player: self.player!) } } } // MARK: - playNextVideo() func playNextVideo() { print("-/-/-/ PNV") let notificationCenter = NotificationCenter.default // Clear everything layerManager.clearLayerAnimations(player: self.player!) for view in AerialView.sharedViews { view.layerManager.clearLayerAnimations(player: self.player!) } // remove old entries notificationCenter.removeObserver(self) let player = AVPlayer() // play another video let oldPlayer = self.player self.player = player player.isMuted = PrefsAdvanced.muteSound // player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil) self.playerLayer.player = self.player if AerialView.shouldFade { self.playerLayer.opacity = 0 } else { self.playerLayer.opacity = 1.0 } if self.isPreview { AerialView.previewPlayer = player } debugLog("\(self.description) Setting player for all player layers in \(AerialView.sharedViews)") for view in AerialView.sharedViews { view.playerLayer.player = player } if oldPlayer == AerialView.previewPlayer { AerialView.previewView?.playerLayer.player = self.player } // get a list of current videos that should be excluded from the candidate selection // for the next video. This prevents the same video from being shown twice in a row // as well as the same video being shown on two different monitors even when sharingPlayers // is false let currentVideos: [AerialVideo] = AerialView.players.compactMap { (player) -> AerialVideo? in (player.currentItem as? AerialPlayerItem)?.video } let (randomVideo, pshouldLoop) = ManifestLoader.instance.randomVideo(excluding: currentVideos) // If we only have one video in the playlist, we can rewind it for seamless transitions self.shouldLoop = pshouldLoop guard let video = randomVideo else { errorLog("\(self.description) Error grabbing random video!") return } self.currentVideo = video // Workaround to avoid local playback making network calls let item = AerialPlayerItem(video: video) if !video.isAvailableOffline { player.replaceCurrentItem(with: item) debugLog("\(self.description) streaming video (not fully available offline) : \(video.url)") } else { let localurl = URL(fileURLWithPath: VideoCache.cachePath(forVideo: video)!) let localitem = AVPlayerItem(url: localurl) player.replaceCurrentItem(with: localitem) debugLog("\(self.description) playing video (OFFLINE MODE) : \(localurl)") } guard let currentItem = player.currentItem else { errorLog("\(self.description) No current item!") return } debugLog("\(self.description) observing current item \(currentItem)") // Descriptions and fades are set when we begin playback if !observerWasSet { observerWasSet = true playerLayer.addObserver(self, forKeyPath: "readyForDisplay", options: .initial, context: nil) } notificationCenter.addObserver(self, selector: #selector(AerialView.playerItemDidReachEnd(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: currentItem) notificationCenter.addObserver(self, selector: #selector(AerialView.playerItemNewErrorLogEntryNotification(_:)), name: NSNotification.Name.AVPlayerItemNewErrorLogEntry, object: currentItem) notificationCenter.addObserver(self, selector: #selector(AerialView.playerItemFailedtoPlayToEnd(_:)), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: currentItem) notificationCenter.addObserver(self, selector: #selector(AerialView.playerItemPlaybackStalledNotification(_:)), name: NSNotification.Name.AVPlayerItemPlaybackStalled, object: currentItem) player.actionAtItemEnd = AVPlayer.ActionAtItemEnd.none } override var acceptsFirstResponder: Bool { // swiftlint:disable:next implicit_getter get { return true } } // MARK: - Extra Animations private func fastFadeOut(andPlayNext: Bool) { // We need to clear the current animations running on playerLayer isQuickFading = true // Lock the use of keydown playerLayer.removeAllAnimations() let fadeOutAnimation = CAKeyframeAnimation(keyPath: "opacity") fadeOutAnimation.values = [1, 0] as [Int] fadeOutAnimation.keyTimes = [0, AerialView.fadeDuration] as [NSNumber] fadeOutAnimation.duration = AerialView.fadeDuration fadeOutAnimation.delegate = self fadeOutAnimation.isRemovedOnCompletion = false fadeOutAnimation.calculationMode = CAAnimationCalculationMode.cubic if andPlayNext { playerLayer.add(fadeOutAnimation, forKey: "quickfadeandnext") } else { playerLayer.add(fadeOutAnimation, forKey: "quickfade") } } // Stop callback for fastFadeOut func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { isQuickFading = false // Release our ugly lock playerLayer.opacity = 0 if anim == playerLayer.animation(forKey: "quickfadeandnext") { debugLog("stop and next") playerLayer.removeAllAnimations() // Make sure we get rid of our anim playNextVideo() } else { debugLog("stop") playerLayer.removeAllAnimations() // Make sure we get rid of our anim } } // Create a move animation func createMoveAnimation(layer: CALayer, to: CGPoint, duration: Double) -> CABasicAnimation { let moveAnimation = CABasicAnimation(keyPath: "position") moveAnimation.fromValue = layer.position moveAnimation.toValue = to moveAnimation.duration = duration layer.position = to return moveAnimation } // MARK: - Preferences override var hasConfigureSheet: Bool { return true } override var configureSheet: NSWindow? { if let controller = preferencesController { return controller.window } let controller = PreferencesWindowController(windowNibName: "PreferencesWindow") preferencesController = controller return controller.window } }
35.891182
172
0.608364
f45f88e0a954746fbda29daf3d4b56e193787eb9
1,100
// // MapLocationController.swift // CWWeChat // // Created by wei chen on 2017/9/20. // Copyright © 2017年 cwwise. All rights reserved. // import UIKit import MapKit protocol MapLocationControllerDelegate: class { func sendLocation(_ location: CLLocationCoordinate2D) } class MapLocationController: UIViewController { weak var delegate: MapLocationControllerDelegate? var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() mapView = MKMapView(frame: self.view.bounds) mapView.delegate = self self.view.addSubview(mapView) let sendItem = UIBarButtonItem(title: "发送", style: .done, target: self, action: #selector(sendLocation)) self.navigationItem.rightBarButtonItem = sendItem } @objc func sendLocation() { // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension MapLocationController: MKMapViewDelegate { }
21.568627
112
0.656364
72677ab8d3b0c0711171865826ed384f79f18231
2,057
import UIKit class GuiLiteImage { let width, height, colorBytes : Int let buffer: UnsafeMutableRawPointer init(width: Int, height: Int, colorBytes: Int) { self.width = width self.height = height self.colorBytes = colorBytes self.buffer = malloc(width * height * 4) } func getUiImage() -> CGImage?{ let pixData = (colorBytes == 2) ? getPixelsFrom16bits() : getPixelsFrom32bits() if(pixData == nil){ return nil } let providerRef = CGDataProvider(data: pixData!) let bitmapInfo:CGBitmapInfo = [.byteOrder32Little, CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue)] return CGImage(width: Int(width), height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo, provider: providerRef!, decode: nil, shouldInterpolate: true, intent: .defaultIntent) } func getPixelsFrom16bits()->CFData?{ let rawData = getUiOfHelloWave() if rawData == nil{ return nil } for index in 0..<width * height { let rgb16 = rawData?.load(fromByteOffset: index * 2, as: UInt16.self) let rgb32 = UInt32(rgb16!) let color = ((rgb32 & 0xF800) << 8 | ((rgb32 & 0x7E0) << 5) | ((rgb32 & 0x1F) << 3)) buffer.storeBytes(of: color, toByteOffset: index * 4, as: UInt32.self) } let rawPointer = UnsafeRawPointer(buffer) let pixData: UnsafePointer = rawPointer.assumingMemoryBound(to: UInt8.self) return CFDataCreate(nil, pixData, width * height * 4) } func getPixelsFrom32bits()->CFData?{ let rawData = getUiOfHelloWave() if rawData == nil{ return nil } let rawPointer = UnsafeRawPointer(rawData) let pixData: UnsafePointer = rawPointer!.assumingMemoryBound(to: UInt8.self) return CFDataCreate(nil, pixData, width * height * 4) } }
38.092593
268
0.614001
729096a01ca4a234386aa0afe6087ebb02ccfeec
446
// // TransparentNavigationBar.swift // CardCollectionView // // Created by Kyle Zaragoza on 7/11/16. // Copyright © 2016 Kyle Zaragoza. All rights reserved. // import UIKit class TransparentNavigationBar: UINavigationBar { // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } }
22.3
78
0.713004
091aa81b125e0a65f05098ef33c11b1adff81e7a
6,760
/* Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest @testable import AST @testable import Parser @testable import Lexer class ParserDeclarationStatementTests: XCTestCase { func testStartWithDeclarationKeyword() { parseStatementAndTest("import foo", "import foo", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is ImportDeclaration) }) parseStatementAndTest("let a=1", "let a = 1", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is ConstantDeclaration) }) parseStatementAndTest("var a=1", "var a = 1", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is VariableDeclaration) }) parseStatementAndTest("typealias a=b", "typealias a = b", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is TypealiasDeclaration) }) parseStatementAndTest("func f()", "func f()", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is FunctionDeclaration) }) parseStatementAndTest("enum e{}", "enum e {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is EnumDeclaration) }) parseStatementAndTest("indirect enum ie{}", "indirect enum ie {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is EnumDeclaration) }) parseStatementAndTest("struct s{}", "struct s {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is StructDeclaration) }) parseStatementAndTest("init(){}", "init() {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is InitializerDeclaration) }) parseStatementAndTest("deinit{}", "deinit {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is DeinitializerDeclaration) }) parseStatementAndTest("extension ext:base{}", "extension ext: base {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is ExtensionDeclaration) }) parseStatementAndTest("subscript(i:Int)->Element{}", "subscript(i: Int) -> Element {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is SubscriptDeclaration) }) parseStatementAndTest("subscript(i:Int)->Element{}", "subscript(i: Int) -> Element {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is SubscriptDeclaration) }) parseStatementAndTest("protocol p{}", "protocol p {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is ProtocolDeclaration) }) } func testStartWithAttributes() { parseStatementAndTest( "@discardableResult func f(){}", "@discardableResult func f() {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is FunctionDeclaration) }) parseStatementAndTest( "@available(*, unavailable, renamed: \"foo\") func f(){}", "@available(*, unavailable, renamed: \"foo\") func f() {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is FunctionDeclaration) }) parseStatementAndTest( "@a(h()t) @b(h[]t) @c(h{}t) func f(){}", "@a(h()t) @b(h[]t) @c(h{}t) func f() {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is FunctionDeclaration) }) } func testStartWithModifiers() { for modifier in Token.Kind.declarationModifiers { parseStatementAndTest("\(modifier) func f(){}", "\(modifier) func f() {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is FunctionDeclaration) }) } for modifier in Token.Kind.accessLevelModifiers { parseStatementAndTest("\(modifier) func f(){}", "\(modifier) func f() {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is FunctionDeclaration) }) } for modifier in Token.Kind.mutationModifiers { parseStatementAndTest("\(modifier) func f(){}", "\(modifier) func f() {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is FunctionDeclaration) }) } } func testClassDeclaration() { parseStatementAndTest("class c{}", "class c {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is ClassDeclaration) }) } func testOperatorDeclaration() { parseStatementAndTest("prefix operator <!>", "prefix operator <!>", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is OperatorDeclaration) }) } func testPrecedenceGroupDeclaration() { parseStatementAndTest("precedencegroup foo {}", "precedencegroup foo {}", testClosure: { stmt in XCTAssertTrue(stmt is Declaration) XCTAssertTrue(stmt is PrecedenceGroupDeclaration) }) } func testDeclarations() { let stmtParser = getParser("let a = 1 ; var b = 2 \n init() {};func foo()") do { let stmts = try stmtParser.parseStatements() XCTAssertEqual(stmts.count, 4) XCTAssertEqual(stmts.textDescription, "let a = 1\nvar b = 2\ninit() {}\nfunc foo()") XCTAssertTrue(stmts[0] is ConstantDeclaration) XCTAssertTrue(stmts[1] is VariableDeclaration) XCTAssertTrue(stmts[2] is InitializerDeclaration) XCTAssertTrue(stmts[3] is FunctionDeclaration) } catch { XCTFail("Failed in parsing a list of declarations as statements.") } } static var allTests = [ ("testStartWithDeclarationKeyword", testStartWithDeclarationKeyword), ("testStartWithAttributes", testStartWithAttributes), ("testStartWithModifiers", testStartWithModifiers), ("testClassDeclaration", testClassDeclaration), ("testOperatorDeclaration", testOperatorDeclaration), ("testPrecedenceGroupDeclaration", testPrecedenceGroupDeclaration), ("testDeclarations", testDeclarations), ] }
38.850575
114
0.689645
019dbfd16365ab174222e24333c181c1bb92f25d
2,118
/** * Copyright IBM Corporation 2017 * * 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 XCTest @testable import Kitura final class TestStack: XCTestCase, KituraTestSuite { static var allTests: [(String, (TestStack) -> () throws -> Void)] { return [ ("testEmpty", testEmpty), ("testPushPop", testPushPop) ] } func testEmpty() { let stack = Stack<Int>() XCTAssertNil(stack.topItem) } private func assertTopItem<Element: Equatable>(_ stack: Stack<Element>, item: Element) { guard let topItem = stack.topItem else { XCTFail("stack.topItem unexpectedly nil") return } XCTAssertEqual(item, topItem, "expected \(item), returned \(topItem)") } private func popAndAssert<Element: Equatable>(_ stack: inout Stack<Element>, item: Element) { let popped = stack.pop() XCTAssertEqual(item, popped, "expected \(item), returned \(popped)") } func testPushPop() { var stack = Stack<Int>() stack.push(1) assertTopItem(stack, item: 1) stack.push(2) assertTopItem(stack, item: 2) stack.push(3) assertTopItem(stack, item: 3) popAndAssert(&stack, item: 3) assertTopItem(stack, item: 2) stack.push(4) assertTopItem(stack, item: 4) popAndAssert(&stack, item: 4) assertTopItem(stack, item: 2) popAndAssert(&stack, item: 2) assertTopItem(stack, item: 1) popAndAssert(&stack, item: 1) XCTAssertNil(stack.topItem) } }
27.868421
97
0.630784
48712991a51a56e1d3d38091f85ec3796b97ea50
846
// // CombineExtTests.swift // CombineExtTests // // Created by Rogerio de Paula Assis on Jun 30, 2019. // Copyright © 2019 CombineExt. All rights reserved. // @testable import CombineExt import XCTest class CombineExtTests: XCTestCase { static var allTests = [ ("testExample", testExample), ] func testExample() { // Given let vc = UIViewController() let publisher = vc.methodInvoked(#selector(UIViewController.viewDidLoad)) let expectation = self.expectation(description: "View did load expectation") _ = publisher.sink { values in // Then XCTAssertEqual(values.count, 0) expectation.fulfill() } // When vc.viewDidLoad() self.wait(for: [expectation], timeout: 1.0) } }
23.5
84
0.593381
0e895f19ac041de3366ce9faae7016707e8ace7b
903
import GRDB import MarketKit class BlockchainSettingRecord: Record { let blockchainUid: String let key: String let value: String init(blockchainUid: String, key: String, value: String) { self.blockchainUid = blockchainUid self.key = key self.value = value super.init() } override class var databaseTableName: String { "blockchain_settings" } enum Columns: String, ColumnExpression { case blockchainUid, key, value } required init(row: Row) { blockchainUid = row[Columns.blockchainUid] key = row[Columns.key] value = row[Columns.value] super.init(row: row) } override func encode(to container: inout PersistenceContainer) { container[Columns.blockchainUid] = blockchainUid container[Columns.key] = key container[Columns.value] = value } }
22.575
68
0.640089
f96fca84ad92f4bc0db69a1db0253ff42fde0947
2,293
// // SceneDelegate.swift // todoapp // // Created by Firas Al-Doghman on 28/4/21. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.264151
147
0.712604