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
8acac30b42839ce14cc15e462ddf9851edfc5219
4,736
// // MediaKeyTapInternals.swift // Castle // // A wrapper around the C APIs required for a CGEventTap // // Created by Nicholas Hurden on 18/02/2016. // Copyright © 2016 Nicholas Hurden. All rights reserved. // import Cocoa import CoreGraphics enum EventTapError: Error { case eventTapCreationFailure case runLoopSourceCreationFailure } extension EventTapError: CustomStringConvertible { var description: String { switch self { case .eventTapCreationFailure: return "Event tap creation failed: is your application sandboxed?" case .runLoopSourceCreationFailure: return "Runloop source creation failed" } } } protocol MediaKeyTapInternalsDelegate { func updateInterceptMediaKeys(_ intercept: Bool) func handle(keyEvent: KeyEvent) func isInterceptingMediaKeys() -> Bool } class MediaKeyTapInternals { typealias EventTapCallback = @convention(block) (CGEventType, CGEvent) -> CGEvent? var delegate: MediaKeyTapInternalsDelegate? var keyEventPort: CFMachPort? var runLoopSource: CFRunLoopSource? var callback: EventTapCallback? var runLoopQueue: DispatchQueue? var runLoop: CFRunLoop? deinit { stopWatchingMediaKeys() } /** Enable/Disable the underlying tap */ func enableTap(_ onOff: Bool) { if let port = self.keyEventPort, let runLoop = self.runLoop { CFRunLoopPerformBlock(runLoop, CFRunLoopMode.commonModes as CFTypeRef) { CGEvent.tapEnable(tap: port, enable: onOff) } CFRunLoopWakeUp(runLoop) } } /** Restart the tap, placing it in front of existing taps */ func restartTap() throws { stopWatchingMediaKeys() try startWatchingMediaKeys(restart: true) } func startWatchingMediaKeys(restart: Bool = false) throws { let eventTapCallback: EventTapCallback = { type, event in if type == .tapDisabledByTimeout { if let port = self.keyEventPort { CGEvent.tapEnable(tap: port, enable: true) } return event } else if type == .tapDisabledByUserInput { return event } return DispatchQueue.main.sync { return self.handle(event: event, ofType: type) } } try startKeyEventTap(callback: eventTapCallback, restart: restart) callback = eventTapCallback } func stopWatchingMediaKeys() { CFRunLoopSourceInvalidate <^> runLoopSource CFRunLoopStop <^> runLoop CFMachPortInvalidate <^> keyEventPort } private func handle(event: CGEvent, ofType type: CGEventType) -> CGEvent? { if let nsEvent = NSEvent(cgEvent: event) { guard type.rawValue == UInt32(NX_SYSDEFINED) && nsEvent.isMediaKeyEvent && delegate?.isInterceptingMediaKeys() ?? false else { return event } self.delegate?.handle(keyEvent: nsEvent.keyEvent) return nil } return event } private func startKeyEventTap(callback: @escaping EventTapCallback, restart: Bool) throws { // On a restart we don't want to interfere with the application watcher if !restart { delegate?.updateInterceptMediaKeys(true) } keyEventPort = keyCaptureEventTapPort(callback: callback) guard let port = keyEventPort else { throw EventTapError.eventTapCreationFailure } runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorSystemDefault, port, 0) guard let source = runLoopSource else { throw EventTapError.runLoopSourceCreationFailure } let queue = DispatchQueue(label: "MediaKeyTap Runloop", attributes: []) self.runLoopQueue = queue queue.async { self.runLoop = CFRunLoopGetCurrent() CFRunLoopAddSource(self.runLoop, source, CFRunLoopMode.commonModes) CFRunLoopRun() } } private func keyCaptureEventTapPort(callback: @escaping EventTapCallback) -> CFMachPort? { let cCallback: CGEventTapCallBack = { proxy, type, event, refcon in let innerBlock = unsafeBitCast(refcon, to: EventTapCallback.self) return innerBlock(type, event).map(Unmanaged.passUnretained) } let refcon = unsafeBitCast(callback, to: UnsafeMutableRawPointer.self) return CGEvent.tapCreate( tap: .cgSessionEventTap, place: .headInsertEventTap, options: .defaultTap, eventsOfInterest: CGEventMask(1 << NX_SYSDEFINED), callback: cCallback, userInfo: refcon) } }
32
105
0.647382
1c9971f41325afed8083d1f9fb7957e5c569da24
5,656
// // STPE2ETest.swift // StripeiOS Tests // // Created by David Estes on 2/16/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // import XCTest import Stripe class STPE2ETest: XCTestCase { let E2ETestTimeout : TimeInterval = 120 struct E2EExpectation { var amount: Int var currency: String var accountID: String } class E2EBackend { static let backendAPIURL = URL(string: "https://stp-e2e.glitch.me")! func createPaymentIntent(completion: @escaping (STPPaymentIntentParams, E2EExpectation) -> Void) { requestAPI("create_pi", method: "POST") { (json) in let paymentIntentClientSecret = json["paymentIntent"] as! String let expectedAmount = json["expectedAmount"] as! Int let expectedCurrency = json["expectedCurrency"] as! String let expectedAccountID = json["expectedAccountID"] as! String let publishableKey = json["publishableKey"] as! String STPAPIClient.shared.publishableKey = publishableKey completion(STPPaymentIntentParams(clientSecret: paymentIntentClientSecret), E2EExpectation(amount: expectedAmount, currency: expectedCurrency, accountID: expectedAccountID)) } } func fetchPaymentIntent(id: String, completion: @escaping (E2EExpectation) -> Void) { requestAPI("fetch_pi", queryItems: [URLQueryItem(name: "pi", value: id)]) { (json) in let resultAmount = json["amount"] as! Int let resultCurrency = json["currency"] as! String let resultAccountID = json["on_behalf_of"] as! String completion(E2EExpectation(amount: resultAmount, currency: resultCurrency, accountID: resultAccountID)) } } private func requestAPI(_ resource: String, method: String = "GET", queryItems: [URLQueryItem] = [], completion: @escaping ([String : Any]) -> Void) { var url = URLComponents(url: Self.backendAPIURL.appendingPathComponent(resource), resolvingAgainstBaseURL: false)! url.queryItems = queryItems var request = URLRequest(url: url.url!) request.httpMethod = method let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in guard let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] else { XCTFail("Did not receive valid JSON response from E2E server. \(String(describing: error))") return } DispatchQueue.main.async { completion(json) } }) task.resume() } } static let TestPM: STPPaymentMethodParams = { let testCard = STPPaymentMethodCardParams() testCard.number = "4242424242424242" testCard.expYear = 2050 testCard.expMonth = 12 testCard.cvc = "123" return STPPaymentMethodParams(card: testCard, billingDetails: nil, metadata: nil) }() // MARK: LOG.04.01c // In this test, a PaymentIntent object is created from an example merchant backend, // confirmed by the iOS SDK, and then retrieved to validate that the original amount, // currency, and merchant are the same as the original inputs. func testE2E() throws { continueAfterFailure = false let backend = E2EBackend() let createPI = XCTestExpectation(description: "Create PaymentIntent") let fetchPIBackend = XCTestExpectation(description: "Fetch and check PaymentIntent via backend") let fetchPIClient = XCTestExpectation(description: "Fetch and check PaymentIntent via client") let confirmPI = XCTestExpectation(description: "Confirm PaymentIntent") // Create a PaymentIntent backend.createPaymentIntent { (pip, expected) in createPI.fulfill() // Confirm the PaymentIntent using a test card pip.paymentMethodParams = STPE2ETest.TestPM STPAPIClient.shared.confirmPaymentIntent(with: pip) { (confirmedPI, confirmError) in confirmPI.fulfill() XCTAssertNotNil(confirmedPI) XCTAssertNil(confirmError) // Check the PI information using the backend backend.fetchPaymentIntent(id: pip.stripeId!) { (expectationResult) in XCTAssertEqual(expectationResult.amount, expected.amount) XCTAssertEqual(expectationResult.accountID, expected.accountID) XCTAssertEqual(expectationResult.currency, expected.currency) fetchPIBackend.fulfill() } // Check the PI information using the client STPAPIClient.shared.retrievePaymentIntent(withClientSecret: pip.clientSecret) { (fetchedPI, fetchError) in XCTAssertNil(fetchError) let fetchedPI = fetchedPI! XCTAssertEqual(fetchedPI.status, .succeeded) XCTAssertEqual(fetchedPI.amount, expected.amount) XCTAssertEqual(fetchedPI.currency, expected.currency) // The client can't check the "on_behalf_of" field, so we check it via the merchant test above. fetchPIClient.fulfill() } } } wait(for: [createPI, confirmPI, fetchPIBackend, fetchPIClient], timeout: E2ETestTimeout) } }
47.529412
189
0.621641
de16fdc4a9ba8cd317af84d2b0f502e1901660db
3,361
// // ALKConversationListViewControllerTests.swift // ApplozicSwiftDemoTests // // Created by Shivam Pokhriyal on 13/10/18. // Copyright © 2018 Applozic. All rights reserved. // import ApplozicCore import XCTest @testable import ApplozicSwift class ALKConversationListViewControllerTests: XCTestCase { var conversationListVC: ALKConversationListViewController! override func setUp() { super.setUp() conversationListVC = ALKConversationListViewController(configuration: ALKConfiguration()) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testNewMessage_WhenActiveThreadIsDifferent() { let conversationVM = ALKConversationViewModel(contactId: nil, channelKey: nil, localizedStringFileName: ALKConfiguration().localizedStringFileName) let message = MockMessage().message let result = conversationListVC.isNewMessageForActiveThread(alMessage: message, vm: conversationVM) XCTAssertFalse(result) } func testNewMessage_WhenActiveThreadIsSame() { let conversationVM = ALKConversationViewModel( contactId: "testUser123", channelKey: nil, localizedStringFileName: ALKConfiguration().localizedStringFileName ) let message = MockMessage().message message.contactIds = "testUser123" let result = conversationListVC .isNewMessageForActiveThread(alMessage: message, vm: conversationVM) XCTAssertTrue(result) } func testDelegateCallback_whenMessageThreadIsSelected() { let selectItemExpectation = XCTestExpectation(description: "Conversation list item selected") let conversation = ConversationListTest() conversation.selectItemExpectation = selectItemExpectation let conversationVC = ALKConversationViewControllerMock(configuration: ALKConfiguration(), individualLaunch: true) conversationVC.viewModel = ALKConversationViewModelMock(contactId: nil, channelKey: 000, localizedStringFileName: ALKConfiguration().localizedStringFileName) // Pass all mocks conversationListVC.delegate = conversation conversationListVC.dbService = ALMessageDBServiceMock() conversationListVC.conversationViewController = conversationVC // Select first thread conversationListVC.viewWillAppear(false) let firstIndex = IndexPath(row: 0, section: 0) XCTAssertNotNil(conversationListVC.tableView) let tableView = conversationListVC.tableView tableView.delegate?.tableView?(tableView, didSelectRowAt: firstIndex) wait(for: [selectItemExpectation], timeout: 2) } func testMessageSentByLoggedInUser_WhenTypeOutBox() { let message = MockMessage().message message.contactIds = "testUser123" message.type = "5" // Message type OUTBOX XCTAssertTrue(conversationListVC.isMessageSentByLoggedInUser(alMessage: message)) } func testMessageSentByLoggedInUser_WhenTypeInBox() { let message = MockMessage().message message.contactIds = "testUser123" message.type = "4" // Message type INBOX XCTAssertFalse(conversationListVC.isMessageSentByLoggedInUser(alMessage: message)) } }
41.493827
165
0.73133
d77bad63e4b6c96baa3932b65e39c7584b9d5471
335
// // RecommendationsRouter.swift // MoneyHelper // // Created by Kirill Klebanov on 16/09/2017. // Copyright © 2017 Surf. All rights reserved. // import UIKit final class RecommendationsRouter: RecommendationsRouterInput { // MARK: Properties weak var view: ModuleTransitionable? // MARK: RecommendationsRouterInput }
16.75
63
0.737313
67b456823968bb31c59edc7349383732be4cbc8a
8,336
// // ImageTransformer.swift // PodImage // // Created by Etienne Goulet-Lang on 12/5/16. // Copyright © 2016 Etienne Goulet-Lang. All rights reserved. // import Foundation import UIKit import CoreGraphics public class BaseImageTransformer { private class func createImageRect(avail: CGRect,_ image: CGSize) -> CGRect { var retSize = image //Image Larger? if retSize.width > avail.width { retSize.height = retSize.height * (avail.width / retSize.width) retSize.width = avail.width } // Is the image still larger? if retSize.height > avail.height { retSize.width = retSize.width * (avail.height / retSize.height) retSize.height = avail.height } return CGRect( x: (avail.width - retSize.width) / 2 + avail.origin.x, y: (avail.height - retSize.height) / 2 + avail.origin.y, width: retSize.width, height: retSize.height) } // This method takes an image and centers it in box - with insets - and respects the image's // aspect ratio. public class func centerImage(imageRef: UIImage?, size: CGSize, insets: UIEdgeInsets) -> UIImage? { guard let image = imageRef else { return imageRef } let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) image.draw(in: createImageRect(avail: UIEdgeInsetsInsetRect(rect, insets), image.size)) let ret = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return ret; } // Circle Transform public class func circle(imageRef: UIImage?, radiusPrecentage: CGFloat) -> UIImage? { guard let image = imageRef else { return imageRef } let xOffset: CGFloat = (image.size.width < image.size.height) ? (0) : (image.size.width - image.size.height) / 2 let yOffset: CGFloat = (image.size.width < image.size.height) ? (image.size.height - image.size.width) / 2 : (0) let size: CGFloat = (image.size.width < image.size.height) ? (image.size.width) : (image.size.height) UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, 0.0) let context = UIGraphicsGetCurrentContext() let radius: CGFloat = size * radiusPrecentage / 2 context?.beginPath() context?.addArc(center: CGPoint(x: size / 2, y: size / 2), radius: radius, startAngle: 0, endAngle: CGFloat(2 * Double.pi), clockwise: true) context?.closePath() context?.clip() let targetRect = CGRect(x: -xOffset, y: -yOffset, width: image.size.width, height: image.size.height); image.draw(in: targetRect) let ret = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return ret; } // Background Transform public class func setBackgroundColor(imageRef: UIImage?, color: UIColor?) -> UIImage? { guard let image = imageRef, let c = color else { return imageRef } UIGraphicsBeginImageContextWithOptions(CGSize(width: image.size.width, height: image.size.height), false, 0.0) let context = UIGraphicsGetCurrentContext() let targetRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height); context?.setFillColor(c.cgColor) context?.fill(targetRect) image.draw(in: targetRect) let ret = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return ret; } // Mask public class func imageWithColorMask(imageRef: UIImage?, color: UIColor) -> UIImage? { guard let image = imageRef, let cgImage = image.cgImage else { return imageRef } let imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height) UIGraphicsBeginImageContextWithOptions(imageRect.size, false, image.scale) let context = UIGraphicsGetCurrentContext() context?.scaleBy(x: 1, y: -1) context?.translateBy(x: 0, y: -(imageRect.size.height)) context?.clip(to: imageRect, mask: cgImage) context?.setFillColor(color.cgColor) context?.fill(imageRect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } // Different Orientations public class func flip(imageRef: UIImage?, scale: CGFloat, orientation: UIImageOrientation) -> UIImage? { guard let image = imageRef, let cgImage = image.cgImage else { return imageRef } return UIImage(cgImage: cgImage, scale: scale, orientation: orientation) } public class func flipHorizontally(imageRef: UIImage?) -> UIImage? { guard let image = imageRef else { return imageRef } return flip(imageRef: image, scale: 1, orientation: .upMirrored) } // Stretchable private class func suggestedEdgeInsets(size: CGSize) -> UIEdgeInsets { let center = CGPoint(x: size.width / 2.0, y: size.height / 2.0) return UIEdgeInsetsMake(center.y, center.x, center.y, center.x) } public class func strectchableImage(imageRef: UIImage?, insets: UIEdgeInsets = UIEdgeInsets.zero) -> UIImage? { guard let image = imageRef else { return imageRef } let eInsets = (!UIEdgeInsetsEqualToEdgeInsets(insets, UIEdgeInsets.zero)) ? (insets) : (suggestedEdgeInsets(size: image.size)) return image.resizableImage(withCapInsets: eInsets, resizingMode: .stretch) } //Transform public class func rotateImage(imageRef: UIImage?, orientation: UIImageOrientation) -> UIImage? { guard let image = imageRef, image.cgImage != nil else { return imageRef } if (orientation == UIImageOrientation.right) { return rotateImage(image: image, radians: CGFloat(0.5 * Double.pi)) } else if (orientation == UIImageOrientation.left) { return rotateImage(image: image, radians: -CGFloat(0.5 * Double.pi)) } else if (orientation == UIImageOrientation.down) { return rotateImage(image: image, radians: CGFloat(Double.pi)) } return image } private class func rotateImage(image: UIImage, radians: CGFloat) -> UIImage { let rotatedViewBox = UIView(frame: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)) let transform = CGAffineTransform(rotationAngle: radians) rotatedViewBox.transform = transform let rotatedSize = rotatedViewBox.frame.size // Create the bitmap context UIGraphicsBeginImageContext(rotatedSize); let context = UIGraphicsGetCurrentContext(); // Move the origin to the middle of the image so we will rotate and scale around the center. context?.translateBy(x: rotatedSize.width/2, y: rotatedSize.height/2); // Rotate the image context context?.rotate(by: radians); // Now, draw the rotated/scaled image into the context context?.scaleBy(x: 1.0, y: -1.0); context?.draw(image.cgImage!, in: CGRect(x: -image.size.width / 2, y: -image.size.height / 2, width: image.size.width, height: image.size.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage ?? image } // Image from UIView public class func imageFromView(view: UIView?) -> UIImage? { guard let v = view else { return nil } UIGraphicsBeginImageContextWithOptions(v.bounds.size, true, 0.0) if let context = UIGraphicsGetCurrentContext() { v.layer.render(in: context) let ret = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return ret; } return nil } }
38.772093
154
0.620321
6a71ddfb4ddadf6990bd5cd8432218970a382c48
1,472
import XCTest @testable import XCResourceCommand final class LocalizationConfigurationTests: XCTestCase { func test_initWithArgument_withVerifyComment() throws { // Given let argument = "comment:verify-comment" // When let config = try XCTUnwrap(LocalizationConfiguration(argument: argument)) // Then XCTAssertEqual(config.mergeStrategy, .add(.comment)) XCTAssertEqual(config.verifiesComment, true) } func test_initWithArgument_withoutVerifyComment() throws { // Given let argument = "comment:" // When let config = try XCTUnwrap(LocalizationConfiguration(argument: argument)) // Then XCTAssertEqual(config.mergeStrategy, .add(.comment)) XCTAssertEqual(config.verifiesComment, false) } func test_initWithArgument_withoutVerifyCommentSeparator() throws { // Given let argument = "comment" // When let config = try XCTUnwrap(LocalizationConfiguration(argument: argument)) // Then XCTAssertEqual(config.mergeStrategy, .add(.comment)) XCTAssertEqual(config.verifiesComment, false) } func test_initWithArgument_withUnknownOption() throws { // Given let argument = "comment:unknown-value" // When, Then XCTAssertNil(LocalizationConfiguration(argument: argument)) } }
30.040816
81
0.638587
e5231ce23f49e5b3be506d80dc42092c1a530612
10,960
// // NSAttributedString+Extension.swift // SDBaseClassLib // // Created by Liu Sida on 2021/4/3. // import Foundation extension NSAttributedString: SDPOPCompatible {} // MARK:- 一、文本设置的基本扩展 public extension SDPOP where Base: NSAttributedString { // MARK: 1.1、设置特定区域的字体大小 /// 设置特定区域的字体大小 /// - Parameters: /// - font: 字体 /// - range: 区域 /// - Returns: 返回设置后的富文本 func setRangeFontText(font: UIFont, range: NSRange) -> NSAttributedString { return setSpecificRangeTextMoreAttributes(attributes: [NSAttributedString.Key.font : font], range: range) } // MARK: 1.2、设置特定文字的字体大小 /// 设置特定文字的字体大小 /// - Parameters: /// - text: 特定文字 /// - font: 字体 /// - Returns: 返回设置后的富文本 func setSpecificTextFont(_ text: String, font: UIFont) -> NSAttributedString { return setSpecificTextMoreAttributes(text, attributes: [NSAttributedString.Key.font : font]) } // MARK: 1.3、设置特定区域的字体颜色 /// 设置特定区域的字体颜色 /// - Parameters: /// - color: 字体颜色 /// - range: 区域 /// - Returns: 返回设置后的富文本 func setSpecificRangeTextColor(color: UIColor, range: NSRange) -> NSAttributedString { return setSpecificRangeTextMoreAttributes(attributes: [NSAttributedString.Key.foregroundColor : color], range: range) } // MARK: 1.4、设置特定文字的字体颜色 /// 设置特定文字的字体颜色 /// - Parameters: /// - text: 特定文字 /// - color: 字体颜色 /// - Returns: 返回设置后的富文本 func setSpecificTextColor(_ text: String, color: UIColor) -> NSAttributedString { return setSpecificTextMoreAttributes(text, attributes: [NSAttributedString.Key.foregroundColor : color]) } // MARK: 1.5、设置特定区域行间距 /// 设置特定区域行间距 /// - Parameters: /// - lineSpace: 行间距 /// - alignment: 对齐方式 /// - range: 区域 /// - Returns: 返回设置后的富文本 func setSpecificRangeTextLineSpace(lineSpace: CGFloat, alignment: NSTextAlignment, range: NSRange) -> NSAttributedString { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = lineSpace paragraphStyle.alignment = alignment return setSpecificRangeTextMoreAttributes(attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle], range: range) } // MARK: 1.6、设置特定文字行间距 /// 设置特定文字行间距 /// - Parameters: /// - text: 特定的文字 /// - lineSpace: 行间距 /// - alignment: 对齐方式 /// - Returns: 返回设置后的富文本 func setSpecificTextLineSpace(_ text: String, lineSpace: CGFloat, alignment: NSTextAlignment) -> NSAttributedString { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = lineSpace paragraphStyle.alignment = alignment return setSpecificTextMoreAttributes(text, attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle]) } // MARK: 1.7、设置特定区域的下划线 /// 设置特定区域的下划线 /// - Parameters: /// - color: 下划线颜色 /// - stytle: 下划线样式,默认单下划线 /// - range: 特定区域范围 /// - Returns: 返回设置后的富文本 func setSpecificRangeUnderLine(color: UIColor, stytle: NSUnderlineStyle = .single, range: NSRange) -> NSAttributedString { // 下划线样式 let lineStytle = NSNumber(value: Int8(stytle.rawValue)) return setSpecificRangeTextMoreAttributes(attributes: [NSAttributedString.Key.underlineStyle: lineStytle, NSAttributedString.Key.underlineColor: color], range: range) } // MARK: 1.8、设置特定文字的下划线 /// 设置特定文字的下划线 /// - Parameters: /// - text: 特定文字 /// - color: 下划线颜色 /// - stytle: 下划线样式,默认单下划线 /// - Returns: 返回设置后的富文本 func setSpecificTextUnderLine(_ text: String, color: UIColor, stytle: NSUnderlineStyle = .single) -> NSAttributedString { // 下划线样式 let lineStytle = NSNumber(value: Int8(stytle.rawValue)) return setSpecificTextMoreAttributes(text, attributes: [NSAttributedString.Key.underlineStyle : lineStytle, NSAttributedString.Key.underlineColor: color]) } // MARK: 1.9、设置特定区域的删除线 /// 设置特定区域的删除线 /// - Parameters: /// - color: 删除线颜色 /// - range: 范围 /// - Returns: 返回设置后的富文本 func setSpecificRangeDeleteLine(color: UIColor, range: NSRange) -> NSAttributedString { var attributes = Dictionary<NSAttributedString.Key, Any>() // 删除线样式 let lineStytle = NSNumber(value: Int8(NSUnderlineStyle.single.rawValue)) attributes[NSAttributedString.Key.strikethroughStyle] = lineStytle attributes[NSAttributedString.Key.strikethroughColor] = color let version = UIDevice.sd.currentSystemVersion as NSString if version.floatValue >= 10.3 { attributes[NSAttributedString.Key.baselineOffset] = 0 } else if version.floatValue <= 9.0 { attributes[NSAttributedString.Key.strikethroughStyle] = [] } return setSpecificRangeTextMoreAttributes(attributes: attributes, range: range) } // MARK: 1.10、设置特定文字的删除线 /// 设置特定文字的删除线 /// - Parameters: /// - text: 特定文字 /// - color: 删除线颜色 /// - Returns: 返回设置后的富文本 func setSpecificTextDeleteLine(_ text: String, color: UIColor) -> NSAttributedString { var attributes = Dictionary<NSAttributedString.Key, Any>() // 删除线样式 let lineStytle = NSNumber(value: Int8(NSUnderlineStyle.single.rawValue)) attributes[NSAttributedString.Key.strikethroughStyle] = lineStytle attributes[NSAttributedString.Key.strikethroughColor] = color let version = UIDevice.sd.currentSystemVersion as NSString if version.floatValue >= 10.3 { attributes[NSAttributedString.Key.baselineOffset] = 0 } else if version.floatValue <= 9.0 { attributes[NSAttributedString.Key.strikethroughStyle] = [] } return setSpecificTextMoreAttributes(text, attributes: attributes) } // MARK: 1.11、插入图片 /// 插入图片 /// - Parameters: /// - imgName: 要添加的图片名称,如果是网络图片,需要传入完整路径名,且imgBounds必须传值 /// - imgBounds: 图片的大小,默认为.zero,即自动根据图片大小设置,并以底部基线为标准。 y > 0 :图片向上移动;y < 0 :图片向下移动 /// - imgIndex: 图片的位置,默认放在开头 /// - Returns: 返回设置后的富文本 func insertImage(imgName: String, imgBounds: CGRect = .zero, imgIndex: Int = 0) -> NSAttributedString { let attributedString = NSMutableAttributedString(attributedString: self.base) // NSTextAttachment可以将要插入的图片作为特殊字符处理 let attch = NSTextAttachment() attch.image = loadImage(imageName: imgName) attch.bounds = imgBounds // 创建带有图片的富文本 let string = NSAttributedString(attachment: attch) // 将图片添加到富文本 attributedString.insert(string, at: imgIndex) return attributedString } // MARK: 1.12、首行缩进 /// 首行缩进 /// - Parameter edge: 缩进宽度 /// - Returns: 返回设置后的富文本 func firstLineLeftEdge(_ edge: CGFloat) -> NSAttributedString { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.firstLineHeadIndent = edge return setSpecificRangeTextMoreAttributes(attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle], range: NSRange(location: 0, length: self.base.length)) } // MARK: 1.13、设置特定区域的多个字体属性 /// 设置特定区域的多个字体属性 /// - Parameters: /// - attributes: 字体属性 /// - range: 特定区域 /// - Returns: 返回设置后的富文本 func setSpecificRangeTextMoreAttributes(attributes: Dictionary<NSAttributedString.Key, Any>, range: NSRange) -> NSAttributedString { let mutableAttributedString = NSMutableAttributedString(attributedString: self.base) for name in attributes.keys { mutableAttributedString.addAttribute(name, value: attributes[name] ?? "", range: range) } return mutableAttributedString } // MARK: 1.14、设置特定文字的多个字体属性 /// 设置特定文字的多个字体属性 /// - Parameters: /// - text: 特定文字 /// - attributes: 字体属性 /// - Returns: 返回设置后的富文本 func setSpecificTextMoreAttributes(_ text: String, attributes: Dictionary<NSAttributedString.Key, Any>) -> NSAttributedString { let mutableAttributedString = NSMutableAttributedString(attributedString: self.base) let rangeArray = getStringRangeArray(with: [text]) if !rangeArray.isEmpty { for name in attributes.keys { for range in rangeArray { mutableAttributedString.addAttribute(name, value: attributes[name] ?? "", range: range) } } } return mutableAttributedString } // MARK: 1.15、设置特定区域的倾斜 /// 设置特定区域的倾斜 /// - Parameters: /// - inclination: 倾斜度 /// - range: 特定区域范围 /// - Returns: 返回设置后的富文本 func setSpecificRangeBliqueness(inclination: Float = 0, range: NSRange) -> NSAttributedString { return setSpecificRangeTextMoreAttributes(attributes: [NSAttributedString.Key.obliqueness: inclination], range: range) } // MARK: 1.16、设置特定文字的倾斜 /// 设置特定文字的倾斜 /// - Parameters: /// - text: 特定文字 /// - inclination: 倾斜度 /// - Returns: 返回设置后的富文本 func setSpecificTextBliqueness(_ text: String, inclination: Float = 0) -> NSAttributedString { return setSpecificTextMoreAttributes(text, attributes: [NSAttributedString.Key.obliqueness : inclination]) } } // MARK:- Private Func public extension SDPOP where Base: NSAttributedString { /// 获取对应字符串的range数组 /// - Parameter textArray: 字符串数组 /// - Returns: range数组 private func getStringRangeArray(with textArray: Array<String>) -> Array<NSRange> { var rangeArray = Array<NSRange>() // 遍历 for str in textArray { if base.string.contains(str) { let subStrArr = base.string.components(separatedBy: str) var subStrIndex = 0 for i in 0 ..< (subStrArr.count - 1) { let subDivisionStr = subStrArr[i] if i == 0 { subStrIndex += (subDivisionStr.lengthOfBytes(using: .unicode) / 2) } else { subStrIndex += (subDivisionStr.lengthOfBytes(using: .unicode) / 2 + str.lengthOfBytes(using: .unicode) / 2) } let newRange = NSRange(location: subStrIndex, length: str.count) rangeArray.append(newRange) } } } return rangeArray } // MARK: 加载网络图片 /// 加载网络图片 /// - Parameter imageName: 图片名 /// - Returns: 图片 private func loadImage(imageName: String) -> UIImage? { if imageName.hasPrefix("http://") || imageName.hasPrefix("https://") { let imageURL = URL(string: imageName) var imageData: Data? = nil do { imageData = try Data(contentsOf: imageURL!) return UIImage(data: imageData!)! } catch { return nil } } return UIImage(named: imageName)! } }
38.591549
174
0.632847
0ace202c0e5540b9363d57fa35ca9f668b74751c
2,482
/* Developer : Warren Seto Classes : CompactVideoCell, LargeVideoCell, SubscriptionCell, SearchHeaderView, VideoTitleCell, VideoDescriptionCell, VideoIconCell Protocols : VideoProtocol, SearchProtocol Extensions: UICollectionViewController, UINavigationController, String -> heightWithConstrainedWidth(...) Project : Players App (v2) */ import UIKit extension UICollectionViewController { open override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } extension UINavigationController { open override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } open override var prefersStatusBarHidden: Bool { return false } } extension String { func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude), boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil) return boundingBox.height } } protocol VideoProtocol { func loadVideo(result: VideoResult) } protocol SearchProtocol { func applyFilters(newFilter: String, newOptions: [Int]) } final class CompactVideoCell : UICollectionViewCell { @IBOutlet weak var title : UILabel! @IBOutlet weak var thumbnail : UIImageView! @IBOutlet weak var views : UILabel! @IBOutlet weak var duration : UILabel! @IBOutlet weak var channelName : UILabel! } final class LargeVideoCell : UICollectionViewCell { @IBOutlet weak var title : UILabel! @IBOutlet weak var thumbnail : UIImageView! @IBOutlet weak var subtitle : UILabel! @IBOutlet weak var duration : UILabel! } final class SubscriptionCell : UICollectionViewCell { @IBOutlet weak var thumbnail : UIImageView! @IBOutlet weak var name : UILabel! } final class SearchHeaderView : UICollectionReusableView { @IBOutlet weak var headerStyle : UIVisualEffectView! @IBOutlet weak var searchField : UITextField! } final class VideoTitleCell : UICollectionViewCell { @IBOutlet weak var title : UILabel! } final class VideoDescriptionCell : UICollectionViewCell { @IBOutlet weak var detail : UITextView! } final class VideoIconCell : UICollectionViewCell { @IBOutlet weak var thumbnail : UIImageView! @IBOutlet weak var info : UILabel! }
28.204545
157
0.729251
5d6f22fac874d8ba40fcb1f6a6686c46026ecb01
27,370
// // PieRadarChartViewBase.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif /// Base class of PieChartView and RadarChartView. open class PieRadarChartViewBase: ChartViewBase { /// holds the normalized version of the current rotation angle of the chart private var _rotationAngle = CGFloat(270.0) /// holds the raw version of the current rotation angle of the chart private var _rawRotationAngle = CGFloat(270.0) /// flag that indicates if rotation is enabled or not @objc open var rotationEnabled = true /// Sets the minimum offset (padding) around the chart, defaults to 0.0 @objc open var minOffset = CGFloat(0.0) /// iOS && OSX only: Enabled multi-touch rotation using two fingers. private var _rotationWithTwoFingers = false private var _tapGestureRecognizer: NSUITapGestureRecognizer! #if !os(tvOS) private var _rotationGestureRecognizer: NSUIRotationGestureRecognizer! #endif public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { stopDeceleration() } internal override func initialize() { super.initialize() _tapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: #selector(tapGestureRecognized(_:))) self.addGestureRecognizer(_tapGestureRecognizer) #if !os(tvOS) _rotationGestureRecognizer = NSUIRotationGestureRecognizer(target: self, action: #selector(rotationGestureRecognized(_:))) self.addGestureRecognizer(_rotationGestureRecognizer) _rotationGestureRecognizer.isEnabled = rotationWithTwoFingers #endif } internal override func calcMinMax() { /*_xAxis.axisRange = Double((_data?.xVals.count ?? 0) - 1)*/ } open override var maxVisibleCount: Int { get { return data?.entryCount ?? 0 } } open override func notifyDataSetChanged() { calcMinMax() if let data = _data , _legend !== nil { _legendRenderer.computeLegend(data: data) } calculateOffsets() setNeedsDisplay() } internal override func calculateOffsets() { var legendLeft = CGFloat(0.0) var legendRight = CGFloat(0.0) var legendBottom = CGFloat(0.0) var legendTop = CGFloat(0.0) if _legend != nil && _legend.enabled && !_legend.drawInside { let fullLegendWidth = min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) switch _legend.orientation { case .vertical: var xLegendOffset: CGFloat = 0.0 if _legend.horizontalAlignment == .left || _legend.horizontalAlignment == .right { if _legend.verticalAlignment == .center { // this is the space between the legend and the chart let spacing = CGFloat(13.0) xLegendOffset = fullLegendWidth + spacing } else { // this is the space between the legend and the chart let spacing = CGFloat(8.0) let legendWidth = fullLegendWidth + spacing let legendHeight = _legend.neededHeight + _legend.textHeightMax let c = self.midPoint let bottomX = _legend.horizontalAlignment == .right ? self.bounds.width - legendWidth + 15.0 : legendWidth - 15.0 let bottomY = legendHeight + 15 let distLegend = distanceToCenter(x: bottomX, y: bottomY) let reference = getPosition(center: c, dist: self.radius, angle: angleForPoint(x: bottomX, y: bottomY)) let distReference = distanceToCenter(x: reference.x, y: reference.y) let minOffset = CGFloat(5.0) if bottomY >= c.y && self.bounds.height - legendWidth > self.bounds.width { xLegendOffset = legendWidth } else if distLegend < distReference { let diff = distReference - distLegend xLegendOffset = minOffset + diff } } } switch _legend.horizontalAlignment { case .left: legendLeft = xLegendOffset case .right: legendRight = xLegendOffset case .center: switch _legend.verticalAlignment { case .top: legendTop = min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) case .bottom: legendBottom = min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) default: break } } case .horizontal: var yLegendOffset: CGFloat = 0.0 if _legend.verticalAlignment == .top || _legend.verticalAlignment == .bottom { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = self.requiredLegendOffset yLegendOffset = min( _legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } switch _legend.verticalAlignment { case .top: legendTop = yLegendOffset case .bottom: legendBottom = yLegendOffset default: break } } legendLeft += self.requiredBaseOffset legendRight += self.requiredBaseOffset legendTop += self.requiredBaseOffset legendBottom += self.requiredBaseOffset } legendTop += self.extraTopOffset legendRight += self.extraRightOffset legendBottom += self.extraBottomOffset legendLeft += self.extraLeftOffset var minOffset = self.minOffset if self is RadarChartView { let x = self.xAxis if x.isEnabled && x.drawLabelsEnabled { minOffset = max(minOffset, x.labelRotatedWidth) } } let offsetLeft = max(minOffset, legendLeft) let offsetTop = max(minOffset, legendTop) let offsetRight = max(minOffset, legendRight) let offsetBottom = max(minOffset, max(self.requiredBaseOffset, legendBottom)) _viewPortHandler.restrainViewPort(offsetLeft: offsetLeft, offsetTop: offsetTop, offsetRight: offsetRight, offsetBottom: offsetBottom) } /// - returns: The angle relative to the chart center for the given point on the chart in degrees. /// The angle is always between 0 and 360°, 0° is NORTH, 90° is EAST, ... @objc open func angleForPoint(x: CGFloat, y: CGFloat) -> CGFloat { let c = centerOffsets let tx = Double(x - c.x) let ty = Double(y - c.y) let length = sqrt(tx * tx + ty * ty) let r = acos(ty / length) var angle = r.RAD2DEG if x > c.x { angle = 360.0 - angle } // add 90° because chart starts EAST angle = angle + 90.0 // neutralize overflow if angle > 360.0 { angle = angle - 360.0 } return CGFloat(angle) } /// Calculates the position around a center point, depending on the distance /// from the center, and the angle of the position around the center. @objc open func getPosition(center: CGPoint, dist: CGFloat, angle: CGFloat) -> CGPoint { return CGPoint(x: center.x + dist * cos(angle.DEG2RAD), y: center.y + dist * sin(angle.DEG2RAD)) } /// - returns: The distance of a certain point on the chart to the center of the chart. @objc open func distanceToCenter(x: CGFloat, y: CGFloat) -> CGFloat { let c = self.centerOffsets var dist = CGFloat(0.0) var xDist = CGFloat(0.0) var yDist = CGFloat(0.0) if x > c.x { xDist = x - c.x } else { xDist = c.x - x } if y > c.y { yDist = y - c.y } else { yDist = c.y - y } // pythagoras dist = sqrt(pow(xDist, 2.0) + pow(yDist, 2.0)) return dist } /// - returns: The xIndex for the given angle around the center of the chart. /// -1 if not found / outofbounds. @objc open func indexForAngle(_ angle: CGFloat) -> Int { fatalError("indexForAngle() cannot be called on PieRadarChartViewBase") } /// current rotation angle of the pie chart /// /// **default**: 270 --> top (NORTH) /// - returns: Will always return a normalized value, which will be between 0.0 < 360.0 @objc open var rotationAngle: CGFloat { get { return _rotationAngle } set { _rawRotationAngle = newValue _rotationAngle = newValue.normalizedAngle setNeedsDisplay() } } /// gets the raw version of the current rotation angle of the pie chart the returned value could be any value, negative or positive, outside of the 360 degrees. /// this is used when working with rotation direction, mainly by gestures and animations. @objc open var rawRotationAngle: CGFloat { return _rawRotationAngle } /// - returns: The diameter of the pie- or radar-chart @objc open var diameter: CGFloat { var content = _viewPortHandler.contentRect content.origin.x += extraLeftOffset content.origin.y += extraTopOffset content.size.width -= extraLeftOffset + extraRightOffset content.size.height -= extraTopOffset + extraBottomOffset return min(content.width, content.height) } /// - returns: The radius of the chart in pixels. @objc open var radius: CGFloat { fatalError("radius cannot be called on PieRadarChartViewBase") } /// - returns: The required offset for the chart legend. internal var requiredLegendOffset: CGFloat { fatalError("requiredLegendOffset cannot be called on PieRadarChartViewBase") } /// - returns: The base offset needed for the chart without calculating the /// legend size. internal var requiredBaseOffset: CGFloat { fatalError("requiredBaseOffset cannot be called on PieRadarChartViewBase") } open override var chartYMax: Double { return 0.0 } open override var chartYMin: Double { return 0.0 } @objc open var isRotationEnabled: Bool { return rotationEnabled } /// flag that indicates if rotation is done with two fingers or one. /// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events. /// /// On iOS this will disable one-finger rotation. /// On OSX this will keep two-finger multitouch rotation, and one-pointer mouse rotation. /// /// **default**: false @objc open var rotationWithTwoFingers: Bool { get { return _rotationWithTwoFingers } set { _rotationWithTwoFingers = newValue #if !os(tvOS) _rotationGestureRecognizer.isEnabled = _rotationWithTwoFingers #endif } } /// flag that indicates if rotation is done with two fingers or one. /// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events. /// /// On iOS this will disable one-finger rotation. /// On OSX this will keep two-finger multitouch rotation, and one-pointer mouse rotation. /// /// **default**: false @objc open var isRotationWithTwoFingers: Bool { return _rotationWithTwoFingers } // MARK: - Animation private var _spinAnimator: Animator! /// Applys a spin animation to the Chart. @objc open func spin(duration: TimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easing: ChartEasingFunctionBlock?) { if _spinAnimator != nil { _spinAnimator.stop() } _spinAnimator = Animator() _spinAnimator.updateBlock = { self.rotationAngle = (toAngle - fromAngle) * CGFloat(self._spinAnimator.phaseX) + fromAngle } _spinAnimator.stopBlock = { self._spinAnimator = nil } _spinAnimator.animate(xAxisDuration: duration, easing: easing) } @objc open func spin(duration: TimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easingOption: ChartEasingOption) { spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: easingFunctionFromOption(easingOption)) } @objc open func spin(duration: TimeInterval, fromAngle: CGFloat, toAngle: CGFloat) { spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: nil) } @objc open func stopSpinAnimation() { if _spinAnimator != nil { _spinAnimator.stop() } } // MARK: - Gestures private var _rotationGestureStartPoint: CGPoint! private var _isRotating = false private var _startAngle = CGFloat(0.0) private struct AngularVelocitySample { var time: TimeInterval var angle: CGFloat } private var _velocitySamples = [AngularVelocitySample]() private var _decelerationLastTime: TimeInterval = 0.0 private var _decelerationDisplayLink: NSUIDisplayLink! private var _decelerationAngularVelocity: CGFloat = 0.0 internal final func processRotationGestureBegan(location: CGPoint) { self.resetVelocity() if rotationEnabled { self.sampleVelocity(touchLocation: location) } self.setGestureStartAngle(x: location.x, y: location.y) _rotationGestureStartPoint = location } internal final func processRotationGestureMoved(location: CGPoint) { if isDragDecelerationEnabled { sampleVelocity(touchLocation: location) } if !_isRotating && distance( eventX: location.x, startX: _rotationGestureStartPoint.x, eventY: location.y, startY: _rotationGestureStartPoint.y) > CGFloat(8.0) { _isRotating = true } else { self.updateGestureRotation(x: location.x, y: location.y) setNeedsDisplay() } } internal final func processRotationGestureEnded(location: CGPoint) { if isDragDecelerationEnabled { stopDeceleration() sampleVelocity(touchLocation: location) _decelerationAngularVelocity = calculateVelocity() if _decelerationAngularVelocity != 0.0 { _decelerationLastTime = CACurrentMediaTime() _decelerationDisplayLink = NSUIDisplayLink(target: self, selector: #selector(PieRadarChartViewBase.decelerationLoop)) _decelerationDisplayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes) } } } internal final func processRotationGestureCancelled() { if _isRotating { _isRotating = false } } #if !os(OSX) open override func nsuiTouchesBegan(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { // if rotation by touch is enabled if rotationEnabled { stopDeceleration() if !rotationWithTwoFingers, let touchLocation = touches.first?.location(in: self) { processRotationGestureBegan(location: touchLocation) } } if !_isRotating { super.nsuiTouchesBegan(touches, withEvent: event) } } open override func nsuiTouchesMoved(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if rotationEnabled && !rotationWithTwoFingers, let touch = touches.first { let touchLocation = touch.location(in: self) processRotationGestureMoved(location: touchLocation) } if !_isRotating { super.nsuiTouchesMoved(touches, withEvent: event) } } open override func nsuiTouchesEnded(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if !_isRotating { super.nsuiTouchesEnded(touches, withEvent: event) } if rotationEnabled && !rotationWithTwoFingers, let touch = touches.first { let touchLocation = touch.location(in: self) processRotationGestureEnded(location: touchLocation) } if _isRotating { _isRotating = false } } open override func nsuiTouchesCancelled(_ touches: Set<NSUITouch>?, withEvent event: NSUIEvent?) { super.nsuiTouchesCancelled(touches, withEvent: event) processRotationGestureCancelled() } #endif #if os(OSX) open override func mouseDown(with theEvent: NSEvent) { // if rotation by touch is enabled if rotationEnabled { stopDeceleration() let location = self.convert(theEvent.locationInWindow, from: nil) processRotationGestureBegan(location: location) } if !_isRotating { super.mouseDown(with: theEvent) } } open override func mouseDragged(with theEvent: NSEvent) { if rotationEnabled { let location = self.convert(theEvent.locationInWindow, from: nil) processRotationGestureMoved(location: location) } if !_isRotating { super.mouseDragged(with: theEvent) } } open override func mouseUp(with theEvent: NSEvent) { if !_isRotating { super.mouseUp(with: theEvent) } if rotationEnabled { let location = self.convert(theEvent.locationInWindow, from: nil) processRotationGestureEnded(location: location) } if _isRotating { _isRotating = false } } #endif private func resetVelocity() { _velocitySamples.removeAll(keepingCapacity: false) } private func sampleVelocity(touchLocation: CGPoint) { let currentTime = CACurrentMediaTime() _velocitySamples.append(AngularVelocitySample(time: currentTime, angle: angleForPoint(x: touchLocation.x, y: touchLocation.y))) // Remove samples older than our sample time - 1 seconds var i = 0, count = _velocitySamples.count while (i < count - 2) { if currentTime - _velocitySamples[i].time > 1.0 { _velocitySamples.remove(at: 0) i -= 1 count -= 1 } else { break } i += 1 } } private func calculateVelocity() -> CGFloat { if _velocitySamples.isEmpty { return 0.0 } var firstSample = _velocitySamples[0] var lastSample = _velocitySamples[_velocitySamples.count - 1] // Look for a sample that's closest to the latest sample, but not the same, so we can deduce the direction var beforeLastSample = firstSample for i in stride(from: (_velocitySamples.count - 1), through: 0, by: -1) { beforeLastSample = _velocitySamples[i] if beforeLastSample.angle != lastSample.angle { break } } // Calculate the sampling time var timeDelta = lastSample.time - firstSample.time if timeDelta == 0.0 { timeDelta = 0.1 } // Calculate clockwise/ccw by choosing two values that should be closest to each other, // so if the angles are two far from each other we know they are inverted "for sure" var clockwise = lastSample.angle >= beforeLastSample.angle if (abs(lastSample.angle - beforeLastSample.angle) > 270.0) { clockwise = !clockwise } // Now if the "gesture" is over a too big of an angle - then we know the angles are inverted, and we need to move them closer to each other from both sides of the 360.0 wrapping point if lastSample.angle - firstSample.angle > 180.0 { firstSample.angle += 360.0 } else if firstSample.angle - lastSample.angle > 180.0 { lastSample.angle += 360.0 } // The velocity var velocity = abs((lastSample.angle - firstSample.angle) / CGFloat(timeDelta)) // Direction? if !clockwise { velocity = -velocity } return velocity } /// sets the starting angle of the rotation, this is only used by the touch listener, x and y is the touch position private func setGestureStartAngle(x: CGFloat, y: CGFloat) { _startAngle = angleForPoint(x: x, y: y) // take the current angle into consideration when starting a new drag _startAngle -= _rotationAngle } /// updates the view rotation depending on the given touch position, also takes the starting angle into consideration private func updateGestureRotation(x: CGFloat, y: CGFloat) { self.rotationAngle = angleForPoint(x: x, y: y) - _startAngle } @objc open func stopDeceleration() { if _decelerationDisplayLink !== nil { _decelerationDisplayLink.remove(from: RunLoop.main, forMode: RunLoopMode.commonModes) _decelerationDisplayLink = nil } } @objc private func decelerationLoop() { let currentTime = CACurrentMediaTime() _decelerationAngularVelocity *= self.dragDecelerationFrictionCoef let timeInterval = CGFloat(currentTime - _decelerationLastTime) self.rotationAngle += _decelerationAngularVelocity * timeInterval _decelerationLastTime = currentTime if(abs(_decelerationAngularVelocity) < 0.001) { stopDeceleration() } } /// - returns: The distance between two points private func distance(eventX: CGFloat, startX: CGFloat, eventY: CGFloat, startY: CGFloat) -> CGFloat { let dx = eventX - startX let dy = eventY - startY return sqrt(dx * dx + dy * dy) } /// - returns: The distance between two points private func distance(from: CGPoint, to: CGPoint) -> CGFloat { let dx = from.x - to.x let dy = from.y - to.y return sqrt(dx * dx + dy * dy) } /// reference to the last highlighted object private var _lastHighlight: Highlight! @objc private func tapGestureRecognized(_ recognizer: NSUITapGestureRecognizer) { if recognizer.state == NSUIGestureRecognizerState.ended { if !self.isHighLightPerTapEnabled { return } let location = recognizer.location(in: self) let high = self.getHighlightByTouchPoint(location) self.highlightValue(high, callDelegate: true) } } #if !os(tvOS) @objc private func rotationGestureRecognized(_ recognizer: NSUIRotationGestureRecognizer) { if recognizer.state == NSUIGestureRecognizerState.began { stopDeceleration() _startAngle = self.rawRotationAngle } if recognizer.state == NSUIGestureRecognizerState.began || recognizer.state == NSUIGestureRecognizerState.changed { let angle = recognizer.nsuiRotation.RAD2DEG self.rotationAngle = _startAngle + angle setNeedsDisplay() } else if recognizer.state == NSUIGestureRecognizerState.ended { let angle = recognizer.nsuiRotation.RAD2DEG self.rotationAngle = _startAngle + angle setNeedsDisplay() if isDragDecelerationEnabled { stopDeceleration() _decelerationAngularVelocity = recognizer.velocity.RAD2DEG if _decelerationAngularVelocity != 0.0 { _decelerationLastTime = CACurrentMediaTime() _decelerationDisplayLink = NSUIDisplayLink(target: self, selector: #selector(PieRadarChartViewBase.decelerationLoop)) _decelerationDisplayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes) } } } } #endif }
31.568627
191
0.558933
389eca868f59b585ba3bbb60af1efe104261ca46
110,279
import UIKit import WMF #if OSM import Mapbox #endif import MapKit @objc(WMFPlacesViewController) class PlacesViewController: ViewController, UISearchBarDelegate, ArticlePopoverViewControllerDelegate, PlaceSearchSuggestionControllerDelegate, WMFLocationManagerDelegate, NSFetchedResultsControllerDelegate, UIPopoverPresentationControllerDelegate, ArticlePlaceViewDelegate, UIGestureRecognizerDelegate, HintPresenting { fileprivate var mapView: MapView! @IBOutlet weak var mapContainerView: UIView! @IBOutlet weak var redoSearchButton: UIButton! @IBOutlet weak var didYouMeanButton: UIButton! var fakeProgressController: FakeProgressController! @IBOutlet weak var recenterOnUserLocationButton: UIButton! @IBOutlet weak var listAndSearchOverlayContainerView: RoundedCornerView! @IBOutlet weak var listAndSearchOverlaySliderSeparator: UIView! @IBOutlet weak var listAndSearchOverlayBottomConstraint: NSLayoutConstraint! @IBOutlet weak var listAndSearchOverlayHeightConstraint: NSLayoutConstraint! @IBOutlet weak var listAndSearchOverlaySliderHeightConstraint: NSLayoutConstraint! @IBOutlet weak var listAndSearchOverlaySliderView: UIView! @IBOutlet weak var listContainerView: UIView! var listViewController: ArticleLocationCollectionViewController! @IBOutlet weak var searchSuggestionView: UITableView! @IBOutlet var emptySearchOverlayView: PlaceSearchEmptySearchOverlayView! @objc public var dataStore: MWKDataStore! fileprivate let locationSearchFetcher = WMFLocationSearchFetcher() fileprivate let searchFetcher = WMFSearchFetcher() fileprivate let wikidataFetcher = WikidataFetcher(session: Session.shared, configuration: Configuration.current) fileprivate let locationManager = WMFLocationManager.fine() fileprivate let animationDuration = 0.6 fileprivate let animationScale = CGFloat(0.6) fileprivate let popoverFadeDuration = 0.25 fileprivate let searchHistoryCountLimit = 15 fileprivate var searchSuggestionController: PlaceSearchSuggestionController! fileprivate var siteURL: URL { return MWKLanguageLinkController.sharedInstance().appLanguage?.siteURL() ?? NSURL.wmf_URLWithDefaultSiteAndCurrentLocale()! } fileprivate var currentGroupingPrecision: QuadKeyPrecision = 1 fileprivate var selectedArticlePopover: ArticlePopoverViewController? fileprivate var selectedArticleAnnotationView: MapAnnotationView? fileprivate var selectedArticleKey: String? fileprivate var articleKeyToSelect: String? fileprivate var currentSearchRegion: MKCoordinateRegion? fileprivate var performDefaultSearchOnNextMapRegionUpdate = false fileprivate var isMovingToRegion = false fileprivate var previouslySelectedArticlePlaceIdentifier: Int? fileprivate var didYouMeanSearch: PlaceSearch? fileprivate var searching: Bool = false fileprivate let imageController = ImageController.shared fileprivate var _displayCountForTopPlaces: Int? fileprivate var displayCountForTopPlaces: Int { get { switch (self.currentSearchFilter) { case .top: return articleFetchedResultsController?.fetchedObjects?.count ?? 0 case .saved: return _displayCountForTopPlaces ?? 0 } } } lazy fileprivate var placeSearchService: PlaceSearchService! = { return PlaceSearchService(dataStore: self.dataStore) }() // MARK: - View Lifecycle required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) title = CommonStrings.placesTabTitle extendedLayoutIncludesOpaqueBars = true edgesForExtendedLayout = UIRectEdge.all } // MARK - Search lazy var searchBarContainerView: UIView = { let searchBarContainerView = UIView() searchBarStackView.translatesAutoresizingMaskIntoConstraints = false searchBarContainerView.addSubview(searchBarStackView) let leading = searchBarContainerView.layoutMarginsGuide.leadingAnchor.constraint(equalTo: searchBarStackView.leadingAnchor) let trailing = searchBarContainerView.layoutMarginsGuide.trailingAnchor.constraint(equalTo: searchBarStackView.trailingAnchor) let top = searchBarContainerView.topAnchor.constraint(equalTo: searchBarStackView.topAnchor) let bottom = searchBarContainerView.bottomAnchor.constraint(equalTo: searchBarStackView.bottomAnchor) searchBarContainerView.addConstraints([leading, trailing, top, bottom]) return searchBarContainerView }() lazy var searchBarStackView: UIStackView = { let searchBarStackView = UIStackView() searchBar.translatesAutoresizingMaskIntoConstraints = false mapListToggleContainer.translatesAutoresizingMaskIntoConstraints = false searchBarStackView.axis = .horizontal searchBarStackView.alignment = .center searchBarStackView.distribution = .fill searchBarStackView.spacing = 10 searchBarStackView.addArrangedSubview(searchBar) searchBarStackView.addArrangedSubview(mapListToggleContainer) return searchBarStackView }() lazy var searchBar: UISearchBar = { let searchBar = UISearchBar() searchBar.placeholder = WMFLocalizedString("places-search-default-text", value:"Search Places", comment:"Placeholder text that displays where is there no current place search {{Identical|Search}}") searchBar.delegate = self searchBar.returnKeyType = .search searchBar.searchBarStyle = .minimal searchBar.showsCancelButton = false return searchBar }() lazy var mapListToggleContainer: UIView = { let mapListToggleContainer = UIView() mapListToggleContainer.wmf_addSubview(mapListToggle, withConstraintsToEdgesWithInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)) // hax: alignment return mapListToggleContainer }() lazy var mapListToggle: UISegmentedControl = { let mapListToggle = UISegmentedControl() let map = #imageLiteral(resourceName: "places-map") let list = #imageLiteral(resourceName: "places-list") map.accessibilityLabel = WMFLocalizedString("places-accessibility-show-as-map", value:"Show as map", comment:"Accessibility label for the show as map toggle item") list.accessibilityLabel = WMFLocalizedString("places-accessibility-show-as-list", value:"Show as list", comment:"Accessibility label for the show as list toggle item") mapListToggle.insertSegment(with: map, at: 0, animated: false) mapListToggle.insertSegment(with: list, at: 1, animated: false) mapListToggle.selectedSegmentIndex = 0 mapListToggle.addTarget(self, action: #selector(updateViewModeFromSegmentedControl), for: .valueChanged) return mapListToggle }() override func viewDidLoad() { navigationItem.rightBarButtonItem = UIBarButtonItem(title: WMFLocalizedString("places-filter-button-title", value: "Filter", comment: "Title for button that allows users to filter places"), style: .plain, target: self, action: #selector(filterButtonPressed(_:))) navigationBar.addUnderNavigationBarView(searchBarContainerView) navigationBar.displayType = .largeTitle navigationBar.delegate = self navigationBar.isBarHidingEnabled = false listViewController = ArticleLocationCollectionViewController(articleURLs: [], dataStore: dataStore, contentGroup: nil, theme: theme) addChild(listViewController) listViewController.view.frame = listContainerView.bounds listViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] listContainerView.addSubview(listViewController.view) listViewController.didMove(toParent: self) let mapViewFrame = mapContainerView.bounds #if OSM let styleURL = Bundle.main.url(forResource: "mapstyle", withExtension: "json") mapView = MapView(frame: mapViewFrame, styleURL: styleURL) mapView.delegate = self mapView.allowsRotating = false mapView.allowsTilting = false mapView.showsUserLocation = false mapView.logoView.isHidden = true #else mapView = MapView(frame: mapViewFrame) mapView.delegate = self // Setup map view mapView.mapType = .standard mapView.showsBuildings = false mapView.showsTraffic = false mapView.showsPointsOfInterest = false mapView.showsScale = false mapView.showsUserLocation = true mapView.isRotateEnabled = false mapView.isPitchEnabled = false #endif mapContainerView.wmf_addSubviewWithConstraintsToEdges(mapView) fakeProgressController = FakeProgressController(progress: navigationBar, delegate: navigationBar) // Setup location manager locationManager.delegate = self // Setup Redo search button redoSearchButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15) redoSearchButton.setTitleColor(.white, for: .normal) redoSearchButton.setTitle(WMFLocalizedString("places-search-this-area", value:"Results in this area", comment:"A button title that indicates the search will be redone in the visible area"), for: .normal) redoSearchButton.isHidden = true // Setup Did You Mean button didYouMeanButton.setTitleColor(.white, for: .normal) didYouMeanButton.isHidden = true didYouMeanButton.titleLabel?.adjustsFontSizeToFitWidth = true didYouMeanButton.titleLabel?.textAlignment = .center // Setup recenter button recenterOnUserLocationButton.accessibilityLabel = WMFLocalizedString("places-accessibility-recenter-map-on-user-location", value:"Recenter on your location", comment:"Accessibility label for the recenter map on the user's location button") recenterOnUserLocationButton.imageEdgeInsets = UIEdgeInsets(top: 1, left: 0, bottom: 0, right: 1) listAndSearchOverlayContainerView.corners = [.topLeft, .topRight, .bottomLeft, .bottomRight] // Setup search suggestions searchSuggestionController = PlaceSearchSuggestionController() searchSuggestionController.tableView = searchSuggestionView searchSuggestionController.delegate = self super.viewDidLoad() let panGR = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture)) panGR.delegate = self view.addGestureRecognizer(panGR) overlaySliderPanGestureRecognizer = panGR self.view.layoutIfNeeded() } override func viewWillAppear(_ animated: Bool) { // Update saved places locations placeSearchService.fetchSavedArticles(searchString: nil) super.viewWillAppear(animated) if isFirstAppearance { isFirstAppearance = false if UIAccessibility.isVoiceOverRunning { viewMode = .list mapListToggle.selectedSegmentIndex = 1 } else { viewMode = .map } } constrainButtonsToNavigationBar() let defaults = UserDefaults.wmf if !defaults.wmf_placesHasAppeared() { defaults.wmf_setPlacesHasAppeared(true) } guard WMFLocationManager.isAuthorized() else { if !defaults.wmf_placesDidPromptForLocationAuthorization() { defaults.wmf_setPlacesDidPromptForLocationAuthorization(true) promptForLocationAccess() } else { performDefaultSearchOnNextMapRegionUpdate = currentSearch == nil } return } locationManager.startMonitoringLocation() mapView.showsUserLocation = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self, name: UIWindow.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIWindow.keyboardWillHideNotification, object: nil) locationManager.stopMonitoringLocation() mapView.showsUserLocation = false } private func constrainButtonsToNavigationBar() { let recenterOnUserLocationButtonTopConstraint = recenterOnUserLocationButton.topAnchor.constraint(equalTo: navigationBar.bottomAnchor, constant: 17) let redoSearchButtonTopConstraint = redoSearchButton.topAnchor.constraint(equalTo: navigationBar.bottomAnchor, constant: 17) let didYouMeanButtonTopConstraint = didYouMeanButton.topAnchor.constraint(equalTo: navigationBar.bottomAnchor, constant: 17) NSLayoutConstraint.activate([recenterOnUserLocationButtonTopConstraint, redoSearchButtonTopConstraint, didYouMeanButtonTopConstraint]) } func selectVisibleArticle(articleKey: String) -> Bool { let annotations = mapView.visibleAnnotations for annotation in annotations { guard let place = annotation as? ArticlePlace, place.articles.count == 1, let article = place.articles.first, article.key == articleKey else { continue } selectArticlePlace(place) return true } return false } func selectVisibleKeyToSelectIfNecessary() { guard !isMovingToRegion, countOfAnimatingAnnotations == 0, let keyToSelect = articleKeyToSelect, viewMode == .map else { return } guard selectVisibleArticle(articleKey: keyToSelect) else { return } articleKeyToSelect = nil } fileprivate func article(at indexPath: IndexPath) -> WMFArticle? { guard let sections = articleFetchedResultsController?.sections, indexPath.section < sections.count, indexPath.item < sections[indexPath.section].numberOfObjects else { return nil } return articleFetchedResultsController?.object(at: indexPath) } public func logListViewImpression(forIndexPath indexPath: IndexPath) { } public func logListViewImpressionsForVisibleCells() { for indexPath in listViewController.collectionView.indexPathsForVisibleItems { logListViewImpression(forIndexPath: indexPath) } } func updateShouldShowAllImagesIfNecessary() { let visibleAnnotations = mapView.visibleAnnotations var visibleArticleCount = 0 var visibleGroupCount = 0 for annotation in visibleAnnotations { guard let place = annotation as? ArticlePlace else { continue } if place.articles.count == 1 { visibleArticleCount += 1 } else { visibleGroupCount += 1 } } let articlesPerSquarePixel = CGFloat(visibleArticleCount) / mapView.bounds.width * mapView.bounds.height let shouldShowAllImages = visibleGroupCount == 0 && visibleArticleCount > 0 && articlesPerSquarePixel < 40 set(shouldShowAllImages: shouldShowAllImages) } func set(shouldShowAllImages: Bool) { if shouldShowAllImages != showingAllImages { for annotation in mapView.annotations { guard let view = mapView.view(for: annotation) as? ArticlePlaceView else { continue } view.set(alwaysShowImage: shouldShowAllImages, animated: true) } showingAllImages = shouldShowAllImages } } var countOfAnimatingAnnotations = 0 { didSet { if countOfAnimatingAnnotations == 0 { selectVisibleKeyToSelectIfNecessary() } } } // MARKL - Filtering // hax private func setCheckmark(for alertAction: UIAlertAction, in alertController: UIAlertController) { let key = "checked" for action in alertController.actions { action.setValue(false, forKey: key) } alertAction.setValue(true, forKey: key) } @objc private func filterButtonPressed(_ sender: UIBarButtonItem) { let alertController = UIAlertController(title: WMFLocalizedString("places-filter-articles-action-sheet-title", value: "Filter articles", comment: "Title for action sheet that allows users to filter Places articles"), message: nil, preferredStyle: .actionSheet) let topReadArticlesAction = UIAlertAction(title: WMFLocalizedString("places-filter-top-read-articles", value: "Top read articles", comment: "Title for action that allows users to filter top read articles"), style: .default) { _ in self.currentSearchFilter = .top } let savedArticlesAction = UIAlertAction(title: WMFLocalizedString("places-filter-saved-articles", value:"Saved articles", comment:"Title of places search filter that searches saved articles"), style: .default) { _ in self.currentSearchFilter = .saved } alertController.addAction(topReadArticlesAction) alertController.addAction(savedArticlesAction) let checkedAction = currentSearchFilter == .top ? topReadArticlesAction : savedArticlesAction self.setCheckmark(for: checkedAction, in: alertController) alertController.addAction(UIAlertAction(title: CommonStrings.cancelActionTitle, style: .cancel)) alertController.popoverPresentationController?.barButtonItem = sender present(alertController, animated: true) } // MARK: - Map Region fileprivate func region(thatFits regionToFit: MKCoordinateRegion) -> MKCoordinateRegion { var region = mapView.regionThatFits(regionToFit) if region.span.latitudeDelta == 0 || region.span.longitudeDelta == 0 || region.span.latitudeDelta.isNaN || region.span.longitudeDelta.isNaN || region.span.latitudeDelta.isInfinite || region.span.longitudeDelta.isInfinite { region = regionToFit } return region } fileprivate var _mapRegion: MKCoordinateRegion? fileprivate var mapRegion: MKCoordinateRegion? { set { guard let value = newValue else { _mapRegion = nil return } let region = self.region(thatFits: value) _mapRegion = region regroupArticlesIfNecessary(forVisibleRegion: region) updateViewIfMapMovedSignificantly(forVisibleRegion: region) let mapViewRegion = mapView.region guard mapViewRegion.center.longitude != region.center.longitude || mapViewRegion.center.latitude != region.center.latitude || mapViewRegion.span.longitudeDelta != region.span.longitudeDelta || mapViewRegion.span.latitudeDelta != region.span.latitudeDelta else { selectVisibleKeyToSelectIfNecessary() return } guard !isViewModeOverlay || overlayState == .min else { let factor = UIApplication.shared.wmf_isRTL ? 0.1 : -0.1 let adjustedCenter = CLLocationCoordinate2DMake(region.center.latitude, region.center.longitude + factor * region.span.latitudeDelta) let adjustedRegion = MKCoordinateRegion(center: adjustedCenter, span: region.span) mapView.setRegion(adjustedRegion, animated: true) return } mapView.setRegion(region, animated: true) } get { return _mapRegion } } func region(thatFits articles: [WMFArticle]) -> MKCoordinateRegion { let coordinates: [CLLocationCoordinate2D] = articles.compactMap({ (article) -> CLLocationCoordinate2D? in return article.coordinate }) guard coordinates.count > 1 else { return coordinates.wmf_boundingRegion(with: 10000) } let initialRegion = coordinates.wmf_boundingRegion(with: 50) return coordinates.wmf_boundingRegion(with: 0.25 * initialRegion.width) } // MARK: - Searching var currentSearch: PlaceSearch? { didSet { guard let search = currentSearch else { return } updateSearchBarText(forSearch: search) performSearch(search) switch search.type { case .nearby: break case .location: guard !search.needsWikidataQuery else { break } fallthrough default: saveToHistory(search: search) } } } func performDefaultSearchIfNecessary(withRegion region: MKCoordinateRegion?) { guard currentSearch == nil else { return } performDefaultSearch(withRegion: region) } func isDefaultSearch(_ placeSearch: PlaceSearch) -> Bool { return placeSearch.type == .location && placeSearch.string == nil && placeSearch.searchResult == nil && placeSearch.origin == .system } func performDefaultSearch(withRegion region: MKCoordinateRegion?) { currentSearch = PlaceSearch(filter: currentSearchFilter, type: .location, origin: .system, sortStyle: .links, string: nil, region: region, localizedDescription: WMFLocalizedString("places-search-top-articles", value:"All top articles", comment:"A search suggestion for top articles"), searchResult: nil) } var articleFetchedResultsController: NSFetchedResultsController<WMFArticle>? { didSet { oldValue?.delegate = nil for article in oldValue?.fetchedObjects ?? [] { article.placesSortOrder = NSNumber(integerLiteral: 0) } do { try dataStore.viewContext.save() try articleFetchedResultsController?.performFetch() } catch let fetchError { DDLogError("Error fetching articles for places: \(fetchError)") } updatePlaces() articleFetchedResultsController?.delegate = self } } func isDistanceSignificant(betweenRegion searchRegion: MKCoordinateRegion, andRegion visibleRegion: MKCoordinateRegion) -> Bool { let distance = CLLocation(latitude: visibleRegion.center.latitude, longitude: visibleRegion.center.longitude).distance(from: CLLocation(latitude: searchRegion.center.latitude, longitude: searchRegion.center.longitude)) let searchWidth = searchRegion.width let searchHeight = searchRegion.height let searchRegionMinDimension = min(searchWidth, searchHeight) guard searchRegionMinDimension > 0 else { return distance > 1000 } let isDistanceSignificant = distance/searchRegionMinDimension > 0.33 guard !isDistanceSignificant else { return true } let visibleWidth = visibleRegion.width let visibleHeight = visibleRegion.height guard searchWidth > 0, visibleWidth > 0, visibleHeight > 0, searchHeight > 0 else { return false } let widthRatio = visibleWidth/searchWidth let heightRatio = visibleHeight/searchHeight let ratio = min(widthRatio, heightRatio) return ratio > 1.33 || ratio < 0.67 } func updateViewIfMapMovedSignificantly(forVisibleRegion visibleRegion: MKCoordinateRegion) { guard let searchRegion = currentSearchRegion else { redoSearchButton.isHidden = true return } let regionThatFits = region(thatFits: searchRegion) let movedSignificantly = isDistanceSignificant(betweenRegion: regionThatFits, andRegion: visibleRegion) DDLogDebug("movedSignificantly=\(movedSignificantly)") // Update Redo Search Button redoSearchButton.isHidden = !(movedSignificantly) if (movedSignificantly) { // Update Did You Mean Button hideDidYouMeanButton() // Clear count for Top Places _displayCountForTopPlaces = nil } } func performSearch(_ search: PlaceSearch) { guard !searching else { return } guard search.type != .nearby else { currentSearch = nil // will cause the default search to perform after re-centering recenterOnUserLocation(self) return } let done = { self.searching = false self.fakeProgressController.finish() } searching = true redoSearchButton.isHidden = true deselectAllAnnotations() updateSavedPlacesCountInCurrentMapRegionIfNecessary() hideDidYouMeanButton() let siteURL = search.siteURL ?? self.siteURL var searchTerm: String? = nil let sortStyle = search.sortStyle let region = search.region ?? mapRegion ?? mapView.region currentSearchRegion = region if (search.filter == .top && search.type == .location) { if (search.needsWikidataQuery) { performWikidataQuery(forSearch: search) return } } if let currentMapRegion = mapRegion, isDistanceSignificant(betweenRegion: region, andRegion: currentMapRegion) { mapRegion = region } else if mapRegion == nil { mapRegion = region } searchTerm = search.string self.fakeProgressController.start() switch search.filter { case .saved: let moc = dataStore.viewContext placeSearchService.performSearch(search, defaultSiteURL: siteURL, region: region, completion: { (result) in defer { done() } guard result.error == nil else { DDLogError("Error fetching saved articles: \(result.error?.localizedDescription ?? "unknown error")") return } guard let request = result.fetchRequest else { DDLogError("Error fetching saved articles: fetchRequest was nil") return } self.articleFetchedResultsController = NSFetchedResultsController<WMFArticle>(fetchRequest: request, managedObjectContext: self.dataStore.viewContext, sectionNameKeyPath: nil, cacheName: nil) do { let articlesToShow = try moc.fetch(request) self.articleKeyToSelect = articlesToShow.first?.key if !articlesToShow.isEmpty { if (self.currentSearch?.region == nil) { self.currentSearchRegion = self.region(thatFits: articlesToShow) self.mapRegion = self.currentSearchRegion } } if articlesToShow.isEmpty { self.wmf_showAlertWithMessage(WMFLocalizedString("places-no-saved-articles-have-location", value:"None of your saved articles have location information", comment:"Indicates to the user that none of their saved articles have location information")) } } catch let error { DDLogError("Error fetching saved articles: \(error.localizedDescription)") } }) case .top: placeSearchService.performSearch(search, defaultSiteURL: siteURL, region: region, completion: { (result) in defer { done() } guard result.error == nil else { if let error = result.error { WMFAlertManager.sharedInstance.showWarningAlert(result.error!.localizedDescription, sticky: false, dismissPreviousAlerts: true, tapCallBack: nil) let nserror = error as NSError if (nserror.code == Int(WMFLocationSearchErrorCode.noResults.rawValue)) { let completions = self.searchSuggestionController.searches[PlaceSearchSuggestionController.completionSection] if !completions.isEmpty { self.showDidYouMeanButton(search: completions[0]) } } } else { WMFAlertManager.sharedInstance.showWarningAlert(CommonStrings.unknownError, sticky: false, dismissPreviousAlerts: true, tapCallBack: nil) } return } guard let locationResults = result.locationResults else { assertionFailure("no error and missing location results") return } self.updatePlaces(withSearchResults: locationResults) }) } } func showDidYouMeanButton(search: PlaceSearch) { guard let description = search.localizedDescription else { DDLogError("Could not show Did You Mean button = no description for search:\n\(search)") return } DDLogDebug("Did you mean '\(String(describing: search.localizedDescription))'?") self.didYouMeanSearch = search self.didYouMeanButton.isHidden = false let title = String.localizedStringWithFormat(WMFLocalizedString("places-search-did-you-mean", value:"Did you mean %1$@?", comment:"Title displayed on a button shown when the current search has no results. %1$@ is replaced by the short description of the location of the most likely correction."), description) let buttonFont = redoSearchButton.titleLabel?.font let italicsFont = UIFont.italicSystemFont(ofSize: buttonFont?.pointSize ?? 15.0) let nsTitle = title as NSString let attributedTitle = NSMutableAttributedString(string: title) let descriptionRange = nsTitle.range(of: description) attributedTitle.addAttribute(NSAttributedString.Key.font, value: italicsFont, range: descriptionRange) self.didYouMeanButton.setAttributedTitle(attributedTitle, for: .normal) } func hideDidYouMeanButton() { didYouMeanButton.isHidden = true didYouMeanSearch = nil } func performWikidataQuery(forSearch search: PlaceSearch) { let fail = { DispatchQueue.main.async { self.searching = false var newSearch = search newSearch.needsWikidataQuery = false self.currentSearch = newSearch } } guard let articleURL = search.searchResult?.articleURL(forSiteURL: siteURL) else { fail() return } wikidataFetcher.wikidataBoundingRegion(forArticleURL: articleURL, failure: { (error) in DDLogError("Error fetching bounding region from Wikidata: \(error)") fail() }, success: { (region) in DispatchQueue.main.async { self.searching = false var newSearch = search newSearch.needsWikidataQuery = false newSearch.region = region self.currentSearch = newSearch } }) } func updatePlaces(withSearchResults searchResults: [MWKSearchResult]) { if let searchSuggestionArticleURL = currentSearch?.searchResult?.articleURL(forSiteURL: siteURL), let searchSuggestionArticleKey = searchSuggestionArticleURL.wmf_databaseKey { // the user tapped an article in the search suggestions list, so we should select that articleKeyToSelect = searchSuggestionArticleKey } else if currentSearch?.filter == .top { if let centerCoordinate = currentSearch?.region?.center ?? mapRegion?.center { let center = CLLocation(latitude: centerCoordinate.latitude, longitude: centerCoordinate.longitude) var minDistance = CLLocationDistance(Double.greatestFiniteMagnitude) var resultToSelect: MWKSearchResult? for result in searchResults { guard let location = result.location else { continue } let distance = location.distance(from: center) if distance < minDistance { minDistance = distance resultToSelect = result } } let resultURL = resultToSelect?.articleURL(forSiteURL: siteURL) articleKeyToSelect = resultURL?.wmf_databaseKey } else { let firstResultURL = searchResults.first?.articleURL(forSiteURL: siteURL) articleKeyToSelect = firstResultURL?.wmf_databaseKey } } var foundKey = false var keysToFetch: [String] = [] var sort = 1 for result in searchResults { guard let articleURL = result.articleURL(forSiteURL: siteURL), let article = self.dataStore.viewContext.fetchOrCreateArticle(with: articleURL, updatedWith: result), let _ = article.quadKey, let articleKey = article.key else { continue } article.placesSortOrder = NSNumber(value: sort) if articleKeyToSelect != nil && articleKeyToSelect == articleKey { foundKey = true } keysToFetch.append(articleKey) sort += 1 } if !foundKey, let keyToFetch = articleKeyToSelect, let URL = URL(string: keyToFetch), let searchResult = currentSearch?.searchResult { dataStore.viewContext.fetchOrCreateArticle(with: URL, updatedWith: searchResult) keysToFetch.append(keyToFetch) } let request = WMFArticle.fetchRequest() request.predicate = NSPredicate(format: "key in %@", keysToFetch) request.sortDescriptors = [NSSortDescriptor(keyPath: \WMFArticle.placesSortOrder, ascending: true)] articleFetchedResultsController = NSFetchedResultsController<WMFArticle>(fetchRequest: request, managedObjectContext: dataStore.viewContext, sectionNameKeyPath: nil, cacheName: nil) } func updatePlaces() { let articleURLs = articleFetchedResultsController?.fetchedObjects?.compactMap({ (article) -> URL? in return article.url }) listViewController.articleURLs = articleURLs ?? [] currentGroupingPrecision = 0 regroupArticlesIfNecessary(forVisibleRegion: mapRegion ?? mapView.region) if currentSearch?.region == nil { // this means the search was done in the curent map region and the map won't move selectVisibleKeyToSelectIfNecessary() } } func updateSavedPlacesCountInCurrentMapRegionIfNecessary() { guard _displayCountForTopPlaces == nil else { return } if let currentSearch = self.currentSearch, currentSearchFilter == .saved { var tempSearch = PlaceSearch(filter: .top, type: currentSearch.type, origin: .system, sortStyle: currentSearch.sortStyle, string: nil, region: mapView.region, localizedDescription: nil, searchResult: nil) tempSearch.needsWikidataQuery = false placeSearchService.performSearch(tempSearch, defaultSiteURL: siteURL, region: mapView.region, completion: { (searchResult) in guard let locationResults = searchResult.locationResults else { return } DDLogDebug("got \(locationResults.count) top places!") self._displayCountForTopPlaces = locationResults.count }) } } @IBAction func redoSearch(_ sender: Any) { guard let search = currentSearch else { return } redoSearchButton.isHidden = true if isDefaultSearch(search) || (search.type == .location && search.filter == .top) { performDefaultSearch(withRegion: mapView.region) } else { currentSearch = PlaceSearch(filter: currentSearchFilter, type: search.type, origin: .user, sortStyle: search.sortStyle, string: search.string, region: nil, localizedDescription: search.localizedDescription, searchResult: nil) } } @IBAction func didYouMean(_ sender: Any) { defer { hideDidYouMeanButton() } guard let search = self.didYouMeanSearch else { DDLogError("Did You Mean search is unset") return } performSearch(search) } // MARK: - Display Actions func deselectAllAnnotations() { for annotation in mapView.selectedAnnotations { mapView.deselectAnnotation(annotation, animated: true) } } var useOverlay: Bool { get { return traitCollection.horizontalSizeClass == .regular && traitCollection.verticalSizeClass == .regular } } func updateLayout(_ traitCollection: UITraitCollection, animated: Bool) { if useOverlay { switch viewMode { case .search: viewMode = .searchOverlay case .list: fallthrough case .map: viewMode = .listOverlay default: break } } else { switch viewMode { case .searchOverlay: viewMode = .search case .listOverlay: viewMode = .map default: break } } } enum ViewMode { case none case map case list case search case listOverlay case searchOverlay } fileprivate var overlaySliderPanGestureRecognizer: UIPanGestureRecognizer? var initialOverlayHeightForPan: CGFloat? let overlayMidHeight: CGFloat = 388 var overlayMinHeight: CGFloat { get { return 100 + listAndSearchOverlaySliderHeightConstraint.constant } } var overlayMaxHeight: CGFloat { get { return view.bounds.size.height - listAndSearchOverlayContainerView.frame.minY - listAndSearchOverlayBottomConstraint.constant } } enum OverlayState { case min case mid case max } func set(overlayState: OverlayState, withVelocity velocity: CGFloat, animated: Bool) { let currentHeight = listAndSearchOverlayHeightConstraint.constant let newHeight: CGFloat switch overlayState { case .min: newHeight = overlayMinHeight case .max: newHeight = overlayMaxHeight default: newHeight = overlayMidHeight } let springVelocity = velocity / (newHeight - currentHeight) self.view.layoutIfNeeded() let animations = { self.listAndSearchOverlayHeightConstraint.constant = newHeight self.view.layoutIfNeeded() } let duration: TimeInterval = 0.5 self.overlayState = overlayState UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: springVelocity, options: [.allowUserInteraction], animations: animations, completion: { (didFinish) in if overlayState == .max { self.listAndSearchOverlayHeightConstraint.isActive = false self.listAndSearchOverlayBottomConstraint.isActive = true } else { self.listAndSearchOverlayHeightConstraint.isActive = true self.listAndSearchOverlayBottomConstraint.isActive = false } }) } var overlayState = OverlayState.mid @objc func handlePanGesture(_ panGR: UIPanGestureRecognizer) { let minHeight = overlayMinHeight let maxHeight = overlayMaxHeight let midHeight = overlayMidHeight switch panGR.state { case .possible: fallthrough case .began: fallthrough case .changed: let initialHeight: CGFloat if let height = initialOverlayHeightForPan { initialHeight = height } else { if (overlayState == .max) { listAndSearchOverlayHeightConstraint.constant = listAndSearchOverlayContainerView.frame.height } initialHeight = listAndSearchOverlayHeightConstraint.constant initialOverlayHeightForPan = initialHeight listAndSearchOverlayHeightConstraint.isActive = true listAndSearchOverlayBottomConstraint.isActive = false } listAndSearchOverlayHeightConstraint.constant = max(minHeight, initialHeight + panGR.translation(in: view).y) case .ended: fallthrough case .failed: fallthrough case .cancelled: let currentHeight = listAndSearchOverlayHeightConstraint.constant let newState: OverlayState if currentHeight <= midHeight { let min: Bool = currentHeight - minHeight <= midHeight - currentHeight if min { newState = .min } else { newState = .mid } } else { let mid: Bool = currentHeight - midHeight <= maxHeight - currentHeight if mid { newState = .mid } else { newState = .max } } set(overlayState: newState, withVelocity: panGR.velocity(in: view).y, animated: true) initialOverlayHeightForPan = nil break @unknown default: break } } fileprivate func updateTraitBasedViewMode() { //forces an update let oldViewMode = self.viewMode self.viewMode = .none self.viewMode = oldViewMode } var isViewModeOverlay: Bool { get { return traitBasedViewMode == .listOverlay || traitBasedViewMode == .searchOverlay } } var traitBasedViewMode: ViewMode = .none { didSet { guard oldValue != traitBasedViewMode else { return } if oldValue == .search && viewMode != .search { UIView.animate(withDuration: 0.3) { self.mapListToggleContainer.alpha = 1 self.mapListToggleContainer.isHidden = false self.searchBarStackView.layoutIfNeeded() self.searchBar.setShowsCancelButton(false, animated: true) } } else if oldValue != .search && viewMode == .search { UIView.animate(withDuration: 0.3) { self.mapListToggleContainer.isHidden = true self.mapListToggleContainer.alpha = 0 self.searchBarStackView.layoutIfNeeded() self.searchBar.setShowsCancelButton(true, animated: true) } } switch traitBasedViewMode { case .listOverlay: deselectAllAnnotations() listViewController.updateLocationOnVisibleCells() logListViewImpressionsForVisibleCells() mapView.isHidden = false listContainerView.isHidden = false searchSuggestionView.isHidden = true listAndSearchOverlayContainerView.isHidden = false mapListToggleContainer.isHidden = true navigationBar.isInteractiveHidingEnabled = false listViewController.scrollView?.contentInsetAdjustmentBehavior = .automatic case .list: deselectAllAnnotations() listViewController.updateLocationOnVisibleCells() logListViewImpressionsForVisibleCells() emptySearchOverlayView.removeFromSuperview() mapView.isHidden = true listContainerView.isHidden = false searchSuggestionView.isHidden = true listAndSearchOverlayContainerView.isHidden = false navigationBar.isInteractiveHidingEnabled = true listViewController.scrollView?.contentInsetAdjustmentBehavior = .never case .searchOverlay: if overlayState == .min { set(overlayState: .mid, withVelocity: 0, animated: true) } mapView.isHidden = false listContainerView.isHidden = true searchSuggestionView.isHidden = false listAndSearchOverlayContainerView.isHidden = false navigationBar.isInteractiveHidingEnabled = false searchSuggestionView.contentInsetAdjustmentBehavior = .automatic scrollView = nil searchSuggestionController.navigationBarHider = nil case .search: mapView.isHidden = true listContainerView.isHidden = true searchSuggestionView.isHidden = false listAndSearchOverlayContainerView.isHidden = false navigationBar.isInteractiveHidingEnabled = true searchSuggestionView.contentInsetAdjustmentBehavior = .never scrollView = searchSuggestionView searchSuggestionController.navigationBarHider = navigationBarHider case .map: fallthrough default: mapView.isHidden = false listContainerView.isHidden = true searchSuggestionView.isHidden = true listAndSearchOverlayContainerView.isHidden = true navigationBar.isInteractiveHidingEnabled = false } recenterOnUserLocationButton.isHidden = mapView.isHidden if (mapView.isHidden) { redoSearchButton.isHidden = true } else { updateViewIfMapMovedSignificantly(forVisibleRegion: mapView.region) } listAndSearchOverlayContainerView.radius = isViewModeOverlay ? 5 : 0 } } var viewMode: ViewMode = .none { didSet { guard oldValue != viewMode, viewMode != .none else { return } switch viewMode { case .list: traitBasedViewMode = useOverlay ? .listOverlay : .list case .search: traitBasedViewMode = useOverlay ? .searchOverlay : .search case .map: fallthrough default: traitBasedViewMode = useOverlay ? .listOverlay : .map } } } struct OldString { static let noSavedPlaces = WMFLocalizedString("places-filter-no-saved-places", value:"You have no saved places", comment:"Explains that you don't have any saved places") static let savedArticlesFilterLocalizedTitle = WMFLocalizedString("places-filter-saved-articles", value:"Saved articles", comment:"Title of places search filter that searches saved articles") } var currentSearchFilter: PlaceFilterType = .top { // TODO: remember last setting? didSet { guard oldValue != currentSearchFilter else { return } switch viewMode { case .search: updateSearchCompletionsFromSearchBarText() default: if let currentSearch = self.currentSearch { self.currentSearch = PlaceSearch(filter: currentSearchFilter, type: currentSearch.type, origin: .system, sortStyle: currentSearch.sortStyle, string: currentSearch.string, region: nil, localizedDescription: currentSearch.localizedDescription, searchResult: currentSearch.searchResult, siteURL: currentSearch.siteURL) } } } } @objc func updateViewModeFromSegmentedControl() { switch mapListToggle.selectedSegmentIndex { case 0: viewMode = .map default: viewMode = .list } } @objc func updateViewModeToMap() { guard viewIfLoaded != nil else { return } viewMode = .map } func selectArticlePlace(_ articlePlace: ArticlePlace) { mapView.selectAnnotation(articlePlace, animated: articlePlace.identifier != previouslySelectedArticlePlaceIdentifier) previouslySelectedArticlePlaceIdentifier = articlePlace.identifier } // MARK: - Search History fileprivate func searchHistoryGroup(forFilter: PlaceFilterType) -> String { let searchHistoryGroup = "PlaceSearch" return "\(searchHistoryGroup).\(forFilter.stringValue)" } fileprivate func currentSearchHistoryGroup() -> String { return searchHistoryGroup(forFilter: currentSearchFilter) } func saveToHistory(search: PlaceSearch) { guard search.origin == .user else { DDLogDebug("not saving system search to history") return } do { let moc = dataStore.viewContext if let keyValue = keyValue(forPlaceSearch: search, inManagedObjectContext: moc) { keyValue.date = Date() } else if let entity = NSEntityDescription.entity(forEntityName: "WMFKeyValue", in: moc) { let keyValue = WMFKeyValue(entity: entity, insertInto: moc) keyValue.key = search.key keyValue.group = currentSearchHistoryGroup() keyValue.date = Date() keyValue.value = search.dictionaryValue as NSCoding } try moc.save() } catch let error { DDLogError("error saving to place search history: \(error.localizedDescription)") } } func clearSearchHistory() { do { let moc = dataStore.viewContext let request = WMFKeyValue.fetchRequest() request.predicate = NSPredicate(format: "group == %@", currentSearchHistoryGroup()) request.sortDescriptors = [NSSortDescriptor(keyPath: \WMFKeyValue.date, ascending: false)] let results = try moc.fetch(request) for result in results { moc.delete(result) } try moc.save() } catch let error { DDLogError("Error clearing recent place searches: \(error)") } } func keyValue(forPlaceSearch placeSearch: PlaceSearch, inManagedObjectContext moc: NSManagedObjectContext) -> WMFKeyValue? { var keyValue: WMFKeyValue? do { let key = placeSearch.key let request = WMFKeyValue.fetchRequest() request.predicate = NSPredicate(format: "key == %@ && group == %@", key, currentSearchHistoryGroup()) request.fetchLimit = 1 let results = try moc.fetch(request) keyValue = results.first } catch let error { DDLogError("Error fetching place search key value: \(error.localizedDescription)") } return keyValue } // MARK: - Location Access func promptForLocationAccess() { var skipSearchInDismissEnableLocationPanelHandler = false let enableLocationButtonTapHandler: ScrollableEducationPanelButtonTapHandler = { _ in skipSearchInDismissEnableLocationPanelHandler = true // Needed because the call to 'sender.dismiss' below triggers the 'dismissHandler', but we only want to perform the default search if the primary button was not tapped. self.presentedViewController?.dismiss(animated: true, completion: { guard WMFLocationManager.isAuthorizationNotDetermined() else { UIApplication.shared.wmf_openAppSpecificSystemSettings() return } self.locationManager.startMonitoringLocation() }) } let dismissEnableLocationPanelHandler: ScrollableEducationPanelDismissHandler = { if (!skipSearchInDismissEnableLocationPanelHandler) { self.performDefaultSearchIfNecessary(withRegion: nil) } } let enableLocationPanelVC = EnableLocationPanelViewController(showCloseButton: true, primaryButtonTapHandler: enableLocationButtonTapHandler, secondaryButtonTapHandler: nil, dismissHandler: dismissEnableLocationPanelHandler, theme: theme) present(enableLocationPanelVC, animated: true, completion: nil) } // MARK: - Place Grouping fileprivate var groupingTaskGroup: WMFTaskGroup? fileprivate var needsRegroup = false fileprivate var showingAllImages = false fileprivate var greaterThanOneArticleGroupCount = 0 struct ArticleGroup { var articles: [WMFArticle] = [] var latitudeSum: QuadKeyDegrees = 0 var longitudeSum: QuadKeyDegrees = 0 var latitudeAdjustment: QuadKeyDegrees = 0 var longitudeAdjustment: QuadKeyDegrees = 0 var baseQuadKey: QuadKey = 0 var baseQuadKeyPrecision: QuadKeyPrecision = 0 var location: CLLocation { get { return CLLocation(latitude: (latitudeSum + latitudeAdjustment)/CLLocationDegrees(articles.count), longitude: (longitudeSum + longitudeAdjustment)/CLLocationDegrees(articles.count)) } } init () { } init(article: WMFArticle) { articles = [article] latitudeSum = article.coordinate?.latitude ?? 0 longitudeSum = article.coordinate?.longitude ?? 0 baseQuadKey = article.quadKey ?? 0 baseQuadKeyPrecision = QuadKeyPrecision.maxPrecision } } func merge(group: ArticleGroup, key: String, groups: [String: ArticleGroup], groupingDistance: CLLocationDistance) -> Set<String> { var toMerge = Set<String>() if let keyToSelect = articleKeyToSelect, group.articles.first?.key == keyToSelect { //no grouping with the article to select return toMerge } let baseQuadKey = group.baseQuadKey let baseQuadKeyPrecision = group.baseQuadKeyPrecision let baseQuadKeyCoordinate = QuadKeyCoordinate(quadKey: baseQuadKey, precision: baseQuadKeyPrecision) if baseQuadKeyCoordinate.latitudePart > 2 && baseQuadKeyCoordinate.longitudePart > 1 { for t: Int64 in -1...1 { for n: Int64 in -1...1 { guard t != 0 || n != 0 else { continue } let latitudePart = QuadKeyPart(Int64(baseQuadKeyCoordinate.latitudePart) + 2*t) let longitudePart = QuadKeyPart(Int64(baseQuadKeyCoordinate.longitudePart) + n) let adjacentBaseQuadKey = QuadKey(latitudePart: latitudePart, longitudePart: longitudePart, precision: baseQuadKeyPrecision) let adjacentKey = "\(adjacentBaseQuadKey)|\(adjacentBaseQuadKey + 1)" guard let adjacentGroup = groups[adjacentKey] else { continue } if let keyToSelect = articleKeyToSelect, adjacentGroup.articles.first?.key == keyToSelect { //no grouping with the article to select continue } guard group.articles.count > 1 || adjacentGroup.articles.count > 1 else { continue } let location = group.location let distance = adjacentGroup.location.distance(from: location) let distanceToCheck = group.articles.count == 1 || adjacentGroup.articles.count == 1 ? 0.25*groupingDistance : groupingDistance if distance < distanceToCheck { toMerge.insert(adjacentKey) var newGroups = groups newGroups.removeValue(forKey: key) let others = merge(group: adjacentGroup, key: adjacentKey, groups: newGroups, groupingDistance: groupingDistance) toMerge.formUnion(others) } } } } return toMerge } func regroupArticlesIfNecessary(forVisibleRegion visibleRegion: MKCoordinateRegion) { guard groupingTaskGroup == nil else { needsRegroup = true return } assert(Thread.isMainThread) guard let searchRegion = currentSearchRegion else { return } let deltaLon = visibleRegion.span.longitudeDelta let lowestPrecision = QuadKeyPrecision(deltaLongitude: deltaLon) let searchDeltaLon = searchRegion.span.longitudeDelta let lowestSearchPrecision = QuadKeyPrecision(deltaLongitude: searchDeltaLon) var groupingAggressiveness: CLLocationDistance = 0.67 let groupingPrecisionDelta: QuadKeyPrecision = isViewModeOverlay ? 5 : 4 let maxPrecision: QuadKeyPrecision = isViewModeOverlay ? 18 : 17 let minGroupCount = 3 if lowestPrecision + groupingPrecisionDelta <= lowestSearchPrecision { groupingAggressiveness += 0.3 } let currentPrecision = lowestPrecision + groupingPrecisionDelta let groupingPrecision = min(maxPrecision, currentPrecision) guard groupingPrecision != currentGroupingPrecision else { return } let taskGroup = WMFTaskGroup() groupingTaskGroup = taskGroup let groupingDeltaLatitude = groupingPrecision.deltaLatitude let groupingDeltaLongitude = groupingPrecision.deltaLongitude let centerLat = searchRegion.center.latitude let centerLon = searchRegion.center.longitude let groupingDistanceLocation = CLLocation(latitude:centerLat + groupingDeltaLatitude, longitude: centerLon + groupingDeltaLongitude) let centerLocation = CLLocation(latitude:centerLat, longitude: centerLon) let groupingDistance = groupingAggressiveness * groupingDistanceLocation.distance(from: centerLocation) var previousPlaceByArticle: [String: ArticlePlace] = [:] var annotationsToRemove: [Int:ArticlePlace] = [:] for annotation in mapView.annotations { guard let place = annotation as? ArticlePlace else { continue } annotationsToRemove[place.identifier] = place for article in place.articles { guard let key = article.key else { continue } previousPlaceByArticle[key] = place } } var groups: [String: ArticleGroup] = [:] var splittableGroups: [String: ArticleGroup] = [:] for article in articleFetchedResultsController?.fetchedObjects ?? [] { guard let quadKey = article.quadKey else { continue } var group: ArticleGroup let adjustedQuadKey: QuadKey var key: String if groupingPrecision < maxPrecision && (articleKeyToSelect == nil || article.key != articleKeyToSelect) { adjustedQuadKey = quadKey.adjusted(downBy: QuadKeyPrecision.maxPrecision - groupingPrecision) let baseQuadKey = adjustedQuadKey - adjustedQuadKey % 2 key = "\(baseQuadKey)|\(baseQuadKey + 1)" // combine neighboring vertical keys group = groups[key] ?? ArticleGroup() group.baseQuadKey = baseQuadKey group.baseQuadKeyPrecision = groupingPrecision } else { group = ArticleGroup() adjustedQuadKey = quadKey key = "\(adjustedQuadKey)" if var existingGroup = groups[key] { let existingGroupArticleKey = existingGroup.articles.first?.key ?? "" let existingGroupTitle = existingGroup.articles.first?.displayTitle ?? "" existingGroup.latitudeAdjustment = 0.0001 * CLLocationDegrees(existingGroupArticleKey.hash) / CLLocationDegrees(Int.max) existingGroup.longitudeAdjustment = 0.0001 * CLLocationDegrees(existingGroupTitle.hash) / CLLocationDegrees(Int.max) groups[key] = existingGroup let articleKey = article.key ?? "" let articleTitle = article.displayTitle ?? "" group.latitudeAdjustment = 0.0001 * CLLocationDegrees(articleKey.hash) / CLLocationDegrees(Int.max) group.longitudeAdjustment = 0.0001 * CLLocationDegrees(articleTitle.hash) / CLLocationDegrees(Int.max) key = articleKey } group.baseQuadKey = quadKey group.baseQuadKeyPrecision = QuadKeyPrecision.maxPrecision } group.articles.append(article) let coordinate = QuadKeyCoordinate(quadKey: quadKey) group.latitudeSum += coordinate.latitude group.longitudeSum += coordinate.longitude groups[key] = group if group.articles.count > 1 { if group.articles.count < minGroupCount { splittableGroups[key] = group } else { splittableGroups[key] = nil } } } for (key, group) in splittableGroups { for (index, article) in group.articles.enumerated() { groups[key + ":\(index)"] = ArticleGroup(article: article) } groups.removeValue(forKey: key) } greaterThanOneArticleGroupCount = 0 let keys = groups.keys for key in keys { guard var group = groups[key] else { continue } if groupingPrecision < maxPrecision { let toMerge = merge(group: group, key: key, groups: groups, groupingDistance: groupingDistance) for adjacentKey in toMerge { guard let adjacentGroup = groups[adjacentKey] else { continue } group.articles.append(contentsOf: adjacentGroup.articles) group.latitudeSum += adjacentGroup.latitudeSum group.longitudeSum += adjacentGroup.longitudeSum groups.removeValue(forKey: adjacentKey) } if group.articles.count > 1 { greaterThanOneArticleGroupCount += 1 } } var nextCoordinate: CLLocationCoordinate2D? var coordinate = group.location.coordinate let identifier = ArticlePlace.identifierForArticles(articles: group.articles) //check for identical place already on the map if let _ = annotationsToRemove.removeValue(forKey: identifier) { continue } if group.articles.count == 1 { if let article = group.articles.first, let key = article.key, let previousPlace = previousPlaceByArticle[key] { nextCoordinate = coordinate coordinate = previousPlace.coordinate if let thumbnailURL = article.thumbnailURL { imageController.prefetch(withURL: thumbnailURL) } } } else { let groupCount = group.articles.count for article in group.articles { guard let key = article.key, let previousPlace = previousPlaceByArticle[key] else { continue } guard previousPlace.articles.count < groupCount else { nextCoordinate = coordinate coordinate = previousPlace.coordinate break } guard annotationsToRemove.removeValue(forKey: previousPlace.identifier) != nil else { continue } let placeView = mapView.view(for: previousPlace) taskGroup.enter() self.countOfAnimatingAnnotations += 1 UIView.animate(withDuration:animationDuration, delay: 0, options: [.allowUserInteraction], animations: { placeView?.alpha = 0 if (previousPlace.articles.count > 1) { placeView?.transform = CGAffineTransform(scaleX: self.animationScale, y: self.animationScale) } previousPlace.coordinate = coordinate }, completion: { (finished) in taskGroup.leave() self.mapView.removeAnnotation(previousPlace) self.countOfAnimatingAnnotations -= 1 }) } } guard let place = ArticlePlace(coordinate: coordinate, nextCoordinate: nextCoordinate, articles: group.articles, identifier: identifier) else { continue } mapView.addAnnotation(place) groups.removeValue(forKey: key) } for (_, annotation) in annotationsToRemove { let placeView = mapView.view(for: annotation) taskGroup.enter() self.countOfAnimatingAnnotations += 1 UIView.animate(withDuration: 0.5*animationDuration, animations: { placeView?.transform = CGAffineTransform(scaleX: self.animationScale, y: self.animationScale) placeView?.alpha = 0 }, completion: { (finished) in taskGroup.leave() self.mapView.removeAnnotation(annotation) self.countOfAnimatingAnnotations -= 1 }) } currentGroupingPrecision = groupingPrecision if greaterThanOneArticleGroupCount > 0 { set(shouldShowAllImages: false) } taskGroup.waitInBackground { self.groupingTaskGroup = nil self.selectVisibleKeyToSelectIfNecessary() if (self.needsRegroup) { self.needsRegroup = false self.regroupArticlesIfNecessary(forVisibleRegion: self.mapRegion ?? self.mapView.region) } } } // MARK: - Article Popover func showPopover(forAnnotationView annotationView: MapAnnotationView) { guard let place = annotationView.annotation as? ArticlePlace else { return } guard let article = place.articles.first, let coordinate = article.coordinate, let articleKey = article.key else { return } guard selectedArticlePopover == nil else { return } if isViewModeOverlay, let indexPath = articleFetchedResultsController?.indexPath(forObject: article) { listViewController.collectionView.scrollToItem(at: indexPath, at: .top, animated: true) } let articleVC = ArticlePopoverViewController(article) articleVC.delegate = self articleVC.view.alpha = 0 articleVC.apply(theme: theme) articleVC.configureView(withTraitCollection: traitCollection) let articleLocation = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude) if locationManager.isUpdating, let userLocation = locationManager.location { let distance = articleLocation.distance(from: userLocation) let distanceString = MKDistanceFormatter().string(fromDistance: distance) articleVC.descriptionLabel.text = distanceString } else { articleVC.descriptionLabel.text = nil } addChild(articleVC) view.insertSubview(articleVC.view, belowSubview: navigationBar) articleVC.didMove(toParent: self) let size = articleVC.view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) articleVC.preferredContentSize = size selectedArticlePopover = articleVC selectedArticleAnnotationView = annotationView selectedArticleKey = articleKey adjustLayout(ofPopover: articleVC, withSize:size, viewSize:view.bounds.size, forAnnotationView: annotationView) articleVC.update() UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged, argument: articleVC.view) articleVC.view.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin] articleVC.view.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) UIView.animate(withDuration: popoverFadeDuration) { articleVC.view.transform = CGAffineTransform.identity articleVC.view.alpha = 1 } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { (context) in if let popover = self.selectedArticlePopover, let annotationView = self.selectedArticleAnnotationView { self.adjustLayout(ofPopover: popover, withSize: popover.preferredContentSize, viewSize: size, forAnnotationView: annotationView) } self.updateTraitBasedViewMode() }, completion: nil) } override func scrollViewInsetsDidChange() { super.scrollViewInsetsDidChange() emptySearchOverlayView.frame = searchSuggestionView.frame.inset(by: searchSuggestionView.contentInset) } // MARK: HintPresenting var hintController: HintController? func dismissCurrentArticlePopover() { guard let popover = selectedArticlePopover else { return } UIView.animate(withDuration: popoverFadeDuration, animations: { popover.view.alpha = 0 popover.view.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) }) { (done) in popover.willMove(toParent: nil) popover.view.removeFromSuperview() popover.removeFromParent() } selectedArticlePopover = nil selectedArticleAnnotationView = nil } func articlePopoverViewController(articlePopoverViewController: ArticlePopoverViewController, didSelectAction action: WMFArticleAction) { perform(action: action, onArticle: articlePopoverViewController.article) } func perform(action: WMFArticleAction, onArticle article: WMFArticle) { guard let url = article.url else { return } switch action { case .read: navigate(to: url) break case .save: let didSave = dataStore.savedPageList.toggleSavedPage(for: url) if didSave { ReadingListsFunnel.shared.logSaveInPlaces(url) } else { ReadingListsFunnel.shared.logUnsaveInPlaces(url) } break case .share: let addToReadingListActivity = AddToReadingListActivity { let addArticlesToReadingListViewController = AddArticlesToReadingListViewController(with: self.dataStore, articles: [article], theme: self.theme) let navigationController = WMFThemeableNavigationController(rootViewController: addArticlesToReadingListViewController, theme: self.theme) navigationController.isNavigationBarHidden = true addArticlesToReadingListViewController.eventLogAction = { ReadingListsFunnel.shared.logSaveInPlaces(url) } self.present(navigationController, animated: true, completion: nil) } let shareActivityController = ShareActivityController(article: article, customActivities: [addToReadingListActivity]) shareActivityController.popoverPresentationController?.sourceView = view var sourceRect = view.bounds if let shareButton = selectedArticlePopover?.shareButton { sourceRect = view.convert(shareButton.frame, from: shareButton.superview) } shareActivityController.popoverPresentationController?.sourceRect = sourceRect shareActivityController.excludedActivityTypes = [.addToReadingList] present(shareActivityController, animated: true, completion: nil) break case .none: fallthrough default: break } } enum PopoverLocation { case top case bottom case left case right } func adjustLayout(ofPopover articleVC: ArticlePopoverViewController, withSize popoverSize: CGSize, viewSize: CGSize, forAnnotationView annotationView: MapAnnotationView) { var preferredLocations = [PopoverLocation]() let annotationSize = annotationView.frame.size let spacing: CGFloat = 5 let annotationCenter = view.convert(annotationView.center, from: mapView) if isViewModeOverlay { if UIApplication.shared.wmf_isRTL { if annotationCenter.x >= listAndSearchOverlayContainerView.frame.minX { preferredLocations = [.bottom, .left, .right, .top] } else { preferredLocations = [.left, .bottom, .top, .right] } } else { if annotationCenter.x <= listAndSearchOverlayContainerView.frame.maxX { preferredLocations = [.bottom, .right, .left, .top] } else { preferredLocations = [.right, .bottom, .top, .left] } } } let viewCenter = CGPoint(x: view.bounds.midX, y: view.bounds.midY) let popoverDistanceFromAnnotationCenterY = 0.5 * annotationSize.height + spacing let totalHeight = popoverDistanceFromAnnotationCenterY + popoverSize.height + spacing let top = totalHeight - annotationCenter.y let bottom = annotationCenter.y + totalHeight - viewSize.height let popoverDistanceFromAnnotationCenterX = 0.5 * annotationSize.width + spacing let totalWidth = popoverDistanceFromAnnotationCenterX + popoverSize.width + spacing let left = totalWidth - annotationCenter.x let right = annotationCenter.x + totalWidth - viewSize.width let navBarHeight = navigationBar.visibleHeight var x = annotationCenter.x > viewCenter.x ? viewSize.width - popoverSize.width - spacing : spacing var y = annotationCenter.y > viewCenter.y ? viewSize.height - popoverSize.height - spacing : spacing + navBarHeight let canFitTopOrBottom = viewSize.width - annotationCenter.x > 0.5*popoverSize.width && annotationCenter.x > 0.5*popoverSize.width let fitsTop = top < -navBarHeight && canFitTopOrBottom let fitsBottom = bottom < 0 && canFitTopOrBottom let canFitLeftOrRight = viewSize.height - annotationCenter.y > 0.5*popoverSize.height && annotationCenter.y - navBarHeight > 0.5*popoverSize.height let fitsLeft = left < 0 && canFitLeftOrRight let fitsRight = right < 0 && canFitLeftOrRight var didFitPreferredLocation = false for preferredLocation in preferredLocations { didFitPreferredLocation = true if preferredLocation == .top && fitsTop { x = annotationCenter.x - 0.5 * popoverSize.width y = annotationCenter.y - popoverDistanceFromAnnotationCenterY - popoverSize.height } else if preferredLocation == .bottom && fitsBottom { x = annotationCenter.x - 0.5 * popoverSize.width y = annotationCenter.y + popoverDistanceFromAnnotationCenterY } else if preferredLocation == .left && fitsLeft { x = annotationCenter.x - popoverDistanceFromAnnotationCenterX - popoverSize.width y = annotationCenter.y - 0.5 * popoverSize.height } else if preferredLocation == .right && fitsRight { x = annotationCenter.x + popoverDistanceFromAnnotationCenterX y = annotationCenter.y - 0.5 * popoverSize.height } else if preferredLocation == .top && top < -navBarHeight { y = annotationCenter.y - popoverDistanceFromAnnotationCenterY - popoverSize.height } else if preferredLocation == .bottom && bottom < 0 { y = annotationCenter.y + popoverDistanceFromAnnotationCenterY } else if preferredLocation == .left && left < 0 { x = annotationCenter.x - popoverDistanceFromAnnotationCenterX - popoverSize.width } else if preferredLocation == .right && right < 0 { x = annotationCenter.x + popoverDistanceFromAnnotationCenterX } else { didFitPreferredLocation = false } if didFitPreferredLocation { break } } if (!didFitPreferredLocation) { if (fitsTop || fitsBottom) { x = annotationCenter.x - 0.5 * popoverSize.width y = annotationCenter.y + (top < bottom ? 0 - popoverDistanceFromAnnotationCenterY - popoverSize.height : popoverDistanceFromAnnotationCenterY) } else if (fitsLeft || fitsRight) { x = annotationCenter.x + (left < right ? 0 - popoverDistanceFromAnnotationCenterX - popoverSize.width : popoverDistanceFromAnnotationCenterX) y = annotationCenter.y - 0.5 * popoverSize.height } else if (top < -navBarHeight) { y = annotationCenter.y - popoverDistanceFromAnnotationCenterY - popoverSize.height } else if (bottom < 0) { y = annotationCenter.y + popoverDistanceFromAnnotationCenterY } else if (left < 0) { x = annotationCenter.x - popoverDistanceFromAnnotationCenterX - popoverSize.width } else if (right < 0) { x = annotationCenter.x + popoverDistanceFromAnnotationCenterX } } articleVC.view.frame = CGRect(origin: CGPoint(x: x, y: y), size: popoverSize) } // MARK: - Search Filter Dropdown fileprivate func showSearchFilterDropdown(completion: @escaping ((Bool) -> Void)) { } fileprivate func hideSearchFilterDropdown(completion: @escaping ((Bool) -> Void)) { } fileprivate func updateSearchBarText(forSearch search: PlaceSearch) { if (isDefaultSearch(search)) { searchBar.text = nil } else { searchBar.text = search.string ?? search.localizedDescription } } fileprivate func updateSearchBarText() { guard let search = currentSearch else { searchBar.text = nil return } updateSearchBarText(forSearch: search) } func setupEmptySearchOverlayView() { emptySearchOverlayView.mainLabel.text = WMFLocalizedString("places-empty-search-title", value:"Search for Wikipedia articles with geographic locations", comment:"Title text shown on an overlay when there are no recent Places searches. Describes that you can search Wikipedia for articles with geographic locations.") emptySearchOverlayView.detailLabel.text = WMFLocalizedString("places-empty-search-description", value:"Explore cities, countries, continents, natural landmarks, historical events, buildings and more.", comment:"Detail text shown on an overlay when there are no recent Places searches. Describes the kind of articles you can search for.") } // MARK: - Search Suggestions & Completions var currentSearchString: String { guard let currentSearchString = searchBar.text?.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) else { return "" } return currentSearchString } func updateSearchSuggestions(withCompletions completions: [PlaceSearch], isSearchDone: Bool) { guard currentSearchString != "" || !completions.isEmpty else { // Search is empty, run a default search var defaultSuggestions = [PlaceSearch]() let yourLocationSuggestionTitle = WMFLocalizedString("places-search-your-current-location", value:"Your current location", comment:"A search suggestion for showing articles near your current location.") defaultSuggestions.append(PlaceSearch(filter: currentSearchFilter, type: .nearby, origin: .user, sortStyle: .links, string: nil, region: nil, localizedDescription: yourLocationSuggestionTitle, searchResult: nil)) switch (currentSearchFilter) { case .top: defaultSuggestions.append(PlaceSearch(filter: .top, type: .location, origin: .system, sortStyle: .links, string: nil, region: nil, localizedDescription: WMFLocalizedString("places-search-top-articles", value:"All top articles", comment:"A search suggestion for top articles"), searchResult: nil)) case .saved: defaultSuggestions.append(PlaceSearch(filter: .saved, type: .location, origin: .system, sortStyle: .links, string: nil, region: nil, localizedDescription: WMFLocalizedString("places-search-saved-articles", value:"All saved articles", comment:"A search suggestion for saved articles"), searchResult: nil)) } var recentSearches: [PlaceSearch] = [] do { let moc = dataStore.viewContext let request = WMFKeyValue.fetchRequest() request.predicate = NSPredicate(format: "group == %@", currentSearchHistoryGroup()) request.sortDescriptors = [NSSortDescriptor(keyPath: \WMFKeyValue.date, ascending: false)] let results = try moc.fetch(request) let count = results.count if count > searchHistoryCountLimit { for result in results[searchHistoryCountLimit..<count] { moc.delete(result) } } let limit = min(count, searchHistoryCountLimit) recentSearches = try results[0..<limit].map({ (kv) -> PlaceSearch in guard let ps = PlaceSearch(object: kv.value) else { throw PlaceSearchError.deserialization(object: kv.value) } return ps }) } catch let error { DDLogError("Error fetching recent place searches: \(error)") } searchSuggestionController.siteURL = siteURL searchSuggestionController.searches = [defaultSuggestions, recentSearches, [], []] let searchText = searchBar.text ?? "" if !searchText.wmf_hasNonWhitespaceText && recentSearches.isEmpty { setupEmptySearchOverlayView() emptySearchOverlayView.frame = searchSuggestionView.frame.inset(by: searchSuggestionView.contentInset) searchSuggestionView.superview?.addSubview(emptySearchOverlayView) } else { emptySearchOverlayView.removeFromSuperview() } return } emptySearchOverlayView.removeFromSuperview() guard currentSearchString != "" else { searchSuggestionController.searches = [[], [], [], completions] return } let currentSearchScopeName: String switch (currentSearchFilter) { case .top: currentSearchScopeName = WMFLocalizedString("places-search-top-articles-that-match-scope", value: "Nearby", comment: "Title used in search description when searching an area for Top articles") case .saved: currentSearchScopeName = OldString.savedArticlesFilterLocalizedTitle } var currentSearchStringSuggestions = [PlaceSearch]() if isSearchDone { let currentSearchStringTitle = String.localizedStringWithFormat(WMFLocalizedString("places-search-articles-that-match", value:"%1$@ matching “%2$@”", comment:"A search suggestion for filtering the articles in the area by the search string. %1$@ is replaced by the a string depending on the current filter ('Nearby' for 'Top Articles' or 'Saved articles'). %2$@ is replaced with the search string"), currentSearchScopeName, currentSearchString) currentSearchStringSuggestions.append(PlaceSearch(filter: currentSearchFilter, type: .text, origin: .user, sortStyle: .links, string: currentSearchString, region: nil, localizedDescription: currentSearchStringTitle, searchResult: nil)) } searchSuggestionController.searches = [[], [], currentSearchStringSuggestions, completions] } func handleCompletion(searchResults: [MWKSearchResult], siteURL: URL) -> [PlaceSearch] { var set = Set<String>() let completions = searchResults.compactMap { (result) -> PlaceSearch? in guard let location = result.location, let dimension = result.geoDimension?.doubleValue, let url = result.articleURL(forSiteURL: siteURL), let key = url.wmf_databaseKey, !set.contains(key) else { return nil } set.insert(key) let region = [location.coordinate].wmf_boundingRegion(with: dimension) return PlaceSearch(filter: currentSearchFilter, type: .location, origin: .user, sortStyle: .links, string: nil, region: region, localizedDescription: result.displayTitle, searchResult: result, siteURL: siteURL) } updateSearchSuggestions(withCompletions: completions, isSearchDone: true) return completions } @objc public func showNearbyArticles() { guard let _ = view else { // force view instantiation return } guard currentSearch != nil else { // if current search is nil, this is the initial setup for the view and it will recenter automatically return } currentSearch = nil // will cause the default search to perform after re-centering recenterOnUserLocation(self) } @objc public func showArticleURL(_ articleURL: URL) { guard let article = dataStore.fetchArticle(with: articleURL), let title = articleURL.wmf_title, let _ = view else { // force view instantiation return } let region = self.region(thatFits: [article]) let displayTitleHTML = article.displayTitleHTML let displayTitle = article.displayTitle ?? title let searchResult = MWKSearchResult(articleID: 0, revID: 0, title: title, displayTitle: displayTitle, displayTitleHTML: displayTitleHTML, wikidataDescription: article.wikidataDescription, extract: article.snippet, thumbnailURL: article.thumbnailURL, index: nil, titleNamespace: nil, location: article.location) currentSearch = PlaceSearch(filter: .top, type: .location, origin: .user, sortStyle: .links, string: nil, region: region, localizedDescription: title, searchResult: searchResult, siteURL: articleURL.wmf_site) } fileprivate func searchForFirstSearchSuggestion() { if !searchSuggestionController.searches[PlaceSearchSuggestionController.completionSection].isEmpty { currentSearch = searchSuggestionController.searches[PlaceSearchSuggestionController.completionSection][0] } else if !searchSuggestionController.searches[PlaceSearchSuggestionController.currentStringSection].isEmpty { currentSearch = searchSuggestionController.searches[PlaceSearchSuggestionController.currentStringSection][0] } } fileprivate var isWaitingForSearchSuggestionUpdate = false { didSet { if (oldValue == false && isWaitingForSearchSuggestionUpdate == true) { // start progress bar fakeProgressController.start() } else if (isWaitingForSearchSuggestionUpdate == false) { // stop progress bar fakeProgressController.finish() } } } @objc func updateSearchCompletionsFromSearchBarText() { switch currentSearchFilter { case .saved: updateSearchSuggestions(withCompletions: [], isSearchDone: true) self.isWaitingForSearchSuggestionUpdate = false default: updateSearchCompletionsFromSearchBarTextForTopArticles() } } func updateSearchCompletionsFromSearchBarTextForTopArticles() { guard let text = searchBar.text?.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines), text != "" else { updateSearchSuggestions(withCompletions: [], isSearchDone: false) self.isWaitingForSearchSuggestionUpdate = false return } let siteURL = self.siteURL searchFetcher.fetchArticles(forSearchTerm: text, siteURL: siteURL, resultLimit: 24, failure: { (error) in DispatchQueue.main.async { guard text == self.searchBar.text else { return } self.updateSearchSuggestions(withCompletions: [], isSearchDone: false) self.isWaitingForSearchSuggestionUpdate = false } }) { (searchResult) in DispatchQueue.main.async { guard text == self.searchBar.text else { return } if let suggestion = searchResult.searchSuggestion { DDLogDebug("got suggestion! \(suggestion)") } let completions = self.handleCompletion(searchResults: searchResult.results ?? [], siteURL: siteURL) self.isWaitingForSearchSuggestionUpdate = false guard completions.count < 10 else { return } let center = self.mapView.userLocation.coordinate let region = CLCircularRegion(center: center, radius: 40075000, identifier: "world") self.locationSearchFetcher.fetchArticles(withSiteURL: self.siteURL, in: region, matchingSearchTerm: text, sortStyle: .links, resultLimit: 24, completion: { (locationSearchResults) in DispatchQueue.main.async { guard text == self.searchBar.text else { return } var combinedResults: [MWKSearchResult] = searchResult.results ?? [] let newResults = locationSearchResults.results as [MWKSearchResult] combinedResults.append(contentsOf: newResults) let _ = self.handleCompletion(searchResults: combinedResults, siteURL: siteURL) } }) { (error) in } } } } private func closeSearch() { searchBar.endEditing(true) currentSearch = nil performDefaultSearchIfNecessary(withRegion: nil) UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged, argument: view) } // MARK: - UISearchBarDelegate func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { viewMode = .search deselectAllAnnotations() // Only update suggestion on *begin* editing if there is no text // Otherwise, it just clears perfectly good results if currentSearchString == "" { updateSearchSuggestions(withCompletions: [], isSearchDone: false) } } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { isWaitingForSearchSuggestionUpdate = true NSObject.cancelPreviousPerformRequests(withTarget: self) perform(#selector(updateSearchCompletionsFromSearchBarText), with: nil, afterDelay: 0.2) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { closeSearch() } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { guard let searchText = searchBar.text else { assertionFailure("could not read search text") return } guard !searchText.trimmingCharacters(in: .whitespaces).isEmpty else { return } guard !isWaitingForSearchSuggestionUpdate else { return } searchBar.endEditing(true) searchForFirstSearchSuggestion() } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { updateViewModeFromSegmentedControl() } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let article = article(at: indexPath) else { return } perform(action: .read, onArticle: article) } // MARK: - PlaceSearchSuggestionControllerDelegate func placeSearchSuggestionController(_ controller: PlaceSearchSuggestionController, didSelectSearch search: PlaceSearch) { searchBar.endEditing(true) currentSearch = search } func placeSearchSuggestionControllerClearButtonPressed(_ controller: PlaceSearchSuggestionController) { clearSearchHistory() updateSearchSuggestions(withCompletions: [], isSearchDone: false) } func placeSearchSuggestionController(_ controller: PlaceSearchSuggestionController, didDeleteSearch search: PlaceSearch) { let moc = dataStore.viewContext guard let kv = keyValue(forPlaceSearch: search, inManagedObjectContext: moc) else { return } moc.delete(kv) do { try moc.save() } catch let error { DDLogError("Error removing kv: \(error.localizedDescription)") } updateSearchSuggestions(withCompletions: [], isSearchDone: false) } // MARK: - WMFLocationManagerDelegate func updateUserLocationAnnotationViewHeading(_ heading: CLHeading) { guard let view = mapView.view(for: mapView.userLocation) as? UserLocationAnnotationView else { return } view.isHeadingArrowVisible = heading.headingAccuracy > 0 && heading.headingAccuracy < 90 view.heading = heading.trueHeading } func zoomAndPanMapView(toLocation location: CLLocation) { let region = [location.coordinate].wmf_boundingRegion(with: 10000) mapRegion = region if let searchRegion = currentSearchRegion, isDistanceSignificant(betweenRegion: searchRegion, andRegion: region) { performDefaultSearch(withRegion: mapRegion) } else { performDefaultSearchIfNecessary(withRegion: region) } } var panMapToNextLocationUpdate = true func locationManager(_ controller: WMFLocationManager, didUpdate location: CLLocation) { guard panMapToNextLocationUpdate else { return } panMapToNextLocationUpdate = false zoomAndPanMapView(toLocation: location) } func locationManager(_ controller: WMFLocationManager, didReceiveError error: Error) { } func locationManager(_ controller: WMFLocationManager, didUpdate heading: CLHeading) { updateUserLocationAnnotationViewHeading(heading) } func locationManager(_ controller: WMFLocationManager, didChangeEnabledState enabled: Bool) { if enabled { panMapToNextLocationUpdate = currentSearch == nil locationManager.startMonitoringLocation() } else { panMapToNextLocationUpdate = false locationManager.stopMonitoringLocation() performDefaultSearchIfNecessary(withRegion: nil) } } @IBAction fileprivate func recenterOnUserLocation(_ sender: Any) { guard WMFLocationManager.isAuthorized(), let userLocation = locationManager.location else { promptForLocationAccess() return } zoomAndPanMapView(toLocation: userLocation) } // MARK: - NSFetchedResultsControllerDelegate func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { updatePlaces() } // MARK: - UIPopoverPresentationControllerDelegate func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } func popoverPresentationController(_ popoverPresentationController: UIPopoverPresentationController, willRepositionPopoverTo rect: UnsafeMutablePointer<CGRect>, in view: AutoreleasingUnsafeMutablePointer<UIView>) { let oldRect = rect.pointee let center = CGPoint(x: view.pointee.bounds.midX, y: view.pointee.bounds.midY) let newOrigin = CGPoint(x: center.x - 0.5*oldRect.width, y: center.y - 0.5*oldRect.height) rect.pointee = CGRect(origin: newOrigin, size: oldRect.size) } // MARK: - ArticlePlaceViewDelegate func articlePlaceViewWasTapped(_ articlePlaceView: ArticlePlaceView) { guard let article = selectedArticlePopover?.article else { return } perform(action: .read, onArticle: article) } // MARK: - UIGestureRecognizerDelegate func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { guard gestureRecognizer === overlaySliderPanGestureRecognizer else { return false } let location = touch.location(in: view) let shouldReceive = location.x < listAndSearchOverlayContainerView.frame.maxX && abs(location.y - listAndSearchOverlayContainerView.frame.maxY - 10) < 32 return shouldReceive } // MARK: - Themeable override func apply(theme: Theme) { super.apply(theme: theme) guard viewIfLoaded != nil else { return } view.backgroundColor = theme.colors.baseBackground navigationBar.apply(theme: theme) searchBar.apply(theme: theme) searchBar.backgroundColor = theme.colors.paperBackground searchSuggestionController.apply(theme: theme) listAndSearchOverlayContainerView.backgroundColor = theme.colors.chromeBackground listAndSearchOverlaySliderView.backgroundColor = theme.colors.chromeBackground listAndSearchOverlaySliderView.tintColor = theme.colors.tertiaryText mapContainerView.backgroundColor = theme.colors.baseBackground listAndSearchOverlaySliderSeparator.backgroundColor = theme.colors.midBackground emptySearchOverlayView.backgroundColor = theme.colors.midBackground emptySearchOverlayView.mainLabel.textColor = theme.colors.primaryText emptySearchOverlayView.detailLabel.textColor = theme.colors.secondaryText recenterOnUserLocationButton.backgroundColor = theme.colors.chromeBackground selectedArticlePopover?.apply(theme: theme) redoSearchButton.backgroundColor = theme.colors.link didYouMeanButton.backgroundColor = theme.colors.link listViewController.apply(theme: theme) } } extension PlacesViewController { func regionWillChange() { deselectAllAnnotations() isMovingToRegion = true hintController?.dismissHintDueToUserInteraction() } func regionDidChange() { _mapRegion = mapView.region guard performDefaultSearchOnNextMapRegionUpdate == false else { performDefaultSearchOnNextMapRegionUpdate = false performDefaultSearchIfNecessary(withRegion: nil) return } regroupArticlesIfNecessary(forVisibleRegion: mapView.region) updateViewIfMapMovedSignificantly(forVisibleRegion: mapView.region) isMovingToRegion = false selectVisibleKeyToSelectIfNecessary() updateShouldShowAllImagesIfNecessary() } func didSelect(place: ArticlePlace, annotationView: MapAnnotationView) { previouslySelectedArticlePlaceIdentifier = place.identifier guard place.articles.count == 1 else { deselectAllAnnotations() var minDistance = CLLocationDistanceMax let center = CLLocation(latitude: place.coordinate.latitude, longitude: place.coordinate.longitude) for article in place.articles { guard let location = article.location else { continue } let distance = location.distance(from: center) if distance < minDistance { minDistance = distance articleKeyToSelect = article.key } } mapRegion = region(thatFits: place.articles) return } showPopover(forAnnotationView: annotationView) } func didDeselectAnnotation() { selectedArticleKey = nil dismissCurrentArticlePopover() } func viewFor(place: ArticlePlace) -> MapAnnotationView? { let reuseIdentifier = "org.wikimedia.articlePlaceView" var placeView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) as! ArticlePlaceView? if placeView == nil { #if OSM placeView = ArticlePlaceView(reuseIdentifier: reuseIdentifier) #else placeView = ArticlePlaceView(annotation: place, reuseIdentifier: reuseIdentifier) #endif } else { placeView?.prepareForReuse() placeView?.annotation = place } placeView?.delegate = self if showingAllImages { placeView?.set(alwaysShowImage: true, animated: false) } if place.articles.count > 1 && place.nextCoordinate == nil { placeView?.alpha = 0 placeView?.transform = CGAffineTransform(scaleX: animationScale, y: animationScale) DispatchQueue.main.async { self.countOfAnimatingAnnotations += 1 UIView.animate(withDuration: self.animationDuration, delay: 0, options: .allowUserInteraction, animations: { placeView?.transform = CGAffineTransform.identity placeView?.alpha = 1 }, completion: { (done) in self.countOfAnimatingAnnotations -= 1 }) } } else if let nextCoordinate = place.nextCoordinate { placeView?.alpha = 0 DispatchQueue.main.async { self.countOfAnimatingAnnotations += 1 UIView.animate(withDuration: 2*self.animationDuration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: .allowUserInteraction, animations: { place.coordinate = nextCoordinate }, completion: { (done) in self.countOfAnimatingAnnotations -= 1 }) UIView.animate(withDuration: 0.5*self.animationDuration, delay: 0, options: .allowUserInteraction, animations: { placeView?.alpha = 1 }, completion: nil) } } else { placeView?.alpha = 0 DispatchQueue.main.async { self.countOfAnimatingAnnotations += 1 UIView.animate(withDuration: self.animationDuration, delay: 0, options: .allowUserInteraction, animations: { placeView?.alpha = 1 }, completion: { (done) in self.countOfAnimatingAnnotations -= 1 }) } } return placeView } } #if OSM // MARK: - MGLMapViewDelegate extension PlacesViewController: MGLMapViewDelegate { func mapView(_ mapView: MGLMapView, regionWillChangeAnimated animated: Bool) { regionWillChange() } func mapView(_ mapView: MGLMapView, regionDidChangeAnimated animated: Bool) { regionDidChange() } func mapView(_ mapView: MGLMapView, didSelect annotationView: MGLAnnotationView) { guard let place = annotationView.annotation as? ArticlePlace, let annotationView = annotationView as? MapAnnotationView else { return } didSelect(place: place, annotationView: annotationView) } func mapView(_ mapView: MGLMapView, didDeselect view: MGLAnnotationView) { didDeselectAnnotation() } func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? { guard let place = annotation as? ArticlePlace else { return nil } return viewFor(place: place) } func mapView(_ mapView: MGLMapView, didFinishLoading style: MGLStyle) { } } #else // MARK: - MKMapViewDelegate extension PlacesViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) { regionWillChange() } func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { regionDidChange() } func mapView(_ mapView: MKMapView, didSelect annotationView: MKAnnotationView) { guard let place = annotationView.annotation as? ArticlePlace, let annotationView = annotationView as? MapAnnotationView else { return } didSelect(place: place, annotationView: annotationView) } func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) { didDeselectAnnotation() } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { guard let place = annotation as? ArticlePlace else { // CRASH WORKAROUND // The UIPopoverController that the map view presents from the default user location annotation is causing a crash. Using our own annotation view for the user location works around this issue. if let userLocation = annotation as? MKUserLocation { let userViewReuseIdentifier = "org.wikimedia.userLocationAnnotationView" let placeView = mapView.dequeueReusableAnnotationView(withIdentifier: userViewReuseIdentifier) as? UserLocationAnnotationView ?? UserLocationAnnotationView(annotation: userLocation, reuseIdentifier: userViewReuseIdentifier) placeView.annotation = userLocation return placeView } return nil } return viewFor(place: place) } } #endif // MARK: - class PlaceSearchEmptySearchOverlayView: UIView { @IBOutlet weak var mainLabel: UILabel! @IBOutlet weak var detailLabel: UILabel! } // MARK: - UIViewControllerPreviewingDelegate extension PlacesViewController { override func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard viewMode == .list else { return nil } return listViewController.previewingContext(previewingContext, viewControllerForLocation: location) } override func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { viewControllerToCommit.wmf_removePeekableChildViewControllers() if let articleViewController = viewControllerToCommit as? WMFArticleViewController { wmf_push(articleViewController, animated: true) } else { wmf_push(viewControllerToCommit, animated: true) } } } // MARK: - Accessibility extension PlacesViewController { override func accessibilityPerformEscape() -> Bool { switch viewMode { case .search: closeSearch() return true default: if selectedArticlePopover != nil { deselectAllAnnotations() return true } else { return false } } } }
43.848509
455
0.630056
e054270285c44dce8e44df83314c586da08890e3
108,775
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: operations.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } ///Статус запрашиваемых операций public enum OperationState: SwiftProtobuf.Enum { public typealias RawValue = Int ///Статус операции не определён case unspecified // = 0 ///Исполнена case executed // = 1 ///Отменена case canceled // = 2 case UNRECOGNIZED(Int) public init() { self = .unspecified } public init?(rawValue: Int) { switch rawValue { case 0: self = .unspecified case 1: self = .executed case 2: self = .canceled default: self = .UNRECOGNIZED(rawValue) } } public var rawValue: Int { switch self { case .unspecified: return 0 case .executed: return 1 case .canceled: return 2 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension OperationState: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. public static var allCases: [OperationState] = [ .unspecified, .executed, .canceled, ] } #endif // swift(>=4.2) ///Тип операции public enum OperationType: SwiftProtobuf.Enum { public typealias RawValue = Int ///Тип операции не определён case unspecified // = 0 ///Завод денежных средств case input // = 1 ///Удержание налога по купонам case bondTax // = 2 ///Вывод ЦБ case outputSecurities // = 3 ///Доход по сделке РЕПО овернайт case overnight // = 4 ///Удержание налога case tax // = 5 ///Полное погашение облигаций case bondRepaymentFull // = 6 ///Продажа ЦБ с карты case sellCard // = 7 ///Удержание налога по дивидендам case dividendTax // = 8 ///Вывод денежных средств case output // = 9 ///Частичное погашение облигаций case bondRepayment // = 10 ///Корректировка налога case taxCorrection // = 11 ///Удержание комиссии за обслуживание брокерского счёта case serviceFee // = 12 ///Удержание налога за материальную выгоду case benefitTax // = 13 ///Удержание комиссии за непокрытую позицию case marginFee // = 14 ///Покупка ЦБ case buy // = 15 ///Покупка ЦБ с карты case buyCard // = 16 ///Завод ЦБ case inputSecurities // = 17 ///Продажа в результате Margin-call case sellMargin // = 18 ///Удержание комиссии за операцию case brokerFee // = 19 ///Покупка в результате Margin-call case buyMargin // = 20 ///Выплата дивидендов case dividend // = 21 ///Продажа ЦБ case sell // = 22 ///Выплата купонов case coupon // = 23 ///Удержание комиссии SuccessFee case successFee // = 24 ///Передача дивидендного дохода case dividendTransfer // = 25 ///Зачисление вариационной маржи case accruingVarmargin // = 26 ///Списание вариационной маржи case writingOffVarmargin // = 27 ///Покупка в рамках экспирации фьючерсного контракта case deliveryBuy // = 28 ///Продажа в рамках экспирации фьючерсного контракта case deliverySell // = 29 ///Комиссия за управление по счёту автоследования case trackMfee // = 30 ///Комиссия за результат по счёту автоследования case trackPfee // = 31 ///Удержание налога по ставке 15% case taxProgressive // = 32 ///Удержание налога по купонам по ставке 15% case bondTaxProgressive // = 33 ///Удержание налога по дивидендам по ставке 15% case dividendTaxProgressive // = 34 ///Удержание налога за материальную выгоду по ставке 15% case benefitTaxProgressive // = 35 ///Корректировка налога по ставке 15% case taxCorrectionProgressive // = 36 ///Удержание налога за возмещение по сделкам РЕПО по ставке 15% case taxRepoProgressive // = 37 ///Удержание налога за возмещение по сделкам РЕПО case taxRepo // = 38 ///Удержание налога по сделкам РЕПО case taxRepoHold // = 39 ///Возврат налога по сделкам РЕПО case taxRepoRefund // = 40 ///Удержание налога по сделкам РЕПО по ставке 15% case taxRepoHoldProgressive // = 41 ///Возврат налога по сделкам РЕПО по ставке 15% case taxRepoRefundProgressive // = 42 ///Выплата дивидендов на карту case divExt // = 43 case UNRECOGNIZED(Int) public init() { self = .unspecified } public init?(rawValue: Int) { switch rawValue { case 0: self = .unspecified case 1: self = .input case 2: self = .bondTax case 3: self = .outputSecurities case 4: self = .overnight case 5: self = .tax case 6: self = .bondRepaymentFull case 7: self = .sellCard case 8: self = .dividendTax case 9: self = .output case 10: self = .bondRepayment case 11: self = .taxCorrection case 12: self = .serviceFee case 13: self = .benefitTax case 14: self = .marginFee case 15: self = .buy case 16: self = .buyCard case 17: self = .inputSecurities case 18: self = .sellMargin case 19: self = .brokerFee case 20: self = .buyMargin case 21: self = .dividend case 22: self = .sell case 23: self = .coupon case 24: self = .successFee case 25: self = .dividendTransfer case 26: self = .accruingVarmargin case 27: self = .writingOffVarmargin case 28: self = .deliveryBuy case 29: self = .deliverySell case 30: self = .trackMfee case 31: self = .trackPfee case 32: self = .taxProgressive case 33: self = .bondTaxProgressive case 34: self = .dividendTaxProgressive case 35: self = .benefitTaxProgressive case 36: self = .taxCorrectionProgressive case 37: self = .taxRepoProgressive case 38: self = .taxRepo case 39: self = .taxRepoHold case 40: self = .taxRepoRefund case 41: self = .taxRepoHoldProgressive case 42: self = .taxRepoRefundProgressive case 43: self = .divExt default: self = .UNRECOGNIZED(rawValue) } } public var rawValue: Int { switch self { case .unspecified: return 0 case .input: return 1 case .bondTax: return 2 case .outputSecurities: return 3 case .overnight: return 4 case .tax: return 5 case .bondRepaymentFull: return 6 case .sellCard: return 7 case .dividendTax: return 8 case .output: return 9 case .bondRepayment: return 10 case .taxCorrection: return 11 case .serviceFee: return 12 case .benefitTax: return 13 case .marginFee: return 14 case .buy: return 15 case .buyCard: return 16 case .inputSecurities: return 17 case .sellMargin: return 18 case .brokerFee: return 19 case .buyMargin: return 20 case .dividend: return 21 case .sell: return 22 case .coupon: return 23 case .successFee: return 24 case .dividendTransfer: return 25 case .accruingVarmargin: return 26 case .writingOffVarmargin: return 27 case .deliveryBuy: return 28 case .deliverySell: return 29 case .trackMfee: return 30 case .trackPfee: return 31 case .taxProgressive: return 32 case .bondTaxProgressive: return 33 case .dividendTaxProgressive: return 34 case .benefitTaxProgressive: return 35 case .taxCorrectionProgressive: return 36 case .taxRepoProgressive: return 37 case .taxRepo: return 38 case .taxRepoHold: return 39 case .taxRepoRefund: return 40 case .taxRepoHoldProgressive: return 41 case .taxRepoRefundProgressive: return 42 case .divExt: return 43 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension OperationType: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. public static var allCases: [OperationType] = [ .unspecified, .input, .bondTax, .outputSecurities, .overnight, .tax, .bondRepaymentFull, .sellCard, .dividendTax, .output, .bondRepayment, .taxCorrection, .serviceFee, .benefitTax, .marginFee, .buy, .buyCard, .inputSecurities, .sellMargin, .brokerFee, .buyMargin, .dividend, .sell, .coupon, .successFee, .dividendTransfer, .accruingVarmargin, .writingOffVarmargin, .deliveryBuy, .deliverySell, .trackMfee, .trackPfee, .taxProgressive, .bondTaxProgressive, .dividendTaxProgressive, .benefitTaxProgressive, .taxCorrectionProgressive, .taxRepoProgressive, .taxRepo, .taxRepoHold, .taxRepoRefund, .taxRepoHoldProgressive, .taxRepoRefundProgressive, .divExt, ] } #endif // swift(>=4.2) ///Запрос получения списка операций по счёту. public struct OperationsRequest { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Идентификатор счёта клиента public var accountID: String = String() ///Начало периода (по UTC) public var from: SwiftProtobuf.Google_Protobuf_Timestamp { get {return _from ?? SwiftProtobuf.Google_Protobuf_Timestamp()} set {_from = newValue} } /// Returns true if `from` has been explicitly set. public var hasFrom: Bool {return self._from != nil} /// Clears the value of `from`. Subsequent reads from it will return its default value. public mutating func clearFrom() {self._from = nil} ///Окончание периода (по UTC) public var to: SwiftProtobuf.Google_Protobuf_Timestamp { get {return _to ?? SwiftProtobuf.Google_Protobuf_Timestamp()} set {_to = newValue} } /// Returns true if `to` has been explicitly set. public var hasTo: Bool {return self._to != nil} /// Clears the value of `to`. Subsequent reads from it will return its default value. public mutating func clearTo() {self._to = nil} ///Статус запрашиваемых операций public var state: OperationState = .unspecified ///Figi-идентификатор инструмента для фильтрации public var figi: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _from: SwiftProtobuf.Google_Protobuf_Timestamp? = nil fileprivate var _to: SwiftProtobuf.Google_Protobuf_Timestamp? = nil } ///Список операций. public struct OperationsResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Массив операций public var operations: [Operation] = [] public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } ///Данные по операции. public struct Operation { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Идентификатор операции public var id: String { get {return _storage._id} set {_uniqueStorage()._id = newValue} } ///Идентификатор родительской операции public var parentOperationID: String { get {return _storage._parentOperationID} set {_uniqueStorage()._parentOperationID = newValue} } ///Валюта операции public var currency: String { get {return _storage._currency} set {_uniqueStorage()._currency = newValue} } ///Сумма операции public var payment: MoneyValue { get {return _storage._payment ?? MoneyValue()} set {_uniqueStorage()._payment = newValue} } /// Returns true if `payment` has been explicitly set. public var hasPayment: Bool {return _storage._payment != nil} /// Clears the value of `payment`. Subsequent reads from it will return its default value. public mutating func clearPayment() {_uniqueStorage()._payment = nil} ///Цена операции public var price: MoneyValue { get {return _storage._price ?? MoneyValue()} set {_uniqueStorage()._price = newValue} } /// Returns true if `price` has been explicitly set. public var hasPrice: Bool {return _storage._price != nil} /// Clears the value of `price`. Subsequent reads from it will return its default value. public mutating func clearPrice() {_uniqueStorage()._price = nil} ///Статус операции public var state: OperationState { get {return _storage._state} set {_uniqueStorage()._state = newValue} } ///Количество лотов инструмента public var quantity: Int64 { get {return _storage._quantity} set {_uniqueStorage()._quantity = newValue} } ///Неисполненный остаток по сделке public var quantityRest: Int64 { get {return _storage._quantityRest} set {_uniqueStorage()._quantityRest = newValue} } ///Figi-идентификатор инструмента, связанного с операцией public var figi: String { get {return _storage._figi} set {_uniqueStorage()._figi = newValue} } ///Тип инструмента. Возможные значения: </br>**bond** — облигация; </br>**share** — акция; </br>**currency** — валюта; </br>**etf** — фонд; </br>**futures** — фьючерс. public var instrumentType: String { get {return _storage._instrumentType} set {_uniqueStorage()._instrumentType = newValue} } ///Дата и время операции в формате часовом поясе UTC public var date: SwiftProtobuf.Google_Protobuf_Timestamp { get {return _storage._date ?? SwiftProtobuf.Google_Protobuf_Timestamp()} set {_uniqueStorage()._date = newValue} } /// Returns true if `date` has been explicitly set. public var hasDate: Bool {return _storage._date != nil} /// Clears the value of `date`. Subsequent reads from it will return its default value. public mutating func clearDate() {_uniqueStorage()._date = nil} ///Текстовое описание типа операции public var type: String { get {return _storage._type} set {_uniqueStorage()._type = newValue} } ///Тип операции public var operationType: OperationType { get {return _storage._operationType} set {_uniqueStorage()._operationType = newValue} } public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _storage = _StorageClass.defaultInstance } ///Запрос получения текущего портфеля по счёту. public struct PortfolioRequest { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Идентификатор счёта пользователя public var accountID: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } ///Текущий портфель по счёту. public struct PortfolioResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Общая стоимость акций в портфеле в рублях public var totalAmountShares: MoneyValue { get {return _storage._totalAmountShares ?? MoneyValue()} set {_uniqueStorage()._totalAmountShares = newValue} } /// Returns true if `totalAmountShares` has been explicitly set. public var hasTotalAmountShares: Bool {return _storage._totalAmountShares != nil} /// Clears the value of `totalAmountShares`. Subsequent reads from it will return its default value. public mutating func clearTotalAmountShares() {_uniqueStorage()._totalAmountShares = nil} ///Общая стоимость облигаций в портфеле в рублях public var totalAmountBonds: MoneyValue { get {return _storage._totalAmountBonds ?? MoneyValue()} set {_uniqueStorage()._totalAmountBonds = newValue} } /// Returns true if `totalAmountBonds` has been explicitly set. public var hasTotalAmountBonds: Bool {return _storage._totalAmountBonds != nil} /// Clears the value of `totalAmountBonds`. Subsequent reads from it will return its default value. public mutating func clearTotalAmountBonds() {_uniqueStorage()._totalAmountBonds = nil} ///Общая стоимость фондов в портфеле в рублях public var totalAmountEtf: MoneyValue { get {return _storage._totalAmountEtf ?? MoneyValue()} set {_uniqueStorage()._totalAmountEtf = newValue} } /// Returns true if `totalAmountEtf` has been explicitly set. public var hasTotalAmountEtf: Bool {return _storage._totalAmountEtf != nil} /// Clears the value of `totalAmountEtf`. Subsequent reads from it will return its default value. public mutating func clearTotalAmountEtf() {_uniqueStorage()._totalAmountEtf = nil} ///Общая стоимость валют в портфеле в рублях public var totalAmountCurrencies: MoneyValue { get {return _storage._totalAmountCurrencies ?? MoneyValue()} set {_uniqueStorage()._totalAmountCurrencies = newValue} } /// Returns true if `totalAmountCurrencies` has been explicitly set. public var hasTotalAmountCurrencies: Bool {return _storage._totalAmountCurrencies != nil} /// Clears the value of `totalAmountCurrencies`. Subsequent reads from it will return its default value. public mutating func clearTotalAmountCurrencies() {_uniqueStorage()._totalAmountCurrencies = nil} ///Общая стоимость фьючерсов в портфеле в рублях public var totalAmountFutures: MoneyValue { get {return _storage._totalAmountFutures ?? MoneyValue()} set {_uniqueStorage()._totalAmountFutures = newValue} } /// Returns true if `totalAmountFutures` has been explicitly set. public var hasTotalAmountFutures: Bool {return _storage._totalAmountFutures != nil} /// Clears the value of `totalAmountFutures`. Subsequent reads from it will return its default value. public mutating func clearTotalAmountFutures() {_uniqueStorage()._totalAmountFutures = nil} ///Текущая доходность портфеля public var expectedYield: Quotation { get {return _storage._expectedYield ?? Quotation()} set {_uniqueStorage()._expectedYield = newValue} } /// Returns true if `expectedYield` has been explicitly set. public var hasExpectedYield: Bool {return _storage._expectedYield != nil} /// Clears the value of `expectedYield`. Subsequent reads from it will return its default value. public mutating func clearExpectedYield() {_uniqueStorage()._expectedYield = nil} ///Список позиций портфеля public var positions: [PortfolioPosition] { get {return _storage._positions} set {_uniqueStorage()._positions = newValue} } public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _storage = _StorageClass.defaultInstance } ///Запрос позиций портфеля по счёту. public struct PositionsRequest { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Идентификатор счёта пользователя public var accountID: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } ///Список позиций по счёту. public struct PositionsResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Массив валютных позиций портфеля public var money: [MoneyValue] = [] ///Массив заблокированных валютных позиций портфеля public var blocked: [MoneyValue] = [] ///Список ценно-бумажных позиций портфеля public var securities: [PositionsSecurities] = [] ///Признак идущей в данный момент выгрузки лимитов public var limitsLoadingInProgress: Bool = false ///Список фьючерсов портфеля public var futures: [PositionsFutures] = [] public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } ///Запрос доступного для вывода остатка. public struct WithdrawLimitsRequest { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Идентификатор счёта пользователя public var accountID: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } ///Доступный для вывода остаток. public struct WithdrawLimitsResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Массив валютных позиций портфеля public var money: [MoneyValue] = [] ///Массив заблокированных валютных позиций портфеля public var blocked: [MoneyValue] = [] ///Заблокировано под гарантийное обеспечение фьючерсов public var blockedGuarantee: [MoneyValue] = [] public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } ///Позиции портфеля. public struct PortfolioPosition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Figi-идентификатора инструмента public var figi: String { get {return _storage._figi} set {_uniqueStorage()._figi = newValue} } ///Тип инструмента public var instrumentType: String { get {return _storage._instrumentType} set {_uniqueStorage()._instrumentType = newValue} } ///Количество инструмента в портфеле в штуках public var quantity: Quotation { get {return _storage._quantity ?? Quotation()} set {_uniqueStorage()._quantity = newValue} } /// Returns true if `quantity` has been explicitly set. public var hasQuantity: Bool {return _storage._quantity != nil} /// Clears the value of `quantity`. Subsequent reads from it will return its default value. public mutating func clearQuantity() {_uniqueStorage()._quantity = nil} ///Средневзвешенная цена позиции public var averagePositionPrice: MoneyValue { get {return _storage._averagePositionPrice ?? MoneyValue()} set {_uniqueStorage()._averagePositionPrice = newValue} } /// Returns true if `averagePositionPrice` has been explicitly set. public var hasAveragePositionPrice: Bool {return _storage._averagePositionPrice != nil} /// Clears the value of `averagePositionPrice`. Subsequent reads from it will return its default value. public mutating func clearAveragePositionPrice() {_uniqueStorage()._averagePositionPrice = nil} ///Текущая рассчитанная доходность public var expectedYield: Quotation { get {return _storage._expectedYield ?? Quotation()} set {_uniqueStorage()._expectedYield = newValue} } /// Returns true if `expectedYield` has been explicitly set. public var hasExpectedYield: Bool {return _storage._expectedYield != nil} /// Clears the value of `expectedYield`. Subsequent reads from it will return its default value. public mutating func clearExpectedYield() {_uniqueStorage()._expectedYield = nil} /// Текущий НКД public var currentNkd: MoneyValue { get {return _storage._currentNkd ?? MoneyValue()} set {_uniqueStorage()._currentNkd = newValue} } /// Returns true if `currentNkd` has been explicitly set. public var hasCurrentNkd: Bool {return _storage._currentNkd != nil} /// Clears the value of `currentNkd`. Subsequent reads from it will return its default value. public mutating func clearCurrentNkd() {_uniqueStorage()._currentNkd = nil} ///Средняя цена лота в позиции в пунктах (для фьючерсов) public var averagePositionPricePt: Quotation { get {return _storage._averagePositionPricePt ?? Quotation()} set {_uniqueStorage()._averagePositionPricePt = newValue} } /// Returns true if `averagePositionPricePt` has been explicitly set. public var hasAveragePositionPricePt: Bool {return _storage._averagePositionPricePt != nil} /// Clears the value of `averagePositionPricePt`. Subsequent reads from it will return its default value. public mutating func clearAveragePositionPricePt() {_uniqueStorage()._averagePositionPricePt = nil} ///Текущая цена инструмента public var currentPrice: MoneyValue { get {return _storage._currentPrice ?? MoneyValue()} set {_uniqueStorage()._currentPrice = newValue} } /// Returns true if `currentPrice` has been explicitly set. public var hasCurrentPrice: Bool {return _storage._currentPrice != nil} /// Clears the value of `currentPrice`. Subsequent reads from it will return its default value. public mutating func clearCurrentPrice() {_uniqueStorage()._currentPrice = nil} ///Средняя цена лота в позиции по методу FIFO public var averagePositionPriceFifo: MoneyValue { get {return _storage._averagePositionPriceFifo ?? MoneyValue()} set {_uniqueStorage()._averagePositionPriceFifo = newValue} } /// Returns true if `averagePositionPriceFifo` has been explicitly set. public var hasAveragePositionPriceFifo: Bool {return _storage._averagePositionPriceFifo != nil} /// Clears the value of `averagePositionPriceFifo`. Subsequent reads from it will return its default value. public mutating func clearAveragePositionPriceFifo() {_uniqueStorage()._averagePositionPriceFifo = nil} ///Количество лотов в портфеле public var quantityLots: Quotation { get {return _storage._quantityLots ?? Quotation()} set {_uniqueStorage()._quantityLots = newValue} } /// Returns true if `quantityLots` has been explicitly set. public var hasQuantityLots: Bool {return _storage._quantityLots != nil} /// Clears the value of `quantityLots`. Subsequent reads from it will return its default value. public mutating func clearQuantityLots() {_uniqueStorage()._quantityLots = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _storage = _StorageClass.defaultInstance } ///Баланс позиции ценной бумаги. public struct PositionsSecurities { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Figi-идентификатор бумаги public var figi: String = String() ///Заблокировано public var blocked: Int64 = 0 ///Текущий баланс public var balance: Int64 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } ///Баланс фьючерса. public struct PositionsFutures { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Figi-идентификатор фьючерса public var figi: String = String() ///Заблокировано public var blocked: Int64 = 0 ///Текущий баланс public var balance: Int64 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct BrokerReportRequest { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var payload: BrokerReportRequest.OneOf_Payload? = nil public var generateBrokerReportRequest: GenerateBrokerReportRequest { get { if case .generateBrokerReportRequest(let v)? = payload {return v} return GenerateBrokerReportRequest() } set {payload = .generateBrokerReportRequest(newValue)} } public var getBrokerReportRequest: GetBrokerReportRequest { get { if case .getBrokerReportRequest(let v)? = payload {return v} return GetBrokerReportRequest() } set {payload = .getBrokerReportRequest(newValue)} } public var unknownFields = SwiftProtobuf.UnknownStorage() public enum OneOf_Payload: Equatable { case generateBrokerReportRequest(GenerateBrokerReportRequest) case getBrokerReportRequest(GetBrokerReportRequest) #if !swift(>=4.1) public static func ==(lhs: BrokerReportRequest.OneOf_Payload, rhs: BrokerReportRequest.OneOf_Payload) -> Bool { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch (lhs, rhs) { case (.generateBrokerReportRequest, .generateBrokerReportRequest): return { guard case .generateBrokerReportRequest(let l) = lhs, case .generateBrokerReportRequest(let r) = rhs else { preconditionFailure() } return l == r }() case (.getBrokerReportRequest, .getBrokerReportRequest): return { guard case .getBrokerReportRequest(let l) = lhs, case .getBrokerReportRequest(let r) = rhs else { preconditionFailure() } return l == r }() default: return false } } #endif } public init() {} } public struct BrokerReportResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var payload: BrokerReportResponse.OneOf_Payload? = nil public var generateBrokerReportResponse: GenerateBrokerReportResponse { get { if case .generateBrokerReportResponse(let v)? = payload {return v} return GenerateBrokerReportResponse() } set {payload = .generateBrokerReportResponse(newValue)} } public var getBrokerReportResponse: GetBrokerReportResponse { get { if case .getBrokerReportResponse(let v)? = payload {return v} return GetBrokerReportResponse() } set {payload = .getBrokerReportResponse(newValue)} } public var unknownFields = SwiftProtobuf.UnknownStorage() public enum OneOf_Payload: Equatable { case generateBrokerReportResponse(GenerateBrokerReportResponse) case getBrokerReportResponse(GetBrokerReportResponse) #if !swift(>=4.1) public static func ==(lhs: BrokerReportResponse.OneOf_Payload, rhs: BrokerReportResponse.OneOf_Payload) -> Bool { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch (lhs, rhs) { case (.generateBrokerReportResponse, .generateBrokerReportResponse): return { guard case .generateBrokerReportResponse(let l) = lhs, case .generateBrokerReportResponse(let r) = rhs else { preconditionFailure() } return l == r }() case (.getBrokerReportResponse, .getBrokerReportResponse): return { guard case .getBrokerReportResponse(let l) = lhs, case .getBrokerReportResponse(let r) = rhs else { preconditionFailure() } return l == r }() default: return false } } #endif } public init() {} } public struct GenerateBrokerReportRequest { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Идентификатор счёта клиента public var accountID: String = String() ///Начало периода в часовом поясе UTC. public var from: SwiftProtobuf.Google_Protobuf_Timestamp { get {return _from ?? SwiftProtobuf.Google_Protobuf_Timestamp()} set {_from = newValue} } /// Returns true if `from` has been explicitly set. public var hasFrom: Bool {return self._from != nil} /// Clears the value of `from`. Subsequent reads from it will return its default value. public mutating func clearFrom() {self._from = nil} ///Окончание периода в часовом поясе UTC. public var to: SwiftProtobuf.Google_Protobuf_Timestamp { get {return _to ?? SwiftProtobuf.Google_Protobuf_Timestamp()} set {_to = newValue} } /// Returns true if `to` has been explicitly set. public var hasTo: Bool {return self._to != nil} /// Clears the value of `to`. Subsequent reads from it will return its default value. public mutating func clearTo() {self._to = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _from: SwiftProtobuf.Google_Protobuf_Timestamp? = nil fileprivate var _to: SwiftProtobuf.Google_Protobuf_Timestamp? = nil } public struct GenerateBrokerReportResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Идентификатор задачи формирования брокерского отчёта public var taskID: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct GetBrokerReportRequest { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Идентификатор задачи формирования брокерского отчёта public var taskID: String = String() ///Номер страницы отчета (начинается с 1), значение по умолчанию: 0 public var page: Int32 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct GetBrokerReportResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var brokerReport: [BrokerReport] = [] ///Количество записей в отчете public var itemsCount: Int32 = 0 ///Количество страниц с данными отчета (начинается с 0) public var pagesCount: Int32 = 0 ///Текущая страница (начинается с 0) public var page: Int32 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct BrokerReport { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. ///Номер сделки public var tradeID: String { get {return _storage._tradeID} set {_uniqueStorage()._tradeID = newValue} } ///Номер поручения public var orderID: String { get {return _storage._orderID} set {_uniqueStorage()._orderID = newValue} } ///Figi-идентификатор инструмента public var figi: String { get {return _storage._figi} set {_uniqueStorage()._figi = newValue} } ///Признак исполнения public var executeSign: String { get {return _storage._executeSign} set {_uniqueStorage()._executeSign = newValue} } ///Дата и время заключения в часовом поясе UTC. public var tradeDatetime: SwiftProtobuf.Google_Protobuf_Timestamp { get {return _storage._tradeDatetime ?? SwiftProtobuf.Google_Protobuf_Timestamp()} set {_uniqueStorage()._tradeDatetime = newValue} } /// Returns true if `tradeDatetime` has been explicitly set. public var hasTradeDatetime: Bool {return _storage._tradeDatetime != nil} /// Clears the value of `tradeDatetime`. Subsequent reads from it will return its default value. public mutating func clearTradeDatetime() {_uniqueStorage()._tradeDatetime = nil} ///Торговая площадка public var exchange: String { get {return _storage._exchange} set {_uniqueStorage()._exchange = newValue} } ///Режим торгов public var classCode: String { get {return _storage._classCode} set {_uniqueStorage()._classCode = newValue} } ///Вид сделки public var direction: String { get {return _storage._direction} set {_uniqueStorage()._direction = newValue} } ///Сокращённое наименование актива public var name: String { get {return _storage._name} set {_uniqueStorage()._name = newValue} } ///Код актива public var ticker: String { get {return _storage._ticker} set {_uniqueStorage()._ticker = newValue} } ///Цена за единицу public var price: MoneyValue { get {return _storage._price ?? MoneyValue()} set {_uniqueStorage()._price = newValue} } /// Returns true if `price` has been explicitly set. public var hasPrice: Bool {return _storage._price != nil} /// Clears the value of `price`. Subsequent reads from it will return its default value. public mutating func clearPrice() {_uniqueStorage()._price = nil} ///Количество public var quantity: Int64 { get {return _storage._quantity} set {_uniqueStorage()._quantity = newValue} } ///Сумма (без НКД) public var orderAmount: MoneyValue { get {return _storage._orderAmount ?? MoneyValue()} set {_uniqueStorage()._orderAmount = newValue} } /// Returns true if `orderAmount` has been explicitly set. public var hasOrderAmount: Bool {return _storage._orderAmount != nil} /// Clears the value of `orderAmount`. Subsequent reads from it will return its default value. public mutating func clearOrderAmount() {_uniqueStorage()._orderAmount = nil} ///НКД public var aciValue: Quotation { get {return _storage._aciValue ?? Quotation()} set {_uniqueStorage()._aciValue = newValue} } /// Returns true if `aciValue` has been explicitly set. public var hasAciValue: Bool {return _storage._aciValue != nil} /// Clears the value of `aciValue`. Subsequent reads from it will return its default value. public mutating func clearAciValue() {_uniqueStorage()._aciValue = nil} ///Сумма сделки public var totalOrderAmount: MoneyValue { get {return _storage._totalOrderAmount ?? MoneyValue()} set {_uniqueStorage()._totalOrderAmount = newValue} } /// Returns true if `totalOrderAmount` has been explicitly set. public var hasTotalOrderAmount: Bool {return _storage._totalOrderAmount != nil} /// Clears the value of `totalOrderAmount`. Subsequent reads from it will return its default value. public mutating func clearTotalOrderAmount() {_uniqueStorage()._totalOrderAmount = nil} ///Комиссия брокера public var brokerCommission: MoneyValue { get {return _storage._brokerCommission ?? MoneyValue()} set {_uniqueStorage()._brokerCommission = newValue} } /// Returns true if `brokerCommission` has been explicitly set. public var hasBrokerCommission: Bool {return _storage._brokerCommission != nil} /// Clears the value of `brokerCommission`. Subsequent reads from it will return its default value. public mutating func clearBrokerCommission() {_uniqueStorage()._brokerCommission = nil} ///Комиссия биржи public var exchangeCommission: MoneyValue { get {return _storage._exchangeCommission ?? MoneyValue()} set {_uniqueStorage()._exchangeCommission = newValue} } /// Returns true if `exchangeCommission` has been explicitly set. public var hasExchangeCommission: Bool {return _storage._exchangeCommission != nil} /// Clears the value of `exchangeCommission`. Subsequent reads from it will return its default value. public mutating func clearExchangeCommission() {_uniqueStorage()._exchangeCommission = nil} ///Комиссия клир. центра public var exchangeClearingCommission: MoneyValue { get {return _storage._exchangeClearingCommission ?? MoneyValue()} set {_uniqueStorage()._exchangeClearingCommission = newValue} } /// Returns true if `exchangeClearingCommission` has been explicitly set. public var hasExchangeClearingCommission: Bool {return _storage._exchangeClearingCommission != nil} /// Clears the value of `exchangeClearingCommission`. Subsequent reads from it will return its default value. public mutating func clearExchangeClearingCommission() {_uniqueStorage()._exchangeClearingCommission = nil} ///Ставка РЕПО (%) public var repoRate: Quotation { get {return _storage._repoRate ?? Quotation()} set {_uniqueStorage()._repoRate = newValue} } /// Returns true if `repoRate` has been explicitly set. public var hasRepoRate: Bool {return _storage._repoRate != nil} /// Clears the value of `repoRate`. Subsequent reads from it will return its default value. public mutating func clearRepoRate() {_uniqueStorage()._repoRate = nil} ///Контрагент/Брокер public var party: String { get {return _storage._party} set {_uniqueStorage()._party = newValue} } ///Дата расчётов в часовом поясе UTC. public var clearValueDate_p: SwiftProtobuf.Google_Protobuf_Timestamp { get {return _storage._clearValueDate_p ?? SwiftProtobuf.Google_Protobuf_Timestamp()} set {_uniqueStorage()._clearValueDate_p = newValue} } /// Returns true if `clearValueDate_p` has been explicitly set. public var hasClearValueDate_p: Bool {return _storage._clearValueDate_p != nil} /// Clears the value of `clearValueDate_p`. Subsequent reads from it will return its default value. public mutating func clearClearValueDate_p() {_uniqueStorage()._clearValueDate_p = nil} ///Дата поставки в часовом поясе UTC. public var secValueDate: SwiftProtobuf.Google_Protobuf_Timestamp { get {return _storage._secValueDate ?? SwiftProtobuf.Google_Protobuf_Timestamp()} set {_uniqueStorage()._secValueDate = newValue} } /// Returns true if `secValueDate` has been explicitly set. public var hasSecValueDate: Bool {return _storage._secValueDate != nil} /// Clears the value of `secValueDate`. Subsequent reads from it will return its default value. public mutating func clearSecValueDate() {_uniqueStorage()._secValueDate = nil} ///Статус брокера public var brokerStatus: String { get {return _storage._brokerStatus} set {_uniqueStorage()._brokerStatus = newValue} } ///Тип дог. public var separateAgreementType: String { get {return _storage._separateAgreementType} set {_uniqueStorage()._separateAgreementType = newValue} } ///Номер дог. public var separateAgreementNumber: String { get {return _storage._separateAgreementNumber} set {_uniqueStorage()._separateAgreementNumber = newValue} } ///Дата дог. public var separateAgreementDate: String { get {return _storage._separateAgreementDate} set {_uniqueStorage()._separateAgreementDate = newValue} } ///Тип расчёта по сделке public var deliveryType: String { get {return _storage._deliveryType} set {_uniqueStorage()._deliveryType = newValue} } public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _storage = _StorageClass.defaultInstance } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "tinkoff.public.invest.api.contract.v1" extension OperationState: SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "OPERATION_STATE_UNSPECIFIED"), 1: .same(proto: "OPERATION_STATE_EXECUTED"), 2: .same(proto: "OPERATION_STATE_CANCELED"), ] } extension OperationType: SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "OPERATION_TYPE_UNSPECIFIED"), 1: .same(proto: "OPERATION_TYPE_INPUT"), 2: .same(proto: "OPERATION_TYPE_BOND_TAX"), 3: .same(proto: "OPERATION_TYPE_OUTPUT_SECURITIES"), 4: .same(proto: "OPERATION_TYPE_OVERNIGHT"), 5: .same(proto: "OPERATION_TYPE_TAX"), 6: .same(proto: "OPERATION_TYPE_BOND_REPAYMENT_FULL"), 7: .same(proto: "OPERATION_TYPE_SELL_CARD"), 8: .same(proto: "OPERATION_TYPE_DIVIDEND_TAX"), 9: .same(proto: "OPERATION_TYPE_OUTPUT"), 10: .same(proto: "OPERATION_TYPE_BOND_REPAYMENT"), 11: .same(proto: "OPERATION_TYPE_TAX_CORRECTION"), 12: .same(proto: "OPERATION_TYPE_SERVICE_FEE"), 13: .same(proto: "OPERATION_TYPE_BENEFIT_TAX"), 14: .same(proto: "OPERATION_TYPE_MARGIN_FEE"), 15: .same(proto: "OPERATION_TYPE_BUY"), 16: .same(proto: "OPERATION_TYPE_BUY_CARD"), 17: .same(proto: "OPERATION_TYPE_INPUT_SECURITIES"), 18: .same(proto: "OPERATION_TYPE_SELL_MARGIN"), 19: .same(proto: "OPERATION_TYPE_BROKER_FEE"), 20: .same(proto: "OPERATION_TYPE_BUY_MARGIN"), 21: .same(proto: "OPERATION_TYPE_DIVIDEND"), 22: .same(proto: "OPERATION_TYPE_SELL"), 23: .same(proto: "OPERATION_TYPE_COUPON"), 24: .same(proto: "OPERATION_TYPE_SUCCESS_FEE"), 25: .same(proto: "OPERATION_TYPE_DIVIDEND_TRANSFER"), 26: .same(proto: "OPERATION_TYPE_ACCRUING_VARMARGIN"), 27: .same(proto: "OPERATION_TYPE_WRITING_OFF_VARMARGIN"), 28: .same(proto: "OPERATION_TYPE_DELIVERY_BUY"), 29: .same(proto: "OPERATION_TYPE_DELIVERY_SELL"), 30: .same(proto: "OPERATION_TYPE_TRACK_MFEE"), 31: .same(proto: "OPERATION_TYPE_TRACK_PFEE"), 32: .same(proto: "OPERATION_TYPE_TAX_PROGRESSIVE"), 33: .same(proto: "OPERATION_TYPE_BOND_TAX_PROGRESSIVE"), 34: .same(proto: "OPERATION_TYPE_DIVIDEND_TAX_PROGRESSIVE"), 35: .same(proto: "OPERATION_TYPE_BENEFIT_TAX_PROGRESSIVE"), 36: .same(proto: "OPERATION_TYPE_TAX_CORRECTION_PROGRESSIVE"), 37: .same(proto: "OPERATION_TYPE_TAX_REPO_PROGRESSIVE"), 38: .same(proto: "OPERATION_TYPE_TAX_REPO"), 39: .same(proto: "OPERATION_TYPE_TAX_REPO_HOLD"), 40: .same(proto: "OPERATION_TYPE_TAX_REPO_REFUND"), 41: .same(proto: "OPERATION_TYPE_TAX_REPO_HOLD_PROGRESSIVE"), 42: .same(proto: "OPERATION_TYPE_TAX_REPO_REFUND_PROGRESSIVE"), 43: .same(proto: "OPERATION_TYPE_DIV_EXT"), ] } extension OperationsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".OperationsRequest" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "account_id"), 2: .same(proto: "from"), 3: .same(proto: "to"), 4: .same(proto: "state"), 5: .same(proto: "figi"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.accountID) }() case 2: try { try decoder.decodeSingularMessageField(value: &self._from) }() case 3: try { try decoder.decodeSingularMessageField(value: &self._to) }() case 4: try { try decoder.decodeSingularEnumField(value: &self.state) }() case 5: try { try decoder.decodeSingularStringField(value: &self.figi) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 if !self.accountID.isEmpty { try visitor.visitSingularStringField(value: self.accountID, fieldNumber: 1) } try { if let v = self._from { try visitor.visitSingularMessageField(value: v, fieldNumber: 2) } }() try { if let v = self._to { try visitor.visitSingularMessageField(value: v, fieldNumber: 3) } }() if self.state != .unspecified { try visitor.visitSingularEnumField(value: self.state, fieldNumber: 4) } if !self.figi.isEmpty { try visitor.visitSingularStringField(value: self.figi, fieldNumber: 5) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: OperationsRequest, rhs: OperationsRequest) -> Bool { if lhs.accountID != rhs.accountID {return false} if lhs._from != rhs._from {return false} if lhs._to != rhs._to {return false} if lhs.state != rhs.state {return false} if lhs.figi != rhs.figi {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension OperationsResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".OperationsResponse" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "operations"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedMessageField(value: &self.operations) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.operations.isEmpty { try visitor.visitRepeatedMessageField(value: self.operations, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: OperationsResponse, rhs: OperationsResponse) -> Bool { if lhs.operations != rhs.operations {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Operation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Operation" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "id"), 2: .standard(proto: "parent_operation_id"), 3: .same(proto: "currency"), 4: .same(proto: "payment"), 5: .same(proto: "price"), 6: .same(proto: "state"), 7: .same(proto: "quantity"), 8: .standard(proto: "quantity_rest"), 9: .same(proto: "figi"), 10: .standard(proto: "instrument_type"), 11: .same(proto: "date"), 12: .same(proto: "type"), 13: .standard(proto: "operation_type"), ] fileprivate class _StorageClass { var _id: String = String() var _parentOperationID: String = String() var _currency: String = String() var _payment: MoneyValue? = nil var _price: MoneyValue? = nil var _state: OperationState = .unspecified var _quantity: Int64 = 0 var _quantityRest: Int64 = 0 var _figi: String = String() var _instrumentType: String = String() var _date: SwiftProtobuf.Google_Protobuf_Timestamp? = nil var _type: String = String() var _operationType: OperationType = .unspecified static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _id = source._id _parentOperationID = source._parentOperationID _currency = source._currency _payment = source._payment _price = source._price _state = source._state _quantity = source._quantity _quantityRest = source._quantityRest _figi = source._figi _instrumentType = source._instrumentType _date = source._date _type = source._type _operationType = source._operationType } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &_storage._id) }() case 2: try { try decoder.decodeSingularStringField(value: &_storage._parentOperationID) }() case 3: try { try decoder.decodeSingularStringField(value: &_storage._currency) }() case 4: try { try decoder.decodeSingularMessageField(value: &_storage._payment) }() case 5: try { try decoder.decodeSingularMessageField(value: &_storage._price) }() case 6: try { try decoder.decodeSingularEnumField(value: &_storage._state) }() case 7: try { try decoder.decodeSingularInt64Field(value: &_storage._quantity) }() case 8: try { try decoder.decodeSingularInt64Field(value: &_storage._quantityRest) }() case 9: try { try decoder.decodeSingularStringField(value: &_storage._figi) }() case 10: try { try decoder.decodeSingularStringField(value: &_storage._instrumentType) }() case 11: try { try decoder.decodeSingularMessageField(value: &_storage._date) }() case 12: try { try decoder.decodeSingularStringField(value: &_storage._type) }() case 13: try { try decoder.decodeSingularEnumField(value: &_storage._operationType) }() default: break } } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 if !_storage._id.isEmpty { try visitor.visitSingularStringField(value: _storage._id, fieldNumber: 1) } if !_storage._parentOperationID.isEmpty { try visitor.visitSingularStringField(value: _storage._parentOperationID, fieldNumber: 2) } if !_storage._currency.isEmpty { try visitor.visitSingularStringField(value: _storage._currency, fieldNumber: 3) } try { if let v = _storage._payment { try visitor.visitSingularMessageField(value: v, fieldNumber: 4) } }() try { if let v = _storage._price { try visitor.visitSingularMessageField(value: v, fieldNumber: 5) } }() if _storage._state != .unspecified { try visitor.visitSingularEnumField(value: _storage._state, fieldNumber: 6) } if _storage._quantity != 0 { try visitor.visitSingularInt64Field(value: _storage._quantity, fieldNumber: 7) } if _storage._quantityRest != 0 { try visitor.visitSingularInt64Field(value: _storage._quantityRest, fieldNumber: 8) } if !_storage._figi.isEmpty { try visitor.visitSingularStringField(value: _storage._figi, fieldNumber: 9) } if !_storage._instrumentType.isEmpty { try visitor.visitSingularStringField(value: _storage._instrumentType, fieldNumber: 10) } try { if let v = _storage._date { try visitor.visitSingularMessageField(value: v, fieldNumber: 11) } }() if !_storage._type.isEmpty { try visitor.visitSingularStringField(value: _storage._type, fieldNumber: 12) } if _storage._operationType != .unspecified { try visitor.visitSingularEnumField(value: _storage._operationType, fieldNumber: 13) } } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Operation, rhs: Operation) -> Bool { if lhs._storage !== rhs._storage { let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in let _storage = _args.0 let rhs_storage = _args.1 if _storage._id != rhs_storage._id {return false} if _storage._parentOperationID != rhs_storage._parentOperationID {return false} if _storage._currency != rhs_storage._currency {return false} if _storage._payment != rhs_storage._payment {return false} if _storage._price != rhs_storage._price {return false} if _storage._state != rhs_storage._state {return false} if _storage._quantity != rhs_storage._quantity {return false} if _storage._quantityRest != rhs_storage._quantityRest {return false} if _storage._figi != rhs_storage._figi {return false} if _storage._instrumentType != rhs_storage._instrumentType {return false} if _storage._date != rhs_storage._date {return false} if _storage._type != rhs_storage._type {return false} if _storage._operationType != rhs_storage._operationType {return false} return true } if !storagesAreEqual {return false} } if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension PortfolioRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".PortfolioRequest" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "account_id"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.accountID) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.accountID.isEmpty { try visitor.visitSingularStringField(value: self.accountID, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: PortfolioRequest, rhs: PortfolioRequest) -> Bool { if lhs.accountID != rhs.accountID {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension PortfolioResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".PortfolioResponse" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "total_amount_shares"), 2: .standard(proto: "total_amount_bonds"), 3: .standard(proto: "total_amount_etf"), 4: .standard(proto: "total_amount_currencies"), 5: .standard(proto: "total_amount_futures"), 6: .standard(proto: "expected_yield"), 7: .same(proto: "positions"), ] fileprivate class _StorageClass { var _totalAmountShares: MoneyValue? = nil var _totalAmountBonds: MoneyValue? = nil var _totalAmountEtf: MoneyValue? = nil var _totalAmountCurrencies: MoneyValue? = nil var _totalAmountFutures: MoneyValue? = nil var _expectedYield: Quotation? = nil var _positions: [PortfolioPosition] = [] static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _totalAmountShares = source._totalAmountShares _totalAmountBonds = source._totalAmountBonds _totalAmountEtf = source._totalAmountEtf _totalAmountCurrencies = source._totalAmountCurrencies _totalAmountFutures = source._totalAmountFutures _expectedYield = source._expectedYield _positions = source._positions } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &_storage._totalAmountShares) }() case 2: try { try decoder.decodeSingularMessageField(value: &_storage._totalAmountBonds) }() case 3: try { try decoder.decodeSingularMessageField(value: &_storage._totalAmountEtf) }() case 4: try { try decoder.decodeSingularMessageField(value: &_storage._totalAmountCurrencies) }() case 5: try { try decoder.decodeSingularMessageField(value: &_storage._totalAmountFutures) }() case 6: try { try decoder.decodeSingularMessageField(value: &_storage._expectedYield) }() case 7: try { try decoder.decodeRepeatedMessageField(value: &_storage._positions) }() default: break } } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = _storage._totalAmountShares { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } }() try { if let v = _storage._totalAmountBonds { try visitor.visitSingularMessageField(value: v, fieldNumber: 2) } }() try { if let v = _storage._totalAmountEtf { try visitor.visitSingularMessageField(value: v, fieldNumber: 3) } }() try { if let v = _storage._totalAmountCurrencies { try visitor.visitSingularMessageField(value: v, fieldNumber: 4) } }() try { if let v = _storage._totalAmountFutures { try visitor.visitSingularMessageField(value: v, fieldNumber: 5) } }() try { if let v = _storage._expectedYield { try visitor.visitSingularMessageField(value: v, fieldNumber: 6) } }() if !_storage._positions.isEmpty { try visitor.visitRepeatedMessageField(value: _storage._positions, fieldNumber: 7) } } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: PortfolioResponse, rhs: PortfolioResponse) -> Bool { if lhs._storage !== rhs._storage { let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in let _storage = _args.0 let rhs_storage = _args.1 if _storage._totalAmountShares != rhs_storage._totalAmountShares {return false} if _storage._totalAmountBonds != rhs_storage._totalAmountBonds {return false} if _storage._totalAmountEtf != rhs_storage._totalAmountEtf {return false} if _storage._totalAmountCurrencies != rhs_storage._totalAmountCurrencies {return false} if _storage._totalAmountFutures != rhs_storage._totalAmountFutures {return false} if _storage._expectedYield != rhs_storage._expectedYield {return false} if _storage._positions != rhs_storage._positions {return false} return true } if !storagesAreEqual {return false} } if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension PositionsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".PositionsRequest" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "account_id"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.accountID) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.accountID.isEmpty { try visitor.visitSingularStringField(value: self.accountID, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: PositionsRequest, rhs: PositionsRequest) -> Bool { if lhs.accountID != rhs.accountID {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension PositionsResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".PositionsResponse" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "money"), 2: .same(proto: "blocked"), 3: .same(proto: "securities"), 4: .standard(proto: "limits_loading_in_progress"), 5: .same(proto: "futures"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedMessageField(value: &self.money) }() case 2: try { try decoder.decodeRepeatedMessageField(value: &self.blocked) }() case 3: try { try decoder.decodeRepeatedMessageField(value: &self.securities) }() case 4: try { try decoder.decodeSingularBoolField(value: &self.limitsLoadingInProgress) }() case 5: try { try decoder.decodeRepeatedMessageField(value: &self.futures) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.money.isEmpty { try visitor.visitRepeatedMessageField(value: self.money, fieldNumber: 1) } if !self.blocked.isEmpty { try visitor.visitRepeatedMessageField(value: self.blocked, fieldNumber: 2) } if !self.securities.isEmpty { try visitor.visitRepeatedMessageField(value: self.securities, fieldNumber: 3) } if self.limitsLoadingInProgress != false { try visitor.visitSingularBoolField(value: self.limitsLoadingInProgress, fieldNumber: 4) } if !self.futures.isEmpty { try visitor.visitRepeatedMessageField(value: self.futures, fieldNumber: 5) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: PositionsResponse, rhs: PositionsResponse) -> Bool { if lhs.money != rhs.money {return false} if lhs.blocked != rhs.blocked {return false} if lhs.securities != rhs.securities {return false} if lhs.limitsLoadingInProgress != rhs.limitsLoadingInProgress {return false} if lhs.futures != rhs.futures {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension WithdrawLimitsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".WithdrawLimitsRequest" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "account_id"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.accountID) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.accountID.isEmpty { try visitor.visitSingularStringField(value: self.accountID, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: WithdrawLimitsRequest, rhs: WithdrawLimitsRequest) -> Bool { if lhs.accountID != rhs.accountID {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension WithdrawLimitsResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".WithdrawLimitsResponse" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "money"), 2: .same(proto: "blocked"), 3: .standard(proto: "blocked_guarantee"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedMessageField(value: &self.money) }() case 2: try { try decoder.decodeRepeatedMessageField(value: &self.blocked) }() case 3: try { try decoder.decodeRepeatedMessageField(value: &self.blockedGuarantee) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.money.isEmpty { try visitor.visitRepeatedMessageField(value: self.money, fieldNumber: 1) } if !self.blocked.isEmpty { try visitor.visitRepeatedMessageField(value: self.blocked, fieldNumber: 2) } if !self.blockedGuarantee.isEmpty { try visitor.visitRepeatedMessageField(value: self.blockedGuarantee, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: WithdrawLimitsResponse, rhs: WithdrawLimitsResponse) -> Bool { if lhs.money != rhs.money {return false} if lhs.blocked != rhs.blocked {return false} if lhs.blockedGuarantee != rhs.blockedGuarantee {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension PortfolioPosition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".PortfolioPosition" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "figi"), 2: .standard(proto: "instrument_type"), 3: .same(proto: "quantity"), 4: .standard(proto: "average_position_price"), 5: .standard(proto: "expected_yield"), 6: .standard(proto: "current_nkd"), 7: .standard(proto: "average_position_price_pt"), 8: .standard(proto: "current_price"), 9: .standard(proto: "average_position_price_fifo"), 10: .standard(proto: "quantity_lots"), ] fileprivate class _StorageClass { var _figi: String = String() var _instrumentType: String = String() var _quantity: Quotation? = nil var _averagePositionPrice: MoneyValue? = nil var _expectedYield: Quotation? = nil var _currentNkd: MoneyValue? = nil var _averagePositionPricePt: Quotation? = nil var _currentPrice: MoneyValue? = nil var _averagePositionPriceFifo: MoneyValue? = nil var _quantityLots: Quotation? = nil static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _figi = source._figi _instrumentType = source._instrumentType _quantity = source._quantity _averagePositionPrice = source._averagePositionPrice _expectedYield = source._expectedYield _currentNkd = source._currentNkd _averagePositionPricePt = source._averagePositionPricePt _currentPrice = source._currentPrice _averagePositionPriceFifo = source._averagePositionPriceFifo _quantityLots = source._quantityLots } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &_storage._figi) }() case 2: try { try decoder.decodeSingularStringField(value: &_storage._instrumentType) }() case 3: try { try decoder.decodeSingularMessageField(value: &_storage._quantity) }() case 4: try { try decoder.decodeSingularMessageField(value: &_storage._averagePositionPrice) }() case 5: try { try decoder.decodeSingularMessageField(value: &_storage._expectedYield) }() case 6: try { try decoder.decodeSingularMessageField(value: &_storage._currentNkd) }() case 7: try { try decoder.decodeSingularMessageField(value: &_storage._averagePositionPricePt) }() case 8: try { try decoder.decodeSingularMessageField(value: &_storage._currentPrice) }() case 9: try { try decoder.decodeSingularMessageField(value: &_storage._averagePositionPriceFifo) }() case 10: try { try decoder.decodeSingularMessageField(value: &_storage._quantityLots) }() default: break } } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 if !_storage._figi.isEmpty { try visitor.visitSingularStringField(value: _storage._figi, fieldNumber: 1) } if !_storage._instrumentType.isEmpty { try visitor.visitSingularStringField(value: _storage._instrumentType, fieldNumber: 2) } try { if let v = _storage._quantity { try visitor.visitSingularMessageField(value: v, fieldNumber: 3) } }() try { if let v = _storage._averagePositionPrice { try visitor.visitSingularMessageField(value: v, fieldNumber: 4) } }() try { if let v = _storage._expectedYield { try visitor.visitSingularMessageField(value: v, fieldNumber: 5) } }() try { if let v = _storage._currentNkd { try visitor.visitSingularMessageField(value: v, fieldNumber: 6) } }() try { if let v = _storage._averagePositionPricePt { try visitor.visitSingularMessageField(value: v, fieldNumber: 7) } }() try { if let v = _storage._currentPrice { try visitor.visitSingularMessageField(value: v, fieldNumber: 8) } }() try { if let v = _storage._averagePositionPriceFifo { try visitor.visitSingularMessageField(value: v, fieldNumber: 9) } }() try { if let v = _storage._quantityLots { try visitor.visitSingularMessageField(value: v, fieldNumber: 10) } }() } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: PortfolioPosition, rhs: PortfolioPosition) -> Bool { if lhs._storage !== rhs._storage { let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in let _storage = _args.0 let rhs_storage = _args.1 if _storage._figi != rhs_storage._figi {return false} if _storage._instrumentType != rhs_storage._instrumentType {return false} if _storage._quantity != rhs_storage._quantity {return false} if _storage._averagePositionPrice != rhs_storage._averagePositionPrice {return false} if _storage._expectedYield != rhs_storage._expectedYield {return false} if _storage._currentNkd != rhs_storage._currentNkd {return false} if _storage._averagePositionPricePt != rhs_storage._averagePositionPricePt {return false} if _storage._currentPrice != rhs_storage._currentPrice {return false} if _storage._averagePositionPriceFifo != rhs_storage._averagePositionPriceFifo {return false} if _storage._quantityLots != rhs_storage._quantityLots {return false} return true } if !storagesAreEqual {return false} } if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension PositionsSecurities: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".PositionsSecurities" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "figi"), 2: .same(proto: "blocked"), 3: .same(proto: "balance"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.figi) }() case 2: try { try decoder.decodeSingularInt64Field(value: &self.blocked) }() case 3: try { try decoder.decodeSingularInt64Field(value: &self.balance) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.figi.isEmpty { try visitor.visitSingularStringField(value: self.figi, fieldNumber: 1) } if self.blocked != 0 { try visitor.visitSingularInt64Field(value: self.blocked, fieldNumber: 2) } if self.balance != 0 { try visitor.visitSingularInt64Field(value: self.balance, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: PositionsSecurities, rhs: PositionsSecurities) -> Bool { if lhs.figi != rhs.figi {return false} if lhs.blocked != rhs.blocked {return false} if lhs.balance != rhs.balance {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension PositionsFutures: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".PositionsFutures" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "figi"), 2: .same(proto: "blocked"), 3: .same(proto: "balance"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.figi) }() case 2: try { try decoder.decodeSingularInt64Field(value: &self.blocked) }() case 3: try { try decoder.decodeSingularInt64Field(value: &self.balance) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.figi.isEmpty { try visitor.visitSingularStringField(value: self.figi, fieldNumber: 1) } if self.blocked != 0 { try visitor.visitSingularInt64Field(value: self.blocked, fieldNumber: 2) } if self.balance != 0 { try visitor.visitSingularInt64Field(value: self.balance, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: PositionsFutures, rhs: PositionsFutures) -> Bool { if lhs.figi != rhs.figi {return false} if lhs.blocked != rhs.blocked {return false} if lhs.balance != rhs.balance {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension BrokerReportRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BrokerReportRequest" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "generate_broker_report_request"), 2: .standard(proto: "get_broker_report_request"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { var v: GenerateBrokerReportRequest? var hadOneofValue = false if let current = self.payload { hadOneofValue = true if case .generateBrokerReportRequest(let m) = current {v = m} } try decoder.decodeSingularMessageField(value: &v) if let v = v { if hadOneofValue {try decoder.handleConflictingOneOf()} self.payload = .generateBrokerReportRequest(v) } }() case 2: try { var v: GetBrokerReportRequest? var hadOneofValue = false if let current = self.payload { hadOneofValue = true if case .getBrokerReportRequest(let m) = current {v = m} } try decoder.decodeSingularMessageField(value: &v) if let v = v { if hadOneofValue {try decoder.handleConflictingOneOf()} self.payload = .getBrokerReportRequest(v) } }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 switch self.payload { case .generateBrokerReportRequest?: try { guard case .generateBrokerReportRequest(let v)? = self.payload else { preconditionFailure() } try visitor.visitSingularMessageField(value: v, fieldNumber: 1) }() case .getBrokerReportRequest?: try { guard case .getBrokerReportRequest(let v)? = self.payload else { preconditionFailure() } try visitor.visitSingularMessageField(value: v, fieldNumber: 2) }() case nil: break } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: BrokerReportRequest, rhs: BrokerReportRequest) -> Bool { if lhs.payload != rhs.payload {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension BrokerReportResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BrokerReportResponse" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "generate_broker_report_response"), 2: .standard(proto: "get_broker_report_response"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { var v: GenerateBrokerReportResponse? var hadOneofValue = false if let current = self.payload { hadOneofValue = true if case .generateBrokerReportResponse(let m) = current {v = m} } try decoder.decodeSingularMessageField(value: &v) if let v = v { if hadOneofValue {try decoder.handleConflictingOneOf()} self.payload = .generateBrokerReportResponse(v) } }() case 2: try { var v: GetBrokerReportResponse? var hadOneofValue = false if let current = self.payload { hadOneofValue = true if case .getBrokerReportResponse(let m) = current {v = m} } try decoder.decodeSingularMessageField(value: &v) if let v = v { if hadOneofValue {try decoder.handleConflictingOneOf()} self.payload = .getBrokerReportResponse(v) } }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 switch self.payload { case .generateBrokerReportResponse?: try { guard case .generateBrokerReportResponse(let v)? = self.payload else { preconditionFailure() } try visitor.visitSingularMessageField(value: v, fieldNumber: 1) }() case .getBrokerReportResponse?: try { guard case .getBrokerReportResponse(let v)? = self.payload else { preconditionFailure() } try visitor.visitSingularMessageField(value: v, fieldNumber: 2) }() case nil: break } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: BrokerReportResponse, rhs: BrokerReportResponse) -> Bool { if lhs.payload != rhs.payload {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension GenerateBrokerReportRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".GenerateBrokerReportRequest" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "account_id"), 2: .same(proto: "from"), 3: .same(proto: "to"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.accountID) }() case 2: try { try decoder.decodeSingularMessageField(value: &self._from) }() case 3: try { try decoder.decodeSingularMessageField(value: &self._to) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 if !self.accountID.isEmpty { try visitor.visitSingularStringField(value: self.accountID, fieldNumber: 1) } try { if let v = self._from { try visitor.visitSingularMessageField(value: v, fieldNumber: 2) } }() try { if let v = self._to { try visitor.visitSingularMessageField(value: v, fieldNumber: 3) } }() try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: GenerateBrokerReportRequest, rhs: GenerateBrokerReportRequest) -> Bool { if lhs.accountID != rhs.accountID {return false} if lhs._from != rhs._from {return false} if lhs._to != rhs._to {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension GenerateBrokerReportResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".GenerateBrokerReportResponse" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "task_id"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.taskID) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.taskID.isEmpty { try visitor.visitSingularStringField(value: self.taskID, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: GenerateBrokerReportResponse, rhs: GenerateBrokerReportResponse) -> Bool { if lhs.taskID != rhs.taskID {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension GetBrokerReportRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".GetBrokerReportRequest" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "task_id"), 2: .same(proto: "page"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.taskID) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self.page) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.taskID.isEmpty { try visitor.visitSingularStringField(value: self.taskID, fieldNumber: 1) } if self.page != 0 { try visitor.visitSingularInt32Field(value: self.page, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: GetBrokerReportRequest, rhs: GetBrokerReportRequest) -> Bool { if lhs.taskID != rhs.taskID {return false} if lhs.page != rhs.page {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension GetBrokerReportResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".GetBrokerReportResponse" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "broker_report"), 2: .same(proto: "itemsCount"), 3: .same(proto: "pagesCount"), 4: .same(proto: "page"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedMessageField(value: &self.brokerReport) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self.itemsCount) }() case 3: try { try decoder.decodeSingularInt32Field(value: &self.pagesCount) }() case 4: try { try decoder.decodeSingularInt32Field(value: &self.page) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.brokerReport.isEmpty { try visitor.visitRepeatedMessageField(value: self.brokerReport, fieldNumber: 1) } if self.itemsCount != 0 { try visitor.visitSingularInt32Field(value: self.itemsCount, fieldNumber: 2) } if self.pagesCount != 0 { try visitor.visitSingularInt32Field(value: self.pagesCount, fieldNumber: 3) } if self.page != 0 { try visitor.visitSingularInt32Field(value: self.page, fieldNumber: 4) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: GetBrokerReportResponse, rhs: GetBrokerReportResponse) -> Bool { if lhs.brokerReport != rhs.brokerReport {return false} if lhs.itemsCount != rhs.itemsCount {return false} if lhs.pagesCount != rhs.pagesCount {return false} if lhs.page != rhs.page {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension BrokerReport: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BrokerReport" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "trade_id"), 2: .standard(proto: "order_id"), 3: .same(proto: "figi"), 4: .standard(proto: "execute_sign"), 5: .standard(proto: "trade_datetime"), 6: .same(proto: "exchange"), 7: .standard(proto: "class_code"), 8: .same(proto: "direction"), 9: .same(proto: "name"), 10: .same(proto: "ticker"), 11: .same(proto: "price"), 12: .same(proto: "quantity"), 13: .standard(proto: "order_amount"), 14: .standard(proto: "aci_value"), 15: .standard(proto: "total_order_amount"), 16: .standard(proto: "broker_commission"), 17: .standard(proto: "exchange_commission"), 18: .standard(proto: "exchange_clearing_commission"), 19: .standard(proto: "repo_rate"), 20: .same(proto: "party"), 21: .standard(proto: "clear_value_date"), 22: .standard(proto: "sec_value_date"), 23: .standard(proto: "broker_status"), 24: .standard(proto: "separate_agreement_type"), 25: .standard(proto: "separate_agreement_number"), 26: .standard(proto: "separate_agreement_date"), 27: .standard(proto: "delivery_type"), ] fileprivate class _StorageClass { var _tradeID: String = String() var _orderID: String = String() var _figi: String = String() var _executeSign: String = String() var _tradeDatetime: SwiftProtobuf.Google_Protobuf_Timestamp? = nil var _exchange: String = String() var _classCode: String = String() var _direction: String = String() var _name: String = String() var _ticker: String = String() var _price: MoneyValue? = nil var _quantity: Int64 = 0 var _orderAmount: MoneyValue? = nil var _aciValue: Quotation? = nil var _totalOrderAmount: MoneyValue? = nil var _brokerCommission: MoneyValue? = nil var _exchangeCommission: MoneyValue? = nil var _exchangeClearingCommission: MoneyValue? = nil var _repoRate: Quotation? = nil var _party: String = String() var _clearValueDate_p: SwiftProtobuf.Google_Protobuf_Timestamp? = nil var _secValueDate: SwiftProtobuf.Google_Protobuf_Timestamp? = nil var _brokerStatus: String = String() var _separateAgreementType: String = String() var _separateAgreementNumber: String = String() var _separateAgreementDate: String = String() var _deliveryType: String = String() static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _tradeID = source._tradeID _orderID = source._orderID _figi = source._figi _executeSign = source._executeSign _tradeDatetime = source._tradeDatetime _exchange = source._exchange _classCode = source._classCode _direction = source._direction _name = source._name _ticker = source._ticker _price = source._price _quantity = source._quantity _orderAmount = source._orderAmount _aciValue = source._aciValue _totalOrderAmount = source._totalOrderAmount _brokerCommission = source._brokerCommission _exchangeCommission = source._exchangeCommission _exchangeClearingCommission = source._exchangeClearingCommission _repoRate = source._repoRate _party = source._party _clearValueDate_p = source._clearValueDate_p _secValueDate = source._secValueDate _brokerStatus = source._brokerStatus _separateAgreementType = source._separateAgreementType _separateAgreementNumber = source._separateAgreementNumber _separateAgreementDate = source._separateAgreementDate _deliveryType = source._deliveryType } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &_storage._tradeID) }() case 2: try { try decoder.decodeSingularStringField(value: &_storage._orderID) }() case 3: try { try decoder.decodeSingularStringField(value: &_storage._figi) }() case 4: try { try decoder.decodeSingularStringField(value: &_storage._executeSign) }() case 5: try { try decoder.decodeSingularMessageField(value: &_storage._tradeDatetime) }() case 6: try { try decoder.decodeSingularStringField(value: &_storage._exchange) }() case 7: try { try decoder.decodeSingularStringField(value: &_storage._classCode) }() case 8: try { try decoder.decodeSingularStringField(value: &_storage._direction) }() case 9: try { try decoder.decodeSingularStringField(value: &_storage._name) }() case 10: try { try decoder.decodeSingularStringField(value: &_storage._ticker) }() case 11: try { try decoder.decodeSingularMessageField(value: &_storage._price) }() case 12: try { try decoder.decodeSingularInt64Field(value: &_storage._quantity) }() case 13: try { try decoder.decodeSingularMessageField(value: &_storage._orderAmount) }() case 14: try { try decoder.decodeSingularMessageField(value: &_storage._aciValue) }() case 15: try { try decoder.decodeSingularMessageField(value: &_storage._totalOrderAmount) }() case 16: try { try decoder.decodeSingularMessageField(value: &_storage._brokerCommission) }() case 17: try { try decoder.decodeSingularMessageField(value: &_storage._exchangeCommission) }() case 18: try { try decoder.decodeSingularMessageField(value: &_storage._exchangeClearingCommission) }() case 19: try { try decoder.decodeSingularMessageField(value: &_storage._repoRate) }() case 20: try { try decoder.decodeSingularStringField(value: &_storage._party) }() case 21: try { try decoder.decodeSingularMessageField(value: &_storage._clearValueDate_p) }() case 22: try { try decoder.decodeSingularMessageField(value: &_storage._secValueDate) }() case 23: try { try decoder.decodeSingularStringField(value: &_storage._brokerStatus) }() case 24: try { try decoder.decodeSingularStringField(value: &_storage._separateAgreementType) }() case 25: try { try decoder.decodeSingularStringField(value: &_storage._separateAgreementNumber) }() case 26: try { try decoder.decodeSingularStringField(value: &_storage._separateAgreementDate) }() case 27: try { try decoder.decodeSingularStringField(value: &_storage._deliveryType) }() default: break } } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 if !_storage._tradeID.isEmpty { try visitor.visitSingularStringField(value: _storage._tradeID, fieldNumber: 1) } if !_storage._orderID.isEmpty { try visitor.visitSingularStringField(value: _storage._orderID, fieldNumber: 2) } if !_storage._figi.isEmpty { try visitor.visitSingularStringField(value: _storage._figi, fieldNumber: 3) } if !_storage._executeSign.isEmpty { try visitor.visitSingularStringField(value: _storage._executeSign, fieldNumber: 4) } try { if let v = _storage._tradeDatetime { try visitor.visitSingularMessageField(value: v, fieldNumber: 5) } }() if !_storage._exchange.isEmpty { try visitor.visitSingularStringField(value: _storage._exchange, fieldNumber: 6) } if !_storage._classCode.isEmpty { try visitor.visitSingularStringField(value: _storage._classCode, fieldNumber: 7) } if !_storage._direction.isEmpty { try visitor.visitSingularStringField(value: _storage._direction, fieldNumber: 8) } if !_storage._name.isEmpty { try visitor.visitSingularStringField(value: _storage._name, fieldNumber: 9) } if !_storage._ticker.isEmpty { try visitor.visitSingularStringField(value: _storage._ticker, fieldNumber: 10) } try { if let v = _storage._price { try visitor.visitSingularMessageField(value: v, fieldNumber: 11) } }() if _storage._quantity != 0 { try visitor.visitSingularInt64Field(value: _storage._quantity, fieldNumber: 12) } try { if let v = _storage._orderAmount { try visitor.visitSingularMessageField(value: v, fieldNumber: 13) } }() try { if let v = _storage._aciValue { try visitor.visitSingularMessageField(value: v, fieldNumber: 14) } }() try { if let v = _storage._totalOrderAmount { try visitor.visitSingularMessageField(value: v, fieldNumber: 15) } }() try { if let v = _storage._brokerCommission { try visitor.visitSingularMessageField(value: v, fieldNumber: 16) } }() try { if let v = _storage._exchangeCommission { try visitor.visitSingularMessageField(value: v, fieldNumber: 17) } }() try { if let v = _storage._exchangeClearingCommission { try visitor.visitSingularMessageField(value: v, fieldNumber: 18) } }() try { if let v = _storage._repoRate { try visitor.visitSingularMessageField(value: v, fieldNumber: 19) } }() if !_storage._party.isEmpty { try visitor.visitSingularStringField(value: _storage._party, fieldNumber: 20) } try { if let v = _storage._clearValueDate_p { try visitor.visitSingularMessageField(value: v, fieldNumber: 21) } }() try { if let v = _storage._secValueDate { try visitor.visitSingularMessageField(value: v, fieldNumber: 22) } }() if !_storage._brokerStatus.isEmpty { try visitor.visitSingularStringField(value: _storage._brokerStatus, fieldNumber: 23) } if !_storage._separateAgreementType.isEmpty { try visitor.visitSingularStringField(value: _storage._separateAgreementType, fieldNumber: 24) } if !_storage._separateAgreementNumber.isEmpty { try visitor.visitSingularStringField(value: _storage._separateAgreementNumber, fieldNumber: 25) } if !_storage._separateAgreementDate.isEmpty { try visitor.visitSingularStringField(value: _storage._separateAgreementDate, fieldNumber: 26) } if !_storage._deliveryType.isEmpty { try visitor.visitSingularStringField(value: _storage._deliveryType, fieldNumber: 27) } } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: BrokerReport, rhs: BrokerReport) -> Bool { if lhs._storage !== rhs._storage { let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in let _storage = _args.0 let rhs_storage = _args.1 if _storage._tradeID != rhs_storage._tradeID {return false} if _storage._orderID != rhs_storage._orderID {return false} if _storage._figi != rhs_storage._figi {return false} if _storage._executeSign != rhs_storage._executeSign {return false} if _storage._tradeDatetime != rhs_storage._tradeDatetime {return false} if _storage._exchange != rhs_storage._exchange {return false} if _storage._classCode != rhs_storage._classCode {return false} if _storage._direction != rhs_storage._direction {return false} if _storage._name != rhs_storage._name {return false} if _storage._ticker != rhs_storage._ticker {return false} if _storage._price != rhs_storage._price {return false} if _storage._quantity != rhs_storage._quantity {return false} if _storage._orderAmount != rhs_storage._orderAmount {return false} if _storage._aciValue != rhs_storage._aciValue {return false} if _storage._totalOrderAmount != rhs_storage._totalOrderAmount {return false} if _storage._brokerCommission != rhs_storage._brokerCommission {return false} if _storage._exchangeCommission != rhs_storage._exchangeCommission {return false} if _storage._exchangeClearingCommission != rhs_storage._exchangeClearingCommission {return false} if _storage._repoRate != rhs_storage._repoRate {return false} if _storage._party != rhs_storage._party {return false} if _storage._clearValueDate_p != rhs_storage._clearValueDate_p {return false} if _storage._secValueDate != rhs_storage._secValueDate {return false} if _storage._brokerStatus != rhs_storage._brokerStatus {return false} if _storage._separateAgreementType != rhs_storage._separateAgreementType {return false} if _storage._separateAgreementNumber != rhs_storage._separateAgreementNumber {return false} if _storage._separateAgreementDate != rhs_storage._separateAgreementDate {return false} if _storage._deliveryType != rhs_storage._deliveryType {return false} return true } if !storagesAreEqual {return false} } if lhs.unknownFields != rhs.unknownFields {return false} return true } }
40.421776
169
0.714144
624601f9248b028aecb6e5545f6099341e48f75f
129
let greatNovellas = NovellasCollection(novellas:["Mist"]) for novella in greatNovellas { println("I've read: \(novella)") }
21.5
57
0.713178
462a65c0ddd1ff5e3aa9730696f03a020eb632c9
11,611
import AVFoundation import CoreFoundation import VideoToolbox protocol VideoEncoderDelegate: class { func didSetFormatDescription(video formatDescription: CMFormatDescription?) func sampleOutput(video sampleBuffer: CMSampleBuffer) } // MARK: - final class H264Encoder: NSObject { static let supportedSettingsKeys: [String] = [ "muted", "width", "height", "bitrate", "profileLevel", "dataRateLimits", "enabledHardwareEncoder", // macOS only "maxKeyFrameIntervalDuration", "scalingMode" ] static let defaultWidth: Int32 = 480 static let defaultHeight: Int32 = 272 static let defaultBitrate: UInt32 = 160 * 1024 static let defaultScalingMode: String = "Trim" #if os(iOS) static let defaultAttributes: [NSString: AnyObject] = [ kCVPixelBufferIOSurfacePropertiesKey: [:] as AnyObject, kCVPixelBufferOpenGLESCompatibilityKey: kCFBooleanTrue ] #else static let defaultAttributes: [NSString: AnyObject] = [ kCVPixelBufferIOSurfacePropertiesKey: [:] as AnyObject, kCVPixelBufferOpenGLCompatibilityKey: kCFBooleanTrue ] #endif static let defaultDataRateLimits: [Int] = [0, 0] @objc var muted: Bool = false @objc var scalingMode: String = H264Encoder.defaultScalingMode { didSet { guard scalingMode != oldValue else { return } invalidateSession = true } } @objc var width: Int32 = H264Encoder.defaultWidth { didSet { guard width != oldValue else { return } invalidateSession = true } } @objc var height: Int32 = H264Encoder.defaultHeight { didSet { guard height != oldValue else { return } invalidateSession = true } } @objc var enabledHardwareEncoder: Bool = true { didSet { guard enabledHardwareEncoder != oldValue else { return } invalidateSession = true } } @objc var bitrate: UInt32 = H264Encoder.defaultBitrate { didSet { guard bitrate != oldValue else { return } setProperty(kVTCompressionPropertyKey_AverageBitRate, Int(bitrate) as CFTypeRef) } } @objc var dataRateLimits: [Int] = H264Encoder.defaultDataRateLimits { didSet { guard dataRateLimits != oldValue else { return } if dataRateLimits == H264Encoder.defaultDataRateLimits { invalidateSession = true return } setProperty(kVTCompressionPropertyKey_DataRateLimits, dataRateLimits as CFTypeRef) } } @objc var profileLevel: String = kVTProfileLevel_H264_Baseline_3_1 as String { didSet { guard profileLevel != oldValue else { return } invalidateSession = true } } @objc var maxKeyFrameIntervalDuration: Double = 2.0 { didSet { guard maxKeyFrameIntervalDuration != oldValue else { return } setProperty(kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, NSNumber(value: maxKeyFrameIntervalDuration)) } } var locked: UInt32 = 0 var lockQueue = DispatchQueue(label: "com.haishinkit.HaishinKit.H264Encoder.lock") var expectedFPS: Float64 = AVMixer.defaultFPS { didSet { guard expectedFPS != oldValue else { return } setProperty(kVTCompressionPropertyKey_ExpectedFrameRate, NSNumber(value: expectedFPS)) } } var formatDescription: CMFormatDescription? { didSet { guard !CMFormatDescriptionEqual(formatDescription, otherFormatDescription: oldValue) else { return } delegate?.didSetFormatDescription(video: formatDescription) } } weak var delegate: VideoEncoderDelegate? private(set) var isRunning: Bool = false private var supportedProperty: [AnyHashable: Any]? { didSet { guard logger.isEnabledFor(level: .info) else { return } var keys: [String] = [] for (key, _) in supportedProperty ?? [:] { keys.append(key.description) } logger.info(keys.joined(separator: ", ")) } } private(set) var status: OSStatus = noErr private var attributes: [NSString: AnyObject] { var attributes: [NSString: AnyObject] = H264Encoder.defaultAttributes attributes[kCVPixelBufferWidthKey] = NSNumber(value: width) attributes[kCVPixelBufferHeightKey] = NSNumber(value: height) return attributes } private var invalidateSession: Bool = true private var lastImageBuffer: CVImageBuffer? // @see: https://developer.apple.com/library/mac/releasenotes/General/APIDiffsMacOSX10_8/VideoToolbox.html private var properties: [NSString: NSObject] { let isBaseline: Bool = profileLevel.contains("Baseline") var properties: [NSString: NSObject] = [ kVTCompressionPropertyKey_RealTime: kCFBooleanTrue, kVTCompressionPropertyKey_ProfileLevel: profileLevel as NSObject, kVTCompressionPropertyKey_AverageBitRate: Int(bitrate) as NSObject, kVTCompressionPropertyKey_ExpectedFrameRate: NSNumber(value: expectedFPS), kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration: NSNumber(value: maxKeyFrameIntervalDuration), kVTCompressionPropertyKey_AllowFrameReordering: !isBaseline as NSObject, kVTCompressionPropertyKey_PixelTransferProperties: [ "ScalingMode": scalingMode ] as NSObject ] #if os(OSX) if enabledHardwareEncoder { properties[kVTVideoEncoderSpecification_EncoderID] = "com.apple.videotoolbox.videoencoder.h264.gva" as NSObject properties["EnableHardwareAcceleratedVideoEncoder"] = kCFBooleanTrue properties["RequireHardwareAcceleratedVideoEncoder"] = kCFBooleanTrue } #endif if dataRateLimits != H264Encoder.defaultDataRateLimits { properties[kVTCompressionPropertyKey_DataRateLimits] = dataRateLimits as NSObject } if !isBaseline { properties[kVTCompressionPropertyKey_H264EntropyMode] = kVTH264EntropyMode_CABAC } return properties } private var callback: VTCompressionOutputCallback = {( outputCallbackRefCon: UnsafeMutableRawPointer?, sourceFrameRefCon: UnsafeMutableRawPointer?, status: OSStatus, infoFlags: VTEncodeInfoFlags, sampleBuffer: CMSampleBuffer?) in guard let refcon: UnsafeMutableRawPointer = outputCallbackRefCon, let sampleBuffer: CMSampleBuffer = sampleBuffer, status == noErr else { return } let encoder: H264Encoder = Unmanaged<H264Encoder>.fromOpaque(refcon).takeUnretainedValue() encoder.formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer) encoder.delegate?.sampleOutput(video: sampleBuffer) } private var _session: VTCompressionSession? private var session: VTCompressionSession? { get { if _session == nil { guard VTCompressionSessionCreate( allocator: kCFAllocatorDefault, width: width, height: height, codecType: kCMVideoCodecType_H264, encoderSpecification: nil, imageBufferAttributes: attributes as CFDictionary?, compressedDataAllocator: nil, outputCallback: callback, refcon: Unmanaged.passUnretained(self).toOpaque(), compressionSessionOut: &_session ) == noErr else { logger.warn("create a VTCompressionSessionCreate") return nil } invalidateSession = false status = VTSessionSetProperties(_session!, propertyDictionary: properties as CFDictionary) status = VTCompressionSessionPrepareToEncodeFrames(_session!) supportedProperty = _session?.copySupportedPropertyDictionary() } return _session } set { if let session: VTCompressionSession = _session { VTCompressionSessionInvalidate(session) } _session = newValue } } func encodeImageBuffer(_ imageBuffer: CVImageBuffer, presentationTimeStamp: CMTime, duration: CMTime) { guard isRunning && locked == 0 else { return } if invalidateSession { session = nil } guard let session: VTCompressionSession = session else { return } var flags: VTEncodeInfoFlags = [] VTCompressionSessionEncodeFrame( session, imageBuffer: muted ? lastImageBuffer ?? imageBuffer : imageBuffer, presentationTimeStamp: presentationTimeStamp, duration: duration, frameProperties: nil, sourceFrameRefcon: nil, infoFlagsOut: &flags ) if !muted { lastImageBuffer = imageBuffer } } private func setProperty(_ key: CFString, _ value: CFTypeRef?) { lockQueue.async { guard let session: VTCompressionSession = self._session else { return } self.status = VTSessionSetProperty( session, key: key, value: value ) } } #if os(iOS) @objc private func applicationWillEnterForeground(_ notification: Notification) { invalidateSession = true } @objc private func didAudioSessionInterruption(_ notification: Notification) { guard let userInfo: [AnyHashable: Any] = notification.userInfo, let value: NSNumber = userInfo[AVAudioSessionInterruptionTypeKey] as? NSNumber, let type: AVAudioSession.InterruptionType = AVAudioSession.InterruptionType(rawValue: value.uintValue) else { return } switch type { case .ended: invalidateSession = true default: break } } #endif } extension H264Encoder: Running { // MARK: Running func startRunning() { lockQueue.async { self.isRunning = true #if os(iOS) NotificationCenter.default.addObserver( self, selector: #selector(self.didAudioSessionInterruption), name: AVAudioSession.interruptionNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(self.applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil ) #endif } } func stopRunning() { lockQueue.async { self.session = nil self.lastImageBuffer = nil self.formatDescription = nil #if os(iOS) NotificationCenter.default.removeObserver(self) #endif self.isRunning = false } } }
34.659701
124
0.60813
6254e362dca154b7f9694d3da2427ff276267f33
11,252
// RUN: %target-swift-emit-silgen -enable-sil-opaque-values -enable-sil-ownership -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s // RUN: %target-swift-emit-silgen -target x86_64-apple-macosx10.9 -enable-sil-opaque-values -enable-sil-ownership -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck --check-prefix=CHECK-OSX %s public typealias AnyObject = Builtin.AnyObject precedencegroup AssignmentPrecedence {} precedencegroup CastingPrecedence {} precedencegroup ComparisonPrecedence {} public protocol _ObjectiveCBridgeable {} public protocol UnkeyedDecodingContainer { var isAtEnd: Builtin.Int1 { get } } public protocol Decoder { func unkeyedContainer() throws -> UnkeyedDecodingContainer } // Test open_existential_value ownership // --- // CHECK-LABEL: sil @$ss11takeDecoder4fromBi1_s0B0_p_tKF : $@convention(thin) (@in_guaranteed Decoder) -> (Builtin.Int1, @error Error) { // CHECK: bb0(%0 : @guaranteed $Decoder): // CHECK: [[OPENED:%.*]] = open_existential_value %0 : $Decoder to $@opened("{{.*}}") Decoder // CHECK: [[WT:%.*]] = witness_method $@opened("{{.*}}") Decoder, #Decoder.unkeyedContainer!1 : <Self where Self : Decoder> (Self) -> () throws -> UnkeyedDecodingContainer, %3 : $@opened("{{.*}}") Decoder : $@convention(witness_method: Decoder) <τ_0_0 where τ_0_0 : Decoder> (@in_guaranteed τ_0_0) -> (@out UnkeyedDecodingContainer, @error Error) // CHECK: try_apply [[WT]]<@opened("{{.*}}") Decoder>([[OPENED]]) : $@convention(witness_method: Decoder) <τ_0_0 where τ_0_0 : Decoder> (@in_guaranteed τ_0_0) -> (@out UnkeyedDecodingContainer, @error Error), normal bb2, error bb1 // // CHECK:bb{{.*}}([[RET1:%.*]] : @owned $UnkeyedDecodingContainer): // CHECK: [[BORROW2:%.*]] = begin_borrow [[RET1]] : $UnkeyedDecodingContainer // CHECK: [[OPENED2:%.*]] = open_existential_value [[BORROW2]] : $UnkeyedDecodingContainer to $@opened("{{.*}}") UnkeyedDecodingContainer // CHECK: [[WT2:%.*]] = witness_method $@opened("{{.*}}") UnkeyedDecodingContainer, #UnkeyedDecodingContainer.isAtEnd!getter.1 : <Self where Self : UnkeyedDecodingContainer> (Self) -> () -> Builtin.Int1, [[OPENED2]] : $@opened("{{.*}}") UnkeyedDecodingContainer : $@convention(witness_method: UnkeyedDecodingContainer) <τ_0_0 where τ_0_0 : UnkeyedDecodingContainer> (@in_guaranteed τ_0_0) -> Builtin.Int1 // CHECK: [[RET2:%.*]] = apply [[WT2]]<@opened("{{.*}}") UnkeyedDecodingContainer>([[OPENED2]]) : $@convention(witness_method: UnkeyedDecodingContainer) <τ_0_0 where τ_0_0 : UnkeyedDecodingContainer> (@in_guaranteed τ_0_0) -> Builtin.Int1 // CHECK: end_borrow [[BORROW2]] : $UnkeyedDecodingContainer // CHECK: destroy_value [[RET1]] : $UnkeyedDecodingContainer // CHECK-NOT: destroy_value %0 : $Decoder // CHECK: return [[RET2]] : $Builtin.Int1 // CHECK-LABEL: } // end sil function '$ss11takeDecoder4fromBi1_s0B0_p_tKF' public func takeDecoder(from decoder: Decoder) throws -> Builtin.Int1 { let container = try decoder.unkeyedContainer() return container.isAtEnd } // Test unsafe_bitwise_cast nontrivial ownership. // --- // CHECK-LABEL: sil @$ss13unsafeBitCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U { // CHECK: bb0([[ARG0:%.*]] : @guaranteed $T, [[ARG1:%.*]] : $@thick U.Type): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG0]] : $T // CHECK: [[RESULT:%.*]] = unchecked_bitwise_cast [[ARG_COPY]] : $T to $U // CHECK: [[RESULT_COPY:%.*]] = copy_value [[RESULT]] : $U // CHECK: destroy_value [[ARG_COPY]] : $T // CHECK: return [[RESULT_COPY]] : $U // CHECK-LABEL: } // end sil function '$ss13unsafeBitCast_2toq_x_q_mtr0_lF' public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U { return Builtin.reinterpretCast(x) } // A lot of standard library support is necessary to support raw enums. // -------------------------------------------------------------------- infix operator == : ComparisonPrecedence infix operator ~= : ComparisonPrecedence public struct Bool { var _value: Builtin.Int1 public init() { let zero: Int64 = 0 self._value = Builtin.trunc_Int64_Int1(zero._value) } internal init(_ v: Builtin.Int1) { self._value = v } public init(_ value: Bool) { self = value } } extension Bool { public func _getBuiltinLogicValue() -> Builtin.Int1 { return _value } } public protocol Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. static func == (lhs: Self, rhs: Self) -> Bool } public func ~= <T : Equatable>(a: T, b: T) -> Bool { return a == b } public protocol RawRepresentable { associatedtype RawValue init?(rawValue: RawValue) var rawValue: RawValue { get } } public func == <T : RawRepresentable>(lhs: T, rhs: T) -> Bool where T.RawValue : Equatable { return lhs.rawValue == rhs.rawValue } public typealias _MaxBuiltinIntegerType = Builtin.IntLiteral public protocol _ExpressibleByBuiltinIntegerLiteral { init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType) } public protocol ExpressibleByIntegerLiteral { associatedtype IntegerLiteralType : _ExpressibleByBuiltinIntegerLiteral init(integerLiteral value: IntegerLiteralType) } extension ExpressibleByIntegerLiteral where Self : _ExpressibleByBuiltinIntegerLiteral { @_transparent public init(integerLiteral value: Self) { self = value } } public protocol ExpressibleByStringLiteral {} public protocol ExpressibleByFloatLiteral {} public protocol ExpressibleByUnicodeScalarLiteral {} public protocol ExpressibleByExtendedGraphemeClusterLiteral {} public struct Int64 : ExpressibleByIntegerLiteral, _ExpressibleByBuiltinIntegerLiteral, Equatable { public var _value: Builtin.Int64 public init(_builtinIntegerLiteral x: _MaxBuiltinIntegerType) { _value = Builtin.s_to_s_checked_trunc_IntLiteral_Int64(x).0 } public typealias IntegerLiteralType = Int64 public init(integerLiteral value: Int64) { self = value } public static func ==(_ lhs: Int64, rhs: Int64) -> Bool { return Bool(Builtin.cmp_eq_Int64(lhs._value, rhs._value)) } } // Test ownership of multi-case Enum values in the context of to @in thunks. // --- // CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @$ss17FloatingPointSignOSQsSQ2eeoiySbx_xtFZTW : $@convention(witness_method: Equatable) (@in_guaranteed FloatingPointSign, @in_guaranteed FloatingPointSign, @thick FloatingPointSign.Type) -> Bool { // CHECK: bb0(%0 : $FloatingPointSign, %1 : $FloatingPointSign, %2 : $@thick FloatingPointSign.Type): // CHECK: %3 = function_ref @$ss2eeoiySbx_xtSYRzSQ8RawValueRpzlF : $@convention(thin) <τ_0_0 where τ_0_0 : RawRepresentable, τ_0_0.RawValue : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool // CHECK: %4 = apply %3<FloatingPointSign>(%0, %1) : $@convention(thin) <τ_0_0 where τ_0_0 : RawRepresentable, τ_0_0.RawValue : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool // CHECK: return %4 : $Bool // CHECK-LABEL: } // end sil function '$ss17FloatingPointSignOSQsSQ2eeoiySbx_xtFZTW' public enum FloatingPointSign: Int64 { /// The sign for a positive value. case plus /// The sign for a negative value. case minus } #if os(macOS) // Test open_existential_value used in a conversion context. // (the actual bridging call is dropped because we don't import Swift). // --- // CHECK-OSX-LABEL: sil @$ss26_unsafeDowncastToAnyObject04fromD0yXlyp_tF : $@convention(thin) (@in_guaranteed Any) -> @owned AnyObject { // CHECK-OSX: bb0(%0 : @guaranteed $Any): // CHECK-OSX: [[COPY:%.*]] = copy_value %0 : $Any // CHECK-OSX: [[BORROW2:%.*]] = begin_borrow [[COPY]] : $Any // CHECK-OSX: [[VAL:%.*]] = open_existential_value [[BORROW2]] : $Any to $@opened // CHECK-OSX: [[COPY2:%.*]] = copy_value [[VAL]] : $@opened // CHECK-OSX: end_borrow [[BORROW2]] : $Any // CHECK-OSX: destroy_value [[COPY2]] : $@opened // CHECK-OSX: destroy_value [[COPY]] : $Any // CHECK-OSX-NOT: destroy_value %0 : $Any // CHECK-OSX: return undef : $AnyObject // CHECK-OSX-LABEL: } // end sil function '$ss26_unsafeDowncastToAnyObject04fromD0yXlyp_tF' public func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject { return any as AnyObject } #endif public protocol Error {} #if os(macOS) // Test open_existential_box_value in a conversion context. // --- // CHECK-OSX-LABEL: sil @$ss3foo1eys5Error_pSg_tF : $@convention(thin) (@guaranteed Optional<Error>) -> () { // CHECK-OSX: [[BORROW:%.*]] = begin_borrow %{{.*}} : $Error // CHECK-OSX: [[VAL:%.*]] = open_existential_box_value [[BORROW]] : $Error to $@opened // CHECK-OSX: [[COPY:%.*]] = copy_value [[VAL]] : $@opened // CHECK-OSX: [[ANY:%.*]] = init_existential_value [[COPY]] : $@opened // CHECK-OSX: end_borrow [[BORROW]] : $Error // CHECK-OSX-LABEL: } // end sil function '$ss3foo1eys5Error_pSg_tF' public func foo(e: Error?) { if let u = e { let a: Any = u _ = a } } #endif public enum Optional<Wrapped> { case none case some(Wrapped) } public protocol IP {} public protocol Seq { associatedtype Iterator : IP func makeIterator() -> Iterator } extension Seq where Self.Iterator == Self { public func makeIterator() -> Self { return self } } public struct EnumIter<Base : IP> : IP, Seq { internal var _base: Base public typealias Iterator = EnumIter<Base> } // Test passing a +1 RValue to @in_guaranteed. // --- // CHECK-LABEL: sil @$ss7EnumSeqV12makeIterators0A4IterVy0D0QzGyF : $@convention(method) <Base where Base : Seq> (@in_guaranteed EnumSeq<Base>) -> @out EnumIter<Base.Iterator> { // CHECK: bb0(%0 : @guaranteed $EnumSeq<Base>): // CHECK: [[MT:%.*]] = metatype $@thin EnumIter<Base.Iterator>.Type // CHECK: [[FIELD:%.*]] = struct_extract %0 : $EnumSeq<Base>, #EnumSeq._base // CHECK: [[COPY:%.*]] = copy_value [[FIELD]] : $Base // CHECK: [[WT:%.*]] = witness_method $Base, #Seq.makeIterator!1 : <Self where Self : Seq> (Self) -> () -> Self.Iterator : $@convention(witness_method: Seq) <τ_0_0 where τ_0_0 : Seq> (@in_guaranteed τ_0_0) -> @out τ_0_0.Iterator // CHECK: [[ITER:%.*]] = apply [[WT]]<Base>([[COPY]]) : $@convention(witness_method: Seq) <τ_0_0 where τ_0_0 : Seq> (@in_guaranteed τ_0_0) -> @out τ_0_0.Iterator // CHECK: destroy_value [[COPY]] : $Base // CHECK: [[FN:%.*]] = function_ref @$ss8EnumIterV5_baseAByxGx_tcfC : $@convention(method) <τ_0_0 where τ_0_0 : IP> (@in τ_0_0, @thin EnumIter<τ_0_0>.Type) -> @out EnumIter<τ_0_0> // CHECK: [[RET:%.*]] = apply [[FN]]<Base.Iterator>([[ITER]], [[MT]]) : $@convention(method) <τ_0_0 where τ_0_0 : IP> (@in τ_0_0, @thin EnumIter<τ_0_0>.Type) -> @out EnumIter<τ_0_0> // CHECK: return [[RET]] : $EnumIter<Base.Iterator> // CHECK-LABEL: } // end sil function '$ss7EnumSeqV12makeIterators0A4IterVy0D0QzGyF' public struct EnumSeq<Base : Seq> : Seq { public typealias Iterator = EnumIter<Base.Iterator> internal var _base: Base public func makeIterator() -> Iterator { return EnumIter(_base: _base.makeIterator()) } }
43.612403
405
0.694899
87603e16de923fd8ec5feae7a9a4a9a5dc5e0456
1,710
// // LaunchAtLoginHelper.swift // OpenSim // // Created by Luo Sheng on 07/05/2017. // Copyright © 2017 Luo Sheng. All rights reserved. // import Foundation func getLoginItems() -> LSSharedFileList? { let allocator = CFAllocatorGetDefault().takeRetainedValue() let kLoginItems = kLSSharedFileListSessionLoginItems.takeUnretainedValue() guard let loginItems = LSSharedFileListCreate(allocator, kLoginItems, nil) else { return nil } return loginItems.takeRetainedValue() } func existingItem(itemUrl: URL) -> LSSharedFileListItem? { guard let loginItems = getLoginItems() else { return nil } var seed: UInt32 = 0 if let currentItems = LSSharedFileListCopySnapshot(loginItems, &seed).takeRetainedValue() as? [LSSharedFileListItem] { for item in currentItems { let resolutionFlags = UInt32(kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes) if let cfurl = LSSharedFileListItemCopyResolvedURL(item, resolutionFlags, nil) { let url = cfurl.takeRetainedValue() as URL if itemUrl == url { return item } } } } return nil } func setLaunchAtLogin(itemUrl: URL, enabled: Bool) { guard let loginItems = getLoginItems() else { return } if let item = existingItem(itemUrl: itemUrl) { if (!enabled) { LSSharedFileListItemRemove(loginItems, item) } } else { if (enabled) { LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst.takeUnretainedValue(), nil, nil, itemUrl as CFURL, nil, nil) } } }
31.090909
147
0.650292
143a671e0db0adaf9159d3029858c1ff33ae9fd3
13,407
// // K5000SysexMessages.swift // // Created by Kurt Arnlund on 1/12/19. // Copyright © 2019 AudioKit. All rights reserved. // // A rather complete set of Kawai K5000 Sysex Message Definitions // Used as an example of how to setup Sysex Messages import Foundation import AudioKit /// K5000 manufacturer and machine bytes enum kawaiK5000: MIDIByte { case manufacturerId = 0x40 case machine = 0x0A } /// K5000 sysex messages all have a midi channel byte enum K5000sysexChannel: MIDIByte { case channel0 = 0x00 case channel1 = 0x01 case channel2 = 0x02 case channel3 = 0x03 case channel4 = 0x04 case channel5 = 0x05 case channel6 = 0x06 case channel7 = 0x07 case channel8 = 0x08 case channel9 = 0x09 case channel10 = 0x0A case channel11 = 0x0B case channel12 = 0x0C case channel13 = 0x0D case channel14 = 0x0E case channel15 = 0x0F } // MARK: - Usefull runs of sysex bytes let kawaiK5000sysexStart: [MIDIByte] = [AKMIDISystemCommand.sysex.rawValue, kawaiK5000.manufacturerId.rawValue] /// Request type words used across all devices public enum K5000requestTypes: MIDIWord { case single = 0x0000 case block = 0x0100 } /// K5000SR requests public enum K5000SRdumpRequests: MIDIWord { case areaA = 0x0000 case areaC = 0x2000 case areaD = 0x0002 } /// K5000SR (with ME1 memory card installed) requests public enum K5000ME1dumpRequests: MIDIWord { case areaE = 0x0003 case areaF = 0x0004 } /// K5000W requests public enum K5000WdumpRequests: MIDIWord { case dump_reqest = 0x0000 case areaBpcm = 0x0001 case drumKit = 0x1000 case drumInst = 0x1100 } /// Sysex Message for the K5000S/R class K5000messages { /// Block Single Dump Request (ADD A1-128) /// /// This request results in 77230 bytes of SYSEX - it take several seconds to get the full result /// /// - Parameter channel: K5000sysexChannel 0x00 - 0x0F /// - Returns: [MIDIByte] func blockSingleAreaA(channel: K5000sysexChannel) -> [MIDIByte] { let request: [MIDIByte] = kawaiK5000sysexStart + [channel.rawValue, K5000requestTypes.block.rawValue.msb, K5000requestTypes.block.rawValue.lsb, kawaiK5000.machine.rawValue, K5000SRdumpRequests.areaA.rawValue.msb, K5000SRdumpRequests.areaA.rawValue.lsb, 0x00, AKMIDISystemCommand.sysexEnd.rawValue] return request } /// One Single Dump Request (ADD A1-128) /// /// This request results in 1242 bytes of SYSEX response /// /// - Parameters: /// - channel: K5000sysexChannel 0x00 - 0x0F /// - patch: (ADD A1-128) 0x00 - 0x7f /// - Returns: [MIDIByte] func oneSingleAreaA(channel: K5000sysexChannel, patch: UInt8) -> [MIDIByte] { guard patch <= 0x7f else { return [] } let request: [MIDIByte] = kawaiK5000sysexStart + [channel.rawValue, K5000requestTypes.single.rawValue.msb, K5000requestTypes.single.rawValue.lsb, kawaiK5000.machine.rawValue, K5000SRdumpRequests.areaA.rawValue.msb, K5000SRdumpRequests.areaA.rawValue.lsb, patch, AKMIDISystemCommand.sysexEnd.rawValue] return request } /// Block Combi Dump Request (Combi C1-64) /// /// This request results in 6600 bytes of SYSEX reponse /// /// - Parameters: /// - channel: K5000sysexChannel 0x00 - 0x0F /// - Returns: [MIDIByte] func blockCombinationAreaC(channel: K5000sysexChannel) -> [MIDIByte] { let request: [MIDIByte] = kawaiK5000sysexStart + [channel.rawValue, K5000requestTypes.block.rawValue.msb, K5000requestTypes.block.rawValue.lsb, kawaiK5000.machine.rawValue, K5000SRdumpRequests.areaC.rawValue.msb, K5000SRdumpRequests.areaC.rawValue.lsb, 0x00, AKMIDISystemCommand.sysexEnd.rawValue] return request } /// One Combi Dump Request (Combi C1-64) /// /// This request results in 112 bytes of SYSEX reponse /// /// - Parameters: /// - channel: K5000sysexChannel 0x00 - 0x0F /// - combi: (Combi C1-64) 0x00 - 0x3f /// - Returns: [MIDIByte] func oneCombinationAreaC(channel: K5000sysexChannel, combi: UInt8) -> [MIDIByte] { guard combi <= 0x3f else { return [] } let request: [MIDIByte] = kawaiK5000sysexStart + [channel.rawValue, K5000requestTypes.single.rawValue.msb, K5000requestTypes.single.rawValue.lsb, kawaiK5000.machine.rawValue, K5000SRdumpRequests.areaC.rawValue.msb, K5000SRdumpRequests.areaC.rawValue.lsb, combi, AKMIDISystemCommand.sysexEnd.rawValue] return request } /// Block Single Dump Request (ADD D1-128) /// /// This request results in 130428 bytes of SYSEX response /// /// - Parameters: /// - channel: K5000sysexChannel 0x00 - 0x0F /// - Returns: [MIDIByte] func blockSingleAreaD(channel: K5000sysexChannel) -> [MIDIByte] { let request: [MIDIByte] = kawaiK5000sysexStart + [channel.rawValue, K5000requestTypes.block.rawValue.msb, K5000requestTypes.block.rawValue.lsb, kawaiK5000.machine.rawValue, K5000SRdumpRequests.areaD.rawValue.msb, K5000SRdumpRequests.areaD.rawValue.lsb, 0x00, AKMIDISystemCommand.sysexEnd.rawValue] return request } /// One Single Dump Request (ADD D1-128) /// /// This request results in 1962 bytes of SYSEX response /// /// - Parameters: /// - channel: K5000sysexChannel 0x00 - 0x0F /// - patch: (ADD D1-128) 0x00 - 0x7F /// - Returns: [MIDIByte] func oneSingleAreaD(channel: K5000sysexChannel, patch: UInt8) -> [MIDIByte] { guard patch <= 0x7f else { return [] } let request: [MIDIByte] = kawaiK5000sysexStart + [channel.rawValue, K5000requestTypes.single.rawValue.msb, K5000requestTypes.single.rawValue.lsb, kawaiK5000.machine.rawValue, K5000SRdumpRequests.areaD.rawValue.msb, K5000SRdumpRequests.areaD.rawValue.lsb, patch, AKMIDISystemCommand.sysexEnd.rawValue] return request } /// Block Single Dump Request (ADD E1-128 - ME1 installed) /// /// This request results in 102340 bytes of SYSEX response /// /// - Parameters: /// - channel: K5000sysexChannel 0x00 - 0x0F /// - Returns: [MIDIByte] func blockSingleAreaE(channel: K5000sysexChannel) -> [MIDIByte] { let request: [MIDIByte] = kawaiK5000sysexStart + [channel.rawValue, K5000requestTypes.block.rawValue.msb, K5000requestTypes.block.rawValue.lsb, kawaiK5000.machine.rawValue, K5000ME1dumpRequests.areaE.rawValue.msb, K5000ME1dumpRequests.areaE.rawValue.lsb, 0x00, AKMIDISystemCommand.sysexEnd.rawValue] return request } /// One Single Dump Request (ADD E1-128 - ME1 installed) /// /// This request results in 2768 bytes of SYSEX response /// /// - Parameters: /// - channel: K5000sysexChannel 0x00 - 0x0F /// - patch: (ADD E1-128) 0x00 - 0x7F /// - Returns: [MIDIByte] func oneSingleAreaE(channel: K5000sysexChannel, patch: UInt8) -> [MIDIByte] { guard patch <= 0x7f else { return [] } let request: [MIDIByte] = kawaiK5000sysexStart + [channel.rawValue, K5000requestTypes.single.rawValue.msb, K5000requestTypes.single.rawValue.lsb, kawaiK5000.machine.rawValue, K5000ME1dumpRequests.areaE.rawValue.msb, K5000ME1dumpRequests.areaE.rawValue.lsb, patch, AKMIDISystemCommand.sysexEnd.rawValue] return request } /// Block Single Dump Request (ADD F1-128 - ME1 installed) /// /// This request results in 110634 bytes of SYSEX response /// /// - Parameters: /// - channel: K5000sysexChannel 0x00 - 0x0F /// - Returns: [MIDIByte] func blockSingleAreaF(channel: K5000sysexChannel) -> [MIDIByte] { let request: [MIDIByte] = kawaiK5000sysexStart + [channel.rawValue, K5000requestTypes.block.rawValue.msb, K5000requestTypes.block.rawValue.lsb, kawaiK5000.machine.rawValue, K5000ME1dumpRequests.areaF.rawValue.msb, K5000ME1dumpRequests.areaF.rawValue.lsb, 0x00, AKMIDISystemCommand.sysexEnd.rawValue] return request } /// One Single Dump Request (ADD F1-128 - ME1 installed) /// /// This request results in 1070 bytes of SYSEX response /// /// - Parameters: /// - channel: K5000sysexChannel 0x00 - 0x0F /// - patch: (ADD F1-128) 0x00 - 0x7F /// - Returns: [MIDIByte] func oneSingleAreaF(channel: K5000sysexChannel, patch: UInt8) -> [MIDIByte] { guard patch <= 0x7f else { return [] } let request: [MIDIByte] = kawaiK5000sysexStart + [channel.rawValue, K5000requestTypes.single.rawValue.msb, K5000requestTypes.single.rawValue.lsb, kawaiK5000.machine.rawValue, K5000ME1dumpRequests.areaF.rawValue.msb, K5000ME1dumpRequests.areaF.rawValue.lsb, patch, AKMIDISystemCommand.sysexEnd.rawValue] return request } } /// Sysex Message for the K5000W class K5000Wmessages { /// Block Single Dump Request PCM Area (B70-116) /// /// - Parameter channel: K5000sysexChannel 0x00 - 0x0F /// - Returns: [MIDIByte] func blockSingleAreaBpcm(channel: K5000sysexChannel) -> [MIDIByte] { let request: [MIDIByte] = kawaiK5000sysexStart + [channel.rawValue, K5000requestTypes.block.rawValue.msb, K5000requestTypes.block.rawValue.lsb, kawaiK5000.machine.rawValue, K5000WdumpRequests.areaBpcm.rawValue.msb, K5000WdumpRequests.areaBpcm.rawValue.lsb, 0x00, AKMIDISystemCommand.sysexEnd.rawValue] return request } /// One Single Dumpe Request PCM Area (B70-116) /// /// - Parameters: /// - channel: K5000sysexChannel 0x00 - 0x0F /// - patch: patch number 0x45 - 0x73 /// - Returns: [MIDIByte] func oneSingleAreaBpcm(channel: K5000sysexChannel, patch: UInt8) -> [MIDIByte] { guard patch >= 0x45 && patch <= 0x73 else { return [] } let request: [MIDIByte] = kawaiK5000sysexStart + [channel.rawValue, K5000requestTypes.single.rawValue.msb, K5000requestTypes.single.rawValue.lsb, kawaiK5000.machine.rawValue, K5000WdumpRequests.areaBpcm.rawValue.msb, K5000WdumpRequests.areaBpcm.rawValue.lsb, 0x00, AKMIDISystemCommand.sysexEnd.rawValue] return request } /// Drum Kit Request (B117) /// /// - Parameters: /// - channel: K5000sysexChannel 0x00 - 0x0F /// - Returns: [MIDIByte] func drumKit(channel: K5000sysexChannel) -> [MIDIByte] { let request: [MIDIByte] = kawaiK5000sysexStart + [channel.rawValue, K5000requestTypes.single.rawValue.msb, K5000requestTypes.single.rawValue.lsb, kawaiK5000.machine.rawValue, K5000WdumpRequests.drumKit.rawValue.msb, K5000WdumpRequests.drumKit.rawValue.lsb, 0x00, AKMIDISystemCommand.sysexEnd.rawValue] return request } /// Block Drum Instrument Dump Request (Inst U1-32) /// /// - Parameters: /// - channel: K5000sysexChannel 0x00 - 0x0F /// - Returns: [MIDIByte] func blockDrumInstrument(channel: K5000sysexChannel) -> [MIDIByte] { let request: [MIDIByte] = kawaiK5000sysexStart + [channel.rawValue, K5000requestTypes.block.rawValue.msb, K5000requestTypes.block.rawValue.lsb, kawaiK5000.machine.rawValue, K5000WdumpRequests.drumInst.rawValue.msb, K5000WdumpRequests.drumInst.rawValue.lsb, 0x00, AKMIDISystemCommand.sysexEnd.rawValue] return request } /// One Drum Instrument Dump Request (Inst U1-32) /// /// - Parameters: /// - channel: K5000sysexChannel 0x00 - 0x0F /// - instrument: instrument number 0x00 - 0x1F /// - Returns: [MIDIByte] func oneDrumInstrument(channel: K5000sysexChannel, instrument: UInt8) -> [MIDIByte] { guard instrument <= 0x1f else { return [] } let request: [MIDIByte] = kawaiK5000sysexStart + [channel.rawValue, K5000requestTypes.single.rawValue.msb, K5000requestTypes.single.rawValue.lsb, kawaiK5000.machine.rawValue, K5000WdumpRequests.drumInst.rawValue.msb, K5000WdumpRequests.drumInst.rawValue.lsb, instrument, AKMIDISystemCommand.sysexEnd.rawValue] return request } }
35.752
111
0.622287
75bb6bc09aa2271842f175539067ad6440bc9487
495
//: [Table of Contents](Table%20of%20Contents) //: Credit to [@aligatr](https://twitter.com/aligatr) extension Sequence where Iterator.Element: Hashable { public var uniques: AnySequence<Iterator.Element> { var seen = Set<Iterator.Element>() var underlyingIterator = makeIterator() return AnySequence { AnyIterator { while let next = underlyingIterator.next() { if !seen.contains(next) { seen.insert(next) return next } } return nil } } } }
20.625
53
0.664646
fb63d6cf68932bddc60b7cedc4b694f678659ef4
558
import Foundation public final class Company: Generator { public func name() -> String { return generate("company.name") } public func suffix() -> String { return generate("company.suffix") } public func catchPhrase() -> String { return randomWordsFromKey("company.buzzwords") } public func bs() -> String { return randomWordsFromKey("company.bs") } public func logo() -> String { let number = Int(arc4random_uniform(13)) + 1 return "http://pigment.github.io/fake-logos/logos/medium/color/\(number).png" } }
21.461538
81
0.666667
e816239bc9b890818e1cb6b68b9c218629b0e1f6
2,342
// // GPXImporter.swift // Velik // // Created by Grigory Avdyushin on 24/06/2020. // Copyright © 2020 Grigory Avdyushin. All rights reserved. // import Combine import Injected import Foundation import CoreLocation protocol DataImporter { var availableGPX: AnyPublisher<GPXTrack, Never> { get } func `import`(url: URL) throws func save() } class GPXImporter: DataImporter { @Injected private var storage: StorageService private let available = PassthroughSubject<GPXTrack, Never>() let availableGPX: AnyPublisher<GPXTrack, Never> var gpx: GPXTrack? init() { availableGPX = available.eraseToAnyPublisher() } func `import`(url: URL) throws { let xml = try String(contentsOf: url) let gpx: GPXTrack = try XMLDecoder.decode(xml) available.send(gpx) self.gpx = gpx } func save() { guard let gpx = gpx, !gpx.locations.isEmpty else { return } let duration: TimeInterval if let minTimestamp = gpx.locations.min(by: \.timestamp)?.timestamp, let maxTimestamp = gpx.locations.max(by: \.timestamp)?.timestamp { duration = minTimestamp.distance(to: maxTimestamp) } else { duration = 0 } var current = gpx.locations.first! var distance: CLLocationDistance = 0.0 gpx.locations.dropFirst().forEach { distance += current.distance(from: $0) current = $0 } let avgSpeed = gpx.locations.average(by: \.speed) let maxSpeed = gpx.locations.max(by: \.speed)?.speed ?? .zero let elevationGainProcessor = ElevationGainProcessor(initialAltitude: gpx.locations.first!.altitude) var elevationGain: CLLocationDistance = 0.0 gpx.locations.dropFirst().forEach { elevationGain = elevationGainProcessor.process(input: $0.altitude) } storage.createNewRide( name: gpx.name ?? "Untitled", summary: RideService.Summary( duration: duration, distance: distance, avgSpeed: avgSpeed, maxSpeed: maxSpeed, elevationGain: elevationGain ), locations: gpx.locations, createdAt: gpx.timestamp ) } }
27.552941
107
0.605465
e511986405d1dfc4fc10d4412cf4d7cf4ad73bf6
5,781
// // JoinChannelVC.swift // APIExample // // Created by 张乾泽 on 2020/4/17. // Copyright © 2020 Agora Corp. All rights reserved. // import UIKit import AGEVideoLayout import AgoraRtcKit class PrecallTestEntry : UIViewController { var agoraKit: AgoraRtcEngineKit! var timer:Timer? var echoTesting:Bool = false @IBOutlet weak var lastmileBtn: UIButton! @IBOutlet weak var echoTestBtn: UIButton! @IBOutlet weak var lastmileResultLabel: UILabel! @IBOutlet weak var lastmileProbResultLabel: UILabel! @IBOutlet weak var lastmileActivityView: UIActivityIndicatorView! @IBOutlet weak var echoTestCountDownLabel: UILabel! @IBOutlet weak var echoTestPopover: UIView! @IBOutlet weak var echoValidateCountDownLabel: UILabel! @IBOutlet weak var echoValidatePopover: UIView! @IBOutlet weak var preview: UIView! override func viewDidLoad() { super.viewDidLoad() // set up agora instance when view loadedlet config = AgoraRtcEngineConfig() let config = AgoraRtcEngineConfig() config.appId = KeyCenter.AppId config.areaCode = GlobalSettings.shared.area.rawValue // setup log file path let logConfig = AgoraLogConfig() logConfig.level = .info config.logConfig = logConfig agoraKit = AgoraRtcEngineKit.sharedEngine(with: config, delegate: self) // have to be a broadcaster for doing echo test agoraKit.setChannelProfile(.liveBroadcasting) agoraKit.setClientRole(.broadcaster) } @IBAction func doLastmileTest(sender: UIButton) { lastmileActivityView.startAnimating() let config = AgoraLastmileProbeConfig() // do uplink testing config.probeUplink = true; // do downlink testing config.probeDownlink = true; // expected uplink bitrate, range: [100000, 5000000] config.expectedUplinkBitrate = 100000; // expected downlink bitrate, range: [100000, 5000000] config.expectedDownlinkBitrate = 100000; agoraKit.startLastmileProbeTest(config) } @IBAction func doEchoTest(sender: UIButton) { agoraKit.startEchoTest(withInterval: 10, successBlock: nil) showPopover(isValidate: false, seconds: 10) {[unowned self] in self.showPopover(isValidate: true, seconds: 10) {[unowned self] in self.agoraKit.stopEchoTest() } } } @IBAction func doEchoVideoTest(sender: UIButton) { if(echoTesting){ agoraKit.stopEchoTest() echoTestBtn.title = "Start Video/Audio Test".localized echoTesting = false } else{ let config = AgoraEchoTestConfiguration() echoTestBtn.title = "Stop Video/Audio Test".localized config.channelId = "randomChannel" config.view = self.preview config.enableAudio = true config.enableVideo = true agoraKit.startEchoTest(withConfig: config) echoTesting = true } } // show popover and hide after seconds func showPopover(isValidate:Bool, seconds:Int, callback:@escaping (() -> Void)) { var count = seconds var countDownLabel:UILabel? var popover:UIView? if(isValidate) { countDownLabel = echoValidateCountDownLabel popover = echoValidatePopover } else { countDownLabel = echoTestCountDownLabel popover = echoTestPopover } countDownLabel?.text = "\(count)" popover?.isHidden = false timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {[unowned self] (timer) in count -= 1 countDownLabel?.text = "\(count)" if(count == 0) { self.timer?.invalidate() popover?.isHidden = true callback() } } } override func willMove(toParent parent: UIViewController?) { if parent == nil { // clean up // important, you will not be able to join a channel // if you are in the middle of a testing timer?.invalidate() agoraKit.stopEchoTest() agoraKit.stopLastmileProbeTest() } } } extension PrecallTestEntry:AgoraRtcEngineDelegate { /// callback to get lastmile quality 2seconds after startLastmileProbeTest func rtcEngine(_ engine: AgoraRtcEngineKit, lastmileQuality quality: AgoraNetworkQuality) { lastmileResultLabel.text = "Quality: \(quality.description())" } /// callback to get more detail lastmile quality after startLastmileProbeTest func rtcEngine(_ engine: AgoraRtcEngineKit, lastmileProbeTest result: AgoraLastmileProbeResult) { let rtt = "Rtt: \(result.rtt)ms" let downlinkBandwidth = "DownlinkAvailableBandwidth: \(result.downlinkReport.availableBandwidth)Kbps" let downlinkJitter = "DownlinkJitter: \(result.downlinkReport.jitter)ms" let downlinkLoss = "DownlinkLoss: \(result.downlinkReport.packetLossRate)%" let uplinkBandwidth = "UplinkAvailableBandwidth: \(result.uplinkReport.availableBandwidth)Kbps" let uplinkJitter = "UplinkJitter: \(result.uplinkReport.jitter)ms" let uplinkLoss = "UplinkLoss: \(result.uplinkReport.packetLossRate)%" lastmileProbResultLabel.text = [rtt, downlinkBandwidth, downlinkJitter, downlinkLoss, uplinkBandwidth, uplinkJitter, uplinkLoss].joined(separator: "\n") // stop testing after get last mile detail result engine.stopLastmileProbeTest() lastmileActivityView.stopAnimating() } }
37.538961
160
0.646947
7a9e7da3463678feae6e9322b53bb23b30188366
513
// // AppDelegate.swift // TestCellSwiftVersion // // Created by tomfriwel on 20/04/2017. // Copyright © 2017 tomfriwel. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
19
71
0.719298
e0d2ff277d65f458846b7b984642ecbed0f942c6
2,167
// // AppDelegate.swift // LLScreenLock // // Created by Ruris on 02/07/2021. // Copyright (c) 2021 Ruris. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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.106383
285
0.753576
dd1e9214a397593108951f338b50af4fdc17230e
7,358
// // MagiSearchMainView.swift // MagiSearchDemo // // Created by 安然 on 2018/5/28. // Copyright © 2018年 MacBook. All rights reserved. // import UIKit open class MagiSearchMainView: UIView { let width = UIScreen.main.bounds.width let height = UIScreen.main.bounds.height var categoryLabel: UILabel! var magiCategoryButtons = [MagiCategoryButton]() var searchHistoryLabel: UILabel! var magiSearchHistoryViews = [MagiSearchHistoryView]() var magiSearchHistoryButtons = [MagiSearchHistoryButton]() var clearHistoryButton: UIButton! var margin: CGFloat = 15 weak var delegate: MagiSearchMainViewDelegate? var magiSearch = MagiSearch() public override init(frame: CGRect) { super.init(frame: frame) guard let categories = MagiSearch.shared.getCategories() else { return } initView(categories) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setMagiCategoryButtonType(type: MagiHotSearchStyle) { for magiCategoryButton in self.magiCategoryButtons { magiCategoryButton.type = type } } @objc func magiCategoryButtonClicked(_ sender: UIButton) { guard let text = magiCategoryButtons[sender.tag].titleLabel?.text else { return } magiSearch.appendSearchHistories(value: text) delegate?.magiCategoryButtonClicked(text) } @objc func magiSearchHistoryButtonClicked(_ sender: UIButton) { guard let text = magiSearchHistoryButtons[sender.tag].textLabel.text else { return } delegate?.magiSearchHistoryButtonClicked(text) } @objc func clearHistoryButtonClicked() { magiSearch.setSearchHistories(value: [String]()) redrawSearchHistoryButtons() } @objc func closeButtonClicked(_ sender: UIButton) { magiSearch.deleteSearchHistories(index: sender.tag) redrawSearchHistoryButtons() } func initView(_ categories: [String]) { categoryLabel = UILabel(frame: CGRect(x: margin, y: 0, width: width - 40, height: 50)) categoryLabel.text = "热门" categoryLabel.font = UIFont.systemFont(ofSize: 13) categoryLabel.textColor = UIColor.darkGray addSubview(categoryLabel) let font = UIFont.systemFont(ofSize: 12) let userAttributes = [NSAttributedStringKey.font : font, NSAttributedStringKey.foregroundColor: UIColor.gray] var formerWidth: CGFloat = margin var formerHeight: CGFloat = 50 for i in 0..<categories.count { let size = categories[i].size(withAttributes: userAttributes) if i > 0 { formerWidth = magiCategoryButtons[i-1].frame.size.width + magiCategoryButtons[i-1].frame.origin.x + 10 if formerWidth + size.width + margin > UIScreen.main.bounds.width { formerHeight += magiCategoryButtons[i-1].frame.size.height + 10 formerWidth = margin } } let button = MagiCategoryButton(frame: CGRect(x: formerWidth, y: formerHeight, width: size.width + 10, height: size.height + 10)) button.addTarget(self, action: #selector(magiCategoryButtonClicked(_:)), for: .touchUpInside) button.setTitle(categories[i], for: .normal) button.tag = i magiCategoryButtons.append(button) addSubview(button) } guard let originY = magiCategoryButtons.last?.frame.origin.y else { return } searchHistoryLabel = UILabel(frame: CGRect(x: margin, y: originY + 30, width: width - 40, height: 40)) searchHistoryLabel.text = "搜索历史" searchHistoryLabel.font = UIFont.systemFont(ofSize: 13) searchHistoryLabel.textColor = UIColor.darkGray addSubview(searchHistoryLabel) redrawSearchHistoryButtons() } func redrawSearchHistoryButtons() { for magiSearchHistoryView in magiSearchHistoryViews { magiSearchHistoryView.removeFromSuperview() } magiSearchHistoryViews.removeAll() magiSearchHistoryButtons.removeAll() if self.clearHistoryButton != nil { self.clearHistoryButton.removeFromSuperview() } let histories = magiSearch.getSearchHistories() ?? [String]() let searchHistoryLabelOriginY: CGFloat = searchHistoryLabel.frame.origin.y + searchHistoryLabel.frame.height for i in 0..<histories.count { let view = MagiSearchHistoryView(frame: CGRect(x: margin, y: searchHistoryLabelOriginY + CGFloat(i * 40), width: width - (margin * 2), height: 40)) view.magiSearchHistoryButton.addTarget(self, action: #selector(magiSearchHistoryButtonClicked(_:)), for: .touchUpInside) view.closeButton.addTarget(self, action: #selector(closeButtonClicked(_:)), for: .touchUpInside) view.magiSearchHistoryButton.textLabel.text = histories[i] view.magiSearchHistoryButton.tag = i view.closeButton.tag = i magiSearchHistoryViews.append(view) magiSearchHistoryButtons.append(view.magiSearchHistoryButton) addSubview(view) } var clearHistoryButtonY: CGFloat = 0.0 if let y = magiSearchHistoryViews.last?.frame.maxY { clearHistoryButtonY = y + margin } else { clearHistoryButtonY = searchHistoryLabel.frame.maxY + margin } clearHistoryButton = UIButton(frame: CGRect(x: margin, y: clearHistoryButtonY, width: width - (margin * 2), height: 40)) clearHistoryButton.setTitle("清空搜索历史", for: .normal) clearHistoryButton.titleLabel?.font = UIFont.systemFont(ofSize: 13) clearHistoryButton.setTitleColor(UIColor.darkGray, for: .normal) clearHistoryButton.setTitleColor(UIColor.lightGray, for: .highlighted) clearHistoryButton.addTarget(self, action: #selector(clearHistoryButtonClicked), for: .touchUpInside) addSubview(clearHistoryButton) if histories.count == 0 { clearHistoryButton.isHidden = true searchHistoryLabel.isHidden = true } else { clearHistoryButton.isHidden = false searchHistoryLabel.isHidden = false } delegate?.magiSearchMainViewSearchHistoryChanged() } }
39.138298
141
0.577603
bbc5f28da60614978e51d032ee934f0572b38dd7
330
// 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 class B { func a: (A, y: T> V, let f = b: C { b("","](m([1) func a<l : B.a: d { } protocol A { let v: (n: a<T>() }
22
87
0.639394
e4bf29c27422aa64d68eae9d6fef2cce37816169
1,262
// // FrameConnack.swift // CocoaMQTT // // Created by JianBo on 2019/8/7. // Copyright © 2019 emqx.io. All rights reserved. // import Foundation struct FrameConnAck: Frame { var fixedHeader: UInt8 = FrameType.connack.rawValue // --- Attributes var returnCode: CocoaMQTTConnAck var sessPresent: Bool = false // --- Attributes End init(code: CocoaMQTTConnAck) { returnCode = code } } extension FrameConnAck { func variableHeader() -> [UInt8] { return [sessPresent.bit, returnCode.rawValue] } func payload() -> [UInt8] { return [] } } extension FrameConnAck: InitialWithBytes { init?(fixedHeader: UInt8, bytes: [UInt8]) { guard fixedHeader == FrameType.connack.rawValue else { return nil } guard bytes.count == 2 else { return nil } sessPresent = Bool(bit: bytes[0] & 0x01) guard let ack = CocoaMQTTConnAck(rawValue: bytes[1]) else { return nil } returnCode = ack } } extension FrameConnAck: CustomStringConvertible { var description: String { return "CONNACK(code: \(returnCode), sp: \(sessPresent))" } }
20.031746
67
0.580032
188c543ea09426219f396975c2817f5ac712e2db
213
// 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 < { case [ { protocol c { class case ,
17.75
87
0.737089
1d58a5afff0643dd8213a0d5b6032dc5d964097c
1,698
// // ProfileViewController.swift // twitter_alamofire_demo // // Created by student on 10/13/18. // Copyright © 2018 Charles Hieger. All rights reserved. // import UIKit import AlamofireImage class ProfileViewController: UIViewController { @IBOutlet var banner: UIImageView! @IBOutlet var profilePic: UIImageView! @IBOutlet var username: UILabel! @IBOutlet var screename: UILabel! @IBOutlet var descriptionLabel: UILabel! @IBOutlet var tweetCount: UILabel! @IBOutlet var followingCount: UILabel! @IBOutlet var followerCount: UILabel! override func viewDidLoad() { super.viewDidLoad() banner.af_setImage(withURL: (User.current?.profileBannerUrl)!) profilePic.af_setImage(withURL: (User.current?.profilePictureUrl)!) username.text = User.current?.name screename.text = User.current?.screenName descriptionLabel.text = User.current?.description tweetCount.text = String(User.current?.tweetCount as! Int) followingCount.text = String(User.current?.followingCount as! Int) followerCount.text = String(User.current?.followerCount as! Int) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
32.037736
106
0.694935
dea3a71535c5b945c87d75ac3b25bea4cd4e11b9
171
// // Time+CoreDataClass.swift // // // Created by Ian Cooper on 9/2/21. // // import Foundation import CoreData @objc(Time) public class Time: NSManagedObject { }
10.6875
36
0.666667
5b23c844a188fdcd84edf0b1fa11947a28a63de0
333
// RUN: %target-swift-emit-ir %s -I %S/Inputs -enable-experimental-cxx-interop | %FileCheck %s import Extensions extension Outer.Space.Foo { func foo() {} } Outer.Space.Foo().foo() // CHECK: call swiftcc void @"$sSo5OuterO5SpaceO3FooV4mainE3fooyyF" // CHECK: define hidden swiftcc void @"$sSo5OuterO5SpaceO3FooV4mainE3fooyyF"
23.785714
94
0.738739
e533ddbc90180bf1ab7082654a25770fe5067d05
1,321
// // MDSortOrderOption.swift // // The MIT License // Copyright (c) 2021 - 2022 O2ter Limited. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // public enum MDSortOrderOption: CaseIterable, Sendable { case ascending case descending }
41.28125
81
0.743376
26f15019b9a6af622a794a8714ea4061d4816475
1,783
// // MKPolygon+Union.swift // // Created by Adrian Schoenig on 18/2/17. // // import MapKit extension Polygon { static func union(_ polygons: [Polygon]) throws -> [Polygon] { let sorted = polygons.sorted { first, second in if first.minY < second.minY { return true } else if second.minY < first.minY { return false } else { return first.minX < second.minX } } return try sorted.reduce([]) { polygons, polygon in try union(polygons, with: polygon) } } static func union(_ polygons: [Polygon], with polygon: Polygon) throws -> [Polygon] { var grower = polygon.clockwise() var newArray: [Polygon] = [] for existing in polygons { if existing.contains(grower) { grower = existing continue } let clockwise = existing.clockwise() let intersections = grower.intersections(clockwise) if intersections.count > 0 { let merged = try grower.union(clockwise, with: intersections) if !merged { newArray.append(clockwise) } } else { newArray.append(clockwise) } } newArray.append(grower) return newArray } } extension MKPolygon { class func union(_ polygons: [MKPolygon], completion: @escaping (Result<[MKPolygon], Error>) -> Void) { let queue = DispatchQueue(label: "MKPolygonUnionMerger", qos: .background) queue.async { let result = Result { try union(polygons) } DispatchQueue.main.async { completion(result) } } } class func union(_ mkPolygons: [MKPolygon]) throws -> [MKPolygon] { let polygons = mkPolygons.map(Polygon.init) let union = try Polygon.union(polygons) return union.map(\.polygon) } }
24.424658
105
0.61189
dd0f088dd9b997e2a753740c9d0733aa167d335f
103
import XCTest @testable import MemoryGraphTests XCTMain([ testCase(MemoryGraphTests.allTests), ])
14.714286
40
0.786408
edd0e65f8049e637229d2462e4c9299fb8a8fd1c
226
// // DemoView.swift // UIViewFormXIB(POP) // // Created by Allison on 2017/4/27. // Copyright © 2017年 Allison. All rights reserved. // import UIKit class DemoView: UIView ,NibLoadable{ var name : String? }
12.555556
51
0.646018
9b188ba18d58186f22a3427cfe75f1d85845df1d
5,271
// Generated by msgbuilder 2020-05-15 06:20:49 +0000 import RosTime import StdMsgs extension visualization_msgs { /// See http://www.ros.org/wiki/rviz/DisplayTypes/Marker and http://www.ros.org/wiki/rviz/Tutorials/Markers%3A%20Basic%20Shapes for more information on using this message with rviz ///Only used if the type specified has some use for them (eg. POINTS, LINE_STRIP, ...) ///Only used if the type specified has some use for them (eg. POINTS, LINE_STRIP, ...) ///number of colors must either be 0 or equal to the number of points ///NOTE: alpha is not yet used /// NOTE: only used for text markers /// NOTE: only used for MESH_RESOURCE markers public struct Marker: MessageWithHeader { public static let md5sum: String = "fc60f67ee1b0328d53f32573aafeb4d9" public static let datatype = "visualization_msgs/Marker" public static let definition = """ # See http://www.ros.org/wiki/rviz/DisplayTypes/Marker and http://www.ros.org/wiki/rviz/Tutorials/Markers%3A%20Basic%20Shapes for more information on using this message with rviz uint8 ARROW=0 uint8 CUBE=1 uint8 SPHERE=2 uint8 CYLINDER=3 uint8 LINE_STRIP=4 uint8 LINE_LIST=5 uint8 CUBE_LIST=6 uint8 SPHERE_LIST=7 uint8 POINTS=8 uint8 TEXT_VIEW_FACING=9 uint8 MESH_RESOURCE=10 uint8 TRIANGLE_LIST=11 uint8 ADD=0 uint8 MODIFY=0 uint8 DELETE=2 uint8 DELETEALL=3 Header header # header for time/frame information string ns # Namespace to place this object in... used in conjunction with id to create a unique name for the object int32 id # object ID useful in conjunction with the namespace for manipulating and deleting the object later int32 type # Type of object int32 action # 0 add/modify an object, 1 (deprecated), 2 deletes an object, 3 deletes all objects geometry_msgs/Pose pose # Pose of the object geometry_msgs/Vector3 scale # Scale of the object 1,1,1 means default (usually 1 meter square) std_msgs/ColorRGBA color # Color [0.0-1.0] duration lifetime # How long the object should last before being automatically deleted. 0 means forever bool frame_locked # If this marker should be frame-locked, i.e. retransformed into its frame every timestep #Only used if the type specified has some use for them (eg. POINTS, LINE_STRIP, ...) geometry_msgs/Point[] points #Only used if the type specified has some use for them (eg. POINTS, LINE_STRIP, ...) #number of colors must either be 0 or equal to the number of points #NOTE: alpha is not yet used std_msgs/ColorRGBA[] colors # NOTE: only used for text markers string text # NOTE: only used for MESH_RESOURCE markers string mesh_resource bool mesh_use_embedded_materials """ public static let ARROW: UInt8 = 0 public static let CUBE: UInt8 = 1 public static let SPHERE: UInt8 = 2 public static let CYLINDER: UInt8 = 3 public static let LINE_STRIP: UInt8 = 4 public static let LINE_LIST: UInt8 = 5 public static let CUBE_LIST: UInt8 = 6 public static let SPHERE_LIST: UInt8 = 7 public static let POINTS: UInt8 = 8 public static let TEXT_VIEW_FACING: UInt8 = 9 public static let MESH_RESOURCE: UInt8 = 10 public static let TRIANGLE_LIST: UInt8 = 11 public static let ADD: UInt8 = 0 public static let MODIFY: UInt8 = 0 public static let DELETE: UInt8 = 2 public static let DELETEALL: UInt8 = 3 public var header: std_msgs.Header public var ns: String public var id: Int32 public var type: Int32 public var action: Int32 public var pose: geometry_msgs.Pose public var scale: geometry_msgs.Vector3 public var color: std_msgs.ColorRGBA public var lifetime: Duration public var frame_locked: Bool public var points: [geometry_msgs.Point] public var colors: [std_msgs.ColorRGBA] public var text: String public var mesh_resource: String public var mesh_use_embedded_materials: Bool public init(header: std_msgs.Header, ns: String, id: Int32, type: Int32, action: Int32, pose: geometry_msgs.Pose, scale: geometry_msgs.Vector3, color: std_msgs.ColorRGBA, lifetime: Duration, frame_locked: Bool, points: [geometry_msgs.Point], colors: [std_msgs.ColorRGBA], text: String, mesh_resource: String, mesh_use_embedded_materials: Bool) { self.header = header self.ns = ns self.id = id self.type = type self.action = action self.pose = pose self.scale = scale self.color = color self.lifetime = lifetime self.frame_locked = frame_locked self.points = points self.colors = colors self.text = text self.mesh_resource = mesh_resource self.mesh_use_embedded_materials = mesh_use_embedded_materials } public init() { header = std_msgs.Header() ns = String() id = Int32() type = Int32() action = Int32() pose = geometry_msgs.Pose() scale = geometry_msgs.Vector3() color = std_msgs.ColorRGBA() lifetime = Duration() frame_locked = Bool() points = [geometry_msgs.Point]() colors = [std_msgs.ColorRGBA]() text = String() mesh_resource = String() mesh_use_embedded_materials = Bool() } } }
41.833333
347
0.705938
8740829317aa36183ee80a36f055f187663b5ab4
465
// // UrlDefine.swift // Take_Phonto // // Created by luozhuang on 2018/1/7. // Copyright © 2018年 lkb. All rights reserved. // import UIKit let BaseUrl = "http://www.likangbin.com/" //注册 let regApi = "reg.php" //登录 let loginApi = "login.php" //上传图片 let uploadApi = "other_uploadImg.php" //发帖 let sendPostApi = "SendPost.php" //帖子列表 let postList = "postList.php" class UrlDefine: NSObject { }
9.6875
47
0.584946
0965507ac4aa1ff5994973848845f6148284c572
10,658
// // User.swift // ApiCore // // Created by Ondrej Rafaj on 11/12/2017. // import Foundation import Vapor import Fluent import FluentPostgreSQL //import DbCore /// Users array type typealias public typealias Users = [User] /// User object public final class User: DbCoreModel { /// Registration object public struct Registration: Content { /// Template object public struct Template: Content { /// Verification public var verification: String /// Server link public var link: String /// User registration public var user: Registration } /// Username public var username: String /// First name public var firstname: String /// Last name public var lastname: String /// Email public var email: String /// Password public var password: String /// Convert to user public func newUser(on req: Request) throws -> User { let user = try User(username: username, firstname: firstname, lastname: lastname, email: email, password: password.passwordHash(req), disabled: false, su: false) return user } } /// Auth public struct Auth { /// Login object public struct Login: Content { /// Email public let email: String /// Password public let password: String /// Initializer (optional) public init?(email: String, password: String) throws { guard email.count > 3 else { throw AuthError.invalidEmail } guard try password.validatePassword() else { throw AuthError.invalidPassword(reason: .generic) } self.email = email self.password = password } } /// Change password public struct Password: Content { /// Password public let password: String /// Initializer (optional) public init?(password: String) throws { guard try password.validatePassword() else { throw AuthError.invalidPassword(reason: .generic) } self.password = password } } /// Token object public struct Token: Content { /// Token public let token: String } /// URL object public struct URI: Content { /// Target URI to tell client where to redirect public let targetUri: String? } /// Email confirmation object public struct EmailConfirmation: Content { /// Email public let email: String /// Target URI to tell client where to redirect public let targetUri: String? enum CodingKeys: String, CodingKey { case email case targetUri = "target" } } /// Recovery email template object public struct RecoveryTemplate: Content { /// Verification hash (JWT token) public let verification: String /// Recovery validation endpoint link public let link: String? /// User public var user: User /// Finish recovery link public var finish: String /// System wide template data public var system: FrontendSystemData /// Initializer /// /// - Parameters: /// - verification: Verification token /// - link: Full verification link /// - user: User model /// - req: Request /// - Throws: whatever comes it's way public init(verification: String, link: String? = nil, user: User, on req: Request) throws { self.verification = verification self.link = link self.user = user finish = req.serverURL().absoluteString.finished(with: "/") + "auth/finish-recovery?token=" + verification system = try FrontendSystemData(req) } } } /// User displayable object public final class Display: DbCoreModel { /// Object Id public var id: DbIdentifier? // Username / nickname public var username: String /// First name public var firstname: String /// Last name public var lastname: String /// Email public var email: String /// Date registered public var registered: Date /// User disabled public var disabled: Bool /// Super user public var su: Bool /// Initializer public init(username: String, firstname: String, lastname: String, email: String, disabled: Bool = true, su: Bool = false) { self.username = username self.firstname = firstname self.lastname = lastname self.email = email self.registered = Date() self.disabled = disabled self.su = su } /// Initializer public init(_ user: User) { self.id = user.id self.username = user.username self.firstname = user.firstname self.lastname = user.lastname self.email = user.email self.registered = user.registered self.disabled = user.disabled self.su = user.su } } /// Public displayable object /// Should be displayed when accessing users you shouldn't see otherwise (so keep it private!) public final class AllSearch: Content { /// Object Id public var id: DbIdentifier? // Username / nickname public var username: String /// First name public var firstname: String /// Last name public var lastname: String /// Avatar image (gravatar) public var avatar: String /// Date registered public var registered: Date /// User disabled public var disabled: Bool /// Super user public var su: Bool /// Initializer required public init(user: User) { id = user.id username = user.username firstname = String(user.firstname.first ?? "?") + "....." lastname = user.lastname registered = user.registered disabled = user.disabled su = user.su let email = user.email avatar = email.imageUrlHashFromMail } } /// Id object public struct Id: Content { /// Id public var id: DbIdentifier? /// Initializer public init(id: DbIdentifier) { self.id = id } } /// Disable object public struct Disable: Content { /// Id public var id: DbIdentifier /// Acccount should be disabled / enable public var disable: Bool /// Initializer public init(id: DbIdentifier, disable: Bool) { self.id = id self.disable = disable } } /// Object Id public var id: DbIdentifier? // Username / nickname public var username: String /// First name public var firstname: String /// Last name public var lastname: String /// Email public var email: String /// Password public var password: String? /// Date registered public var registered: Date /// User disabled public var disabled: Bool /// User verified public var verified: Bool /// Super user public var su: Bool /// Initializer public init(username: String, firstname: String, lastname: String, email: String, password: String? = nil, token: String? = nil, disabled: Bool = true, su: Bool = false) { self.username = username self.firstname = firstname self.lastname = lastname self.email = email self.password = password self.registered = Date() self.disabled = disabled self.verified = false self.su = su } } // MARK: - Relationships extension User { /// Teams relation public var teams: Siblings<User, Team, TeamUser> { return siblings() } } // MARK: - Migrations extension User: Migration { /// Migration preparations public static func prepare(on connection: ApiCoreConnection) -> Future<Void> { return Database.create(self, on: connection) { (schema) in schema.field(for: \.id, isIdentifier: true) schema.field(for: \.username, type: .varchar(80), .notNull) schema.field(for: \.firstname, type: .varchar(80), .notNull) schema.field(for: \.lastname, type: .varchar(140), .notNull) schema.field(for: \.email, type: .varchar(141), .notNull) schema.field(for: \.password, type: .varchar(64)) schema.field(for: \.registered, type: .timestamp, .notNull) schema.field(for: \.verified, type: .bool, .notNull) schema.field(for: \.disabled, type: .bool, .notNull) schema.field(for: \.su, type: .bool, .notNull) } } /// Migration reverse public static func revert(on connection: ApiCoreConnection) -> Future<Void> { return Database.delete(User.self, on: connection) } } extension User { /// Convert to displayable object public func asDisplay() -> User.Display { return User.Display(self) } } extension User.Auth.Password { public func validate() throws -> Bool { return try password.validatePassword() } }
26.711779
175
0.510602
21e69e575a6b056ce47ae6f64ec4329042660866
1,618
import NetTime import XCTest final class LocalTimeTests: XCTestCase { func testInitValidation() { XCTAssertNotNil(LocalTime(hour: 23, minute: 59, second: 59)) XCTAssertNotNil(LocalTime(hour: 0, minute: 0, second: 60)) XCTAssertNotNil(LocalTime(hour: 0, minute: 0, second: 0)) XCTAssertNotNil(LocalTime(hour: 0, minute: 0, second: 0, secondFraction: [0, 9, 0, 9])) } func testInitInvalidation() { XCTAssertNil(LocalTime(hour: -1, minute: 59, second: 59)) XCTAssertNil(LocalTime(hour: 24, minute: 59, second: 59)) XCTAssertNil(LocalTime(hour: 23, minute: -1, second: 59)) XCTAssertNil(LocalTime(hour: 23, minute: 60, second: 59)) XCTAssertNil(LocalTime(hour: 23, minute: 59, second: -1)) XCTAssertNil(LocalTime(hour: 23, minute: 59, second: 61)) XCTAssertNil(LocalTime(hour: 0, minute: 0, second: 0, secondFraction: [10, 0])) } func testSerialization() { XCTAssertEqual( LocalTime(hour: 23, minute: 59, second: 59)?.description, "23:59:59" ) XCTAssertEqual( LocalTime(hour: 23, minute: 59, second: 59, secondFraction: [0, 9, 0, 9])?.description, "23:59:59.0909" ) } func testDeserialization() { XCTAssertEqual( LocalTime(rfc3339String: "23:59:59"), LocalTime(hour: 23, minute: 59, second: 59) ) XCTAssertEqual( LocalTime(rfc3339String: "23:59:59.0909"), LocalTime(hour: 23, minute: 59, second: 59, secondFraction: [0, 9, 0, 9]) ) } }
35.173913
99
0.598888
ac878e8de315bd7c899f9be5c32fe3d5fb1a572b
1,954
// // SplitViewController.swift // Example // // Created by phimage on 21/08/16. // Copyright © 2016 phimage. All rights reserved. // import Cocoa import CustomSegue class SplitViewController: NSViewController { @IBOutlet weak var checkbox: NSButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func prepare(for segue: NSStoryboardSegue, sender: Any?) { if let segue = segue as? SplitViewSegue { segue.replace = checkbox.state == .on if let d = segue.destinationController as? DestinationSplitViewController { d.segue = segue } } } } class DestinationSplitViewController: NSViewController { @IBOutlet weak var tableView: NSTableView! var segue: SplitViewSegue? @IBAction func dismissSegue(_ sender: AnyObject?) { segue?.unperform() } override func prepare(for segue: NSStoryboardSegue, sender: Any?) { if let segue = segue as? TablePopoverSegue , segue.identifier == "rowdetail" { segue.popoverBehavior = .transient segue.tableView = tableView // TIPS get selected object and pass info to the destination controller let selectedRow = tableView.selectedRow if (selectedRow >= 0) { } } } } extension DestinationSplitViewController: NSTableViewDataSource, NSTableViewDelegate { func numberOfRows(in tableView: NSTableView) -> Int { return 2 } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { return "\(row)" } func tableViewSelectionDidChange(_ notification: Notification) { self.performSegue(withIdentifier: "rowdetail", sender: notification.object) } }
26.053333
108
0.625384
d9688b4c061ad02b663816194980bd8f2f8b064c
1,230
// // UIColor+.swift // HeartManager // // Created by 中西康之 on 2019/05/15. // Copyright © 2019 中西康之. All rights reserved. // import UIKit extension UIColor { class func myLightBlue() -> UIColor { // #9DDCDC let color = UIColor.init(red: 157/255, green: 220/255, blue: 220/255, alpha: 1) return color } class func myDarkBlue() -> UIColor { // #7EC2C2 let color = UIColor.init(red: 126/255, green: 194/255, blue: 194/255, alpha: 1) return color } class func myLightYellow() -> UIColor { // #FFF4E1 let color = UIColor.init(red: 255/255, green: 244/255, blue: 225/255, alpha: 1) return color } class func myLightRed() -> UIColor { let color = UIColor.init(red: 240/255, green: 150/255, blue: 122/255, alpha: 0.3) return color } class func myDarkGray() -> UIColor { // #E67A7A let color = UIColor.init(red: 69/255, green: 69/255, blue: 69/255, alpha: 1) return color } class func mercury() -> UIColor { // EBEBEB let color = UIColor.init(red: 235/255, green: 235/255, blue: 235/255, alpha: 1) return color } }
25.102041
89
0.560163
876469297ca8c89912e60cf4e835e1bfea0de15d
792
#if !os(Linux) import CoreLocation #endif import Foundation // Ported from https://github.com/Turfjs/turf/tree/master/packages/turf-length extension LineSegment { /// Returns the length of the *LineSegment*, in meters. public var length: CLLocationDistance { first.distance(from: second) } } extension GeoJson { /// Returns the receiver's length, in meters. /// /// For *Point*, *MultiPoint*: returns 0 /// /// For *LineString*, *MultiLineString*: returns the length of the line(s) /// /// For *Polygon*, *MultiPolygon*: returns the length of all rings /// /// Everything else: returns the length of the contained geometries public var length: CLLocationDistance { lineSegments.reduce(0.0) { $0 + $1.length } } }
24
78
0.65404
ccfc9f8e81744373c4928d2cf9c0f8042bde61cf
637
// // DateExtension.swift // BLE_shared // // Created by Martin Troup on 24/05/2017. // Copyright © 2017 David Nemec. All rights reserved. // import Foundation extension Date { /// Method to convert Date instance to String with custom date time format. /// /// - Parameter format: format of Date /// - Returns: String instance public func asString(withFormat format: String = "yyyy-MM-dd hh:mm:ss:sss") -> String { let formatter = DateFormatter() formatter.dateFormat = format //formatter.locale = Locale(identifier: "en_US") return formatter.string(from: self) } }
26.541667
91
0.646782
2fc86a5a58c22564c2ae8ab932c161460adeaf49
3,333
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -Xfrontend -enable-experimental-distributed -parse-as-library) | %FileCheck %s --dump-input=always // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: distributed // rdar://76038845 // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime // FIXME(distributed): Distributed actors currently have some issues on windows, isRemote always returns false. rdar://82593574 // UNSUPPORTED: windows import _Distributed distributed actor Capybara { // only the local capybara can do this! func eat() -> String { "watermelon" } } // ==== Fake Transport --------------------------------------------------------- struct ActorAddress: Sendable, Hashable, Codable { let address: String init(parse address: String) { self.address = address } } struct FakeActorSystem: DistributedActorSystem { typealias ActorID = ActorAddress typealias Invocation = FakeInvocation typealias SerializationRequirement = Codable func resolve<Act>(id: ActorID, as actorType: Act.Type) throws -> Act? where Act: DistributedActor { return nil } func assignID<Act>(_ actorType: Act.Type) -> ActorID where Act: DistributedActor { let id = ActorAddress(parse: "xxx") return id } func actorReady<Act>(_ actor: Act) where Act: DistributedActor, Act.ID == ActorID { } func resignID(_ id: ActorID) { } func makeInvocation() -> Invocation { .init() } } struct FakeInvocation: DistributedTargetInvocation { typealias ArgumentDecoder = FakeArgumentDecoder typealias SerializationRequirement = Codable mutating func recordGenericSubstitution<T>(mangledType: T.Type) throws {} mutating func recordArgument<Argument: SerializationRequirement>(argument: Argument) throws {} mutating func recordReturnType<R: SerializationRequirement>(mangledType: R.Type) throws {} mutating func recordErrorType<E: Error>(mangledType: E.Type) throws {} mutating func doneRecording() throws {} // === Receiving / decoding ------------------------------------------------- mutating func decodeGenericSubstitutions() throws -> [Any.Type] { [] } mutating func argumentDecoder() -> FakeArgumentDecoder { .init() } mutating func decodeReturnType() throws -> Any.Type? { nil } mutating func decodeErrorType() throws -> Any.Type? { nil } struct FakeArgumentDecoder: DistributedTargetInvocationArgumentDecoder { typealias SerializationRequirement = Codable } } @available(SwiftStdlib 5.5, *) typealias DefaultDistributedActorSystem = FakeActorSystem func test() async throws { let system = FakeActorSystem() let local = Capybara(system: system) // await local.eat() // SHOULD ERROR let valueWhenLocal: String? = await local.whenLocal { __secretlyKnownToBeLocal in __secretlyKnownToBeLocal.eat() } // CHECK: valueWhenLocal: watermelon print("valueWhenLocal: \(valueWhenLocal ?? "nil")") let remote = try Capybara.resolve(id: local.id, using: system) let valueWhenRemote: String? = await remote.whenLocal { __secretlyKnownToBeLocal in __secretlyKnownToBeLocal.eat() } // CHECK: valueWhenRemote: nil print("valueWhenRemote: \(valueWhenRemote ?? "nil")") } @main struct Main { static func main() async { try! await test() } }
29.758929
174
0.706271
1181a4f3d9078d66c77ab5842e5a834fb0912286
2,672
// // WLDataManager.swift // zhihu_swift // // Created by tarena45 on 16/1/25. // Copyright © 2016年 tarena. All rights reserved. // import Foundation import Alamofire import SwiftyJSON /** void test() { int b = 0 static int a = 0 //全局区,程序开始时就创建,只是a只能在方法中访问, } */ //只读计算属性 var dataManager : DataManager { get { struct Singleton { static var predicate : dispatch_once_t = 0 static var instance : DataManager? = nil } dispatch_once(&Singleton.predicate, { () -> Void in Singleton.instance = DataManager() }) return Singleton.instance! } } class DataManager { // class func getInstance() -> DataManager { // struct Singleton { // static var predicate : dispatch_once_t = 0 // static var instance : DataManager? = nil // } // dispatch_once(&Singleton.predicate, { () -> Void in // Singleton.instance = DataManager() // }) // return Singleton.instance! // } /**侧滑界面列表*/ var themes : [ThemeModel] = [] /** 顶部新闻*/ var topStory : [TopStoryModel] = [] /** 当日新闻*/ var contentStory : [ContentStoryModel] = [] /** 旧新闻*/ var pastContentStory : [PastContentStoryItem] = [] var offsetYValue : [(CGFloat,String)] = [] /** 临时数据,修改使用*/ /**侧滑界面列表*/ var tempThemes : [ThemeModel] = [] /** 顶部新闻*/ var tempTopStory : [TopStoryModel] = [] /** 当日新闻*/ var tempContentStory : [ContentStoryModel] = [] /** 旧新闻*/ var tempPastContentStory : [PastContentStoryItem] = [] //MARK:取得主题日报数据 func getThemesDatas(completion : (themes : [ThemeModel])->()) { Alamofire.request(.GET, requestThemes).responseJSON(completionHandler: { [unowned self] (response) -> Void in guard response.result.error == nil else { print("主题日报数据获取失败") return } // let data = JSON(response.result.value!) // NSLog("------- \(data)") // for i in 0..<data.count { // self.themes.append(ThemeModel(id: String(data[i]["id"]), name: String(data[i]["name"]))) // } let data = JSON(response.result.value!)["others"] NSLog("------- \(data)") for i in 0..<data.count { self.themes.append(ThemeModel(id: String(data[i]["id"]) , name: String(data[i]["name"]))) } completion(themes: self.themes) }) } func loadImage(name : String, completion : (image : UIImage) -> ()) { let image = UIImage(named: name) completion(image: image!) } }
29.043478
117
0.546033
5bf1b557fc29d300452ad3fcd908edc9da17a673
4,149
// // PresetsCategoriesViewController.swift // AudioKitSynthOne // // Created by AudioKit Contributors on 9/2/17. // Copyright © 2018 AudioKit. All rights reserved. // import UIKit // MARK: - Preset Category Enum enum PresetCategory: Int { case all case arp case poly case pad case lead case bass case pluck static let categoryCount = 6 static let bankStartingIndex = categoryCount + 2 func description() -> String { switch self { case .all: return "All" case .arp: return "Arp/Seq" case .poly: return "Poly" case .pad: return "Pad" case .lead: return "Lead" case .bass: return "Bass" case .pluck: return "Pluck" } } } protocol CategoryDelegate: AnyObject { func categoryDidChange(_ newCategoryIndex: Int) func bankShare() func bankEdit() } // MARK: - PresetsCategoriesController class PresetsCategoriesViewController: UIViewController { @IBOutlet weak var categoryTableView: UITableView! weak var categoryDelegate: CategoryDelegate? var choices: [Int: String] = [:] { didSet { categoryTableView.reloadData() } } let conductor = Conductor.sharedInstance override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. categoryTableView.separatorColor = #colorLiteral(red: 0.3058823529, green: 0.3058823529, blue: 0.3254901961, alpha: 1) // Create table data source updateChoices() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) guard let presetsControler = parent as? PresetsViewController else { return } categoryDelegate = presetsControler } func updateChoices() { choices.removeAll() // first add PresetCategories to table for i in 0...PresetCategory.categoryCount { choices[i] = PresetCategory(rawValue: i)?.description() } // Add Favorites bank choices[PresetCategory.categoryCount + 1] = "Favorites" // Add Banks to Table for bank in conductor.banks { choices[PresetCategory.bankStartingIndex + bank.position] = "⌾ \(bank.name)" } } } // MARK: - TableViewDataSource extension PresetsCategoriesViewController: UITableViewDataSource { func numberOfSections(in categoryTableView: UITableView) -> Int { return 1 } @objc(tableView:heightForRowAtIndexPath:) func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if choices.isEmpty { return 1 } else { return choices.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Get current category guard let category = choices[(indexPath as NSIndexPath).row] else { return CategoryCell() } if let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell") as? CategoryCell { // Cell updated in CategoryCell.swift cell.delegate = self cell.configureCell(category: category) return cell } else { return CategoryCell() } } } // MARK: - TableViewDelegate extension PresetsCategoriesViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Update category categoryDelegate?.categoryDidChange((indexPath as NSIndexPath).row) } } // MARK: - Cell Delegate // Pass the button calls up to PresetsView Controller extension PresetsCategoriesViewController: CategoryCellDelegate { func bankShare() { categoryDelegate?.bankShare() } func bankEdit() { categoryDelegate?.bankEdit() } }
24.993976
126
0.627621
eb887d8e6dc49a2630f1a9baeb590b09d0e18636
409
// // Pino.swift // Agenda // // Created by Alura Roxo on 10/01/18. // Copyright © 2018 Alura. All rights reserved. // import UIKit import MapKit class Pino: NSObject, MKAnnotation { var title: String? var icon: UIImage? var color: UIColor? var coordinate: CLLocationCoordinate2D init(coordenada:CLLocationCoordinate2D) { self.coordinate = coordenada } }
16.36
48
0.650367
753d762ae8a31eb275b4cad64b5e60193d1ebbb2
2,035
// Created on 21/01/21. import UIKit public class VMCharacterDisplayInlineView: UIStackView, VMViewCode { public init() { super.init(frame: .zero) setupView() } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override var isLoading: Bool { get { itemsIsLoading } set { itemsIsLoading = newValue nameLabel.isLoading = newValue thumbnailChracterImageView.isLoading = newValue } } public var thumbnail: UIImage? { get { thumbnailChracterImageView.image } set { thumbnailChracterImageView.image = newValue } } public var name: String? { get { nameLabel.text } set { nameLabel.text = newValue } } private let thumbnailSize = CGSize(width: 100, height: 120) private var itemsIsLoading: Bool = false // MARK: Subviews private let thumbnailChracterImageView = VMCharacterImageView() private let nameLabel: UILabel = { let label = UILabel() label.font = VMFont.body(size: .md).font label.textColor = VMColor.neutral.color label.numberOfLines = 4 return label }() // MARK: View funcs open override func layoutSubviews() { super.layoutSubviews() layoutSkeletonIfNeeded() } // MARK: VMViewCode public func buildHierarchy() { addArrangedSubview(thumbnailChracterImageView) addArrangedSubview(nameLabel) } public func setupConstraints() { thumbnailChracterImageView.snp.makeConstraints { maker in maker.height.equalTo(thumbnailSize.height) maker.width.equalTo(thumbnailSize.width) } } public func configViews() { axis = .horizontal alignment = .center spacing = 4 layer.borderWidth = 1 layer.borderColor = VMColor.neutralLight.color?.cgColor layer.cornerRadius = 8 layer.masksToBounds = true } }
24.518072
68
0.625061
3ad9a947d0a717a0014e9b74e73727d88083556c
588
// // LinearScrollingTests.swift // LinearMouseUnitTests // // Created by lujjjh on 2021/11/24. // import XCTest @testable import LinearMouse class LinearScrollingTests: XCTestCase { func testLinearScrolling() throws { let transformer = LinearScrolling(scrollLines: 3) var event = CGEvent(scrollWheelEvent2Source: nil, units: .line, wheelCount: 2, wheel1: 42, wheel2: 42, wheel3: 0)! event = transformer.transform(event)! let view = ScrollWheelEventView(event) XCTAssertEqual(view.deltaX, 3) XCTAssertEqual(view.deltaY, 3) } }
28
122
0.693878
f5ab4ac1a997141359c79a925c8fd4909149e1fa
2,134
// // SceneDelegate.swift // HNScratchSwift // // Created by Hiago Chagas on 29/07/21. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = (scene as? UIWindowScene) else { return } window = UIWindow(frame: UIScreen.main.bounds) window?.windowScene = windowScene let mainVC = ViewController() window?.rootViewController = mainVC window?.makeKeyAndVisible() } 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. } }
38.8
140
0.7015
396effe1ac6346d6b6e0bb7324111a0b6f144b73
1,699
// // Switch.swift // ReactantUI // // Created by Matous Hybl. // Copyright © 2017 Brightify. All rights reserved. // import Foundation #if canImport(UIKit) import UIKit #endif public class Switch: View { public override class var availableProperties: [PropertyDescription] { return Properties.switch.allProperties } public class override func runtimeType() throws -> String { #if os(tvOS) throw TokenizationError.unsupportedElementError(element: Switch.self) #else return "UISwitch" #endif } #if canImport(UIKit) public override func initialize(context: ReactantLiveUIWorker.Context) throws -> UIView { #if os(tvOS) throw TokenizationError.unsupportedElementError(element: Switch.self) #else return UISwitch() #endif } #endif } public class SwitchProperties: ControlProperties { public let isOn: AssignablePropertyDescription<Bool> public let onTintColor: AssignablePropertyDescription<UIColorPropertyType> public let thumbTintColor: AssignablePropertyDescription<UIColorPropertyType> public let onImage: AssignablePropertyDescription<Image> public let offImage: AssignablePropertyDescription<Image> public required init(configuration: Configuration) { isOn = configuration.property(name: "isOn") onTintColor = configuration.property(name: "onTintColor") thumbTintColor = configuration.property(name: "thumbTintColor") onImage = configuration.property(name: "onImage") offImage = configuration.property(name: "offImage") super.init(configuration: configuration) } }
30.339286
93
0.701589
fc43d82036e95b49c2a61b4bc0c117ef4cdadf0f
31,177
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: param.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } struct Mavsdk_Rpc_Param_GetParamIntRequest { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// Name of the parameter var name: String = String() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct Mavsdk_Rpc_Param_GetParamIntResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var paramResult: Mavsdk_Rpc_Param_ParamResult { get {return _paramResult ?? Mavsdk_Rpc_Param_ParamResult()} set {_paramResult = newValue} } /// Returns true if `paramResult` has been explicitly set. var hasParamResult: Bool {return self._paramResult != nil} /// Clears the value of `paramResult`. Subsequent reads from it will return its default value. mutating func clearParamResult() {self._paramResult = nil} /// Value of the requested parameter var value: Int32 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _paramResult: Mavsdk_Rpc_Param_ParamResult? = nil } struct Mavsdk_Rpc_Param_SetParamIntRequest { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// Name of the parameter to set var name: String = String() /// Value the parameter should be set to var value: Int32 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct Mavsdk_Rpc_Param_SetParamIntResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var paramResult: Mavsdk_Rpc_Param_ParamResult { get {return _paramResult ?? Mavsdk_Rpc_Param_ParamResult()} set {_paramResult = newValue} } /// Returns true if `paramResult` has been explicitly set. var hasParamResult: Bool {return self._paramResult != nil} /// Clears the value of `paramResult`. Subsequent reads from it will return its default value. mutating func clearParamResult() {self._paramResult = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _paramResult: Mavsdk_Rpc_Param_ParamResult? = nil } struct Mavsdk_Rpc_Param_GetParamFloatRequest { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// Name of the parameter var name: String = String() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct Mavsdk_Rpc_Param_GetParamFloatResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var paramResult: Mavsdk_Rpc_Param_ParamResult { get {return _paramResult ?? Mavsdk_Rpc_Param_ParamResult()} set {_paramResult = newValue} } /// Returns true if `paramResult` has been explicitly set. var hasParamResult: Bool {return self._paramResult != nil} /// Clears the value of `paramResult`. Subsequent reads from it will return its default value. mutating func clearParamResult() {self._paramResult = nil} /// Value of the requested parameter var value: Float = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _paramResult: Mavsdk_Rpc_Param_ParamResult? = nil } struct Mavsdk_Rpc_Param_SetParamFloatRequest { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// Name of the parameter to set var name: String = String() /// Value the parameter should be set to var value: Float = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct Mavsdk_Rpc_Param_SetParamFloatResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var paramResult: Mavsdk_Rpc_Param_ParamResult { get {return _paramResult ?? Mavsdk_Rpc_Param_ParamResult()} set {_paramResult = newValue} } /// Returns true if `paramResult` has been explicitly set. var hasParamResult: Bool {return self._paramResult != nil} /// Clears the value of `paramResult`. Subsequent reads from it will return its default value. mutating func clearParamResult() {self._paramResult = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _paramResult: Mavsdk_Rpc_Param_ParamResult? = nil } struct Mavsdk_Rpc_Param_GetAllParamsRequest { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct Mavsdk_Rpc_Param_GetAllParamsResponse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// Collection of all parameters var params: Mavsdk_Rpc_Param_AllParams { get {return _params ?? Mavsdk_Rpc_Param_AllParams()} set {_params = newValue} } /// Returns true if `params` has been explicitly set. var hasParams: Bool {return self._params != nil} /// Clears the value of `params`. Subsequent reads from it will return its default value. mutating func clearParams() {self._params = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _params: Mavsdk_Rpc_Param_AllParams? = nil } /// /// Type for integer parameters. struct Mavsdk_Rpc_Param_IntParam { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// Name of the parameter var name: String = String() /// Value of the parameter var value: Int32 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// /// Type for float paramters. struct Mavsdk_Rpc_Param_FloatParam { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// Name of the parameter var name: String = String() /// Value of the parameter var value: Float = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// /// Type collecting all integer and float parameters. struct Mavsdk_Rpc_Param_AllParams { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// Collection of all parameter names and values of type int var intParams: [Mavsdk_Rpc_Param_IntParam] = [] /// Collection of all parameter names and values of type float var floatParams: [Mavsdk_Rpc_Param_FloatParam] = [] var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// Result type. struct Mavsdk_Rpc_Param_ParamResult { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// Result enum value var result: Mavsdk_Rpc_Param_ParamResult.Result = .unknown /// Human-readable English string describing the result var resultStr: String = String() var unknownFields = SwiftProtobuf.UnknownStorage() /// Possible results returned for param requests. enum Result: SwiftProtobuf.Enum { typealias RawValue = Int /// Unknown result case unknown // = 0 /// Request succeeded case success // = 1 /// Request timed out case timeout // = 2 /// Connection error case connectionError // = 3 /// Wrong type case wrongType // = 4 /// Parameter name too long (> 16) case paramNameTooLong // = 5 case UNRECOGNIZED(Int) init() { self = .unknown } init?(rawValue: Int) { switch rawValue { case 0: self = .unknown case 1: self = .success case 2: self = .timeout case 3: self = .connectionError case 4: self = .wrongType case 5: self = .paramNameTooLong default: self = .UNRECOGNIZED(rawValue) } } var rawValue: Int { switch self { case .unknown: return 0 case .success: return 1 case .timeout: return 2 case .connectionError: return 3 case .wrongType: return 4 case .paramNameTooLong: return 5 case .UNRECOGNIZED(let i): return i } } } init() {} } #if swift(>=4.2) extension Mavsdk_Rpc_Param_ParamResult.Result: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. static var allCases: [Mavsdk_Rpc_Param_ParamResult.Result] = [ .unknown, .success, .timeout, .connectionError, .wrongType, .paramNameTooLong, ] } #endif // swift(>=4.2) // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "mavsdk.rpc.param" extension Mavsdk_Rpc_Param_GetParamIntRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".GetParamIntRequest" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "name"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.name) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.name.isEmpty { try visitor.visitSingularStringField(value: self.name, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Mavsdk_Rpc_Param_GetParamIntRequest, rhs: Mavsdk_Rpc_Param_GetParamIntRequest) -> Bool { if lhs.name != rhs.name {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Mavsdk_Rpc_Param_GetParamIntResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".GetParamIntResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "param_result"), 2: .same(proto: "value"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._paramResult) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self.value) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._paramResult { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } if self.value != 0 { try visitor.visitSingularInt32Field(value: self.value, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Mavsdk_Rpc_Param_GetParamIntResponse, rhs: Mavsdk_Rpc_Param_GetParamIntResponse) -> Bool { if lhs._paramResult != rhs._paramResult {return false} if lhs.value != rhs.value {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Mavsdk_Rpc_Param_SetParamIntRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".SetParamIntRequest" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "name"), 2: .same(proto: "value"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.name) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self.value) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.name.isEmpty { try visitor.visitSingularStringField(value: self.name, fieldNumber: 1) } if self.value != 0 { try visitor.visitSingularInt32Field(value: self.value, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Mavsdk_Rpc_Param_SetParamIntRequest, rhs: Mavsdk_Rpc_Param_SetParamIntRequest) -> Bool { if lhs.name != rhs.name {return false} if lhs.value != rhs.value {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Mavsdk_Rpc_Param_SetParamIntResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".SetParamIntResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "param_result"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._paramResult) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._paramResult { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Mavsdk_Rpc_Param_SetParamIntResponse, rhs: Mavsdk_Rpc_Param_SetParamIntResponse) -> Bool { if lhs._paramResult != rhs._paramResult {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Mavsdk_Rpc_Param_GetParamFloatRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".GetParamFloatRequest" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "name"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.name) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.name.isEmpty { try visitor.visitSingularStringField(value: self.name, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Mavsdk_Rpc_Param_GetParamFloatRequest, rhs: Mavsdk_Rpc_Param_GetParamFloatRequest) -> Bool { if lhs.name != rhs.name {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Mavsdk_Rpc_Param_GetParamFloatResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".GetParamFloatResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "param_result"), 2: .same(proto: "value"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._paramResult) }() case 2: try { try decoder.decodeSingularFloatField(value: &self.value) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._paramResult { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } if self.value != 0 { try visitor.visitSingularFloatField(value: self.value, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Mavsdk_Rpc_Param_GetParamFloatResponse, rhs: Mavsdk_Rpc_Param_GetParamFloatResponse) -> Bool { if lhs._paramResult != rhs._paramResult {return false} if lhs.value != rhs.value {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Mavsdk_Rpc_Param_SetParamFloatRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".SetParamFloatRequest" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "name"), 2: .same(proto: "value"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.name) }() case 2: try { try decoder.decodeSingularFloatField(value: &self.value) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.name.isEmpty { try visitor.visitSingularStringField(value: self.name, fieldNumber: 1) } if self.value != 0 { try visitor.visitSingularFloatField(value: self.value, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Mavsdk_Rpc_Param_SetParamFloatRequest, rhs: Mavsdk_Rpc_Param_SetParamFloatRequest) -> Bool { if lhs.name != rhs.name {return false} if lhs.value != rhs.value {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Mavsdk_Rpc_Param_SetParamFloatResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".SetParamFloatResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "param_result"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._paramResult) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._paramResult { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Mavsdk_Rpc_Param_SetParamFloatResponse, rhs: Mavsdk_Rpc_Param_SetParamFloatResponse) -> Bool { if lhs._paramResult != rhs._paramResult {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Mavsdk_Rpc_Param_GetAllParamsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".GetAllParamsRequest" static let _protobuf_nameMap = SwiftProtobuf._NameMap() mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Mavsdk_Rpc_Param_GetAllParamsRequest, rhs: Mavsdk_Rpc_Param_GetAllParamsRequest) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Mavsdk_Rpc_Param_GetAllParamsResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".GetAllParamsResponse" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "params"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._params) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._params { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Mavsdk_Rpc_Param_GetAllParamsResponse, rhs: Mavsdk_Rpc_Param_GetAllParamsResponse) -> Bool { if lhs._params != rhs._params {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Mavsdk_Rpc_Param_IntParam: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".IntParam" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "name"), 2: .same(proto: "value"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.name) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self.value) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.name.isEmpty { try visitor.visitSingularStringField(value: self.name, fieldNumber: 1) } if self.value != 0 { try visitor.visitSingularInt32Field(value: self.value, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Mavsdk_Rpc_Param_IntParam, rhs: Mavsdk_Rpc_Param_IntParam) -> Bool { if lhs.name != rhs.name {return false} if lhs.value != rhs.value {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Mavsdk_Rpc_Param_FloatParam: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".FloatParam" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "name"), 2: .same(proto: "value"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.name) }() case 2: try { try decoder.decodeSingularFloatField(value: &self.value) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.name.isEmpty { try visitor.visitSingularStringField(value: self.name, fieldNumber: 1) } if self.value != 0 { try visitor.visitSingularFloatField(value: self.value, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Mavsdk_Rpc_Param_FloatParam, rhs: Mavsdk_Rpc_Param_FloatParam) -> Bool { if lhs.name != rhs.name {return false} if lhs.value != rhs.value {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Mavsdk_Rpc_Param_AllParams: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".AllParams" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "int_params"), 2: .standard(proto: "float_params"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedMessageField(value: &self.intParams) }() case 2: try { try decoder.decodeRepeatedMessageField(value: &self.floatParams) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.intParams.isEmpty { try visitor.visitRepeatedMessageField(value: self.intParams, fieldNumber: 1) } if !self.floatParams.isEmpty { try visitor.visitRepeatedMessageField(value: self.floatParams, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Mavsdk_Rpc_Param_AllParams, rhs: Mavsdk_Rpc_Param_AllParams) -> Bool { if lhs.intParams != rhs.intParams {return false} if lhs.floatParams != rhs.floatParams {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Mavsdk_Rpc_Param_ParamResult: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".ParamResult" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "result"), 2: .standard(proto: "result_str"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularEnumField(value: &self.result) }() case 2: try { try decoder.decodeSingularStringField(value: &self.resultStr) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.result != .unknown { try visitor.visitSingularEnumField(value: self.result, fieldNumber: 1) } if !self.resultStr.isEmpty { try visitor.visitSingularStringField(value: self.resultStr, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Mavsdk_Rpc_Param_ParamResult, rhs: Mavsdk_Rpc_Param_ParamResult) -> Bool { if lhs.result != rhs.result {return false} if lhs.resultStr != rhs.resultStr {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Mavsdk_Rpc_Param_ParamResult.Result: SwiftProtobuf._ProtoNameProviding { static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "RESULT_UNKNOWN"), 1: .same(proto: "RESULT_SUCCESS"), 2: .same(proto: "RESULT_TIMEOUT"), 3: .same(proto: "RESULT_CONNECTION_ERROR"), 4: .same(proto: "RESULT_WRONG_TYPE"), 5: .same(proto: "RESULT_PARAM_NAME_TOO_LONG"), ] }
37.115476
150
0.725984
6762b31469d3872e656b06c775d8e19d49c7c506
316
open class RoundRect: Locus { public let rect: Rect public let rx: Double public let ry: Double public init(rect: Rect, rx: Double = 0, ry: Double = 0) { self.rect = rect self.rx = rx self.ry = ry } override open func bounds() -> Rect { return rect } }
18.588235
61
0.550633
3888c7c57cdec054dbcea156091ee3c4ae84ddcf
6,412
/*Copyright (c) 2016, Andrew Walz. 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. 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 HOLDER 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 UIKit import AVFoundation class ViewController: SwiftyCamViewController, SwiftyCamViewControllerDelegate { @IBOutlet weak var captureButton : SwiftyRecordButton! @IBOutlet weak var flipCameraButton : UIButton! @IBOutlet weak var flashButton : UIButton! override func viewDidLoad() { super.viewDidLoad() shouldPrompToAppSettings = true cameraDelegate = self maximumVideoDuration = 10.0 shouldUseDeviceOrientation = true allowAutoRotate = true audioEnabled = true // disable capture button until session starts captureButton.buttonEnabled = false } override var prefersStatusBarHidden: Bool { return true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) captureButton.delegate = self } func swiftyCamSessionDidStartRunning(_ swiftyCam: SwiftyCamViewController) { print("Session did start running") captureButton.buttonEnabled = true } func swiftyCamSessionDidStopRunning(_ swiftyCam: SwiftyCamViewController) { print("Session did stop running") captureButton.buttonEnabled = false } func swiftyCam(_ swiftyCam: SwiftyCamViewController, didTake photo: UIImage) { let newVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PhotoViewController") as! PhotoViewController newVC.backgroundImage = photo self.present(newVC, animated: true, completion: nil) } func swiftyCam(_ swiftyCam: SwiftyCamViewController, didBeginRecordingVideo camera: SwiftyCamViewController.CameraSelection) { print("Did Begin Recording") captureButton.growButton() hideButtons() } func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFinishRecordingVideo camera: SwiftyCamViewController.CameraSelection) { print("Did finish Recording") captureButton.shrinkButton() showButtons() } func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFinishProcessVideoAt url: URL) { let newVC = VideoViewController(videoURL: url) self.present(newVC, animated: true, completion: nil) } func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFocusAtPoint point: CGPoint) { print("Did focus at point: \(point)") focusAnimationAt(point) } func swiftyCamDidFailToConfigure(_ swiftyCam: SwiftyCamViewController) { let message = NSLocalizedString("Unable to capture media", comment: "Alert message when something goes wrong during capture session configuration") let alertController = UIAlertController(title: "AVCam", message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Alert OK button"), style: .cancel, handler: nil)) present(alertController, animated: true, completion: nil) } func swiftyCam(_ swiftyCam: SwiftyCamViewController, didChangeZoomLevel zoom: CGFloat) { print("Zoom level did change. Level: \(zoom)") print(zoom) } func swiftyCam(_ swiftyCam: SwiftyCamViewController, didSwitchCameras camera: SwiftyCamViewController.CameraSelection) { print("Camera did change to \(camera.rawValue)") print(camera) } func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFailToRecordVideo error: Error) { print(error) } @IBAction func cameraSwitchTapped(_ sender: Any) { switchCamera() } @IBAction func toggleFlashTapped(_ sender: Any) { flashEnabled = !flashEnabled toggleFlashAnimation() } } // UI Animations extension ViewController { fileprivate func hideButtons() { UIView.animate(withDuration: 0.25) { self.flashButton.alpha = 0.0 self.flipCameraButton.alpha = 0.0 } } fileprivate func showButtons() { UIView.animate(withDuration: 0.25) { self.flashButton.alpha = 1.0 self.flipCameraButton.alpha = 1.0 } } fileprivate func focusAnimationAt(_ point: CGPoint) { let focusView = UIImageView(image: #imageLiteral(resourceName: "focus")) focusView.center = point focusView.alpha = 0.0 view.addSubview(focusView) UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: { focusView.alpha = 1.0 focusView.transform = CGAffineTransform(scaleX: 1.25, y: 1.25) }) { (success) in UIView.animate(withDuration: 0.15, delay: 0.5, options: .curveEaseInOut, animations: { focusView.alpha = 0.0 focusView.transform = CGAffineTransform(translationX: 0.6, y: 0.6) }) { (success) in focusView.removeFromSuperview() } } } fileprivate func toggleFlashAnimation() { if flashEnabled == true { flashButton.setImage(#imageLiteral(resourceName: "flash"), for: UIControlState()) } else { flashButton.setImage(#imageLiteral(resourceName: "flashOutline"), for: UIControlState()) } } }
39.097561
160
0.709763
26e91eeaff46961ba4cab8cca1cfcc6b67539a0f
1,019
// // exampleFrameworkTests.swift // exampleFrameworkTests // // Created by Sebastian Owodzin on 11/06/2017. // Copyright © 2017 Sebastian Owodzin. All rights reserved. // import XCTest @testable import exampleFramework class exampleFrameworkTests: 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. } } }
27.540541
111
0.649657
3ae0ef7586abc69fa0c30790e86c91645e4927d9
10,268
// // ImageProgressive.swift // Kingfisher // // Created by lixiang on 2019/5/10. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreGraphics private let sharedProcessingQueue: CallbackQueue = .dispatch(DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process")) public struct ImageProgressive { /// A default `ImageProgressive` could be used across. public static let `default` = ImageProgressive( isBlur: true, isFastestScan: true, scanInterval: 0 ) /// Whether to enable blur effect processing let isBlur: Bool /// Whether to enable the fastest scan let isFastestScan: Bool /// Minimum time interval for each scan let scanInterval: TimeInterval public init(isBlur: Bool, isFastestScan: Bool, scanInterval: TimeInterval) { self.isBlur = isBlur self.isFastestScan = isFastestScan self.scanInterval = scanInterval } } protocol ImageSettable: AnyObject { var image: Image? { get set } } final class ImageProgressiveProvider: DataReceivingSideEffect { var onShouldApply: () -> Bool = { return true } func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) { update(data: task.mutableData, with: task.callbacks) } private let option: ImageProgressive private let refresh: (Image) -> Void private let decoder: ImageProgressiveDecoder private let queue = ImageProgressiveSerialQueue(.main) init?(_ options: KingfisherParsedOptionsInfo, refresh: @escaping (Image) -> Void) { guard let option = options.progressiveJPEG else { return nil } self.option = option self.refresh = refresh self.decoder = ImageProgressiveDecoder( option, processingQueue: options.processingQueue ?? sharedProcessingQueue, creatingOptions: options.imageCreatingOptions ) } func update(data: Data, with callbacks: [SessionDataTask.TaskCallback]) { guard !data.isEmpty else { return } let interval = option.scanInterval let isFastest = option.isFastestScan func add(decode data: Data) { queue.add(minimum: interval) { completion in guard self.onShouldApply() else { self.queue.clean() completion() return } self.decoder.decode(data, with: callbacks) { image in defer { completion() } guard self.onShouldApply() else { return } guard let image = image else { return } self.refresh(image) } } } if isFastest { add(decode: decoder.scanning(data) ?? Data()) } else { decoder.scanning(data).forEach { add(decode: $0) } } } } private final class ImageProgressiveDecoder { private let option: ImageProgressive private let processingQueue: CallbackQueue private let creatingOptions: ImageCreatingOptions private(set) var scannedCount = 0 private(set) var scannedIndex = -1 init(_ option: ImageProgressive, processingQueue: CallbackQueue, creatingOptions: ImageCreatingOptions) { self.option = option self.processingQueue = processingQueue self.creatingOptions = creatingOptions } func scanning(_ data: Data) -> [Data] { guard data.kf.contains(jpeg: .SOF2) else { return [] } guard scannedIndex + 1 < data.count else { return [] } var datas: [Data] = [] var index = scannedIndex + 1 var count = scannedCount while index < data.count - 1 { scannedIndex = index // 0xFF, 0xDA - Start Of Scan let SOS = ImageFormat.JPEGMarker.SOS.bytes if data[index] == SOS[0], data[index + 1] == SOS[1] { if count > 0 { datas.append(data[0 ..< index]) } count += 1 } index += 1 } // Found more scans this the previous time guard count > scannedCount else { return [] } scannedCount = count // `> 1` checks that we've received a first scan (SOS) and then received // and also received a second scan (SOS). This way we know that we have // at least one full scan available. guard count > 1 else { return [] } return datas } func scanning(_ data: Data) -> Data? { guard data.kf.contains(jpeg: .SOF2) else { return nil } guard scannedIndex + 1 < data.count else { return nil } var index = scannedIndex + 1 var count = scannedCount var lastSOSIndex = 0 while index < data.count - 1 { scannedIndex = index // 0xFF, 0xDA - Start Of Scan let SOS = ImageFormat.JPEGMarker.SOS.bytes if data[index] == SOS[0], data[index + 1] == SOS[1] { lastSOSIndex = index count += 1 } index += 1 } // Found more scans this the previous time guard count > scannedCount else { return nil } scannedCount = count // `> 1` checks that we've received a first scan (SOS) and then received // and also received a second scan (SOS). This way we know that we have // at least one full scan available. guard count > 1 && lastSOSIndex > 0 else { return nil } return data[0 ..< lastSOSIndex] } func decode(_ data: Data, with callbacks: [SessionDataTask.TaskCallback], completion: @escaping (Image?) -> Void) { guard data.kf.contains(jpeg: .SOF2) else { CallbackQueue.mainCurrentOrAsync.execute { completion(nil) } return } func processing(_ data: Data) { let processor = ImageDataProcessor( data: data, callbacks: callbacks, processingQueue: processingQueue ) processor.onImageProcessed.delegate(on: self) { (self, result) in guard let image = try? result.0.get() else { CallbackQueue.mainCurrentOrAsync.execute { completion(nil) } return } CallbackQueue.mainCurrentOrAsync.execute { completion(image) } } processor.process() } // Blur partial images. let count = scannedCount if option.isBlur, count < 6 { processingQueue.execute { // Progressively reduce blur as we load more scans. let image = KingfisherWrapper<Image>.image( data: data, options: self.creatingOptions ) let radius = max(2, 14 - count * 4) let temp = image?.kf.blurred(withRadius: CGFloat(radius)) processing(temp?.kf.data(format: .JPEG) ?? data) } } else { processing(data) } } } private final class ImageProgressiveSerialQueue { typealias ClosureCallback = ((@escaping () -> Void)) -> Void private let queue: DispatchQueue private var items: [DispatchWorkItem] = [] private var notify: (() -> Void)? private var lastTime: TimeInterval? var count: Int { return items.count } init(_ queue: DispatchQueue) { self.queue = queue } func add(minimum interval: TimeInterval, closure: @escaping ClosureCallback) { let completion = { self.queue.async { guard !self.items.isEmpty else { return } self.items.removeFirst() if let next = self.items.first { self.queue.asyncAfter( deadline: .now() + interval, execute: next ) } else { self.lastTime = Date().timeIntervalSince1970 self.notify?() self.notify = nil } } } let item = DispatchWorkItem { closure(completion) } if items.isEmpty { let difference = Date().timeIntervalSince1970 - (lastTime ?? 0) let delay = difference < interval ? interval - difference : 0 queue.asyncAfter(deadline: .now() + delay, execute: item) } items.append(item) } func notify(_ closure: @escaping () -> Void) { self.notify = closure } func clean() { items.forEach { $0.cancel() } items.removeAll() } }
33.665574
85
0.563693
6233c44476ff7507bf80f11185490863abe585e4
2,285
// // FavoritesViewController.swift // NYTBestsellers // // Created by Aaron Cabreja on 1/25/19. // Copyright © 2019 Pursuit. All rights reserved. // import UIKit class FavoritesViewController: UIViewController { let favoritesView = FavoritesView() var books = BookModel.getBook() { didSet{ DispatchQueue.main.async { self.favoritesView.colloectionView.reloadData() } } } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white favoritesView.colloectionView.dataSource = self favoritesView.colloectionView.register(FavoritesCell.self, forCellWithReuseIdentifier: "Favorites") view.addSubview(favoritesView) } override func viewWillAppear(_ animated: Bool) { books = BookModel.getBook() } @objc private func deleteFavoriteBook(sender: UIButton){ let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let deleteAction = UIAlertAction(title: "Delete", style: .destructive) { alert in let i : Int = (sender.layer.value(forKey: "index")) as! Int BookModel.delete(atIndex: i) self.books = BookModel.getBook() } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) alertController.addAction(deleteAction) alertController.addAction(cancelAction) present(alertController, animated: true) } } extension FavoritesViewController: UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return books.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Favorites", for: indexPath) as? FavoritesCell else { return UICollectionViewCell() } let book = books[indexPath.row] cell.layer.cornerRadius = 20.0 cell.label.text = book.author cell.image.image = UIImage(data: book.imageData) cell.textView.text = book.description cell.button.layer.setValue(indexPath.row, forKey: "index") cell.button.addTarget(self, action: #selector(deleteFavoriteBook), for: .touchUpInside) return cell } }
32.183099
162
0.722101
711a4bbd10ad6e760e0abc41a8da9ade8b8ee8e2
1,799
/** * AppDelegate.swift * CookieCrunch * Copyright (c) 2017 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * 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 @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? }
43.878049
82
0.767649
330f120e078ab5aa2d386bcac8c45cef04281d33
4,519
// Copyright 2017 The casbin Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Expression import Regex public typealias MatchFunction = (String,String) -> Bool public typealias ExpressionFunction = ([Any]) throws -> Bool public struct Util { static func validateVariadicArgs(expentedLen: Int,args: [Any]) -> CasbinError? { if args.count != expentedLen { return .MATCH_ERROR(.MatchFuntionArgsCountError(args.count)) } for p in args { if !(p is String) { return .MATCH_ERROR(.MatchFuntionArgsNotString) } } return nil } public static func escapeAssertion(_ s:String) -> String { var _s = s _s.replaceAll(matching: #"\b(r\d*|p\d*)\."#, with: "$1_") return _s } public static func removeComment(_ s: String) -> String { var _s:String { if let i = s.firstIndex(of: "#") { return String(s[..<i]) } else { return s } } return _s.trimmingCharacters(in: .whitespaces) } public static func escapeEval(_ m:String) -> String { let re = Regex.init(#"\beval\(([^)]*)\)"#) var _m = m _m.replaceAll(matching: re, with: "eval($1)") return _m } public static func parseCsvLine(line: String) -> [String]? { let line = line.trimmingCharacters(in: .whitespaces) if line.isEmpty || line.starts(with: "#") { return nil } let re = Regex(#"(\s*"[^"]*"?|\s*[^,]*)"#) var res:[String] = [] let s = re.allMatches(in: line).map { $0.matchedString.trimmingCharacters(in: .whitespaces) } for col in s { if !col.isEmpty { if col.count >= 2 && col.starts(with: "\"") && col.hasSuffix("\"") { res.append(String(col[col.index(after: col.startIndex)..<col.index(before: col.endIndex)])) } else { res.append(col) } } } if res.isEmpty { return nil } else { return res } } public static func loadPolicyLine(line:String,m:Model) { if line.isEmpty || line.starts(with: "#") { return } if let tokens = Util.parseCsvLine(line: line),!tokens.isEmpty { let key = tokens[0] if let sec = key.first { if let item = m.getModel()[String(sec)] { if let ast = item[key] { ast.policy.append(Array(tokens[1...])) } } } } } public static func loadFilteredPolicyLine(line:String,m:Model,f:Filter) -> Bool { if line.isEmpty || line.starts(with: "#") { return false } if let tokens = Util.parseCsvLine(line: line) { let key = tokens[0] var isFiltered = false if let sec = key.first { let sec = String(sec) if sec == "p" { for (i,rule) in f.p.enumerated() { if !rule.isEmpty && rule != tokens[i + 1] { isFiltered = true } } } if sec == "g" { for (i,rule) in f.g.enumerated() { if !rule.isEmpty && rule != tokens[i + 1] { isFiltered = true } } } if !isFiltered { if let ast = m.getModel()[sec]?[key] { ast.policy.append(Array(tokens[1...])) } } } return isFiltered }else { return false } } }
32.049645
111
0.481965
89694ff355ef2eebe05bd351d110c24c139c4d45
3,931
// // DeviceConsistencyMessage.swift // SignalProtocolSwift-iOS // // Created by User on 18.11.17. // import Foundation /** Device consistency messages can be sent between multiple devices to verify that the identity keys and are consistent across devices. */ struct DeviceConsistencyMessage { /// The consistency signature var signature: DeviceConsistencySignature /// The generation of the consistency message var generation: UInt32 /** Create a new consistency message. - parameter commitment: The hashed identity keys - parameter identityKeyPair: The key pair of the sender - throws: `SignalError` errors */ init(commitment: DeviceConsistencyCommitmentV0, identitykeyPair: KeyPair) throws { let serialized = commitment.serialized /* Calculate VRF signature */ let signature = try identitykeyPair.privateKey.signVRF(message: serialized) /* Verify VRF signature */ let vrfOutput = try identitykeyPair.publicKey.verify(vrfSignature: signature, for: serialized) /* Create and assign the signature */ self.signature = DeviceConsistencySignature(signature: signature, vrfOutput: vrfOutput) self.generation = commitment.generation } } // MARK: Protocol Buffers extension DeviceConsistencyMessage { /** The message converted to a protocol buffer object. */ var object: Signal_DeviceConsistencyCodeMessage { return Signal_DeviceConsistencyCodeMessage.with { $0.generation = self.generation $0.signature = self.signature.signature } } /** Create a consistency message from a protocol buffer object. - parameter object: The protocol buffer object - parameter commitment: The commitment needed for verification - parameter identityKey: The identity key needed for verification - throws: `SignalError` errors */ init(from object: Signal_DeviceConsistencyCodeMessage, commitment: DeviceConsistencyCommitmentV0, identityKey: PublicKey) throws { guard object.hasSignature, object.hasGeneration else { throw SignalError(.invalidProtoBuf, "Missing data in ProtoBuf object") } /* Verify VRF signature */ let vrfOutput = try identityKey.verify(vrfSignature: object.signature, for: commitment.serialized) /* Assign the message fields */ self.generation = object.generation self.signature = DeviceConsistencySignature(signature: object.signature, vrfOutput: vrfOutput) } } extension DeviceConsistencyMessage { /** The message serialized through a protocol buffer. - throws: `SignalError` of type `invalidProtoBuf` - returns: The serialized record of the message */ func data() throws -> Data { do { return try object.serializedData() } catch { throw SignalError(.invalidProtoBuf, "Could not serialize DeviceConsistencyMessage: \(error.localizedDescription)") } } /** Create a consistency message from a serialized protocol buffer record. - parameter data: The serialized data - parameter commitment: The commitment needed for verification - parameter identityKey: The identity key needed for verification - throws: `SignalError` errors */ init(from data: Data, commitment: DeviceConsistencyCommitmentV0, identityKey: PublicKey) throws { let object: Signal_DeviceConsistencyCodeMessage do { object = try Signal_DeviceConsistencyCodeMessage(serializedData: data) } catch { throw SignalError(.invalidProtoBuf, "Could not deserialize DeviceConsistencyMessage: \(error.localizedDescription)") } try self.init(from: object, commitment: commitment, identityKey: identityKey) } }
33.598291
110
0.685067
d5ff56478d9eda248326d8eb0fb6de8400fecefa
679
// RUN: %target-swift-frontend -emit-ir %s | FileCheck %s // rdar://20532214 -- Wrong code for witness method lookup lets executable crash public protocol P1 { func foo(_ rhs: Self) -> Bool } public protocol P2 { associatedtype Index : P1 var startIndex: Index {get} } public protocol P3 : P1 {} public struct C3 : P3 { public func foo(_ rhs: C3) -> Bool { return true } } public struct C2 : P2 { public var startIndex: C3 { return C3() } } extension P2 where Self.Index : P3 { final public var bar: Bool { let i = startIndex return i.foo(i) } } let s = C2() s.bar // CHECK: call {{.*}} @_TWPV29protocol_extensions_constrain2C3S_2P3S_
16.560976
80
0.653903
e8a0f0a4e94305843ebcb3a851442fc6888caeed
73
//Component protocol PeopleComponent { var name:String { get set } }
14.6
31
0.69863
23b325bae76df08f10e1942031593df0c3f6c685
718
// // Regex.swift // CMS-iOS // // Created by Hridik Punukollu on 23/10/19. // Copyright © 2019 Hridik Punukollu. All rights reserved. // import Foundation public class Regex { class func match(pattern: String, text: String) -> [String] { do { let regex = try NSRegularExpression(pattern: pattern, options: []) let results = regex.matches(in: text, options: [], range: NSRange(text.startIndex..., in: text)) return results.map { String(text[Range($0.range, in: text)!]) } } catch let error{ print("The regex pattern was incorrect: \(error.localizedDescription)") return [] } } }
27.615385
108
0.566852
8981714324362b4bf926869b920f6ed7b3771529
2,560
// // Copyright © 2021 Daniel Farrelly // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this list // of conditions and the following disclaimer. // * 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. // // 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 HOLDER 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 Foundation internal struct Section { let title: String? let detail: String? let articles: [Article] internal init?(dictionary: [String: Any]) { // Title if let string = dictionary["title"] as? String, !string.isEmpty { title = string } else { title = nil } // Detail if let string = dictionary["detail"] as? String, !string.isEmpty { detail = string } else { detail = nil } // Articles articles = (dictionary["articles"] as? [[String: Any]])?.map({ Article(dictionary: $0) }).compactMap({ $0 }) ?? [] if articles.count == 0 { return nil } } internal init(title: String?, detail: String?, articles: [Article]!) { self.title = title self.detail = detail self.articles = articles } internal func section(_ filter: (Article) -> Bool) -> Section? { let articles = self.articles.filter(filter) if articles.count == 0 { return nil } return Section(title: self.title, detail: self.detail, articles: articles) } internal func section(_ query: String) -> Section? { return self.section { $0.matches(query) } } internal func section(_ buildNumber: Int) -> Section? { return self.section { $0.matches(buildNumber) } } }
30.47619
116
0.709375
cc52020470dbb9941edf732729db76590bed6611
29,110
// // GalleryViewController.swift // ImageViewer // // Created by Kristian Angyal on 01/07/2016. // Copyright © 2016 MailOnline. All rights reserved. // import UIKit import AVFoundation open class GalleryViewController: UIPageViewController, ItemControllerDelegate { // UI fileprivate let overlayView = BlurView() /// A custom view on the top of the gallery with layout using default (or custom) pinning settings for header. open var headerView: UIView? /// A custom view at the bottom of the gallery with layout using default (or custom) pinning settings for footer. open var footerView: UIView? fileprivate var closeButton: UIButton? = UIButton.closeButton() fileprivate var seeAllCloseButton: UIButton? = nil fileprivate var thumbnailsButton: UIButton? = UIButton.thumbnailsButton() fileprivate var deleteButton: UIButton? = UIButton.deleteButton() fileprivate let scrubber = VideoScrubber() fileprivate weak var initialItemController: ItemController? // LOCAL STATE // represents the current page index, updated when the root view of the view controller representing the page stops animating inside visible bounds and stays on screen. public var currentIndex: Int // Picks up the initial value from configuration, if provided. Subsequently also works as local state for the setting. fileprivate var decorationViewsHidden = false fileprivate var isAnimating = false fileprivate var initialPresentationDone = false // DATASOURCE/DELEGATE fileprivate let itemsDelegate: GalleryItemsDelegate? fileprivate let itemsDataSource: GalleryItemsDataSource fileprivate let pagingDataSource: GalleryPagingDataSource // CONFIGURATION fileprivate var spineDividerWidth: Float = 10 fileprivate var galleryPagingMode = GalleryPagingMode.standard fileprivate var headerLayout = HeaderLayout.center(25) fileprivate var footerLayout = FooterLayout.center(25) fileprivate var closeLayout = ButtonLayout.pinRight(8, 16) fileprivate var seeAllCloseLayout = ButtonLayout.pinRight(8, 16) fileprivate var thumbnailsLayout = ButtonLayout.pinLeft(8, 16) fileprivate var deleteLayout = ButtonLayout.pinRight(8, 66) fileprivate var statusBarHidden = true fileprivate var overlayAccelerationFactor: CGFloat = 1 fileprivate var rotationDuration = 0.15 fileprivate var rotationMode = GalleryRotationMode.always fileprivate let swipeToDismissFadeOutAccelerationFactor: CGFloat = 6 fileprivate var decorationViewsFadeDuration = 0.15 /// COMPLETION BLOCKS /// If set, the block is executed right after the initial launch animations finish. open var launchedCompletion: (() -> Void)? /// If set, called every time ANY animation stops in the page controller stops and the viewer passes a page index of the page that is currently on screen open var landedPageAtIndexCompletion: ((Int) -> Void)? /// If set, launched after all animations finish when the close button is pressed. open var closedCompletion: (() -> Void)? /// If set, launched after all animations finish when the close() method is invoked via public API. open var programmaticallyClosedCompletion: (() -> Void)? /// If set, launched after all animations finish when the swipe-to-dismiss (applies to all directions and cases) gesture is used. open var swipedToDismissCompletion: (() -> Void)? @available(*, unavailable) required public init?(coder: NSCoder) { fatalError() } public init(startIndex: Int, itemsDataSource: GalleryItemsDataSource, itemsDelegate: GalleryItemsDelegate? = nil, displacedViewsDataSource: GalleryDisplacedViewsDataSource? = nil, configuration: GalleryConfiguration = []) { self.currentIndex = startIndex self.itemsDelegate = itemsDelegate self.itemsDataSource = itemsDataSource var continueNextVideoOnFinish: Bool = false ///Only those options relevant to the paging GalleryViewController are explicitly handled here, the rest is handled by ItemViewControllers for item in configuration { switch item { case .imageDividerWidth(let width): spineDividerWidth = Float(width) case .pagingMode(let mode): galleryPagingMode = mode case .headerViewLayout(let layout): headerLayout = layout case .footerViewLayout(let layout): footerLayout = layout case .closeLayout(let layout): closeLayout = layout case .deleteLayout(let layout): deleteLayout = layout case .thumbnailsLayout(let layout): thumbnailsLayout = layout case .statusBarHidden(let hidden): statusBarHidden = hidden case .hideDecorationViewsOnLaunch(let hidden): decorationViewsHidden = hidden case .decorationViewsFadeDuration(let duration): decorationViewsFadeDuration = duration case .rotationDuration(let duration): rotationDuration = duration case .rotationMode(let mode): rotationMode = mode case .overlayColor(let color): overlayView.overlayColor = color case .overlayBlurStyle(let style): overlayView.blurringView.effect = UIBlurEffect(style: style) case .overlayBlurOpacity(let opacity): overlayView.blurTargetOpacity = opacity case .overlayColorOpacity(let opacity): overlayView.colorTargetOpacity = opacity case .blurPresentDuration(let duration): overlayView.blurPresentDuration = duration case .blurPresentDelay(let delay): overlayView.blurPresentDelay = delay case .colorPresentDuration(let duration): overlayView.colorPresentDuration = duration case .colorPresentDelay(let delay): overlayView.colorPresentDelay = delay case .blurDismissDuration(let duration): overlayView.blurDismissDuration = duration case .blurDismissDelay(let delay): overlayView.blurDismissDelay = delay case .colorDismissDuration(let duration): overlayView.colorDismissDuration = duration case .colorDismissDelay(let delay): overlayView.colorDismissDelay = delay case .continuePlayVideoOnEnd(let enabled): continueNextVideoOnFinish = enabled case .seeAllCloseLayout(let layout): seeAllCloseLayout = layout case .videoControlsColor(let color): scrubber.tintColor = color case .closeButtonMode(let buttonMode): switch buttonMode { case .none: closeButton = nil case .custom(let button): closeButton = button case .builtIn: break } case .seeAllCloseButtonMode(let buttonMode): switch buttonMode { case .none: seeAllCloseButton = nil case .custom(let button): seeAllCloseButton = button case .builtIn: break } case .thumbnailsButtonMode(let buttonMode): switch buttonMode { case .none: thumbnailsButton = nil case .custom(let button): thumbnailsButton = button case .builtIn: break } case .deleteButtonMode(let buttonMode): switch buttonMode { case .none: deleteButton = nil case .custom(let button): deleteButton = button case .builtIn: break } default: break } } pagingDataSource = GalleryPagingDataSource(itemsDataSource: itemsDataSource, displacedViewsDataSource: displacedViewsDataSource, scrubber: scrubber, configuration: configuration) super.init(transitionStyle: UIPageViewController.TransitionStyle.scroll, navigationOrientation: UIPageViewController.NavigationOrientation.horizontal, options: [UIPageViewController.OptionsKey.interPageSpacing : NSNumber(value: spineDividerWidth as Float)]) pagingDataSource.itemControllerDelegate = self ///This feels out of place, one would expect even the first presented(paged) item controller to be provided by the paging dataSource but there is nothing we can do as Apple requires the first controller to be set via this "setViewControllers" method. let initialController = pagingDataSource.createItemController(startIndex, isInitial: true) self.setViewControllers([initialController], direction: UIPageViewController.NavigationDirection.forward, animated: false, completion: nil) if let controller = initialController as? ItemController { initialItemController = controller } ///This less known/used presentation style option allows the contents of parent view controller presenting the gallery to "bleed through" the blurView. Otherwise we would see only black color. self.modalPresentationStyle = .overFullScreen self.dataSource = pagingDataSource UIApplication.applicationWindow.windowLevel = (statusBarHidden) ? UIWindow.Level.statusBar + 1 : UIWindow.Level.normal NotificationCenter.default.addObserver(self, selector: #selector(GalleryViewController.rotate), name: UIDevice.orientationDidChangeNotification, object: nil) if continueNextVideoOnFinish { NotificationCenter.default.addObserver(self, selector: #selector(didEndPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil) } } deinit { NotificationCenter.default.removeObserver(self) } @objc func didEndPlaying() { page(toIndex: currentIndex+1) } fileprivate func configureOverlayView() { overlayView.bounds.size = UIScreen.main.bounds.insetBy(dx: -UIScreen.main.bounds.width / 2, dy: -UIScreen.main.bounds.height / 2).size overlayView.center = CGPoint(x: (UIScreen.main.bounds.width / 2), y: (UIScreen.main.bounds.height / 2)) self.view.addSubview(overlayView) self.view.sendSubviewToBack(overlayView) } fileprivate func configureHeaderView() { if let header = headerView { header.alpha = 0 self.view.addSubview(header) } } fileprivate func configureFooterView() { if let footer = footerView { footer.alpha = 0 self.view.addSubview(footer) } } fileprivate func configureCloseButton() { if let closeButton = closeButton { closeButton.addTarget(self, action: #selector(GalleryViewController.closeInteractively), for: .touchUpInside) closeButton.alpha = 0 self.view.addSubview(closeButton) } } fileprivate func configureThumbnailsButton() { if let thumbnailsButton = thumbnailsButton { thumbnailsButton.addTarget(self, action: #selector(GalleryViewController.showThumbnails), for: .touchUpInside) thumbnailsButton.alpha = 0 self.view.addSubview(thumbnailsButton) } } fileprivate func configureDeleteButton() { if let deleteButton = deleteButton { deleteButton.addTarget(self, action: #selector(GalleryViewController.deleteItem), for: .touchUpInside) deleteButton.alpha = 0 self.view.addSubview(deleteButton) } } fileprivate func configureScrubber() { scrubber.alpha = 0 self.view.addSubview(scrubber) } open override func viewDidLoad() { super.viewDidLoad() if #available(iOS 11.0, *) { if (statusBarHidden || UIScreen.hasNotch) { additionalSafeAreaInsets = UIEdgeInsets(top: -20, left: 0, bottom: 0, right: 0) } } configureHeaderView() configureFooterView() configureCloseButton() configureThumbnailsButton() configureDeleteButton() configureScrubber() self.view.clipsToBounds = false } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) guard initialPresentationDone == false else { return } ///We have to call this here (not sooner), because it adds the overlay view to the presenting controller and the presentingController property is set only at this moment in the VC lifecycle. configureOverlayView() ///The initial presentation animations and transitions presentInitially() initialPresentationDone = true } fileprivate func presentInitially() { isAnimating = true ///Animates decoration views to the initial state if they are set to be visible on launch. We do not need to do anything if they are set to be hidden because they are already set up as hidden by default. Unhiding them for the launch is part of chosen UX. initialItemController?.presentItem(alongsideAnimation: { [weak self] in self?.overlayView.present() }, completion: { [weak self] in if let strongSelf = self { if strongSelf.decorationViewsHidden == false { strongSelf.animateDecorationViews(visible: true) } strongSelf.isAnimating = false strongSelf.launchedCompletion?() } }) } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if rotationMode == .always && UIApplication.isPortraitOnly { let transform = windowRotationTransform() let bounds = rotationAdjustedBounds() self.view.transform = transform self.view.bounds = bounds } overlayView.frame = view.bounds.insetBy(dx: -UIScreen.main.bounds.width * 2, dy: -UIScreen.main.bounds.height * 2) layoutButton(closeButton, layout: closeLayout) layoutButton(thumbnailsButton, layout: thumbnailsLayout) layoutButton(deleteButton, layout: deleteLayout) layoutHeaderView() layoutFooterView() layoutScrubber() } private var defaultInsets: UIEdgeInsets { if #available(iOS 11.0, *) { return view.safeAreaInsets } else { return UIEdgeInsets(top: statusBarHidden ? 0.0 : 20.0, left: 0.0, bottom: 0.0, right: 0.0) } } fileprivate func layoutButton(_ button: UIButton?, layout: ButtonLayout) { guard let button = button else { return } switch layout { case .pinRight(let marginTop, let marginRight): button.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin] button.frame.origin.x = self.view.bounds.size.width - marginRight - button.bounds.size.width button.frame.origin.y = defaultInsets.top + marginTop case .pinLeft(let marginTop, let marginLeft): button.autoresizingMask = [.flexibleBottomMargin, .flexibleRightMargin] button.frame.origin.x = marginLeft button.frame.origin.y = defaultInsets.top + marginTop } } fileprivate func layoutHeaderView() { guard let header = headerView else { return } switch headerLayout { case .center(let marginTop): header.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin] header.center = self.view.boundsCenter header.frame.origin.y = defaultInsets.top + marginTop case .pinBoth(let marginTop, let marginLeft,let marginRight): header.autoresizingMask = [.flexibleBottomMargin, .flexibleWidth] header.bounds.size.width = self.view.bounds.width - marginLeft - marginRight header.sizeToFit() header.frame.origin = CGPoint(x: marginLeft, y: defaultInsets.top + marginTop) case .pinLeft(let marginTop, let marginLeft): header.autoresizingMask = [.flexibleBottomMargin, .flexibleRightMargin] header.frame.origin = CGPoint(x: marginLeft, y: defaultInsets.top + marginTop) case .pinRight(let marginTop, let marginRight): header.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin] header.frame.origin = CGPoint(x: self.view.bounds.width - marginRight - header.bounds.width, y: defaultInsets.top + marginTop) } } fileprivate func layoutFooterView() { guard let footer = footerView else { return } switch footerLayout { case .center(let marginBottom): footer.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin] footer.center = self.view.boundsCenter footer.frame.origin.y = self.view.bounds.height - footer.bounds.height - marginBottom - defaultInsets.bottom case .pinBoth(let marginBottom, let marginLeft,let marginRight): footer.autoresizingMask = [.flexibleTopMargin, .flexibleWidth] footer.frame.size.width = self.view.bounds.width - marginLeft - marginRight footer.sizeToFit() footer.frame.origin = CGPoint(x: marginLeft, y: self.view.bounds.height - footer.bounds.height - marginBottom - defaultInsets.bottom) case .pinLeft(let marginBottom, let marginLeft): footer.autoresizingMask = [.flexibleTopMargin, .flexibleRightMargin] footer.frame.origin = CGPoint(x: marginLeft, y: self.view.bounds.height - footer.bounds.height - marginBottom - defaultInsets.bottom) case .pinRight(let marginBottom, let marginRight): footer.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin] footer.frame.origin = CGPoint(x: self.view.bounds.width - marginRight - footer.bounds.width, y: self.view.bounds.height - footer.bounds.height - marginBottom - defaultInsets.bottom) } } fileprivate func layoutScrubber() { scrubber.bounds = CGRect(origin: CGPoint.zero, size: CGSize(width: self.view.bounds.width, height: 40)) scrubber.center = self.view.boundsCenter scrubber.frame.origin.y = (footerView?.frame.origin.y ?? self.view.bounds.maxY) - scrubber.bounds.height } @objc public func deleteItem() { deleteButton?.isEnabled = false view.isUserInteractionEnabled = false itemsDelegate?.removeGalleryItem(at: currentIndex) removePage(atIndex: currentIndex) { [weak self] in self?.deleteButton?.isEnabled = true self?.view.isUserInteractionEnabled = true } } //ThumbnailsimageBlock @objc fileprivate func showThumbnails() { let thumbnailsController = ThumbnailsViewController(itemsDataSource: self.itemsDataSource) if let closeButton = seeAllCloseButton { thumbnailsController.closeButton = closeButton thumbnailsController.closeLayout = seeAllCloseLayout } else if let closeButton = closeButton { let seeAllCloseButton = UIButton(frame: CGRect(origin: CGPoint.zero, size: closeButton.bounds.size)) seeAllCloseButton.setImage(closeButton.image(for: UIControl.State()), for: UIControl.State()) seeAllCloseButton.setImage(closeButton.image(for: .highlighted), for: .highlighted) thumbnailsController.closeButton = seeAllCloseButton thumbnailsController.closeLayout = closeLayout } thumbnailsController.onItemSelected = { [weak self] index in self?.page(toIndex: index) } present(thumbnailsController, animated: true, completion: nil) } open func page(toIndex index: Int) { guard currentIndex != index && index >= 0 && index < self.itemsDataSource.itemCount() else { return } let imageViewController = self.pagingDataSource.createItemController(index) let direction: UIPageViewController.NavigationDirection = index > currentIndex ? .forward : .reverse // workaround to make UIPageViewController happy if direction == .forward { let previousVC = self.pagingDataSource.createItemController(index - 1) setViewControllers([previousVC], direction: direction, animated: true, completion: { finished in DispatchQueue.main.async(execute: { [weak self] in self?.setViewControllers([imageViewController], direction: direction, animated: false, completion: nil) }) }) } else { let nextVC = self.pagingDataSource.createItemController(index + 1) setViewControllers([nextVC], direction: direction, animated: true, completion: { finished in DispatchQueue.main.async(execute: { [weak self] in self?.setViewControllers([imageViewController], direction: direction, animated: false, completion: nil) }) }) } } func removePage(atIndex index: Int, completion: @escaping () -> Void) { // If removing last item, go back, otherwise, go forward let direction: UIPageViewController.NavigationDirection = index < self.itemsDataSource.itemCount() ? .forward : .reverse let newIndex = direction == .forward ? index : index - 1 if newIndex < 0 { close(); return } let vc = self.pagingDataSource.createItemController(newIndex) setViewControllers([vc], direction: direction, animated: true) { _ in completion() } } open func reload(atIndex index: Int) { guard index >= 0 && index < self.itemsDataSource.itemCount() else { return } guard let firstVC = viewControllers?.first, let itemController = firstVC as? ItemController else { return } itemController.fetchImage() } // MARK: - Animations @objc fileprivate func rotate() { /// If the app supports rotation on global level, we don't need to rotate here manually because the rotation /// of key Window will rotate all app's content with it via affine transform and from the perspective of the /// gallery it is just a simple relayout. Allowing access to remaining code only makes sense if the app is /// portrait only but we still want to support rotation inside the gallery. guard UIApplication.isPortraitOnly else { return } guard UIDevice.current.orientation.isFlat == false && isAnimating == false else { return } isAnimating = true UIView.animate(withDuration: rotationDuration, delay: 0, options: UIView.AnimationOptions.curveLinear, animations: { [weak self] () -> Void in self?.view.transform = windowRotationTransform() self?.view.bounds = rotationAdjustedBounds() self?.view.setNeedsLayout() self?.view.layoutIfNeeded() }) { [weak self] finished in self?.isAnimating = false } } /// Invoked when closed programmatically open func close() { closeDecorationViews(programmaticallyClosedCompletion) } /// Invoked when closed via close button @objc fileprivate func closeInteractively() { closeDecorationViews(closedCompletion) } fileprivate func closeDecorationViews(_ completion: (() -> Void)?) { guard isAnimating == false else { return } isAnimating = true if let itemController = self.viewControllers?.first as? ItemController { itemController.closeDecorationViews(decorationViewsFadeDuration) } UIView.animate(withDuration: decorationViewsFadeDuration, animations: { [weak self] in self?.headerView?.alpha = 0.0 self?.footerView?.alpha = 0.0 self?.closeButton?.alpha = 0.0 self?.thumbnailsButton?.alpha = 0.0 self?.deleteButton?.alpha = 0.0 self?.scrubber.alpha = 0.0 }, completion: { [weak self] done in if let strongSelf = self, let itemController = strongSelf.viewControllers?.first as? ItemController { itemController.dismissItem(alongsideAnimation: { strongSelf.overlayView.dismiss() }, completion: { [weak self] in self?.isAnimating = true self?.closeGallery(false, completion: completion) }) } }) } func closeGallery(_ animated: Bool, completion: (() -> Void)?) { self.overlayView.removeFromSuperview() self.modalTransitionStyle = .crossDissolve self.dismiss(animated: animated) { UIApplication.applicationWindow.windowLevel = UIWindow.Level.normal completion?() } } fileprivate func animateDecorationViews(visible: Bool) { let targetAlpha: CGFloat = (visible) ? 1 : 0 UIView.animate(withDuration: decorationViewsFadeDuration, animations: { [weak self] in self?.headerView?.alpha = targetAlpha self?.footerView?.alpha = targetAlpha self?.closeButton?.alpha = targetAlpha self?.thumbnailsButton?.alpha = targetAlpha self?.deleteButton?.alpha = targetAlpha if let _ = self?.viewControllers?.first as? VideoViewController { UIView.animate(withDuration: 0.3, animations: { [weak self] in self?.scrubber.alpha = targetAlpha }) } }) } public func itemControllerWillAppear(_ controller: ItemController) { if let videoController = controller as? VideoViewController { scrubber.player = videoController.player } } public func itemControllerWillDisappear(_ controller: ItemController) { if let _ = controller as? VideoViewController { scrubber.player = nil UIView.animate(withDuration: 0.3, animations: { [weak self] in self?.scrubber.alpha = 0 }) } } public func itemControllerDidAppear(_ controller: ItemController) { self.currentIndex = controller.index self.landedPageAtIndexCompletion?(self.currentIndex) self.headerView?.sizeToFit() self.footerView?.sizeToFit() if let videoController = controller as? VideoViewController { scrubber.player = videoController.player if scrubber.alpha == 0 && decorationViewsHidden == false { UIView.animate(withDuration: 0.3, animations: { [weak self] in self?.scrubber.alpha = 1 }) } } } open func itemControllerDidSingleTap(_ controller: ItemController) { self.decorationViewsHidden.flip() animateDecorationViews(visible: !self.decorationViewsHidden) } open func itemControllerDidLongPress(_ controller: ItemController, in item: ItemView) { switch (controller, item) { case (_ as ImageViewController, let item as UIImageView): guard let image = item.image else { return } let activityVC = UIActivityViewController(activityItems: [image], applicationActivities: nil) self.present(activityVC, animated: true) case (_ as VideoViewController, let item as VideoView): guard let videoUrl = ((item.player?.currentItem?.asset) as? AVURLAsset)?.url else { return } let activityVC = UIActivityViewController(activityItems: [videoUrl], applicationActivities: nil) self.present(activityVC, animated: true) default: return } } public func itemController(_ controller: ItemController, didSwipeToDismissWithDistanceToEdge distance: CGFloat) { if decorationViewsHidden == false { let alpha = 1 - distance * swipeToDismissFadeOutAccelerationFactor closeButton?.alpha = alpha thumbnailsButton?.alpha = alpha deleteButton?.alpha = alpha headerView?.alpha = alpha footerView?.alpha = alpha if controller is VideoViewController { scrubber.alpha = alpha } } self.overlayView.blurringView.alpha = 1 - distance self.overlayView.colorView.alpha = 1 - distance } public func itemControllerDidFinishSwipeToDismissSuccessfully() { self.swipedToDismissCompletion?() self.overlayView.removeFromSuperview() self.dismiss(animated: false, completion: nil) } }
40.599721
262
0.651735
d7d60a206f87537f64b8cab80a105987e7d8d14c
2,172
// // AppDelegate.swift // STTextEdit // // Created by Maple Yin on 12/22/2018. // Copyright (c) 2018 Maple Yin. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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.212766
285
0.753683
4bc28928041c8363c9cf621d2fa6eb26c463bc3c
3,279
// // FHIRServer.swift // SwiftFHIR // // Created by Pascal Pfiffner on 01/24/15. // 2015, SMART Health IT. // import Foundation /** Struct to describe REST request types, with a convenience method to make a request FHIR compliant. */ public enum FHIRRequestType: String { case GET = "GET" case PUT = "PUT" case POST = "POST" case PATCH = "PATCH" case DELETE = "DELETE" case OPTIONS = "OPTIONS" /** Prepare a given mutable URL request with the respective method and body values. */ public func prepare(request: inout URLRequest, body: Data? = nil) { request.httpMethod = rawValue switch self { case .GET: break case .PUT: request.httpBody = body case .POST: request.httpBody = body case .PATCH: request.httpBody = body case .DELETE: break case .OPTIONS: break } } } /** Struct to hold request headers. By default, the "Accept-Charset" header is set to "utf-8" upon initialization. */ public struct FHIRRequestHeaders { /// All the headers the instance is holding on to. public var headers: [FHIRRequestHeaderField: String] public init(_ headers: [FHIRRequestHeaderField: String]? = nil) { var hdrs = [FHIRRequestHeaderField.acceptCharset: "utf-8"] headers?.forEach() { hdrs[$0] = $1 } self.headers = hdrs } public subscript(key: FHIRRequestHeaderField) -> String? { get { return headers[key] } set { headers[key] = newValue } } /** Prepare a given mutable URL request with the receiver's values. */ public func prepare(request: inout URLRequest) { headers.forEach { request.setValue($1, forHTTPHeaderField: $0.rawValue) } } } /** Describe valid (and supported) FHIR request headers. The "Authorization" header is not used in the basic library, it is provided for convenience's sake. */ public enum FHIRRequestHeaderField: String { case accept = "Accept" case acceptCharset = "Accept-Charset" case authorization = "Authorization" case contentType = "Content-Type" case prefer = "Prefer" case ifMatch = "If-Match" case ifNoneMatch = "If-None-Match" case ifModifiedSince = "If-Modified-Since" case ifNoneExist = "If-None-Exist" } /** Protocol for server objects to be used by `FHIRResource` and subclasses. */ public protocol FHIRServer { /** A server object must always have a base URL. */ var baseURL: URL { get } /** Designated initializer. Should make sure that the base URL ends with a "/"! */ init(baseURL base: URL, auth: [String: AnyObject]?) // MARK: - HTTP Request /* Execute a request of given type against the given path, which is relative to the receiver's `baseURL`, with the given resource (if any). - parameter ofType: The HTTP method type of the request - parameter path: The relative path on the server to be interacting against - parameter resource: The resource to be involved in the request, if any - parameter additonalHeaders: The headers to set on the request - parameter callback: A callback, likely called asynchronously, returning a response instance */ func performRequest(ofType: FHIRRequestType, path: String, resource: Resource?, additionalHeaders: FHIRRequestHeaders?, callback: @escaping ((FHIRServerResponse) -> Void)) }
26.443548
172
0.694724
1185eb313a803b43ee35c012f616529399ec61e2
313
// // GeneralInfomation.swift // Main // // Created by iq3AddLi on 2019/09/20. // import Vapor extension GeneralInfomation: Content{} extension GeneralInfomation: LosslessHTTPBodyRepresentable{ func convertToHTTPBody() -> HTTPBody{ return try! HTTPBody(data: JSONEncoder().encode(self)) } }
18.411765
62
0.71246
ffe98653cbb88d7501303299a4a6dfcdd2f1d1a8
1,326
// // RegistrationViewController.swift // RaidaChat // // Created by Владислав on 14.01.2018. // Copyright © 2018 Владислав. All rights reserved. // import UIKit class RegistrationViewController: UIViewController { var raida: ControllerRaida! @IBOutlet weak var login: UITextField! @IBOutlet weak var password: UITextField! override func viewDidLoad() { super.viewDidLoad() login.delegate = self password.delegate = self hideKeyboardWhenTappedAround() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func tapRegistration(_ sender: Any) { raida.requestRegistration(login: login.text!, password: password.text!) self.navigationController?.popViewController(animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
28.212766
106
0.676471
e43184bb912053266d1ae3715fae0b61184d01e6
3,792
import XCTest import Foundation @testable import Emulator6502 final class EorAbsXTests: XCTestCase { func testEorAbsXNoPageChange() { print("debug: testEorAbsXNoPageChange") let pins = Pins() let testValue1:UInt8 = 0x26 let testValue2:UInt8 = 0x1c let memory = TestHelper.initMemory(pins) let memStore:UInt16 = 0x1a3c let offset:UInt8 = 0x05 let actualStore:UInt16 = 0x1a41 // First OP after reset is op memory[TestHelper.RES_ADDR] = TestHelper.EORAbsX memory[TestHelper.RES_ADDR&+1] = UInt8(memStore & 0xff) // low byte memory[TestHelper.RES_ADDR&+2] = UInt8(memStore >> 8) // high byte memory[TestHelper.RES_ADDR&+3] = TestHelper.NOP memory[actualStore] = testValue2 let cpu = CPU6502(pins) cpu.reset() cpu.x.value = offset // Index offset from base address TestHelper.startupSequence(cpu: cpu, pins: pins, mem: memory) cpu.a.value = testValue1 // Set the accumulator // Next instruction should be op at RESET address XCTAssertEqual(pins.address.value, TestHelper.RES_ADDR) XCTAssertEqual(pins.data.value, TestHelper.EORAbsX) print("debug: perform EOR AbsX") // decode OP - fetch ADL TestHelper.cycle(cpu, pins: pins, mem: memory) XCTAssertEqual(cpu.ir.value, TestHelper.EORAbsX) XCTAssertEqual(pins.data.value, UInt8(memStore & 0xff)) // Save ADL - fetch ADH TestHelper.cycle(cpu, pins: pins, mem: memory) XCTAssertEqual(pins.data.value, UInt8(memStore >> 8)) // Save ADH - fetch arg TestHelper.cycle(cpu, pins: pins, mem: memory) XCTAssertEqual(pins.data.value, testValue2) // Ex OR arg to A TestHelper.cycle(cpu, pins: pins, mem: memory) XCTAssertEqual(cpu.a.value, testValue1 ^ testValue2) // Decode NOP TestHelper.cycle(cpu, pins: pins, mem: memory) XCTAssertEqual(cpu.ir.value, TestHelper.NOP) } func testEorAbsXWithPageChange() { print("debug: testEorAbsXWithPageChange") let pins = Pins() let testValue1:UInt8 = 0x26 let testValue2:UInt8 = 0x1c let memory = TestHelper.initMemory(pins) let memStore:UInt16 = 0x1afc let offset:UInt8 = 0x05 let actualStore:UInt16 = 0x1b01 // First OP after reset is op memory[TestHelper.RES_ADDR] = TestHelper.EORAbsX memory[TestHelper.RES_ADDR&+1] = UInt8(memStore & 0xff) // low byte memory[TestHelper.RES_ADDR&+2] = UInt8(memStore >> 8) // high byte memory[TestHelper.RES_ADDR&+3] = TestHelper.NOP memory[actualStore] = testValue2 let cpu = CPU6502(pins) cpu.reset() cpu.x.value = offset // Index offset from base address TestHelper.startupSequence(cpu: cpu, pins: pins, mem: memory) cpu.a.value = testValue1 // Set the accumulator // Next instruction should be op at RESET address XCTAssertEqual(pins.address.value, TestHelper.RES_ADDR) XCTAssertEqual(pins.data.value, TestHelper.EORAbsX) print("debug: perform EOR AbsX") // decode OP - fetch ADL TestHelper.cycle(cpu, pins: pins, mem: memory) XCTAssertEqual(cpu.ir.value, TestHelper.EORAbsX) XCTAssertEqual(pins.data.value, UInt8(memStore & 0xff)) // Save ADL - fetch ADH TestHelper.cycle(cpu, pins: pins, mem: memory) XCTAssertEqual(pins.data.value, UInt8(memStore >> 8)) // Save ADH - fetch arg - discarded TestHelper.cycle(cpu, pins: pins, mem: memory) XCTAssertNotEqual(pins.data.value, testValue2) // Save ADH - fetch arg TestHelper.cycle(cpu, pins: pins, mem: memory) XCTAssertEqual(pins.data.value, testValue2) // Ex OR arg to A TestHelper.cycle(cpu, pins: pins, mem: memory) XCTAssertEqual(cpu.a.value, testValue1 ^ testValue2) // Decode NOP TestHelper.cycle(cpu, pins: pins, mem: memory) XCTAssertEqual(cpu.ir.value, TestHelper.NOP) } }
35.111111
71
0.696466
140253625e7e3ec302c4ef99b551ba10b1ad6e65
347
// // ExceptionCatchable.swift // Swifty // // Created by Yuki Okudera on 2020/03/28. // Copyright © 2020 Yuki Okudera. All rights reserved. // import Foundation protocol ExceptionCatchable {} extension ExceptionCatchable { func execute(_ tryBlock: () -> ()) throws { try ExceptionHandler.catchException(try: tryBlock) } }
18.263158
58
0.688761
5d09466937e345cff2c8ef3d8f530219ed4b38bf
374
// // UIView+Extension.swift // RosbankHackathon // // Created by Evgeniy on 17/11/2018. // Copyright © 2018 Evgeniy. All rights reserved. // import UIKit public extension UIView { public func addSubviews(_ subviews: [UIView]) { subviews.forEach(addSubview) } public func addSubviews(_ subviews: UIView...) { addSubviews(subviews) } }
18.7
52
0.660428
67c8408d4910bf4b133244889bd0d3b7e8e469c8
18,257
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import Foundation import Basic class PathTests: XCTestCase { func testBasics() { XCTAssertEqual(AbsolutePath("/").pathString, "/") XCTAssertEqual(AbsolutePath("/a").pathString, "/a") XCTAssertEqual(AbsolutePath("/a/b/c").pathString, "/a/b/c") XCTAssertEqual(RelativePath(".").pathString, ".") XCTAssertEqual(RelativePath("a").pathString, "a") XCTAssertEqual(RelativePath("a/b/c").pathString, "a/b/c") XCTAssertEqual(RelativePath("~").pathString, "~") // `~` is not special } func testStringInitialization() { let abs1 = AbsolutePath("/") let abs2 = AbsolutePath(abs1, ".") XCTAssertEqual(abs1, abs2) let rel3 = "." let abs3 = AbsolutePath(abs2, rel3) XCTAssertEqual(abs2, abs3) let base = AbsolutePath("/base/path") let abs4 = AbsolutePath("/a/b/c", relativeTo: base) XCTAssertEqual(abs4, AbsolutePath("/a/b/c")) let abs5 = AbsolutePath("./a/b/c", relativeTo: base) XCTAssertEqual(abs5, AbsolutePath("/base/path/a/b/c")) let abs6 = AbsolutePath("~/bla", relativeTo: base) // `~` isn't special XCTAssertEqual(abs6, AbsolutePath("/base/path/~/bla")) } func testStringLiteralInitialization() { let abs = AbsolutePath("/") XCTAssertEqual(abs.pathString, "/") let rel1 = RelativePath(".") XCTAssertEqual(rel1.pathString, ".") let rel2 = RelativePath("~") XCTAssertEqual(rel2.pathString, "~") // `~` is not special } func testRepeatedPathSeparators() { XCTAssertEqual(AbsolutePath("/ab//cd//ef").pathString, "/ab/cd/ef") XCTAssertEqual(AbsolutePath("/ab///cd//ef").pathString, "/ab/cd/ef") XCTAssertEqual(RelativePath("ab//cd//ef").pathString, "ab/cd/ef") XCTAssertEqual(RelativePath("ab//cd///ef").pathString, "ab/cd/ef") } func testTrailingPathSeparators() { XCTAssertEqual(AbsolutePath("/ab/cd/ef/").pathString, "/ab/cd/ef") XCTAssertEqual(AbsolutePath("/ab/cd/ef//").pathString, "/ab/cd/ef") XCTAssertEqual(RelativePath("ab/cd/ef/").pathString, "ab/cd/ef") XCTAssertEqual(RelativePath("ab/cd/ef//").pathString, "ab/cd/ef") } func testDotPathComponents() { XCTAssertEqual(AbsolutePath("/ab/././cd//ef").pathString, "/ab/cd/ef") XCTAssertEqual(AbsolutePath("/ab/./cd//ef/.").pathString, "/ab/cd/ef") XCTAssertEqual(RelativePath("ab/./cd/././ef").pathString, "ab/cd/ef") XCTAssertEqual(RelativePath("ab/./cd/ef/.").pathString, "ab/cd/ef") } func testDotDotPathComponents() { XCTAssertEqual(AbsolutePath("/..").pathString, "/") XCTAssertEqual(AbsolutePath("/../../../../..").pathString, "/") XCTAssertEqual(AbsolutePath("/abc/..").pathString, "/") XCTAssertEqual(AbsolutePath("/abc/../..").pathString, "/") XCTAssertEqual(AbsolutePath("/../abc").pathString, "/abc") XCTAssertEqual(AbsolutePath("/../abc/..").pathString, "/") XCTAssertEqual(AbsolutePath("/../abc/../def").pathString, "/def") XCTAssertEqual(RelativePath("..").pathString, "..") XCTAssertEqual(RelativePath("../..").pathString, "../..") XCTAssertEqual(RelativePath(".././..").pathString, "../..") XCTAssertEqual(RelativePath("../abc/..").pathString, "..") XCTAssertEqual(RelativePath("../abc/.././").pathString, "..") XCTAssertEqual(RelativePath("abc/..").pathString, ".") } func testCombinationsAndEdgeCases() { XCTAssertEqual(AbsolutePath("///").pathString, "/") XCTAssertEqual(AbsolutePath("/./").pathString, "/") XCTAssertEqual(RelativePath("").pathString, ".") XCTAssertEqual(RelativePath(".").pathString, ".") XCTAssertEqual(RelativePath("./abc").pathString, "abc") XCTAssertEqual(RelativePath("./abc/").pathString, "abc") XCTAssertEqual(RelativePath("./abc/../bar").pathString, "bar") XCTAssertEqual(RelativePath("foo/../bar").pathString, "bar") XCTAssertEqual(RelativePath("foo///..///bar///baz").pathString, "bar/baz") XCTAssertEqual(RelativePath("foo/../bar/./").pathString, "bar") XCTAssertEqual(RelativePath("../abc/def/").pathString, "../abc/def") XCTAssertEqual(RelativePath("././././.").pathString, ".") XCTAssertEqual(RelativePath("./././../.").pathString, "..") XCTAssertEqual(RelativePath("./").pathString, ".") XCTAssertEqual(RelativePath(".//").pathString, ".") XCTAssertEqual(RelativePath("./.").pathString, ".") XCTAssertEqual(RelativePath("././").pathString, ".") XCTAssertEqual(RelativePath("../").pathString, "..") XCTAssertEqual(RelativePath("../.").pathString, "..") XCTAssertEqual(RelativePath("./..").pathString, "..") XCTAssertEqual(RelativePath("./../.").pathString, "..") XCTAssertEqual(RelativePath("./////../////./////").pathString, "..") XCTAssertEqual(RelativePath("../a").pathString, "../a") XCTAssertEqual(RelativePath("../a/..").pathString, "..") XCTAssertEqual(RelativePath("a/..").pathString, ".") XCTAssertEqual(RelativePath("a/../////../////./////").pathString, "..") } func testDirectoryNameExtraction() { XCTAssertEqual(AbsolutePath("/").dirname, "/") XCTAssertEqual(AbsolutePath("/a").dirname, "/") XCTAssertEqual(AbsolutePath("/./a").dirname, "/") XCTAssertEqual(AbsolutePath("/../..").dirname, "/") XCTAssertEqual(AbsolutePath("/ab/c//d/").dirname, "/ab/c") XCTAssertEqual(RelativePath("ab/c//d/").dirname, "ab/c") XCTAssertEqual(RelativePath("../a").dirname, "..") XCTAssertEqual(RelativePath("../a/..").dirname, ".") XCTAssertEqual(RelativePath("a/..").dirname, ".") XCTAssertEqual(RelativePath("./..").dirname, ".") XCTAssertEqual(RelativePath("a/../////../////./////").dirname, ".") XCTAssertEqual(RelativePath("abc").dirname, ".") XCTAssertEqual(RelativePath("").dirname, ".") XCTAssertEqual(RelativePath(".").dirname, ".") } func testBaseNameExtraction() { XCTAssertEqual(AbsolutePath("/").basename, "/") XCTAssertEqual(AbsolutePath("/a").basename, "a") XCTAssertEqual(AbsolutePath("/./a").basename, "a") XCTAssertEqual(AbsolutePath("/../..").basename, "/") XCTAssertEqual(RelativePath("../..").basename, "..") XCTAssertEqual(RelativePath("../a").basename, "a") XCTAssertEqual(RelativePath("../a/..").basename, "..") XCTAssertEqual(RelativePath("a/..").basename, ".") XCTAssertEqual(RelativePath("./..").basename, "..") XCTAssertEqual(RelativePath("a/../////../////./////").basename, "..") XCTAssertEqual(RelativePath("abc").basename, "abc") XCTAssertEqual(RelativePath("").basename, ".") XCTAssertEqual(RelativePath(".").basename, ".") } func testSuffixExtraction() { XCTAssertEqual(RelativePath("a").suffix, nil) XCTAssertEqual(RelativePath("a").extension, nil) XCTAssertEqual(RelativePath("a.").suffix, nil) XCTAssertEqual(RelativePath("a.").extension, nil) XCTAssertEqual(RelativePath(".a").suffix, nil) XCTAssertEqual(RelativePath(".a").extension, nil) XCTAssertEqual(RelativePath("").suffix, nil) XCTAssertEqual(RelativePath("").extension, nil) XCTAssertEqual(RelativePath(".").suffix, nil) XCTAssertEqual(RelativePath(".").extension, nil) XCTAssertEqual(RelativePath("..").suffix, nil) XCTAssertEqual(RelativePath("..").extension, nil) XCTAssertEqual(RelativePath("a.foo").suffix, ".foo") XCTAssertEqual(RelativePath("a.foo").extension, "foo") XCTAssertEqual(RelativePath(".a.foo").suffix, ".foo") XCTAssertEqual(RelativePath(".a.foo").extension, "foo") XCTAssertEqual(RelativePath(".a.foo.bar").suffix, ".bar") XCTAssertEqual(RelativePath(".a.foo.bar").extension, "bar") XCTAssertEqual(RelativePath("a.foo.bar").suffix, ".bar") XCTAssertEqual(RelativePath("a.foo.bar").extension, "bar") XCTAssertEqual(RelativePath(".a.foo.bar.baz").suffix, ".baz") XCTAssertEqual(RelativePath(".a.foo.bar.baz").extension, "baz") } func testParentDirectory() { XCTAssertEqual(AbsolutePath("/").parentDirectory, AbsolutePath("/")) XCTAssertEqual(AbsolutePath("/").parentDirectory.parentDirectory, AbsolutePath("/")) XCTAssertEqual(AbsolutePath("/bar").parentDirectory, AbsolutePath("/")) XCTAssertEqual(AbsolutePath("/bar/../foo/..//").parentDirectory.parentDirectory, AbsolutePath("/")) XCTAssertEqual(AbsolutePath("/bar/../foo/..//yabba/a/b").parentDirectory.parentDirectory, AbsolutePath("/yabba")) } func testConcatenation() { XCTAssertEqual(AbsolutePath(AbsolutePath("/"), RelativePath("")).pathString, "/") XCTAssertEqual(AbsolutePath(AbsolutePath("/"), RelativePath(".")).pathString, "/") XCTAssertEqual(AbsolutePath(AbsolutePath("/"), RelativePath("..")).pathString, "/") XCTAssertEqual(AbsolutePath(AbsolutePath("/"), RelativePath("bar")).pathString, "/bar") XCTAssertEqual(AbsolutePath(AbsolutePath("/foo/bar"), RelativePath("..")).pathString, "/foo") XCTAssertEqual(AbsolutePath(AbsolutePath("/bar"), RelativePath("../foo")).pathString, "/foo") XCTAssertEqual(AbsolutePath(AbsolutePath("/bar"), RelativePath("../foo/..//")).pathString, "/") XCTAssertEqual(AbsolutePath(AbsolutePath("/bar/../foo/..//yabba/"), RelativePath("a/b")).pathString, "/yabba/a/b") XCTAssertEqual(AbsolutePath("/").appending(RelativePath("")).pathString, "/") XCTAssertEqual(AbsolutePath("/").appending(RelativePath(".")).pathString, "/") XCTAssertEqual(AbsolutePath("/").appending(RelativePath("..")).pathString, "/") XCTAssertEqual(AbsolutePath("/").appending(RelativePath("bar")).pathString, "/bar") XCTAssertEqual(AbsolutePath("/foo/bar").appending(RelativePath("..")).pathString, "/foo") XCTAssertEqual(AbsolutePath("/bar").appending(RelativePath("../foo")).pathString, "/foo") XCTAssertEqual(AbsolutePath("/bar").appending(RelativePath("../foo/..//")).pathString, "/") XCTAssertEqual(AbsolutePath("/bar/../foo/..//yabba/").appending(RelativePath("a/b")).pathString, "/yabba/a/b") XCTAssertEqual(AbsolutePath("/").appending(component: "a").pathString, "/a") XCTAssertEqual(AbsolutePath("/a").appending(component: "b").pathString, "/a/b") XCTAssertEqual(AbsolutePath("/").appending(components: "a", "b").pathString, "/a/b") XCTAssertEqual(AbsolutePath("/a").appending(components: "b", "c").pathString, "/a/b/c") XCTAssertEqual(AbsolutePath("/a/b/c").appending(components: "", "c").pathString, "/a/b/c/c") XCTAssertEqual(AbsolutePath("/a/b/c").appending(components: "").pathString, "/a/b/c") XCTAssertEqual(AbsolutePath("/a/b/c").appending(components: ".").pathString, "/a/b/c") XCTAssertEqual(AbsolutePath("/a/b/c").appending(components: "..").pathString, "/a/b") XCTAssertEqual(AbsolutePath("/a/b/c").appending(components: "..", "d").pathString, "/a/b/d") XCTAssertEqual(AbsolutePath("/").appending(components: "..").pathString, "/") XCTAssertEqual(AbsolutePath("/").appending(components: ".").pathString, "/") XCTAssertEqual(AbsolutePath("/").appending(components: "..", "a").pathString, "/a") } func testPathComponents() { XCTAssertEqual(AbsolutePath("/").components, ["/"]) XCTAssertEqual(AbsolutePath("/.").components, ["/"]) XCTAssertEqual(AbsolutePath("/..").components, ["/"]) XCTAssertEqual(AbsolutePath("/bar").components, ["/", "bar"]) XCTAssertEqual(AbsolutePath("/foo/bar/..").components, ["/", "foo"]) XCTAssertEqual(AbsolutePath("/bar/../foo").components, ["/", "foo"]) XCTAssertEqual(AbsolutePath("/bar/../foo/..//").components, ["/"]) XCTAssertEqual(AbsolutePath("/bar/../foo/..//yabba/a/b/").components, ["/", "yabba", "a", "b"]) XCTAssertEqual(RelativePath("").components, ["."]) XCTAssertEqual(RelativePath(".").components, ["."]) XCTAssertEqual(RelativePath("..").components, [".."]) XCTAssertEqual(RelativePath("bar").components, ["bar"]) XCTAssertEqual(RelativePath("foo/bar/..").components, ["foo"]) XCTAssertEqual(RelativePath("bar/../foo").components, ["foo"]) XCTAssertEqual(RelativePath("bar/../foo/..//").components, ["."]) XCTAssertEqual(RelativePath("bar/../foo/..//yabba/a/b/").components, ["yabba", "a", "b"]) XCTAssertEqual(RelativePath("../..").components, ["..", ".."]) XCTAssertEqual(RelativePath(".././/..").components, ["..", ".."]) XCTAssertEqual(RelativePath("../a").components, ["..", "a"]) XCTAssertEqual(RelativePath("../a/..").components, [".."]) XCTAssertEqual(RelativePath("a/..").components, ["."]) XCTAssertEqual(RelativePath("./..").components, [".."]) XCTAssertEqual(RelativePath("a/../////../////./////").components, [".."]) XCTAssertEqual(RelativePath("abc").components, ["abc"]) } func testRelativePathFromAbsolutePaths() { XCTAssertEqual(AbsolutePath("/").relative(to: AbsolutePath("/")), RelativePath(".")); XCTAssertEqual(AbsolutePath("/a/b/c/d").relative(to: AbsolutePath("/")), RelativePath("a/b/c/d")); XCTAssertEqual(AbsolutePath("/").relative(to: AbsolutePath("/a/b/c")), RelativePath("../../..")); XCTAssertEqual(AbsolutePath("/a/b/c/d").relative(to: AbsolutePath("/a/b")), RelativePath("c/d")); XCTAssertEqual(AbsolutePath("/a/b/c/d").relative(to: AbsolutePath("/a/b/c")), RelativePath("d")); XCTAssertEqual(AbsolutePath("/a/b/c/d").relative(to: AbsolutePath("/a/c/d")), RelativePath("../../b/c/d")); XCTAssertEqual(AbsolutePath("/a/b/c/d").relative(to: AbsolutePath("/b/c/d")), RelativePath("../../../a/b/c/d")); } func testComparison() { XCTAssertTrue(AbsolutePath("/") <= AbsolutePath("/")); XCTAssertTrue(AbsolutePath("/abc") < AbsolutePath("/def")); XCTAssertTrue(AbsolutePath("/2") <= AbsolutePath("/2.1")); XCTAssertTrue(AbsolutePath("/3.1") > AbsolutePath("/2")); XCTAssertTrue(AbsolutePath("/2") >= AbsolutePath("/2")); XCTAssertTrue(AbsolutePath("/2.1") >= AbsolutePath("/2")); } func testContains() { XCTAssertTrue(AbsolutePath("/a/b/c/d/e/f").contains(AbsolutePath("/a/b/c/d"))) XCTAssertTrue(AbsolutePath("/a/b/c/d/e/f.swift").contains(AbsolutePath("/a/b/c"))) XCTAssertTrue(AbsolutePath("/").contains(AbsolutePath("/"))) XCTAssertTrue(AbsolutePath("/foo/bar").contains(AbsolutePath("/"))) XCTAssertFalse(AbsolutePath("/foo/bar").contains(AbsolutePath("/foo/bar/baz"))) XCTAssertFalse(AbsolutePath("/foo/bar").contains(AbsolutePath("/bar"))) } func testAbsolutePathValidation() { XCTAssertNoThrow(try AbsolutePath(validating: "/a/b/c/d")) XCTAssertThrowsError(try AbsolutePath(validating: "~/a/b/d")) { error in XCTAssertEqual("\(error)", "invalid absolute path '~/a/b/d'; absolute path must begin with '/'") } XCTAssertThrowsError(try AbsolutePath(validating: "a/b/d")) { error in XCTAssertEqual("\(error)", "invalid absolute path 'a/b/d'") } } func testRelativePathValidation() { XCTAssertNoThrow(try RelativePath(validating: "a/b/c/d")) XCTAssertThrowsError(try RelativePath(validating: "/a/b/d")) { error in XCTAssertEqual("\(error)", "invalid relative path '/a/b/d'; relative path should not begin with '/' or '~'") } XCTAssertThrowsError(try RelativePath(validating: "~/a/b/d")) { error in XCTAssertEqual("\(error)", "invalid relative path '~/a/b/d'; relative path should not begin with '/' or '~'") } } func testCodable() throws { struct Foo: Codable, Equatable { var path: AbsolutePath } struct Bar: Codable, Equatable { var path: RelativePath } do { let foo = Foo(path: AbsolutePath("/path/to/foo")) let data = try JSONEncoder().encode(foo) let decodedFoo = try JSONDecoder().decode(Foo.self, from: data) XCTAssertEqual(foo, decodedFoo) } do { let foo = Foo(path: AbsolutePath("/path/to/../to/foo")) let data = try JSONEncoder().encode(foo) let decodedFoo = try JSONDecoder().decode(Foo.self, from: data) XCTAssertEqual(foo, decodedFoo) XCTAssertEqual(foo.path.pathString, "/path/to/foo") XCTAssertEqual(decodedFoo.path.pathString, "/path/to/foo") } do { let bar = Bar(path: RelativePath("path/to/bar")) let data = try JSONEncoder().encode(bar) let decodedBar = try JSONDecoder().decode(Bar.self, from: data) XCTAssertEqual(bar, decodedBar) } do { let bar = Bar(path: RelativePath("path/to/../to/bar")) let data = try JSONEncoder().encode(bar) let decodedBar = try JSONDecoder().decode(Bar.self, from: data) XCTAssertEqual(bar, decodedBar) XCTAssertEqual(bar.path.pathString, "path/to/bar") XCTAssertEqual(decodedBar.path.pathString, "path/to/bar") } } // FIXME: We also need tests for join() operations. // FIXME: We also need tests for dirname, basename, suffix, etc. // FIXME: We also need test for stat() operations. }
52.613833
122
0.610834
bbe408398bb128a731322d5eab5029621491a2a2
2,116
// // WokroutHistoryRow.swift // BodyProgress // // Created by Karthick Selvaraj on 15/05/20. // Copyright © 2020 Mallow Technologies Private Limited. All rights reserved. // import SwiftUI struct WokroutHistoryRow: View { @Environment(\.managedObjectContext) var managedObjectContext @EnvironmentObject var appSettings: AppSettings @ObservedObject var workoutHistory: WorkoutHistory var body: some View { NavigationLink(destination: WorkoutHistroyDetails(selectedWorkout: workoutHistory).environmentObject(self.appSettings).environment(\.managedObjectContext, self.managedObjectContext)) { HStack(alignment: .center) { VStack(alignment: .leading, spacing: 4) { Text(workoutHistory.wName) .font(kPrimaryHeadlineFont) .fontWeight(.bold) HStack { Text("\(workoutHistory.wBodyPart.rawValue)") .font(kPrimarySubheadlineFont) .foregroundColor(.secondary) Circle() .fill(Color.secondary) .frame(width: 5, height: 5) Text("\(workoutHistory.wCreatedAt, formatter: DateFormatter().appDormatter)") .font(kPrimarySubheadlineFont) .foregroundColor(.secondary) } } .padding([.top, .bottom], 5) Spacer() Image(systemName: workoutHistory.isAllSetCompleted() ? "checkmark.seal.fill" : "xmark.seal.fill") .imageScale(.large) .foregroundColor(workoutHistory.isAllSetCompleted() ? Color(AppThemeColours.green.uiColor()) : Color(AppThemeColours.orange.uiColor())) .font(kPrimaryBodyFont) .padding(.trailing, 10) } } } } struct WokroutHistoryRow_Previews: PreviewProvider { static var previews: some View { Text("Sample") } }
38.472727
192
0.562382
791d00011473f3715020417d7874762428fda98e
4,681
// RUN: %target-swift-frontend %s -g -emit-ir -o - | %FileCheck %s // Ensure that the debug info we're emitting passes the back end verifier. // RUN: %target-swift-frontend %s -g -S -o - | %FileCheck %s --check-prefix ASM-%target-object-format // ASM-macho: .section __DWARF,__debug_info // ASM-elf: .section .debug_info,"",{{[@%]}}progbits // ASM-coff: .section .debug_info,"dr" // Test variables-interpreter.swift runs this code with `swift -g -i`. // Test variables-repl.swift runs this code with `swift -g < variables.swift`. // CHECK-DAG: ![[TLC:.*]] = !DIModule({{.*}}, name: "variables" // Global variables. var glob_i8: Int8 = 8 // CHECK-DAG: !DIGlobalVariable(name: "glob_i8",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I8:[^,]+]] var glob_i16: Int16 = 16 // CHECK-DAG: !DIGlobalVariable(name: "glob_i16",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I16:[^,]+]] var glob_i32: Int32 = 32 // CHECK-DAG: !DIGlobalVariable(name: "glob_i32",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I32:[^,]+]] var glob_i64: Int64 = 64 // CHECK-DAG: !DIGlobalVariable(name: "glob_i64",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I64:[^,]+]] var glob_f: Float = 2.89 // CHECK-DAG: !DIGlobalVariable(name: "glob_f",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[F:[^,]+]] var glob_d: Double = 3.14 // CHECK-DAG: !DIGlobalVariable(name: "glob_d",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[D:[^,]+]] var glob_b: Bool = true // CHECK-DAG: !DIGlobalVariable(name: "glob_b",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[B:[^,]+]] var glob_s: String = "😄" // CHECK-DAG: !DIGlobalVariable(name: "glob_s",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[S:[^,]+]] // FIXME: Dreadful type-checker performance prevents this from being this single // print expression: // print("\(glob_v), \(glob_i8), \(glob_i16), \(glob_i32), \(glob_i64), \(glob_f), \(glob_d), \(glob_b), \(glob_s)", terminator: "") print(", \(glob_i8)", terminator: "") print(", \(glob_i16)", terminator: "") print(", \(glob_i32)", terminator: "") print(", \(glob_i64)", terminator: "") print(", \(glob_f)", terminator: "") print(", \(glob_d)", terminator: "") print(", \(glob_b)", terminator: "") print(", \(glob_s)", terminator: "") var unused: Int32 = -1 // CHECK-DAG: ![[RT:[0-9]+]] ={{.*}}"Swift.swiftmodule" // Stack variables. func foo(_ dt: Float) -> Float { // CHECK-DAG: call void @llvm.dbg.declare // CHECK-DAG: !DILocalVariable(name: "f" let f: Float = 9.78 // CHECK-DAG: !DILocalVariable(name: "r" let r: Float = f*dt return r } var g = foo(1.0); // Tuple types. var tuple: (Int, Bool) = (1, true) // CHECK-DAG: !DIGlobalVariable(name: "tuple", linkageName: "$s{{9variables|4main}}5tupleSi_Sbtvp",{{.*}} type: ![[TUPTY:[^,)]+]] // CHECK-DAG: ![[TUPTY]] = !DICompositeType({{.*}}identifier: "$sSi_SbtD" func myprint(_ p: (i: Int, b: Bool)) { print("\(p.i) -> \(p.b)") } myprint(tuple) // Arrays are represented as an instantiation of Array. // CHECK-DAG: ![[ARRAYTY:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Array", // CHECK-DAG: !DIGlobalVariable(name: "array_of_tuples",{{.*}} type: ![[ARRAYTY]] var array_of_tuples : [(a : Int, b : Int)] = [(1,2)] var twod : [[Int]] = [[1]] func bar(_ x: [(a : Int, b : Int)], y: [[Int]]) { } // CHECK-DAG: !DIGlobalVariable(name: "P",{{.*}} type: ![[PTY:[0-9]+]] // CHECK-DAG: ![[PTUP:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "$sSd1x_Sd1ySd1ztD", // CHECK-DAG: ![[PTY]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$s{{9variables|4main}}5PointaD",{{.*}} baseType: ![[PTUP]] typealias Point = (x: Double, y: Double, z: Double) var P:Point = (1, 2, 3) func myprint(_ p: (x: Double, y: Double, z: Double)) { print("(\(p.x), \(p.y), \(p.z))") } myprint(P) // CHECK-DAG: !DIGlobalVariable(name: "P2",{{.*}} type: ![[APTY:[0-9]+]] // CHECK-DAG: ![[APTY]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$s{{9variables|4main}}13AliasForPointaD",{{.*}} baseType: ![[PTY:[0-9]+]] typealias AliasForPoint = Point var P2:AliasForPoint = (4, 5, 6) myprint(P2) // Unions. enum TriValue { case false_ case true_ case top } // CHECK-DAG: !DIGlobalVariable(name: "unknown",{{.*}} type: ![[TRIVAL:[0-9]+]] // CHECK-DAG: ![[TRIVAL]] = !DICompositeType({{.*}}name: "TriValue", var unknown = TriValue.top func myprint(_ value: TriValue) { switch value { case TriValue.false_: print("false") case TriValue.true_: print("true") case TriValue.top: print("⊤") } } myprint(unknown) // CHECK-DAG: !DIFile(filename: "variables.swift"
39.669492
142
0.590258
c11a1020992f1f98477e58977a0b6d380a4d3366
935
// // ArticleDetailViewModelDependencies.swift // NewsApp // // Created by HARUTYUNYAN LAPUSHNYAN Garnik on 26/06/2020. // Copyright © 2020 HARUTYUNYAN LAPUSHNYAN Garnik. All rights reserved. // import Foundation protocol ArticleDetailViewModelDependenciesProtocol { var repository: ArticleDetailClient { get } var sessionManager: SessionManagerProtocol { get } var favoritesPersistence: FavoritesPersistenceProtocol { get } } final class ArticleDetailViewModelDependencies: ArticleDetailViewModelDependenciesProtocol { lazy var repository: ArticleDetailClient = DefaultArticleDetailClient(dependencies: DefaultArticleDetailClientDependencies()) lazy var sessionManager: SessionManagerProtocol = DefaultSessionManager(dependencies: DefaultSessionManagerDependencies()) lazy var favoritesPersistence: FavoritesPersistenceProtocol = FavoritesPersistence(dependencies: FavoritesPersistenceDependencies()) }
42.5
136
0.825668
b9a2968326c27b5e4792915e34d109c06b13d11a
4,735
// // CollectionViewController.swift // My-MosaicLayout // // Created by Panda on 16/3/9. // Copyright © 2016年 v2panda. All rights reserved. // import UIKit import FMMosaicLayout class CollectionViewController: UICollectionViewController, FMMosaicLayoutDelegate{ var imageArray = [String]() override func viewDidLoad() { super.viewDidLoad() print(ABC) imageArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21"] let mosaicLayout : FMMosaicLayout = FMMosaicLayout() self.collectionView?.collectionViewLayout = mosaicLayout // Register cell classes // self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 10 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imageArray.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cells", forIndexPath: indexPath) as! CollectionViewCell let randomBlue = CGFloat(drand48()) let randomRed = CGFloat(drand48()) let randomGreen = CGFloat(drand48()) cell.backgroundColor = UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0) cell.alpha = 0 cell.myImageView.image = UIImage(named: imageArray[indexPath.row]) let cellDelay = UInt64((arc4random() % 600)/1000) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(cellDelay * NSEC_PER_SEC )), dispatch_get_main_queue()) { () -> Void in UIView.animateWithDuration(0.8, animations: { () -> Void in cell.alpha = 1.0 }) } return cell } // MARK: FMMosaicLayoutDelegate func collectionView(collectionView: UICollectionView!, layout collectionViewLayout: FMMosaicLayout!, numberOfColumnsInSection section: Int) -> Int { return 1 } func collectionView(collectionView: UICollectionView!, layout collectionViewLayout: FMMosaicLayout!, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 1.0, left: 1.0, bottom: 1.0, right: 1.0) } func collectionView(collectionView: UICollectionView!, layout collectionViewLayout: FMMosaicLayout!, interitemSpacingForSectionAtIndex section: Int) -> CGFloat { return 1.0 } func collectionView(collectionView: UICollectionView!, layout collectionViewLayout: FMMosaicLayout!, mosaicCellSizeForItemAtIndexPath indexPath: NSIndexPath! ) -> FMMosaicCellSize { return indexPath.item % 7 == 0 ? FMMosaicCellSize.Big : FMMosaicCellSize.Small } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { return false } override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { } */ }
36.423077
185
0.690813
0ec42d807ff8b92e41a14dc617d576c09588f71d
457
// // URLEncodable.swift // Lever // // Created by devedbox on 2018/8/11. // import Foundation //public protocol URLEncoder { // func encode(url: URLConvertiable, with params: [AnyHashable: Any]) throws -> URLConvertiable //} // //public protocol URLEncodable { // //} // //extension URLEncodable { // public func encode(contents: [AnyHashable: Any], with encoder: URLEncoder) throws -> URLConvertiable { // return try encoder // } //}
19.869565
108
0.665208
506139d1481f08a2466ea4f628dd35fde355abb0
3,556
// // RouterMock.swift // ApplicationCoordinator // // Created by Andrey on 02.09.16. // Copyright © 2016 Andrey Panov. All rights reserved. // import UIKit @testable import ApplicationCoordinator protocol RouterMock: Router { var navigationStack: [UIViewController] {get} var presented: UIViewController? {get} } final class RouterMockImp: RouterMock { // in test cases router store the rootController referense private(set) var navigationStack: [UIViewController] = [] private(set) var presented: UIViewController? private var completions: [UIViewController : () -> Void] = [:] func toPresent() -> UIViewController? { return nil } //all of the actions without animation func present(_ module: Presentable?) { present(module, animated: false) } func present(_ module: Presentable?, animated: Bool) { guard let controller = module?.toPresent() else { return } presented = controller } func push(_ module: Presentable?) { push(module, animated: false) } func push(_ module: Presentable?, animated: Bool) { push(module, animated: animated, completion: nil) } func push(_ module: Presentable?, hideBottomBar: Bool) { guard let controller = module?.toPresent(), (controller is UINavigationController == false) else { assertionFailure("Deprecated push UINavigationController."); return } controller.hidesBottomBarWhenPushed = hideBottomBar push(module, animated: false) } func push(_ module: Presentable?, animated: Bool, hideBottomBar: Bool, completion: (() -> Void)?) { guard let controller = module?.toPresent(), (controller is UINavigationController == false) else { assertionFailure("Deprecated push UINavigationController."); return } controller.hidesBottomBarWhenPushed = hideBottomBar navigationStack.append(controller) } func push(_ module: Presentable?, animated: Bool, completion: (() -> Void)?) { guard let controller = module?.toPresent(), (controller is UINavigationController == false) else { assertionFailure("Deprecated push UINavigationController."); return } navigationStack.append(controller) } func popModule() { popModule(animated: false) } func popModule(animated: Bool) { let controller = navigationStack.removeLast() runCompletion(for: controller) } func dismissModule() { dismissModule(animated: false, completion: nil) } func dismissModule(animated: Bool, completion: (() -> Void)?) { presented = nil } func setRootModule(_ module: Presentable?) { guard let controller = module?.toPresent() else { return } navigationStack.append(controller) } func setRootModule(_ module: Presentable?, hideBar: Bool) { assertionFailure("This method is not used.") } func popToRootModule(animated: Bool) { guard let first = navigationStack.first else { return } navigationStack.forEach { controller in runCompletion(for: controller) } navigationStack = [first] } private func runCompletion(for controller: UIViewController) { guard let completion = completions[controller] else { return } completion() completions.removeValue(forKey: controller) } }
30.655172
103
0.638639
feac0f718a5b0409851dbef520977fb339275c59
803
// RUN: %target-swift-frontend -primary-file %s %S/Inputs/specialize_inherited_multifile.swift -O -emit-sil -sil-verify-all | %FileCheck %s @_optimize(none) func takesBase<T : Base>(t: T) {} @inline(never) func takesHasAssocType<T : HasAssocType>(t: T) { takesBase(t: t.value) } // Make sure the ConcreteDerived : Base conformance is available here. // CHECK-LABEL: sil shared [noinline] @_T030specialize_inherited_multifile17takesHasAssocTypeyx1t_tAA0efG0RzlFAA08ConcreteefG0C_Tg5 : $@convention(thin) (@owned ConcreteHasAssocType) -> () // CHECK: [[FN:%.*]] = function_ref @_T030specialize_inherited_multifile9takesBaseyx1t_tAA0E0RzlF // CHECK: apply [[FN]]<ConcreteDerived>({{%.*}}) // CHECK: return public func takesConcreteHasAssocType(c: ConcreteHasAssocType) { takesHasAssocType(t: c) }
42.263158
188
0.757161
b94999465f123032f957981e78ef7bf96f2f6ffe
6,671
// // 🦠 Corona-Warn-App // import UIKit import OpenCombine class TanInputViewController: UIViewController, ENANavigationControllerWithFooterChild { // MARK: - Init init( viewModel: TanInputViewModel, dismiss: @escaping () -> Void ) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) navigationItem.rightBarButtonItem = CloseBarButtonItem(onTap: dismiss) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Overrides override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = ColorCompatibility.systemBackground setupViews() setupViewModelBindings() footerView?.isHidden = false } override var navigationItem: UINavigationItem { navigationFooterItem } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) DispatchQueue.main.async { [weak self] in self?.tanInputView.becomeFirstResponder() } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) tanInputView.resignFirstResponder() } // MARK: - Protocol ENANavigationControllerWithFooterChild func navigationController(_ navigationController: ENANavigationControllerWithFooter, didTapPrimaryButton button: UIButton) { viewModel.submitTan() } // MARK: - Private private let viewModel: TanInputViewModel private var bindings: Set<AnyCancellable> = [] private var tanInputView: TanInputView! private var errorLabel: ENALabel! private var scrollView: UIScrollView! private var stackView: UIStackView! private lazy var navigationFooterItem: ENANavigationFooterItem = { let item = ENANavigationFooterItem() item.primaryButtonTitle = AppStrings.ExposureSubmissionTanEntry.submit item.isPrimaryButtonEnabled = false item.isSecondaryButtonHidden = true item.title = AppStrings.ExposureSubmissionTanEntry.title return item }() private var observer: NSKeyValueObservation? private func setupViews() { // scrollView needs to respect footerView, this gets done with a bottom insert by 55 scrollView = UIScrollView(frame: view.frame) scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 55, right: 0.0) scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) // Scrollview content size will change if we set the errorLabel to a text. // We need to scroll the content area to show the error, if the footer view intersects with the error label. // Ff the error label resets to empty we will scroll back to a negative top value to make sure scrollview // is in top position (-103 is basically the default value). observer = scrollView.observe(\UIScrollView.contentSize, options: .new, changeHandler: { [weak self] scrollView, _ in if self?.errorLabel.text != nil { guard let self = self, let footerView = self.footerView else { return } DispatchQueue.main.async { let footerViewRect = footerView.convert(footerView.bounds, to: scrollView) if footerViewRect.intersects(self.stackView.frame) { Log.debug("ContentSize changed - we might need to scroll to the visible rect by now") let delta = footerViewRect.height - (self.stackView.frame.origin.y + self.stackView.frame.size.height) + scrollView.contentOffset.y let bottomOffset = CGPoint(x: 0, y: delta) scrollView.setContentOffset(bottomOffset, animated: true) } } } else { let bottomOffset = CGPoint(x: 0, y: -103) scrollView.setContentOffset(bottomOffset, animated: true) } }) NSLayoutConstraint.activate([ view.safeAreaLayoutGuide.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), view.safeAreaLayoutGuide.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), view.topAnchor.constraint(equalTo: scrollView.topAnchor), view.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor) ]) stackView = UIStackView() stackView.axis = .vertical stackView.spacing = 18.0 stackView.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(stackView) NSLayoutConstraint.activate([ stackView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor), stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 15.0), stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: 15.0), stackView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 15), stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor) ]) let descriptionLabel = ENALabel() descriptionLabel.style = .headline descriptionLabel.text = AppStrings.ExposureSubmissionTanEntry.description descriptionLabel.translatesAutoresizingMaskIntoConstraints = false descriptionLabel.textColor = .enaColor(for: .textPrimary1) descriptionLabel.numberOfLines = 0 tanInputView = TanInputView(frame: .zero, viewModel: viewModel) tanInputView.isUserInteractionEnabled = true tanInputView.translatesAutoresizingMaskIntoConstraints = false errorLabel = ENALabel() errorLabel.style = .headline errorLabel.text = "" errorLabel.translatesAutoresizingMaskIntoConstraints = false errorLabel.textColor = .enaColor(for: .textSemanticRed) errorLabel.numberOfLines = 0 stackView.addArrangedSubview(descriptionLabel) stackView.addArrangedSubview(tanInputView) stackView.addArrangedSubview(errorLabel) } private func setupViewModelBindings() { // viewModel will notify controller to enabled / disabler primary footer button viewModel.$isPrimaryButtonEnabled.sink { [weak self] isEnabled in DispatchQueue.main.async { self?.navigationFooterItem?.isPrimaryButtonEnabled = isEnabled } }.store(in: &bindings) // viewModel will notify controller to enable / disable loadingIndicator on primary footer button viewModel.$isPrimaryBarButtonIsLoading.sink { [weak self] isLoading in DispatchQueue.main.async { self?.navigationFooterItem?.isPrimaryButtonLoading = isLoading } }.store(in: &bindings) // viewModel will notify about changes on errorText. errorText can contain the TAN for submission, there for it is private data. viewModel.$errorText.sink { [weak self] newErrorText in Log.debug("viewModel errorText did update to: \(private: newErrorText, public: "teletan id")") DispatchQueue.main.async { self?.errorLabel.text = newErrorText } }.store(in: &bindings) viewModel.didDissMissInvalidTanAlert = { [weak self] in self?.navigationFooterItem?.isPrimaryButtonLoading = false self?.navigationFooterItem?.isPrimaryButtonEnabled = true self?.tanInputView.becomeFirstResponder() } } }
35.110526
137
0.76915
bf614d75552c31f6895d96365a5618d48b4988b9
3,040
// // CategoryListViewController.swift // EBook // // Created by Daniel on 2021/9/8. // import UIKit import RxDataSources class CategoryListViewController: BaseViewController, BindableType { var viewModel: CategoryListViewModelType! var isChild = false private lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: App.screenWidth - 16, height: 90) layout.sectionInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) let view = UICollectionView(frame: .zero, collectionViewLayout: layout) view.showsVerticalScrollIndicator = false; view.showsHorizontalScrollIndicator = false; view.backgroundColor = R.color.windowBgColor() view.register(R.nib.bookIntroCell) adjustScrollView(view, with: self) return view }() private var dataSource: RxCollectionViewSectionedReloadDataSource<SectionModel<String, Book>>! private var collectionViewConfigure: CollectionViewSectionedDataSource<SectionModel<String, Book>>.ConfigureCell { return { _, collectionView, indexPath, item in guard var cell = collectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.bookIntroCell, for: indexPath) else { fatalError() } cell.bind(to: BookIntroCellViewModel(book: item)) return cell } } private var refreshHeader: SPRefreshHeader! private var refreshFooter: MJRefreshAutoNormalFooter! override func viewDidLoad() { super.viewDidLoad() setup() } func bindViewModel() { let output = viewModel.output let input = viewModel.input rx.disposeBag ~ [ output.sections ~> collectionView.rx.items(dataSource: dataSource), output.footerRefreshing ~> refreshFooter.rx.refreshStatus, output.headerRefreshing ~> refreshHeader.rx.refreshStatus, output.isFooterHidden ~> refreshFooter.rx.isHidden, collectionView.rx.modelSelected(Book.self) ~> input.itemSelectAction.inputs, ] } func loadData() {} } private extension CategoryListViewController { func setup() { navigationBar.isHidden = true view.addSubview(collectionView) collectionView.snp.makeConstraints { $0.edges.equalTo(UIEdgeInsets.zero) } dataSource = RxCollectionViewSectionedReloadDataSource<SectionModel<String, Book>>(configureCell: collectionViewConfigure) refreshHeader = SPRefreshHeader(refreshingTarget: self, refreshingAction: #selector(loadNew)) refreshFooter = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMore)) collectionView.mj_header = refreshHeader collectionView.mj_footer = refreshFooter } @objc func loadNew() { viewModel.input.loadNewData() } @objc func loadMore() { viewModel.input.loadMore() } }
35.348837
140
0.684868
0afc80aaf373306630252184ce0f94d582707a19
229
// // Created by Dariusz Rybicki on 27/11/15. // Copyright © 2015 EL Passion. All rights reserved. // import Foundation class Circle { let type: CircleType init(type: CircleType) { self.type = type } }
13.470588
53
0.628821
4886f484a689196e0a507656794c22e908714246
3,928
// // NavigationBar.swift // Tangem Tap // // Created by Andrew Son on 21/11/20. // Copyright © 2020 Tangem AG. All rights reserved. // import SwiftUI struct ArrowBack: View { let action: () -> Void let height: CGFloat var color: Color = .tangemTapGrayDark6 var body: some View { Button(action: action, label: { Image(systemName: "chevron.left") .frame(width: height, height: height) .font(.system(size: 20, weight: .medium)) .foregroundColor(color) }) .frame(width: height, height: height) } } struct NavigationBar<LeftButtons: View, RightButtons: View>: View { struct Settings { let titleFont: Font let titleColor: Color let backgroundColor: Color let horizontalPadding: CGFloat let height: CGFloat init(titleFont: Font = .system(size: 17, weight: .medium), titleColor: Color = .tangemTapGrayDark6, backgroundColor: Color = .tangemTapBgGray, horizontalPadding: CGFloat = 0, height: CGFloat = 44) { self.titleFont = titleFont self.titleColor = titleColor self.backgroundColor = backgroundColor self.horizontalPadding = horizontalPadding self.height = height } // static var `default`: Settings { .init() } } private let title: LocalizedStringKey private let settings: Settings private let leftButtons: LeftButtons private let rightButtons: RightButtons init( title: LocalizedStringKey, settings: Settings = .init(), @ViewBuilder leftItems: () -> LeftButtons, @ViewBuilder rightItems: () -> RightButtons ) { self.title = title self.settings = settings leftButtons = leftItems() rightButtons = rightItems() } var body: some View { ZStack { HStack { leftButtons Spacer() rightButtons } Text(title) .font(settings.titleFont) .foregroundColor(settings.titleColor) } .padding(.horizontal, settings.horizontalPadding) .frame(height: settings.height) .background(settings.backgroundColor.edgesIgnoringSafeArea(.all)) } } extension NavigationBar where LeftButtons == EmptyView { init( title: LocalizedStringKey, settings: Settings = .init(), @ViewBuilder rightButtons: () -> RightButtons ) { leftButtons = EmptyView() self.rightButtons = rightButtons() self.title = title self.settings = settings } } extension NavigationBar where RightButtons == EmptyView { init( title: LocalizedStringKey, settings: Settings = .init(), @ViewBuilder leftButtons: () -> LeftButtons ) { rightButtons = EmptyView() self.leftButtons = leftButtons() self.title = title self.settings = settings } } extension NavigationBar where LeftButtons == ArrowBack, RightButtons == EmptyView { init( title: LocalizedStringKey, settings: Settings = .init(), backAction: @escaping () -> Void ) { leftButtons = ArrowBack(action: { backAction() }, height: settings.height) rightButtons = EmptyView() self.title = title self.settings = settings } } extension NavigationBar where LeftButtons == ArrowBack, RightButtons == EmptyView { init( title: LocalizedStringKey, settings: Settings = .init(), presentationMode: Binding<PresentationMode> ) { leftButtons = ArrowBack(action: { presentationMode.wrappedValue.dismiss() }, height: settings.height) rightButtons = EmptyView() self.title = title self.settings = settings } } struct NavigationBar_Previews: PreviewProvider { static var previews: some View { Group { VStack { NavigationBar(title: "Hello, World!", backAction: {}) Spacer() }.deviceForPreview(.iPhone11Pro) VStack { NavigationBar(title: "Hello, World!", rightButtons: { Button(action: {}, label: { Image("verticalDots") .foregroundColor(Color.tangemTapGrayDark6) .frame(width: 44.0, height: 44.0, alignment: .center) }) }) Spacer() }.deviceForPreview(.iPhone11ProMax) } } }
23.520958
83
0.683299
ffb8da3a78813a283d0a357d629a9c53d3d2f928
312
// // Em.swift // SwiftHtml // // Created by Tibor Bodecs on 2021. 07. 19.. // /// The `<em>` tag is used to define emphasized text. The content inside is typically displayed in italic. /// /// A screen reader will pronounce the words in `<em>` with an emphasis, using verbal stress. open class Em: Tag { }
22.285714
106
0.669872
91c5850b536e08006aacd50a20c675e8ec8348cc
1,299
// // UIStoryboard+Expand.swift // Convenient // // Created by Tanfanfan on 2017/1/13. // Copyright © 2017年 Tanfanfan. All rights reserved. // import UIKit public protocol StoryboardIdentifiableType { static var storyboardIdentifiable: String { get } } extension StoryboardIdentifiableType where Self: UIViewController { public static var storyboardIdentifiable: String { return String(describing: self) } } extension UIViewController: StoryboardIdentifiableType { } public extension UIStoryboard { public enum Storyboard: String { case Main } public convenience init(storyboard: Storyboard, bundle bundleOrNil: Bundle? = nil) { self.init(name: storyboard.rawValue, bundle: bundleOrNil) } public class func storyboard(storyboard: Storyboard, bundle: Bundle? = nil) -> UIStoryboard { return UIStoryboard(name: storyboard.rawValue, bundle: bundle) } public func instantiateViewController<T: UIViewController>() -> T { guard let viewController = self.instantiateViewController(withIdentifier: T.storyboardIdentifiable) as? T else { fatalError("Couldn't instantiate view controller with identifier \(T.storyboardIdentifiable) ") } return viewController } }
26.510204
120
0.705928
1ecdb673af3c119afee7b3f95fd495d12d51e5c4
608
// // StravaResult.swift // StravaZpot // // Created by Tomás Ruiz López on 2/11/16. // Copyright © 2016 SweetZpot AS. All rights reserved. // import Foundation public enum StravaResult<T : Equatable> { case success(T) case error(StravaError) } extension StravaResult : Equatable {} public func ==<T>(lhs : StravaResult<T>, rhs : StravaResult<T>) -> Bool where T : Equatable { switch(lhs, rhs) { case let (.success(left), .success(right)): return left == right case let (.error(left), .error(right)): return left == right default: return false } }
21.714286
93
0.634868
56dc18b14fdcf0e7080f9fdb1126f53ce137295b
3,562
// // Config.swift // Desk360 // // Created by samet on 4.11.2019. // // import PersistenceKit public struct Config { public private(set) static var shared = Config() public private(set) var model = Stores.configStore.object public func updateConfig(_ newModel: ConfigModel) { Config.shared.model = newModel } } enum FieldType: Int, Codable { case line = 1 case box = 2 case shadow = 3 } enum ButtonType: Int, Codable { case radius1 = 1 case radius2 = 2 case sharp = 3 case fullWidth = 4 } /// Use `SupportMessage` to map JSON object returned from the methods in `SupportService`ss public struct ConfigModel { /// General settings all config. var generalSettings: GeneralConfigModel? /// First screen all config. var firstScreen: FirstScreenConfigModel? /// Createpre screen all config. var createPreScreen: CreatePreScreenConfigModel? /// Create screen all config. var createScreen: CreateScreenConfigModel? /// listing screen all config. var ticketListingScreen: TicketListScreenConfigModel? /// Listing detail screen all config. var ticketDetail: TicketTableViewCellConfigModel? /// Succsess screen all config. var successScreen: TicketSuccessScreenConfigModel? var customFields: [Field]? } extension ConfigModel: Codable { private enum CodingKeys: String, CodingKey { case first_screen case general_settings case create_pre_screen case create_screen case ticket_list_screen case ticket_detail_screen case ticket_success_screen case custom_fields } /// Creates a new instance by decoding from the given decoder. /// /// - Parameter decoder: The decoder to read data from. /// - Throws: Decoding error. public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) do { firstScreen = try? container.decode(FirstScreenConfigModel.self, forKey: .first_screen) generalSettings = try? container.decode(GeneralConfigModel.self, forKey: .general_settings) createPreScreen = try? container.decode(CreatePreScreenConfigModel.self, forKey: .create_pre_screen) createScreen = try? container.decode(CreateScreenConfigModel.self, forKey: .create_screen) ticketListingScreen = try? container.decode(TicketListScreenConfigModel.self, forKey: .ticket_list_screen) ticketDetail = try? container.decode(TicketTableViewCellConfigModel.self, forKey: .ticket_detail_screen) successScreen = try? container.decode(TicketSuccessScreenConfigModel.self, forKey: .ticket_success_screen) customFields = try (container.decodeIfPresent([Field].self, forKey: .custom_fields)) } catch let error as DecodingError { print(error) throw error } } /// Encodes this value into the given encoder. /// /// - Parameter encoder: The encoder to write data to. /// - Throws: Encoding error. public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) do { try container.encode(firstScreen, forKey: .first_screen) try container.encode(generalSettings, forKey: .general_settings) try container.encode(createPreScreen, forKey: .create_pre_screen) try container.encode(createScreen, forKey: .create_screen) try container.encode(ticketListingScreen, forKey: .ticket_list_screen) try container.encode(ticketDetail, forKey: .ticket_detail_screen) try container.encode(successScreen, forKey: .ticket_success_screen) try container.encodeIfPresent(customFields, forKey: .custom_fields) } catch let error as EncodingError { print(error) throw error } } }
28.95935
109
0.762212
e8226953d2b2845898106f39713543d40c6c20b9
863
// // Created by Jake Lin on 12/10/15. // Copyright © 2015 IBAnimatable. All rights reserved. // import UIKit public protocol NavigationBarDesignable { /** Specify whether is solid color only, if `true` will remove hairline from navigation bar */ var solidColor: Bool { get set } } public extension NavigationBarDesignable where Self: UINavigationBar { public func configureNavigationBar() { if solidColor { let emptyImage = UIImage() setBackgroundImage(emptyImage, for: .any, barMetrics: .default) shadowImage = emptyImage // Need to manually untick translucent in Interface Builder, // otherwise, it will have constrait issue in IB although it is correct in run time. // translucent = false } else { setBackgroundImage(nil, for: .any, barMetrics: .default) shadowImage = nil } } }
28.766667
90
0.692932
287d972f01b90835d0247f5d042c1fd94fe96804
5,131
// // Utils.swift // OpenTokReactNative // // Created by Manik Sachdeva on 11/3/18. // Copyright © 2018 TokBox Inc. All rights reserved. // import Foundation class Utils { static func sanitizeCameraResolution(_ resolution: Any) -> OTCameraCaptureResolution { guard let cameraResolution = resolution as? String else { return .medium }; switch cameraResolution { case "HIGH": return .high; case "LOW": return .low; default: return .medium; } } static func sanitizeFrameRate(_ frameRate: Any) -> OTCameraCaptureFrameRate { guard let cameraFrameRate = frameRate as? Int else { return OTCameraCaptureFrameRate(rawValue: 30)!; } return OTCameraCaptureFrameRate(rawValue: cameraFrameRate)!; } static func sanitizePreferredFrameRate(_ frameRate: Any) -> Float { guard let sanitizedFrameRate = frameRate as? Float else { return Float.greatestFiniteMagnitude; } return sanitizedFrameRate; } static func sanitizePreferredResolution(_ resolution: Any) -> CGSize { guard let preferredRes = resolution as? Dictionary<String, Any> else { return CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) }; return CGSize(width: preferredRes["width"] as! CGFloat, height: preferredRes["height"] as! CGFloat); } static func sanitizeBooleanProperty(_ property: Any) -> Bool { guard let prop = property as? Bool else { return true; } return prop; } static func sanitizeStringProperty(_ property: Any) -> String { guard let prop = property as? String else { return ""; } return prop; } static func getPublisherId(_ publisher: OTPublisher) -> String { let publisherIds = OTRN.sharedState.publishers.filter {$0.value == publisher} guard let publisherId = publisherIds.first else { return ""; } return publisherId.key; } static func convertOTSubscriberVideoEventReasonToString(_ reason: OTSubscriberVideoEventReason) -> String { switch reason { case OTSubscriberVideoEventReason.publisherPropertyChanged: return "PublisherPropertyChanged" case OTSubscriberVideoEventReason.subscriberPropertyChanged: return "SubscriberPropertyChanged" case OTSubscriberVideoEventReason.qualityChanged: return "QualityChanged" case OTSubscriberVideoEventReason.codecNotSupported: return "CodecNotSupported" } } static func sanitizeIncludeServer(_ value: Any) -> OTSessionICEIncludeServers { var includeServers = OTSessionICEIncludeServers.all; if let includeServer = value as? String, includeServer == "custom" { includeServers = OTSessionICEIncludeServers.custom; } return includeServers; } static func sanitizeTransportPolicy(_ value: Any) -> OTSessionICETransportPolicy { var transportPolicy = OTSessionICETransportPolicy.all; if let policy = value as? String, policy == "relay" { transportPolicy = OTSessionICETransportPolicy.relay; } return transportPolicy; } static func sanitiseServerList(_ serverList: Any) -> [(urls: [String], userName: String, credential: String)] { var iceServerList: [([String], String, String)] = [] if let serverList = serverList as? [[String: Any]] { for server in serverList { if let urls = server["urls"] as? [String], let username = server["username"] as? String, let credential = server["credential"] as? String { iceServerList.append((urls, username, credential)) } } } return iceServerList } static func sanitizeIceServer(_ serverList: Any, _ transportPolicy: Any, _ includeServer: Any) -> OTSessionICEConfig { let myICEServerConfiguration: OTSessionICEConfig = OTSessionICEConfig(); myICEServerConfiguration.includeServers = Utils.sanitizeIncludeServer(includeServer); myICEServerConfiguration.transportPolicy = Utils.sanitizeTransportPolicy(transportPolicy); let serverList = Utils.sanitiseServerList(serverList); for server in serverList { for url in server.urls { myICEServerConfiguration.addICEServer(withURL: url, userName: server.userName, credential: server.credential, error: nil); } } return myICEServerConfiguration; } static func convertVideoContentHint(_ videoContentHint: Any) -> OTVideoContentHint { guard let contentHint = videoContentHint as? String else { return OTVideoContentHint.none }; switch contentHint { case "motion": return OTVideoContentHint.motion case "detail": return OTVideoContentHint.detail case "text": return OTVideoContentHint.text default: return OTVideoContentHint.none } } }
41.048
176
0.657572
61f3eb37a3034d6e7adcb13330705b3e94075d6e
689
// // FYFNameSpace.swift // FBSnapshotTestCase // // Created by 范云飞 on 2022/3/18. // import UIKit /// 定义泛型结构体保存当前实例 public struct FYFNameSpace<Base> { public let base: Base public init(_ base: Base) { self.base = base } } /// 定义使用命名空间协议 public protocol FYFNameSpaceWrappable { associatedtype WrappableType var fyf: WrappableType { get } static var fyf: WrappableType.Type { get } } /// 为FYFNameSpaceWrappable添加默认实现 public extension FYFNameSpaceWrappable { var fyf: FYFNameSpace<Self> { get { return FYFNameSpace.init(self) } } static var fyf: FYFNameSpace<Self>.Type { get { return FYFNameSpace<Self>.self } } }
19.138889
46
0.664731
ef356a76e49d0416a369f28e0b116bb874d72ca8
7,280
// // OMPlayerProgressView.swift // OMusic // // Created by Jonathan Lu on 2020/2/24. // Copyright © 2020 Jonathan Lu. All rights reserved. // import UIKit import Masonry protocol OMPlayerProgressViewDelegate: AnyObject { func progressView(_ progressView: OMPlayerProgressView, didChanged currentTime: Float64) } class OMPlayerProgressView: UIView { //MARK: Properties public weak var delegate: OMPlayerProgressViewDelegate? private(set) public var isDraggingSlider: Bool = false private var progressSliderOriginalBounds: CGRect? private var shouldIgnoreProgress: Bool = false private(set) var style: Style = .normal public struct Style : Hashable, Equatable, RawRepresentable { public let rawValue: Int internal init(rawValue: Int) { self.rawValue = rawValue } } private(set) public var progressSlider: UISlider = { let slider = UISlider() let thumbImage = UIImage.init(systemName: "circle.fill")?.sd_tintedImage(with: THEME_GREEN_COLOR) slider.setThumbImage(thumbImage?.byResize(to: .init(width: 12, height: 12))?.sd_tintedImage(with: THEME_GREEN_COLOR), for: .normal) slider.minimumTrackTintColor = THEME_GREEN_COLOR slider.maximumTrackTintColor = THEME_GRAY_COLOR slider.setThumbImage(thumbImage, for: .highlighted) slider.setThumbImage(thumbImage, for: .selected) // slider.addTarget(self, action: #selector(handleSliderValueChanged(_:event:)), for: .touchDragInside) slider.addTarget(self, action: #selector(handleSliderValueChanged(_:event:)), for: .valueChanged) slider.addTarget(self, action: #selector(handleSliderTouchUp(_:)), for: .touchUpInside) slider.addTarget(self, action: #selector(handleSliderTouchUp(_:)), for: .touchUpOutside) return slider }() private var minTimeLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = .clear label.font = MIFont.lanProFont(size: 11, weight: .regular) label.textColor = THEME_GRAY_COLOR.setAlpha(0.7) label.textAlignment = .left label.text = "--:--" return label }() private var maxTimeLabel: UILabel = { let label = UILabel() label.backgroundColor = .clear label.translatesAutoresizingMaskIntoConstraints = false label.font = MIFont.lanProFont(size: 11, weight: .regular) label.textColor = THEME_GRAY_COLOR.setAlpha(0.7) label.textAlignment = .right label.text = "--:--" return label }() //MARK: Functions // override init(frame: CGRect) { // super.init(frame: frame) // addSubviews() // ListenerCenter.shared.addListener(listener: self, type: .playerStatusEvent) // } override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = .clear addSubviews() OMPlayerListenerCenter.shared.addListener(listener: self, type: .playerStatusEvent) } deinit { OMPlayerListenerCenter.shared.removeAllListener(listener: self) } private func addSubviews() { addSubview(progressSlider) progressSlider.mas_makeConstraints { (make) in make?.leading.equalTo()(self.mas_leading) make?.trailing.equalTo()(self.mas_trailing) make?.top.equalTo()(self.mas_top) make?.height.offset()(29) } addSubview(minTimeLabel) minTimeLabel.mas_makeConstraints { (make) in make?.leading.equalTo()(self.mas_leading) make?.top.equalTo()(self.progressSlider.mas_bottom)?.offset()(1) make?.height.offset()(14) make?.width.offset()(42) } addSubview(maxTimeLabel) maxTimeLabel.mas_makeConstraints { (make) in make?.trailing.equalTo()(self.mas_trailing) make?.top.equalTo()(self.progressSlider.mas_bottom)?.offset()(1) make?.height.offset()(14) make?.width.offset()(42) } } /// 重置计数与slider public func reset() { minTimeLabel.text = "00:00" maxTimeLabel.text = "--:--" progressSlider.setValue(0, animated: true) } } // MARK: - Actions extension OMPlayerProgressView { @objc private func handleSliderValueChanged(_ slider: UISlider, event: UIEvent) { isDraggingSlider = true minTimeLabel.text = minuteAndSecondStr(second: Float64(slider.value)) } @objc private func handleSliderTouchUp(_ slider: UISlider) { delegate?.progressView(self, didChanged: Float64(slider.value)) isDraggingSlider = false } } // MARK: - Utils extension OMPlayerProgressView { private func minuteAndSecondStr(second: Float64) -> String { let str = String(format: "%02ld:%02ld", Int64(second / 60), Int64(second.truncatingRemainder(dividingBy: 60))) // 02:30 return str } /// 更新视图 /// - Parameters: /// - currentTime: 当前时间 /// - totalTime: 总共时间 public func update(currentTime: Float64, totalTime: Float64) { guard currentTime >= 0 && totalTime >= 0 && totalTime >= currentTime else { return } if isDraggingSlider || shouldIgnoreProgress { return } minTimeLabel.text = minuteAndSecondStr(second: currentTime) maxTimeLabel.text = minuteAndSecondStr(second: totalTime) progressSlider.setValue(Float(currentTime), animated: true) progressSlider.maximumValue = Float(totalTime) } /// 更改样式 /// - Parameter style: OMPlayerProgressVIew.Style public func setStyle(_ style: Style) { self.style = style switch style { case .normal: UIView.animate(withDuration: 0.2) { self.progressSlider.maximumTrackTintColor = THEME_GRAY_COLOR self.minTimeLabel.textColor = THEME_GRAY_COLOR.setAlpha(0.7) self.maxTimeLabel.textColor = THEME_GRAY_COLOR.setAlpha(0.7) } case .colorful: UIView.animate(withDuration: 0.2) { self.progressSlider.maximumTrackTintColor = UIColor.white.setAlpha(0.3) self.minTimeLabel.textColor = UIColor.white.setAlpha(0.7) self.maxTimeLabel.textColor = UIColor.white.setAlpha(0.7) } default: UIView.animate(withDuration: 0.2) { self.progressSlider.maximumTrackTintColor = THEME_GRAY_COLOR self.minTimeLabel.textColor = THEME_GRAY_COLOR.setAlpha(0.7) self.maxTimeLabel.textColor = THEME_GRAY_COLOR.setAlpha(0.7) } } } } // MARK: - PlayerStatusListenerProtocol extension OMPlayerProgressView: OMPlayerControllerEventListenerProtocol { func onPlayerControllerEventDetected(event: OMPlayerControllerEventType) { shouldIgnoreProgress = event != .playing } } //MARK: OMPLayerProgressView.Style extension OMPlayerProgressView.Style { static let normal: OMPlayerProgressView.Style = .init(rawValue: 0) static let colorful: OMPlayerProgressView.Style = .init(rawValue: 1) }
33.860465
139
0.648764
1dc985e447135c349fa435e5cb203576af984f29
1,457
// // ObjectMapper+Rx.swift // Drrrible // // Created by Suyeol Jeon on 08/03/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import Moya import ObjectMapper import RxSwift extension ObservableType where E == Moya.Response { func map<T: ImmutableMappable>(_ mappableType: T.Type) -> Observable<T> { return self.mapString() .map { jsonString -> T in return try Mapper<T>().map(JSONString: jsonString) } .do(onError: { error in if error is MapError { log.error(error) } }) } func map<T: ImmutableMappable>(_ mappableType: [T].Type) -> Observable<[T]> { return self.mapString() .map { jsonString -> [T] in return try Mapper<T>().mapArray(JSONString: jsonString) } .do(onError: { error in if error is MapError { log.error(error) } }) } func map<T: ImmutableMappable>(_ mappableType: List<T>.Type) -> Observable<List<T>> { return self .map { response in let jsonString = try response.mapString() let items = try Mapper<T>().mapArray(JSONString: jsonString) let nextURL = (response.response as? HTTPURLResponse)? .findLink(relation: "next") .flatMap { URL(string: $0.uri) } return List<T>(items: items, nextURL: nextURL) } .do(onError: { error in if error is MapError { log.error(error) } }) } }
25.561404
87
0.589568
1e68fa0d12fa25eeb9dff9cc68c8a2165881093c
5,657
import XCTest class BTDropInUICustomizationTests: XCTestCase { func testInit_withLightColorScheme() { let uiCustomization = BTDropInUICustomization(colorScheme: .light) XCTAssertTrue(uiCustomization.useBlurs) XCTAssertEqual(uiCustomization.postalCodeFormFieldKeyboardType, .default) XCTAssertEqual(uiCustomization.barBackgroundColor, UIColor.white) XCTAssertEqual(uiCustomization.formBackgroundColor, UIColor.btuik_color(fromHex:"EFEFF4", alpha:1.0)) XCTAssertEqual(uiCustomization.formFieldBackgroundColor, UIColor.white) XCTAssertEqual(uiCustomization.primaryTextColor, UIColor.black) XCTAssertEqual(uiCustomization.secondaryTextColor, UIColor.btuik_color(fromHex:"3C3C43", alpha:1.0)) XCTAssertEqual(uiCustomization.placeholderTextColor, UIColor.lightGray) XCTAssertEqual(uiCustomization.lineColor, UIColor.btuik_color(fromHex:"BFBFBF", alpha:1.0)) XCTAssertEqual(uiCustomization.blurStyle, .extraLight) XCTAssertEqual(uiCustomization.activityIndicatorViewStyle, .gray) XCTAssertEqual(uiCustomization.overlayColor, UIColor.btuik_color(fromHex:"000000", alpha:0.5)) XCTAssertEqual(uiCustomization.tintColor, UIColor.btuik_color(fromHex:"2489F6", alpha:1.0)) XCTAssertEqual(uiCustomization.disabledColor, UIColor.lightGray) XCTAssertEqual(uiCustomization.errorForegroundColor, UIColor.btuik_color(fromHex:"ff3b30", alpha:1.0)) XCTAssertEqual(uiCustomization.switchThumbTintColor, UIColor.white) XCTAssertEqual(uiCustomization.switchOnTintColor, UIColor.green) XCTAssertEqual(uiCustomization.keyboardAppearance, .light) XCTAssertNil(uiCustomization.fontFamily) XCTAssertNil(uiCustomization.boldFontFamily) XCTAssertNil(uiCustomization.navigationBarTitleTextColor) XCTAssertFalse(uiCustomization.disableDynamicType) } func testInit_withDarkColorScheme() { let uiCustomization = BTDropInUICustomization(colorScheme: .dark) XCTAssertTrue(uiCustomization.useBlurs) XCTAssertEqual(uiCustomization.postalCodeFormFieldKeyboardType, .default) XCTAssertEqual(uiCustomization.barBackgroundColor, UIColor.btuik_color(fromHex:"222222", alpha:1.0)) XCTAssertEqual(uiCustomization.formBackgroundColor, UIColor.btuik_color(fromHex:"222222", alpha:1.0)) XCTAssertEqual(uiCustomization.formFieldBackgroundColor, UIColor.btuik_color(fromHex:"333333", alpha:1.0)) XCTAssertEqual(uiCustomization.primaryTextColor, UIColor.white) XCTAssertEqual(uiCustomization.secondaryTextColor, UIColor.btuik_color(fromHex:"EBEBF5", alpha:1.0)) XCTAssertEqual(uiCustomization.placeholderTextColor, UIColor.btuik_color(fromHex:"8E8E8E", alpha:1.0)) XCTAssertEqual(uiCustomization.lineColor, UIColor.btuik_color(fromHex:"666666", alpha:1.0)) XCTAssertEqual(uiCustomization.blurStyle, .dark) XCTAssertEqual(uiCustomization.activityIndicatorViewStyle, .white) XCTAssertEqual(uiCustomization.overlayColor, UIColor.btuik_color(fromHex: "000000", alpha: 0.5)) XCTAssertEqual(uiCustomization.tintColor, UIColor.btuik_color(fromHex: "2489F6", alpha:1.0)) XCTAssertEqual(uiCustomization.disabledColor, UIColor.lightGray) XCTAssertEqual(uiCustomization.errorForegroundColor, UIColor.btuik_color(fromHex: "ff3b30", alpha:1.0)) XCTAssertEqual(uiCustomization.switchThumbTintColor, UIColor.white) XCTAssertEqual(uiCustomization.switchOnTintColor, UIColor.green) XCTAssertNil(uiCustomization.fontFamily) XCTAssertNil(uiCustomization.boldFontFamily) XCTAssertNil(uiCustomization.navigationBarTitleTextColor) XCTAssertFalse(uiCustomization.disableDynamicType) } func testInit_withDynamicColorScheme_whenSystemIsInLightMode() { if #available(iOS 13, *) { let uiCustomization = BTDropInUICustomization(colorScheme: .dynamic) XCTAssertTrue(uiCustomization.useBlurs) XCTAssertEqual(uiCustomization.postalCodeFormFieldKeyboardType, .default); XCTAssertEqual(uiCustomization.barBackgroundColor, UIColor.systemBackground) XCTAssertEqual(uiCustomization.formBackgroundColor, UIColor.systemGroupedBackground) XCTAssertEqual(uiCustomization.formFieldBackgroundColor, UIColor.secondarySystemGroupedBackground) XCTAssertEqual(uiCustomization.primaryTextColor, UIColor.label) XCTAssertEqual(uiCustomization.secondaryTextColor, UIColor.secondaryLabel) XCTAssertEqual(uiCustomization.placeholderTextColor, UIColor.placeholderText) XCTAssertEqual(uiCustomization.lineColor, UIColor.separator) XCTAssertEqual(uiCustomization.blurStyle, .systemMaterial) XCTAssertEqual(uiCustomization.activityIndicatorViewStyle, .medium) XCTAssertEqual(uiCustomization.overlayColor, UIColor.black.withAlphaComponent(0.5)) XCTAssertEqual(uiCustomization.tintColor, UIColor.systemBlue) XCTAssertEqual(uiCustomization.disabledColor, UIColor.systemGray) XCTAssertEqual(uiCustomization.errorForegroundColor, UIColor.systemRed) XCTAssertEqual(uiCustomization.switchThumbTintColor, UIColor.white) XCTAssertEqual(uiCustomization.switchOnTintColor, UIColor.systemGreen) XCTAssertNil(uiCustomization.fontFamily) XCTAssertNil(uiCustomization.boldFontFamily) XCTAssertNil(uiCustomization.navigationBarTitleTextColor) XCTAssertFalse(uiCustomization.disableDynamicType) } } }
59.547368
114
0.769312
4baf09cad907d8ba51aa3f4befdeebfe0949dd11
1,602
// // PostEditorMessageCell.swift // Graygram // // Created by Suyeol Jeon on 08/03/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import UIKit final class PostEditorMessageCell: UITableViewCell { // MARK: Constants struct Font { static let textView = UIFont.systemFont(ofSize: 14) } // MARK: Properties var textDidChange: ((String?) -> Void)? // MARK: UI fileprivate let textView = UITextView() // MARK: Initializing override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none self.textView.font = Font.textView self.textView.delegate = self self.contentView.addSubview(self.textView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Configuring func configure(message: String?) { self.textView.text = message self.setNeedsLayout() } // MARK: Size class func height(width: CGFloat, message: String?) -> CGFloat { let messageHeight = message?.size(width: width, font: Font.textView).height ?? 0 let minimumHeight = ceil(Font.textView.lineHeight * 3) + 10 + 10 // UITextView의 기본 inset return max(messageHeight, minimumHeight) } // MARK: Layout override func layoutSubviews() { super.layoutSubviews() self.textView.frame = self.contentView.bounds } } extension PostEditorMessageCell: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { self.textDidChange?(textView.text) } }
20.538462
92
0.696005
1e45c2c27fc0a4c7fdbf722ac9ae6f5a75350f36
6,767
// // MainViewController.swift // KMNavigationBarTransition // // Created by Zhouqi Mo on 1/1/16. // Copyright © 2017 Zhouqi Mo. All rights reserved. // import UIKit class MainViewController: UITableViewController { // MARK: Constants struct Constants { struct Segue { static let ShowNextIdentifier = "Show Next" static let SetStyleIdentifier = "Set Style" } } // MARK: Properties var currentNavigationBarData: NavigationBarData! var nextNavigationBarData: NavigationBarData! @IBOutlet weak var nextNavigationBarTitleColorText: UILabel! @IBOutlet weak var nextNavigationBarTintColorText: UILabel! @IBOutlet weak var nextNavigatioBarBackgroundImageColorText: UILabel! @IBOutlet weak var nextNavigationBarPrefersHiddenSwitch: UISwitch! @IBOutlet weak var nextNavigationBarPrefersShadowImageHiddenSwitch: UISwitch! // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() if currentNavigationBarData == nil { currentNavigationBarData = NavigationBarData() } nextNavigationBarData = currentNavigationBarData nextNavigationBarTitleColorText.text = nextNavigationBarData.titleColor.rawValue nextNavigationBarTintColorText.text = nextNavigationBarData.barTintColor.rawValue nextNavigatioBarBackgroundImageColorText.text = nextNavigationBarData.backgroundImageColor.rawValue nextNavigationBarPrefersHiddenSwitch.isOn = nextNavigationBarData.prefersHidden nextNavigationBarPrefersShadowImageHiddenSwitch.isOn = nextNavigationBarData.prefersShadowImageHidden if let titleColor = currentNavigationBarData.titleColor.toUIColor { navigationController?.navigationBar.tintColor = titleColor navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: titleColor] } navigationController?.navigationBar.barTintColor = currentNavigationBarData.barTintColor.toUIColor navigationController?.navigationBar.setBackgroundImage(currentNavigationBarData.backgroundImageColor.toUIImage, for: .default) navigationController?.navigationBar.shadowImage = (currentNavigationBarData.prefersShadowImageHidden) ? UIImage() : nil title = "Title " + "\(navigationController!.viewControllers.count)" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(currentNavigationBarData.prefersHidden, animated: animated) } } // MARK: - Target Action extension MainViewController { @IBAction func nextNavigationBarPrefersShadowImageHidden(_ sender: UISwitch) { nextNavigationBarData.prefersShadowImageHidden = sender.isOn } @IBAction func nextNavigationBarPrefersHidden(_ sender: UISwitch) { nextNavigationBarData.prefersHidden = sender.isOn } @IBAction func navigationBarTranslucent(_ sender: UISwitch) { navigationController?.navigationBar.isTranslucent = sender.isOn } } // MARK: - Table view data source extension MainViewController { override func numberOfSections(in tableView: UITableView) -> Int { return navigationController?.viewControllers.first == self ? 2 : 1 } } // MARK: - Table view delegate extension MainViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch (indexPath.section, indexPath.row) { case (0, 0), (0, 1), (0, 2): performSegue(withIdentifier: Constants.Segue.SetStyleIdentifier, sender: self) default: break } } } // MARK: - Navigation extension MainViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let identifier = segue.identifier { switch identifier { case Constants.Segue.SetStyleIdentifier: guard let settingsViewController = segue.destination as? SettingsViewController else { return } guard let selectedIndexPath = tableView.indexPathForSelectedRow else { return } var colorsArray = [NavigationBarBackgroundViewColor]() var selectedIndex: Int? var block: ((_ color: NavigationBarBackgroundViewColor) -> Void)? switch (selectedIndexPath.section, selectedIndexPath.row) { case (0, 0): colorsArray = NavigationBarData.BarTintColorArray selectedIndex = colorsArray.index(of: NavigationBarBackgroundViewColor(rawValue: nextNavigationBarTintColorText.text!)!) block = { self.nextNavigationBarData.barTintColor = $0 self.nextNavigationBarTintColorText.text = $0.rawValue } case (0, 1): colorsArray = NavigationBarData.BackgroundImageColorArray selectedIndex = colorsArray.index(of: NavigationBarBackgroundViewColor(rawValue: nextNavigatioBarBackgroundImageColorText.text!)!) block = { self.nextNavigationBarData.backgroundImageColor = $0 self.nextNavigatioBarBackgroundImageColorText.text = $0.rawValue } case (0, 2): colorsArray = NavigationBarData.BackgroundImageColorArray selectedIndex = colorsArray.index(of: NavigationBarBackgroundViewColor(rawValue: nextNavigationBarTitleColorText.text!)!) block = { self.nextNavigationBarData.titleColor = $0 self.nextNavigationBarTitleColorText.text = $0.rawValue } default: break } settingsViewController.colorsData = (colorsArray, selectedIndex) settingsViewController.configurationBlock = block settingsViewController.titleText = tableView.cellForRow(at: selectedIndexPath)?.textLabel?.text ?? "" case Constants.Segue.ShowNextIdentifier: guard let viewController = segue.destination as? MainViewController else { return } viewController.currentNavigationBarData = nextNavigationBarData break default: break } } } }
39.343023
150
0.649623
18ee470d4b378a8027bf40fecd531411450efb56
11,442
// // Submodule.swift // SwiftGit2-OSX // // Created by UKS on 06.10.2020. // Copyright © 2020 GitHub, Inc. All rights reserved. // import Clibgit2 import Essentials public class Submodule: InstanceProtocol { public let pointer: OpaquePointer public required init(_ pointer: OpaquePointer) { self.pointer = pointer } deinit { git_submodule_free(pointer) } } public extension Submodule { var name: String { String(cString: git_submodule_name(pointer)) } /// Get the path to the submodule. RELATIVE! Almost allways the same as "name" parameter var path: String { String(cString: git_submodule_path(pointer)) } var pathAbs : R<String> { self.repo() | { $0.directoryURL | { $0.path } } } /// Url to remote repo (https or ssh) var url: String { String(cString: git_submodule_url(pointer)) } /// Get the OID for the submodule in the current working directory. var Oid: OID? { guard let submod = git_submodule_wd_id(pointer) else { return nil } return OID(submod.pointee) } /// Get the OID for the submodule in the current HEAD tree. var headOID: OID? { guard let submod = git_submodule_head_id(pointer) else { return nil } return OID(submod.pointee) } /// Open the repository for a submodule. /// WILL WORK ONLY IF SUBMODULE IS CHECKED OUT INTO WORKING DIRECTORY func repo() -> Result<Repository, Error> { var pointer: OpaquePointer? return _result({ Repository(pointer!) }, pointOfFailure: "git_submodule_open") { git_submodule_open(&pointer, self.pointer) } } func repoExist() -> Bool { (try? repo().get()) != nil } } public extension Duo where T1 == Submodule, T2 == Repository { /// Repository must be PARENT of submodule func getSubmoduleStatus() -> Result<SubmoduleStatusFlags, Error> { let (submodule, parentRepo) = value let ignore = git_submodule_ignore_t.init(SubmoduleIgnore.none.rawValue) var result = UInt32(0) return _result({ SubmoduleStatusFlags(rawValue: result) }, pointOfFailure: "git_submodule_status") { submodule.name.withCString { submoduleName in git_submodule_status(&result, parentRepo.pointer, submoduleName, ignore) } } } func getSubmoduleAbsPath() -> Result<String, Error> { let (submodule, repo) = value return repo.directoryURL.flatMap { url in .success("\(url.path)/\(submodule.path)") } } func fetchRecurseValueSet(_ bool: Bool) -> Result<Void, Error> { let (submodule, repo) = value let valToSet = git_submodule_recurse_t(rawValue: bool ? 1 : 0) return _result({ () }, pointOfFailure: "git_submodule_set_fetch_recurse_submodules") { submodule.name.withCString { submoduleName in git_submodule_set_fetch_recurse_submodules(repo.pointer, submoduleName, valToSet) } } } // TODO: Test Me -- this must be string or Branch? func branchGet() -> String { let (submodule, _) = value if let brPointer = git_submodule_branch(submodule.pointer) { return String(cString: brPointer) } return "" } // TODO: Test Me /// Set the branch for the submodule in the configuration func branchSetAndSync(branchName: String) -> Result<Void, Error> { let (submodule, repo) = value return _result({ () }, pointOfFailure: "git_submodule_set_branch") { branchName.withCString { brName in submodule.name.withCString { submoduleName in git_submodule_set_branch(repo.pointer, submoduleName, brName) } } } .flatMap { submodule.sync() } } // WTF? What this fucking THING is doing? I have no idea. // .resolveUrl() -> "[email protected]:sergiy.vynnychenko/AppCore.git" // .url -> "[email protected]:sergiy.vynnychenko/AppCore.git" // // Resolve a submodule url relative to the given repository. func resolveUrl() -> Result<String, Error> { let (submodule, repo) = value // let buf_ptr = UnsafeMutablePointer<git_buf>.allocate(capacity: 1) var buf = git_buf(ptr: nil, asize: 0, size: 0) return _result({ Buffer(buf: buf) }, pointOfFailure: "git_submodule_resolve_url") { submodule.url.withCString { relativeUrl in git_submodule_resolve_url(&buf, repo.pointer, relativeUrl) } } .flatMap { $0.asString() } } // TODO: Test Me /// Set the URL for the submodule in the configuration func submoduleSetUrlAndSync(newRelativeUrl: String) -> Result<Void, Error> { let (submodule, repo) = value return _result({ () }, pointOfFailure: "git_submodule_set_url") { submodule.name.withCString { submoduleName in newRelativeUrl.withCString { newUrl in git_submodule_set_url(repo.pointer, submoduleName, newUrl) } } } .flatMap { submodule.sync() } } } public extension Submodule { func clone(options: SubmoduleUpdateOptions) -> R<Repository> { git_instance(of: Repository.self, "git_submodule_clone") { pointer in options.with_git_submodule_update_options { options in git_submodule_clone(&pointer, self.pointer, &options) } } } func fetchRecurseValueGet() -> Bool { // "result == 1" return git_submodule_fetch_recurse_submodules(pointer) == git_submodule_recurse_t(rawValue: 1) } // TODO: Test Me /// Copy submodule remote info into submodule repo. func sync() -> Result<Void, Error> { return _result({ () }, pointOfFailure: "git_submodule_sync") { git_submodule_sync(self.pointer) } } // TODO: Test Me. // don't know how to test /// Reread submodule info from config, index, and HEAD | /// Call this to reread cached submodule information for this submodule if you have reason to believe that it has changed. func reload(force: Bool = false) -> Result<Void, Error> { let forceInt: Int32 = force ? 1 : 0 return _result({ () }, pointOfFailure: "git_submodule_reload") { git_submodule_reload(self.pointer, forceInt) } } // TODO: Test Me. /// Update a submodule. /// This will clone a missing submodule and checkout the subrepository to the commit specified in the index of the containing repository. /// If the submodule repository doesn't contain the target commit (e.g. because fetchRecurseSubmodules isn't set), /// then the submodule is fetched using the fetch options supplied in options. func update(options: SubmoduleUpdateOptions, `init`: Bool = false) -> R<Void> { let initBeforeUpdateInt: Int32 = `init` ? 1 : 0 return _result({ () }, pointOfFailure: "git_submodule_update") { options.with_git_submodule_update_options { opt in git_submodule_update(self.pointer, initBeforeUpdateInt, &opt) } } } // TODO: Test Me --- not sure how to test /// Add current submodule HEAD commit to index of superproject. /// writeIndex -- if true - should immediately write the index file. If you pass this as false, you will have to get the git_index and explicitly call `git_index_write()` on it to save the change func addToIndex(writeIndex: Bool = true) -> Result<Void, Error> { let writeIndex: Int32 = writeIndex ? 1 : 0 return _result({ () }, pointOfFailure: "git_submodule_add_to_index") { git_submodule_add_to_index(self.pointer, writeIndex) } } // TODO: Test Me /// Resolve the setup of a new git submodule. | /// This should be called on a submodule once you have called add setup and done the clone of the submodule. /// This adds the .gitmodules file and the newly cloned submodule to the index to be ready to be committed (but doesn't actually do the commit). func finalize() -> Result<Void, Error> { return _result({ () }, pointOfFailure: "git_submodule_add_finalize") { git_submodule_add_finalize(self.pointer) } } // TODO: Test Me. Especially "overwrite" func `init`(overwrite: Bool) -> R<Submodule> { git_try("git_submodule_init") { git_submodule_init(self.pointer, overwrite ? 1 : 0) } | { self } } } /// git_submodule_ignore_t; public enum SubmoduleIgnore: Int32 { case unspecified = -1 // GIT_SUBMODULE_IGNORE_UNSPECIFIED = -1, /**< use the submodule's configuration */ case none = 1 // GIT_SUBMODULE_IGNORE_NONE = 1, /**< any change or untracked == dirty */ case untracked = 2 // GIT_SUBMODULE_IGNORE_UNTRACKED = 2, /**< dirty if tracked files change */ case ignoreDirty = 3 // GIT_SUBMODULE_IGNORE_DIRTY = 3, /**< only dirty if HEAD moved */ case ignoreAll = 4 // GIT_SUBMODULE_IGNORE_ALL = 4, /**< never dirty */ } /// git_submodule_recurse_t; public enum SubmoduleRecurse: UInt32 { case RecurseNo = 0 // GIT_SUBMODULE_RECURSE_NO case RecurseYes = 1 // GIT_SUBMODULE_RECURSE_YES case RecurseOnDemand = 2 // GIT_SUBMODULE_RECURSE_ONDEMAND } public struct SubmoduleStatusFlags: OptionSet { public init(rawValue: UInt32) { self.rawValue = rawValue } public let rawValue: UInt32 public static let InHead = SubmoduleStatusFlags(rawValue: GIT_SUBMODULE_STATUS_IN_HEAD.rawValue) public static let InIndex = SubmoduleStatusFlags(rawValue: GIT_SUBMODULE_STATUS_IN_INDEX.rawValue) public static let InConfig = SubmoduleStatusFlags(rawValue: GIT_SUBMODULE_STATUS_IN_CONFIG.rawValue) public static let InWd = SubmoduleStatusFlags(rawValue: GIT_SUBMODULE_STATUS_IN_WD.rawValue) public static let IndexAdded = SubmoduleStatusFlags(rawValue: GIT_SUBMODULE_STATUS_INDEX_ADDED.rawValue) public static let IndexDeleted = SubmoduleStatusFlags(rawValue: GIT_SUBMODULE_STATUS_INDEX_DELETED.rawValue) public static let IndexModified = SubmoduleStatusFlags(rawValue: GIT_SUBMODULE_STATUS_INDEX_MODIFIED.rawValue) public static let WdUninitialized = SubmoduleStatusFlags(rawValue: GIT_SUBMODULE_STATUS_WD_UNINITIALIZED.rawValue) public static let WdAdded = SubmoduleStatusFlags(rawValue: GIT_SUBMODULE_STATUS_WD_ADDED.rawValue) public static let WdDeleted = SubmoduleStatusFlags(rawValue: GIT_SUBMODULE_STATUS_WD_DELETED.rawValue) public static let WdModified = SubmoduleStatusFlags(rawValue: GIT_SUBMODULE_STATUS_WD_MODIFIED.rawValue) public static let WdIndexModified = SubmoduleStatusFlags(rawValue: GIT_SUBMODULE_STATUS_WD_INDEX_MODIFIED.rawValue) public static let WdWdModified = SubmoduleStatusFlags(rawValue: GIT_SUBMODULE_STATUS_WD_WD_MODIFIED.rawValue) public static let WdUntracked = SubmoduleStatusFlags(rawValue: GIT_SUBMODULE_STATUS_WD_UNTRACKED.rawValue) } /* UNUSED: git_submodule_add_setup git_submodule_clone git_submodule_ignore -- need to use SubmoduleIgnore enum here git_submodule_set_ignore git_submodule_repo_init git_submodule_set_update git_submodule_update_strategy git_submodule_owner -- NEVER USE THIS SHIT. It's killing pointer too fast for you, buddy */
39.591696
199
0.671561
ff344c9ad1d5b0ad5466794b9e201108c4490a82
1,428
// // RpcEngineApi.swift // // // Created by Yehor Popovych on 04.08.2021. // import Foundation public struct SubstrateRpcEngineApi<S: SubstrateProtocol>: SubstrateRpcApi { public weak var substrate: S! public init(substrate: S) { self.substrate = substrate } public func createBlock( empty: Bool, finalize: Bool, parentHash: S.R.THash?, timeout: TimeInterval? = nil, cb: @escaping SRpcApiCallback<CreatedBlock<S.R.THash>> ) { substrate.client.call( method: "engine_createBlock", params: RpcCallParams(empty, finalize, parentHash), timeout: timeout ?? substrate.callTimeout ) { (res: RpcClientResult<CreatedBlock<S.R.THash>>) in cb(res.mapError(SubstrateRpcApiError.rpc)) } } public func finalizeBlock( hash: S.R.THash, justification: Justification?, timeout: TimeInterval? = nil, cb: @escaping SRpcApiCallback<Bool> ) { substrate.client.call( method: "engine_finalizeBlock", params: RpcCallParams(hash, justification), timeout: timeout ?? substrate.callTimeout ) { (res: RpcClientResult<Bool>) in cb(res.mapError(SubstrateRpcApiError.rpc)) } } } extension SubstrateRpcApiRegistry { public var engine: SubstrateRpcEngineApi<S> { getRpcApi(SubstrateRpcEngineApi<S>.self) } }
29.75
92
0.633754
46892dd34196c10c71ab0ab96c73e1dd549bf3de
1,253
// // MockDataSource.swift // My First IOS App // // Created by Antonio López Marín on 27/01/16. // Copyright © 2016 Antonio López Marín. All rights reserved. // import Foundation class MockDataSource: DataSourceProtocol { var items: [Int: Subject] = [:] init(){ self.items = [0: Subject(id: 0, name: "Matematicas"), 1: Subject(id: 1, name: "Lengua"), 2: Subject(id: 2, name: "Carapapas")] } func add(item: Subject) -> Subject{ let newItem: Subject = Subject(id: getNewId(), name: item.name) items[newItem.id] = newItem return newItem } private func getNewId() -> Int{ var id: Int = -1 for(var i = 0; i < items.keys.count; i++){ if !items.keys.contains(i) { id = i break } } return id } func remove(item: Subject){ let index = items.indexForKey(item.id) items.removeAtIndex(index!) } func update(item: Subject){ items.updateValue(item, forKey: item.id) } func get(item: Subject) -> Subject{ return items[item.id]! } func getAll() -> [Subject]{ return Array(items.values) } }
23.203704
133
0.536313
ed3ffa3d22b6dada44c40becf5c94bcdd318b881
281
// // Notifications.swift // EventKit.Example // // Created by Filip Němeček on 04/08/2020. // Copyright © 2020 Filip Němeček. All rights reserved. // import Foundation extension Notification.Name { static let eventsDidChange = Notification.Name("EKEXeventsDidChange") }
20.071429
73
0.733096
aba6c2caca79262ab5cff497b0243c6a954809bf
2,953
// // LinkedList.swift // LeetCodeSample // // Created by NuGelaLies on 11/13/20. // import Foundation class LinkedList<T: Comparable> { typealias Node = LinkedNode<T> var head: Node? var last: Node? { guard var node = head else { return nil } while let next = node.next { node = next } return node } public var count: Int { var count = 1 guard var node = head else { return 0 } while let next = node.next { node = next count += 1 } return count } public var isEmpty: Bool { return head == nil } public func node(at target: Int) -> Node { guard var node = head else { fatalError("empty linkedlist") } guard target >= 0, target < count else { fatalError("out of linkedlist range") } guard target != 0 else { return head! } for _ in 1...target { node = node.next! } return node } public subscript(_ index: Int) -> T { return node(at: index).val } public func append(_ value: T) { let node = Node(value) append(node) } public func append(_ node: Node) { node.next = nil if let next = last { next.next = node node.previous = next } else { head = node } } public func insert(_ value: T, at target: Int) { insert(Node(value), at: target) } public func insert(_ value: Node, at target: Int) { guard let node = head else { head = value return } if target == 0 { node.previous = value value.next = node head = value } else { let prev = self.node(at: target - 1) let current = self.node(at: target) prev.next = value value.next = current current.previous = value value.previous = prev } } public func remove(_ target: Int) -> T { return remove(node(at: target)) } public func remove(_ node: Node) -> T { let prev = node.previous let next = node.next if let previous = prev { previous.next = next } else { head = next } next?.previous = prev node.previous = nil node.next = nil return node.val } } extension LinkedList: CustomDebugStringConvertible { var debugDescription: String { guard !isEmpty else { return "this linkedlist isEmpty" } var list = "[ \(head!.val)" for i in 1..<count { list += " -> \(self.node(at: i).val)" } list += " ]" return list } }
22.371212
55
0.473417
71d2a4319d16cd17398404a352507208e2e66938
7,518
// // DeckEditorTableViewController.swift // TooDoo // // Created by Cali Castle on 12/10/17. // Copyright © 2017 Cali Castle . All rights reserved. // import UIKit import Typist import Haptica import ViewAnimator open class DeckEditorTableViewController: UITableViewController, LocalizableInterface { // MARK: - Properties. /// Determine if it should be adding. var isAdding = true /// Keyboard manager. let keyboard = Typist() // MARK: - View Life Cycle. override open func viewDidLoad() { super.viewDidLoad() modalPresentationCapturesStatusBarAppearance = true localizeInterface() setupViews() configureColors() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !animated { animateViews() navigationController?.navigationBar.alpha = 0 DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(220), execute: { self.animateNavigationBar(delay: 0) }) } registerKeyboardEvents() // Fix the issue when pushed a new view controller and the tool bar gets hidden if let navigationController = navigationController, navigationController.isToolbarHidden && !tableView.isEditing { navigationController.setToolbarHidden(false, animated: true) } } override open func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) keyboard.clear() } /// Localize interface. public func localizeInterface() { } /// Set up views. internal func setupViews() { // Remove delete button when creating new category if isAdding, let items = toolbarItems { setToolbarItems(items.filter({ return $0.tag != 0 }), animated: false) } // Set up navigation items navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(cancelDidTap(_:))) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done".localized, style: .done, target: self, action: #selector(doneDidTap(_:))) } /// Configure colors. internal func configureColors() { // Configure bar buttons if let item = navigationItem.leftBarButtonItem { item.tintColor = currentThemeIsDark() ? UIColor.flatWhiteColorDark().withAlphaComponent(0.8) : UIColor.flatBlack().withAlphaComponent(0.6) } // Set done navigation bar button color if let item = navigationItem.rightBarButtonItem { item.tintColor = currentThemeIsDark() ? .flatYellow() : .flatBlue() } // Set done toolbar button color if let items = toolbarItems { if let item = items.first(where: { return $0.tag == 1 }) { item.tintColor = currentThemeIsDark() ? .flatYellow() : .flatBlue() } } // Set black or white scroll indicator tableView.indicatorStyle = currentThemeIsDark() ? .white : .black let color: UIColor = currentThemeIsDark() ? .white : .flatBlack() // Configure label colors getCellLabels().forEach { $0.textColor = color.withAlphaComponent(0.7) } } /// Get cell labels. internal func getCellLabels() -> [UILabel] { return [] } /// Register keyboard events. internal func registerKeyboardEvents() { keyboard.on(event: .willShow) { guard $0.belongsToCurrentApp else { return } self.navigationController?.setToolbarHidden(true, animated: true) }.on(event: .didHide) { guard $0.belongsToCurrentApp else { return } self.navigationController?.setToolbarHidden(false, animated: true) }.start() } /// Configure input accessory view. internal func configureInputAccessoryView() -> UIToolbar { // Set up recolorable toolbar let inputToolbar = RecolorableToolBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: (navigationController?.toolbar.bounds.height)!)) // Done bar button let doneBarButton = UIBarButtonItem(image: #imageLiteral(resourceName: "checkmark-filled-circle-icon"), style: .done, target: self, action: #selector(doneDidTap(_:))) doneBarButton.tintColor = currentThemeIsDark() ? .flatYellow() : .flatBlue() // All toolbar items var toolbarItems: [UIBarButtonItem] = [] // Add keyboard dismissal button toolbarItems.append(UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(endEditing))) // If not adding, append delete button if !isAdding { let deleteBarButton = UIBarButtonItem(image: #imageLiteral(resourceName: "trash-alt-icon"), style: .done, target: self, action: #selector(deleteDidTap(_:))) deleteBarButton.tintColor = UIColor.flatRed().lighten(byPercentage: 0.2) toolbarItems.append(deleteBarButton) } toolbarItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)) toolbarItems.append(doneBarButton) inputToolbar.items = toolbarItems return inputToolbar } /// Animate views. internal func animateViews() { // Set table view to initially hidden tableView.animateViews(animations: [], initialAlpha: 0, finalAlpha: 0, delay: 0, duration: 0, animationInterval: 0, completion: nil) // Fade in and move from bottom animation to table cells tableView.animateViews(animations: [AnimationType.from(direction: .bottom, offset: 55)], initialAlpha: 0, finalAlpha: 1, delay: 0.25, duration: 0.46, animationInterval: 0.12) } /// Keyboard dismissal. @objc internal func endEditing() { Haptic.impact(.light).generate() SoundManager.play(soundEffect: .Click) tableView.endEditing(true) } /// User tapped cancel button. @objc private func cancelDidTap(_ sender: Any) { // Generate haptic feedback Haptic.impact(.light).generate() tableView.endEditing(true) navigationController?.dismiss(animated: true, completion: nil) } /// When user tapped done. @objc internal func doneDidTap(_ sender: Any) { tableView.endEditing(true) navigationController?.dismiss(animated: true, completion: nil) } /// User tapped delete button. @objc internal func deleteDidTap(_ sender: Any) { tableView.endEditing(true) // Generate haptic feedback and play sound Haptic.notification(.warning).generate() SoundManager.play(soundEffect: .Click) } /// Light status bar. override open var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } /// Status bar animation. override open var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .fade } /// Auto hide home indicator @available(iOS 11, *) override open func prefersHomeIndicatorAutoHidden() -> Bool { return true } }
33.413333
182
0.621575