repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
ivanbruel/Moya-ObjectMapper
Source/RxSwift/ObservableType+ObjectMapper.swift
1
4087
// // ObserverType+ObjectMapper.swift // // Created by Ivan Bruel on 09/12/15. // Copyright © 2015 Ivan Bruel. All rights reserved. // import Foundation import RxSwift import Moya import ObjectMapper /// Extension for processing Responses into Mappable objects through ObjectMapper public extension ObservableType where Element == Response { /// Maps data received from the signal into an object /// which implements the Mappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapObject<T: BaseMappable>(_ type: T.Type, context: MapContext? = nil) -> Observable<T> { return flatMap { response -> Observable<T> in return Observable.just(try response.mapObject(type, context: context)) } } /// Maps data received from the signal into an array of objects /// which implement the Mappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapArray<T: BaseMappable>(_ type: T.Type, context: MapContext? = nil) -> Observable<[T]> { return flatMap { response -> Observable<[T]> in return Observable.just(try response.mapArray(type, context: context)) } } /// Maps data received from the signal into an object /// which implements the Mappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapObject<T: BaseMappable>(_ type: T.Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Observable<T> { return flatMap { response -> Observable<T> in return Observable.just(try response.mapObject(T.self, atKeyPath: keyPath, context: context)) } } /// Maps data received from the signal into an array of objects /// which implement the Mappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapArray<T: BaseMappable>(_ type: T.Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Observable<[T]> { return flatMap { response -> Observable<[T]> in return Observable.just(try response.mapArray(T.self, atKeyPath: keyPath, context: context)) } } } // MARK: - ImmutableMappable public extension ObservableType where Element == Response { /// Maps data received from the signal into an object /// which implements the ImmutableMappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapObject<T: ImmutableMappable>(_ type: T.Type, context: MapContext? = nil) -> Observable<T> { return flatMap { response -> Observable<T> in return Observable.just(try response.mapObject(type, context: context)) } } /// Maps data received from the signal into an array of objects /// which implement the ImmutableMappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapArray<T: ImmutableMappable>(_ type: T.Type, context: MapContext? = nil) -> Observable<[T]> { return flatMap { response -> Observable<[T]> in return Observable.just(try response.mapArray(type, context: context)) } } /// Maps data received from the signal into an object /// which implements the ImmutableMappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapObject<T: ImmutableMappable>(_ type: T.Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Observable<T> { return flatMap { response -> Observable<T> in return Observable.just(try response.mapObject(T.self, atKeyPath: keyPath, context: context)) } } /// Maps data received from the signal into an array of objects /// which implement the ImmutableMappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapArray<T: ImmutableMappable>(_ type: T.Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Observable<[T]> { return flatMap { response -> Observable<[T]> in return Observable.just(try response.mapArray(T.self, atKeyPath: keyPath, context: context)) } } }
mit
4c08232b4531aac05cf027eeb3028511
43.413043
136
0.721243
4.43167
false
false
false
false
AdaptiveMe/adaptive-arp-api-lib-darwin
Pod/Classes/Sources.Api/LoggingBridge.swift
1
5154
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:[email protected]> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:[email protected]> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation /** Interface for Managing the Logging operations Auto-generated implementation of ILogging specification. */ public class LoggingBridge : BaseUtilBridge, ILogging, APIBridge { /** API Delegate. */ private var delegate : ILogging? = nil /** Constructor with delegate. @param delegate The delegate implementing platform specific functions. */ public init(delegate : ILogging?) { self.delegate = delegate } /** Get the delegate implementation. @return ILogging delegate that manages platform specific functions.. */ public final func getDelegate() -> ILogging? { return self.delegate } /** Set the delegate implementation. @param delegate The delegate implementing platform specific functions. */ public final func setDelegate(delegate : ILogging) { self.delegate = delegate; } /** Logs the given message, with the given log level if specified, to the standard platform/environment. @param level Log level @param message Message to be logged @since v2.0 */ public func log(level : ILoggingLogLevel , message : String ) { if (self.delegate != nil) { self.delegate!.log(level, message: message) } } /** Logs the given message, with the given log level if specified, to the standard platform/environment. @param level Log level @param category Category/tag name to identify/filter the log. @param message Message to be logged @since v2.0 */ public func log(level : ILoggingLogLevel , category : String , message : String ) { if (self.delegate != nil) { self.delegate!.log(level, category: category, message: message) } } /** Invokes the given method specified in the API request object. @param request APIRequest object containing method name and parameters. @return APIResponse with status code, message and JSON response or a JSON null string for void functions. Status code 200 is OK, all others are HTTP standard error conditions. */ public override func invoke(request : APIRequest) -> APIResponse? { let response : APIResponse = APIResponse() var responseCode : Int32 = 200 var responseMessage : String = "OK" let responseJSON : String? = "null" switch request.getMethodName()! { case "logLevelMessage": let level0 : ILoggingLogLevel? = ILoggingLogLevel.toEnum(JSONUtil.dictionifyJSON(request.getParameters()![0])["value"] as? String) let message0 : String? = JSONUtil.unescapeString(request.getParameters()![1]) self.log(level0!, message: message0!); case "logLevelCategoryMessage": let level1 : ILoggingLogLevel? = ILoggingLogLevel.toEnum(JSONUtil.dictionifyJSON(request.getParameters()![0])["value"] as? String) let category1 : String? = JSONUtil.unescapeString(request.getParameters()![1]) let message1 : String? = JSONUtil.unescapeString(request.getParameters()![2]) self.log(level1!, category: category1!, message: message1!); default: // 404 - response null. responseCode = 404 responseMessage = "LoggingBridge does not provide the function '\(request.getMethodName()!)' Please check your client-side API version; should be API version >= v2.2.15." } response.setResponse(responseJSON!) response.setStatusCode(responseCode) response.setStatusMessage(responseMessage) return response } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
5e47521fd971e12640bbc8140544dff3
37.736842
186
0.623447
4.842105
false
false
false
false
oNguyenVanHung/TODO-App
TO-DO-APP/Group.swift
1
443
// // Group.swift // TO-DO-APP // // Created by ha.van.duc on 8/16/17. // Copyright © 2017 framgia. All rights reserved. // import Foundation class Group { var groupId = 1 var name = "" var numberTask = 0 var image = "" init(groupId: Int, name: String, numberTask: Int, image: String) { self.groupId = groupId self.name = name self.numberTask = numberTask self.image = image } }
mit
e45dc24b0534a33b972931328dc096a7
18.217391
70
0.588235
3.323308
false
false
false
false
cdillard/SwiftLint
Source/SwiftLintFrameworkTests/RuleConfigurationTests.swift
2
6169
// // RuleConfigurationTests.swift // SwiftLint // // Created by Scott Hoyt on 1/20/16. // Copyright © 2016 Realm. All rights reserved. // import XCTest @testable import SwiftLintFramework import SourceKittenFramework class RuleConfigurationsTests: XCTestCase { // protocol XCTestCaseProvider lazy var allTests: [(String, () throws -> Void)] = [ ("testNameConfigurationSetsCorrectly", self.testNameConfigurationSetsCorrectly), ("testNameConfigurationThrowsOnBadConfig", self.testNameConfigurationThrowsOnBadConfig), ("testNameConfigurationMinLengthThreshold", self.testNameConfigurationMinLengthThreshold), ("testNameConfigurationMaxLengthThreshold", self.testNameConfigurationMaxLengthThreshold), ("testSeverityConfigurationFromString", self.testSeverityConfigurationFromString), ("testSeverityConfigurationFromDictionary", self.testSeverityConfigurationFromDictionary), ("testSeverityConfigurationThrowsOnBadConfig", self.testSeverityConfigurationThrowsOnBadConfig), ("testSeverityLevelConfigParams", self.testSeverityLevelConfigParams), ("testSeverityLevelConfigPartialParams", self.testSeverityLevelConfigPartialParams), ("testRegexConfigurationThrows", self.testRegexConfigurationThrows), ("testRegexRuleDescription", self.testRegexRuleDescription), ] func testNameConfigurationSetsCorrectly() { let config = [ "min_length": ["warning": 17, "error": 7], "max_length": ["warning": 170, "error": 700], "excluded": "id"] var nameConfig = NameConfiguration(minLengthWarning: 0, minLengthError: 0, maxLengthWarning: 0, maxLengthError: 0) let comp = NameConfiguration(minLengthWarning: 17, minLengthError: 7, maxLengthWarning: 170, maxLengthError: 700, excluded: ["id"]) do { try nameConfig.applyConfiguration(config) XCTAssertEqual(nameConfig, comp) } catch { XCTFail("Did not configure correctly") } } func testNameConfigurationThrowsOnBadConfig() { let config = 17 var nameConfig = NameConfiguration(minLengthWarning: 0, minLengthError: 0, maxLengthWarning: 0, maxLengthError: 0) checkError(ConfigurationError.UnknownConfiguration) { try nameConfig.applyConfiguration(config) } } func testNameConfigurationMinLengthThreshold() { var nameConfig = NameConfiguration(minLengthWarning: 7, minLengthError: 17, maxLengthWarning: 0, maxLengthError: 0, excluded: []) XCTAssertEqual(nameConfig.minLengthThreshold, 17) nameConfig.minLength.error = nil XCTAssertEqual(nameConfig.minLengthThreshold, 7) } func testNameConfigurationMaxLengthThreshold() { var nameConfig = NameConfiguration(minLengthWarning: 0, minLengthError: 0, maxLengthWarning: 17, maxLengthError: 7, excluded: []) XCTAssertEqual(nameConfig.maxLengthThreshold, 7) nameConfig.maxLength.error = nil XCTAssertEqual(nameConfig.maxLengthThreshold, 17) } func testSeverityConfigurationFromString() { let config = "Warning" let comp = SeverityConfiguration(.Warning) var severityConfig = SeverityConfiguration(.Error) do { try severityConfig.applyConfiguration(config) XCTAssertEqual(severityConfig, comp) } catch { XCTFail() } } func testSeverityConfigurationFromDictionary() { let config = ["severity": "warning"] let comp = SeverityConfiguration(.Warning) var severityConfig = SeverityConfiguration(.Error) do { try severityConfig.applyConfiguration(config) XCTAssertEqual(severityConfig, comp) } catch { XCTFail() } } func testSeverityConfigurationThrowsOnBadConfig() { let config = 17 var severityConfig = SeverityConfiguration(.Warning) checkError(ConfigurationError.UnknownConfiguration) { try severityConfig.applyConfiguration(config) } } func testSeverityLevelConfigParams() { let severityConfig = SeverityLevelsConfiguration(warning: 17, error: 7) XCTAssertEqual(severityConfig.params, [RuleParameter(severity: .Error, value: 7), RuleParameter(severity: .Warning, value: 17)]) } func testSeverityLevelConfigPartialParams() { let severityConfig = SeverityLevelsConfiguration(warning: 17, error: nil) XCTAssertEqual(severityConfig.params, [RuleParameter(severity: .Warning, value: 17)]) } func testRegexConfigurationThrows() { let config = 17 var regexConfig = RegexConfiguration(identifier: "") checkError(ConfigurationError.UnknownConfiguration) { try regexConfig.applyConfiguration(config) } } func testRegexRuleDescription() { var regexConfig = RegexConfiguration(identifier: "regex") XCTAssertEqual(regexConfig.description, RuleDescription(identifier: "regex", name: "regex", description: "")) regexConfig.name = "name" XCTAssertEqual(regexConfig.description, RuleDescription(identifier: "regex", name: "name", description: "")) } }
mit
59bf8177a8e8b542aac906f9c543ea6e
40.675676
98
0.595655
5.879886
false
true
false
false
tuarua/WebViewANE
native_library/apple/WebViewANE/WebViewANE/Configuration.swift
1
4114
// Copyright 2018 Tua Rua Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Additional Terms // No part, or derivative of this Air Native Extensions's code is permitted // to be sold as the basis of a commercially packaged Air Native Extension which // undertakes the same purpose as this software. That is, a WebView for Windows, // OSX and/or iOS and/or Android. // All Rights Reserved. Tua Rua Ltd. import Foundation import WebKit import FreSwift #if canImport(Cocoa) import Cocoa #endif open class Configuration: WKWebViewConfiguration { private var _bounces: Bool = true public var doesBounce: Bool { return _bounces } private var _useZoomGestures = true public var useZoomGestures: Bool { return _useZoomGestures } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init() { super.init() } convenience init(_ freObject: FREObject?) { guard let rv = freObject, let allowsInlineMediaPlayback = Bool(rv["allowsInlineMediaPlayback"]), let plugInsEnabled = Bool(rv["plugInsEnabled"]), let javaEnabled = Bool(rv["javaEnabled"]), let javaScriptEnabled = Bool(rv["javaScriptEnabled"]), let javaScriptCanOpenWindowsAutomatically = Bool(rv["javaScriptCanOpenWindowsAutomatically"]), let allowsPictureInPictureMediaPlayback = Bool(rv["allowsPictureInPictureMediaPlayback"]), let ignoresViewportScaleLimits = Bool(rv["ignoresViewportScaleLimits"]), let allowsAirPlayForMediaPlayback = Bool(rv["allowsAirPlayForMediaPlayback"]), let limitsNavigationsToAppBoundDomains = Bool(rv["limitsNavigationsToAppBoundDomains"]), let bounces = Bool(rv["bounces"]), let useZoomGestures = Bool(rv["useZoomGestures"]), let minimumFontSize = CGFloat(rv["minimumFontSize"]) else { self.init() return } self.init() self.preferences.javaScriptCanOpenWindowsAutomatically = javaScriptCanOpenWindowsAutomatically self.preferences.javaScriptEnabled = javaScriptEnabled self.preferences.minimumFontSize = minimumFontSize if let freCustom = rv["custom"] { let custom = FREArray(freCustom) for index in 0..<custom.length { if let argFre: FREObject = custom[index], let key = String(argFre["key"]), let val = argFre["value"], let v = FreObjectSwift(val).value { self.preferences.setValue(v, forKey: key) } } } if #available(OSX 10.16, iOS 14.0, *) { self.limitsNavigationsToAppBoundDomains = limitsNavigationsToAppBoundDomains } #if os(iOS) self.allowsInlineMediaPlayback = allowsInlineMediaPlayback self.allowsPictureInPictureMediaPlayback = allowsPictureInPictureMediaPlayback self.allowsAirPlayForMediaPlayback = allowsAirPlayForMediaPlayback self._bounces = bounces self._useZoomGestures = useZoomGestures if #available(iOS 10.0, *) { self.ignoresViewportScaleLimits = ignoresViewportScaleLimits } #else self.preferences.plugInsEnabled = plugInsEnabled self.preferences.javaEnabled = javaEnabled if #available(OSX 10.11, *) { self.allowsAirPlayForMediaPlayback = allowsInlineMediaPlayback } #endif } }
apache-2.0
b46ea04f787b4599dc9485e0e4e1d1ca
38.180952
106
0.658483
4.868639
false
false
false
false
retsohuang/RHMVVMHelpers
Source/MVVM.swift
1
1466
// // MVVM.swift // CloudPassport // // Created by Retso Huang on 12/24/14. // Copyright (c) 2014 Retso Huang. All rights reserved. // import Foundation func uniq<S : SequenceType, T : Hashable where S.Generator.Element == T>(source: S) -> [T] { var buffer = [T]() var addedDict = [T: Bool]() for elem in source { if addedDict[elem] == nil { addedDict[elem] = true buffer.append(elem) } } return buffer } class Dynamic<T> { typealias Observer = T -> Void // MARK: - Variable private var observers = [Int: Observer]() var value: T { didSet { self.send() } } // MARK: - Binding func bind(observer: Observer, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { let hashValue = "\(functionName)\(fileName)\(lineNumber)".hashValue if self.observers[hashValue] == nil { self.observers[hashValue] = observer } } func bindAndFire(observer: Observer, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { self.bind(observer, functionName: functionName, fileName: fileName, lineNumber: lineNumber) observer(value) } // MARK: - Private Function private func send() { for observerkey in self.observers.keys { if let observer = self.observers[observerkey] { observer(value) } } } // MARK: - Initializer init(_ v: T) { value = v } }
mit
a7628dea178890635aa729ef92d1d914
22.66129
134
0.614598
3.788114
false
false
false
false
iOSTestApps/firefox-ios
Client/Frontend/Browser/BrowserViewController.swift
1
87109
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Photos import UIKit import WebKit import Shared import Storage import SnapKit import XCGLogger import Alamofire private let log = XCGLogger.defaultInstance() private let OKString = NSLocalizedString("OK", comment: "OK button") private let CancelString = NSLocalizedString("Cancel", comment: "Cancel button") private let KVOLoading = "loading" private let KVOEstimatedProgress = "estimatedProgress" private let KVOURL = "URL" private let KVOCanGoBack = "canGoBack" private let KVOCanGoForward = "canGoForward" private let ActionSheetTitleMaxLength = 120 private struct BrowserViewControllerUX { private static let BackgroundColor = UIConstants.AppBackgroundColor private static let ShowHeaderTapAreaHeight: CGFloat = 32 private static let BookmarkStarAnimationDuration: Double = 0.5 private static let BookmarkStarAnimationOffset: CGFloat = 80 } class BrowserViewController: UIViewController { var homePanelController: HomePanelViewController? var webViewContainer: UIView! var urlBar: URLBarView! var readerModeBar: ReaderModeBarView? private var statusBarOverlay: UIView! private var toolbar: BrowserToolbar? private var searchController: SearchViewController? private let uriFixup = URIFixup() private var screenshotHelper: ScreenshotHelper! private var homePanelIsInline = false private var searchLoader: SearchLoader! private let snackBars = UIView() private let auralProgress = AuralProgressBar() // location label actions private var pasteGoAction: AccessibleAction! private var pasteAction: AccessibleAction! private var copyAddressAction: AccessibleAction! private weak var tabTrayController: TabTrayController! private let profile: Profile let tabManager: TabManager // These views wrap the urlbar and toolbar to provide background effects on them var header: UIView! var footer: UIView! private var footerBackground: UIView! private var topTouchArea: UIButton! private var scrollController = BrowserScrollingController() private var keyboardState: KeyboardState? let WhiteListedUrls = ["\\/\\/itunes\\.apple\\.com\\/"] // Tracking navigation items to record history types. // TODO: weak references? var ignoredNavigation = Set<WKNavigation>() var typedNavigation = [WKNavigation: VisitType]() var navigationToolbar: BrowserToolbarProtocol { return toolbar ?? urlBar } init(profile: Profile, tabManager: TabManager) { self.profile = profile self.tabManager = tabManager super.init(nibName: nil, bundle: nil) didInit() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } private func didInit() { screenshotHelper = BrowserScreenshotHelper(controller: self) tabManager.addDelegate(self) tabManager.addNavigationDelegate(self) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } func shouldShowFooterForTraitCollection(previousTraitCollection: UITraitCollection) -> Bool { return previousTraitCollection.verticalSizeClass != .Compact && previousTraitCollection.horizontalSizeClass != .Regular } private func updateToolbarStateForTraitCollection(newCollection: UITraitCollection) { let showToolbar = shouldShowFooterForTraitCollection(newCollection) urlBar.setShowToolbar(!showToolbar) toolbar?.removeFromSuperview() toolbar?.browserToolbarDelegate = nil footerBackground?.removeFromSuperview() footerBackground = nil toolbar = nil if showToolbar { toolbar = BrowserToolbar() toolbar?.browserToolbarDelegate = self footerBackground = wrapInEffect(toolbar!, parent: footer) } view.setNeedsUpdateConstraints() if let home = homePanelController { home.view.setNeedsUpdateConstraints() } if let tab = tabManager.selectedTab, webView = tab.webView { updateURLBarDisplayURL(tab) navigationToolbar.updateBackStatus(webView.canGoBack) navigationToolbar.updateForwardStatus(webView.canGoForward) navigationToolbar.updateReloadStatus(tab.loading ?? false) } } override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator) updateToolbarStateForTraitCollection(newCollection) // WKWebView looks like it has a bug where it doesn't invalidate it's visible area when the user // performs a device rotation. Since scrolling calls // _updateVisibleContentRects (https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/API/Cocoa/WKWebView.mm#L1430) // this method nudges the web view's scroll view by a single pixel to force it to invalidate. if let scrollView = self.tabManager.selectedTab?.webView?.scrollView { let contentOffset = scrollView.contentOffset coordinator.animateAlongsideTransition({ context in scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y + 1), animated: true) self.scrollController.showToolbars(animated: false) }, completion: { context in scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y), animated: false) }) } } func SELstatusBarFrameWillChange(notification: NSNotification) { if let statusBarFrame = notification.userInfo![UIApplicationStatusBarFrameUserInfoKey] as? NSValue { scrollController.showToolbars(animated: false) self.view.setNeedsUpdateConstraints() } } func SELtappedTopArea() { scrollController.showToolbars(animated: true) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillChangeStatusBarFrameNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: BookmarkStatusChangedNotification, object: nil) } override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELstatusBarFrameWillChange:", name: UIApplicationWillChangeStatusBarFrameNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELBookmarkStatusDidChange:", name: BookmarkStatusChangedNotification, object: nil) KeyboardHelper.defaultHelper.addDelegate(self) webViewContainer = UIView() view.addSubview(webViewContainer) // Temporary work around for covering the non-clipped web view content statusBarOverlay = UIView() statusBarOverlay.backgroundColor = BrowserViewControllerUX.BackgroundColor view.addSubview(statusBarOverlay) topTouchArea = UIButton() topTouchArea.addTarget(self, action: "SELtappedTopArea", forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(topTouchArea) // Setup the URL bar, wrapped in a view to get transparency effect urlBar = URLBarView() urlBar.setTranslatesAutoresizingMaskIntoConstraints(false) urlBar.delegate = self urlBar.browserToolbarDelegate = self header = wrapInEffect(urlBar, parent: view, backgroundColor: nil) // UIAccessibilityCustomAction subclass holding an AccessibleAction instance does not work, thus unable to generate AccessibleActions and UIAccessibilityCustomActions "on-demand" and need to make them "persistent" e.g. by being stored in BVC pasteGoAction = AccessibleAction(name: NSLocalizedString("Paste & Go", comment: "Paste the URL into the location bar and visit"), handler: { () -> Bool in if let pasteboardContents = UIPasteboard.generalPasteboard().string { self.urlBar(self.urlBar, didSubmitText: pasteboardContents) return true } return false }) pasteAction = AccessibleAction(name: NSLocalizedString("Paste", comment: "Paste the URL into the location bar"), handler: { () -> Bool in if let pasteboardContents = UIPasteboard.generalPasteboard().string { self.urlBar.enterOverlayMode(pasteboardContents) return true } return false }) copyAddressAction = AccessibleAction(name: NSLocalizedString("Copy Address", comment: "Copy the URL from the location bar"), handler: { () -> Bool in if let urlString = self.urlBar.currentURL?.absoluteString { UIPasteboard.generalPasteboard().string = urlString } return true }) searchLoader = SearchLoader(history: profile.history, urlBar: urlBar) footer = UIView() self.view.addSubview(footer) self.view.addSubview(snackBars) snackBars.backgroundColor = UIColor.clearColor() scrollController.urlBar = urlBar scrollController.header = header scrollController.footer = footer scrollController.snackBars = snackBars self.updateToolbarStateForTraitCollection(self.traitCollection) } func loadQueuedTabs() { log.debug("Loading queued tabs.") // This assumes that the DB returns rows in some kind of sane order. // It does in practice, so WFM. self.profile.queue.getQueuedTabs() >>== { c in log.debug("Queue. Count: \(c.count).") if c.count > 0 { var urls = [NSURL]() for (let r) in c { if let url = r?.url.asURL { log.debug("Queuing \(url).") urls.append(url) } } if !urls.isEmpty { dispatch_async(dispatch_get_main_queue()) { self.tabManager.addTabsForURLs(urls, zombie: false) } } } // Clear *after* making an attempt to open. We're making a bet that // it's better to run the risk of perhaps opening twice on a crash, // rather than losing data. self.profile.queue.clearQueuedTabs() } } func startTrackingAccessibilityStatus() { NSNotificationCenter.defaultCenter().addObserverForName(UIAccessibilityVoiceOverStatusChanged, object: nil, queue: nil) { (notification) -> Void in self.auralProgress.hidden = !UIAccessibilityIsVoiceOverRunning() } auralProgress.hidden = !UIAccessibilityIsVoiceOverRunning() } func stopTrackingAccessibilityStatus() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIAccessibilityVoiceOverStatusChanged, object: nil) auralProgress.hidden = true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // On iPhone, if we are about to show the On-Boarding, blank out the browser so that it does // not flash before we present. This change of alpha also participates in the animation when // the intro view is dismissed. if UIDevice.currentDevice().userInterfaceIdiom == .Phone { self.view.alpha = (profile.prefs.intForKey(IntroViewControllerSeenProfileKey) != nil) ? 1.0 : 0.0 } if tabManager.count == 0 && !AppConstants.IsRunningTest { // If we previously crashed, ask the user if they want to restore their tabs if FXCrashDetector.sharedDetector().hasCrashed() { let crashData = FXCrashDetector.sharedDetector().crashData as FXCrashDetectorData crashData.clearPreviousCrash() let alertView = UIAlertView( title: CrashPromptMessaging.CrashPromptTitle, message: CrashPromptMessaging.CrashPromptDescription, delegate: self, cancelButtonTitle: CrashPromptMessaging.CrashPromptNegative, otherButtonTitles: CrashPromptMessaging.CrashPromptAffirmative) alertView.show() } else { tabManager.restoreTabs() } } // If restoring tabs failed, was disabled, there was nothing to restore, or we're running tests, // create an initial about:home tab. if tabManager.count == 0 { let tab = tabManager.addTab() tabManager.selectTab(tab) } } override func viewDidAppear(animated: Bool) { startTrackingAccessibilityStatus() presentIntroViewController() super.viewDidAppear(animated) } override func viewDidDisappear(animated: Bool) { stopTrackingAccessibilityStatus() } override func updateViewConstraints() { super.updateViewConstraints() statusBarOverlay.snp_remakeConstraints { make in make.left.right.equalTo(self.view) make.height.equalTo(UIApplication.sharedApplication().statusBarFrame.height) make.bottom.equalTo(header.snp_top) } topTouchArea.snp_remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight) } urlBar.snp_remakeConstraints { make in make.edges.equalTo(self.header) } header.snp_remakeConstraints { make in let topLayoutGuide = self.topLayoutGuide as! UIView scrollController.headerTopConstraint = make.top.equalTo(topLayoutGuide.snp_bottom).constraint make.height.equalTo(UIConstants.ToolbarHeight) make.left.right.equalTo(self.view) } header.setNeedsUpdateConstraints() readerModeBar?.snp_remakeConstraints { make in make.top.equalTo(self.header.snp_bottom).constraint make.height.equalTo(UIConstants.ToolbarHeight) make.leading.trailing.equalTo(self.view) } webViewContainer.snp_remakeConstraints { make in make.left.right.equalTo(self.view) if let readerModeBarBottom = readerModeBar?.snp_bottom { make.top.equalTo(readerModeBarBottom) } else { make.top.equalTo(self.header.snp_bottom) } if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp_top) } else { make.bottom.equalTo(self.view) } } // Setup the bottom toolbar toolbar?.snp_remakeConstraints { make in make.edges.equalTo(self.footerBackground!) make.height.equalTo(UIConstants.ToolbarHeight) } footer.snp_remakeConstraints { make in scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp_bottom).constraint make.top.equalTo(self.snackBars.snp_top) make.leading.trailing.equalTo(self.view) } adjustFooterSize(top: nil) footerBackground?.snp_remakeConstraints { make in make.bottom.left.right.equalTo(self.footer) make.height.equalTo(UIConstants.ToolbarHeight) } urlBar.setNeedsUpdateConstraints() // Remake constraints even if we're already showing the home controller. // The home controller may change sizes if we tap the URL bar while on about:home. homePanelController?.view.snp_remakeConstraints { make in make.top.equalTo(self.urlBar.snp_bottom) make.left.right.equalTo(self.view) if self.homePanelIsInline { make.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom) } else { make.bottom.equalTo(self.view.snp_bottom) } } } private func wrapInEffect(view: UIView, parent: UIView) -> UIView { return self.wrapInEffect(view, parent: parent, backgroundColor: UIColor.clearColor()) } private func wrapInEffect(view: UIView, parent: UIView, backgroundColor: UIColor?) -> UIView { let effect = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight)) effect.clipsToBounds = true effect.setTranslatesAutoresizingMaskIntoConstraints(false) if let background = backgroundColor { view.backgroundColor = backgroundColor } effect.addSubview(view) parent.addSubview(effect) return effect } private func showHomePanelController(#inline: Bool) { homePanelIsInline = inline if homePanelController == nil { homePanelController = HomePanelViewController() homePanelController!.profile = profile homePanelController!.delegate = self homePanelController!.url = tabManager.selectedTab?.displayURL homePanelController!.view.alpha = 0 addChildViewController(homePanelController!) view.addSubview(homePanelController!.view) homePanelController!.didMoveToParentViewController(self) } var panelNumber = tabManager.selectedTab?.url?.fragment var numberArray = panelNumber?.componentsSeparatedByString("=") homePanelController?.selectedButtonIndex = numberArray?.last?.toInt() ?? 0 // We have to run this animation, even if the view is already showing because there may be a hide animation running // and we want to be sure to override its results. UIView.animateWithDuration(0.2, animations: { () -> Void in self.homePanelController!.view.alpha = 1 }, completion: { finished in if finished { self.webViewContainer.accessibilityElementsHidden = true self.stopTrackingAccessibilityStatus() UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } }) toolbar?.hidden = !inline view.setNeedsUpdateConstraints() } private func hideHomePanelController() { if let controller = homePanelController { UIView.animateWithDuration(0.2, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in controller.view.alpha = 0 }, completion: { finished in if finished { controller.willMoveToParentViewController(nil) controller.view.removeFromSuperview() controller.removeFromParentViewController() self.homePanelController = nil self.webViewContainer.accessibilityElementsHidden = false self.toolbar?.hidden = false self.startTrackingAccessibilityStatus() UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // Refresh the reading view toolbar since the article record may have changed if let readerMode = self.tabManager.selectedTab?.getHelper(name: ReaderMode.name()) as? ReaderMode where readerMode.state == .Active { self.showReaderModeBar(animated: false) } } }) } } private func updateInContentHomePanel(url: NSURL?) { if !urlBar.inOverlayMode { if AboutUtils.isAboutHomeURL(url){ showHomePanelController(inline: (tabManager.selectedTab?.canGoForward ?? false || tabManager.selectedTab?.canGoBack ?? false)) } else { hideHomePanelController() } } } private func showSearchController() { if searchController != nil { return } searchController = SearchViewController() searchController!.searchEngines = profile.searchEngines searchController!.searchDelegate = self searchController!.profile = self.profile searchLoader.addListener(searchController!) addChildViewController(searchController!) view.addSubview(searchController!.view) searchController!.view.snp_makeConstraints { make in make.top.equalTo(self.urlBar.snp_bottom) make.left.right.bottom.equalTo(self.view) return } homePanelController?.view?.hidden = true searchController!.didMoveToParentViewController(self) } private func hideSearchController() { if let searchController = searchController { searchController.willMoveToParentViewController(nil) searchController.view.removeFromSuperview() searchController.removeFromParentViewController() self.searchController = nil homePanelController?.view?.hidden = false } } private func finishEditingAndSubmit(var url: NSURL, visitType: VisitType) { urlBar.currentURL = url urlBar.leaveOverlayMode() if let tab = tabManager.selectedTab, let nav = tab.loadRequest(NSURLRequest(URL: url)) { self.recordNavigationInTab(tab, navigation: nav, visitType: visitType) } } func addBookmark(url: String, title: String?) { let shareItem = ShareItem(url: url, title: title, favicon: nil) profile.bookmarks.shareItem(shareItem) animateBookmarkStar() // Dispatch to the main thread to update the UI dispatch_async(dispatch_get_main_queue()) { _ in self.toolbar?.updateBookmarkStatus(true) self.urlBar.updateBookmarkStatus(true) } } private func animateBookmarkStar() { let offset: CGFloat let button: UIButton! if let toolbar: BrowserToolbar = self.toolbar { offset = BrowserViewControllerUX.BookmarkStarAnimationOffset * -1 button = toolbar.bookmarkButton } else { offset = BrowserViewControllerUX.BookmarkStarAnimationOffset button = self.urlBar.bookmarkButton } let offToolbar = CGAffineTransformMakeTranslation(0, offset) UIView.animateWithDuration(BrowserViewControllerUX.BookmarkStarAnimationDuration, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 2.0, options: nil, animations: { () -> Void in button.transform = offToolbar var rotation = CABasicAnimation(keyPath: "transform.rotation") rotation.toValue = CGFloat(M_PI * 2.0) rotation.cumulative = true rotation.duration = BrowserViewControllerUX.BookmarkStarAnimationDuration + 0.075 rotation.repeatCount = 1.0 rotation.timingFunction = CAMediaTimingFunction(controlPoints: 0.32, 0.70 ,0.18 ,1.00) button.imageView?.layer.addAnimation(rotation, forKey: "rotateStar") }, completion: { finished in UIView.animateWithDuration(BrowserViewControllerUX.BookmarkStarAnimationDuration, delay: 0.15, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: nil, animations: { () -> Void in button.transform = CGAffineTransformIdentity }, completion: nil) }) } private func removeBookmark(url: String) { profile.bookmarks.removeByURL(url).uponQueue(dispatch_get_main_queue()) { res in if res.isSuccess { self.toolbar?.updateBookmarkStatus(false) self.urlBar.updateBookmarkStatus(false) } } } func SELBookmarkStatusDidChange(notification: NSNotification) { if let bookmark = notification.object as? BookmarkItem { if bookmark.url == urlBar.currentURL?.absoluteString { if let userInfo = notification.userInfo as? Dictionary<String, Bool>{ if let added = userInfo["added"]{ self.toolbar?.updateBookmarkStatus(added) self.urlBar.updateBookmarkStatus(added) } } } } } override func accessibilityPerformEscape() -> Bool { if urlBar.inOverlayMode { urlBar.SELdidClickCancel() return true } else if let selectedTab = tabManager.selectedTab where selectedTab.canGoBack { selectedTab.goBack() return true } return false } override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject: AnyObject], context: UnsafeMutablePointer<Void>) { let webView = object as! WKWebView if webView !== tabManager.selectedTab?.webView { return } switch keyPath { case KVOEstimatedProgress: let progress = change[NSKeyValueChangeNewKey] as! Float urlBar.updateProgressBar(progress) // when loading is stopped, KVOLoading is fired first, and only then KVOEstimatedProgress with progress 1.0 which would leave the progress bar running if progress != 1.0 || tabManager.selectedTab?.loading ?? false { auralProgress.progress = Double(progress) } case KVOLoading: let loading = change[NSKeyValueChangeNewKey] as! Bool toolbar?.updateReloadStatus(loading) urlBar.updateReloadStatus(loading) auralProgress.progress = loading ? 0 : nil case KVOURL: if let tab = tabManager.selectedTab where tab.webView === webView { updateURLBarDisplayURL(tab) scrollController.showToolbars(animated: false) if let url = tab.url { if ReaderModeUtils.isReaderModeURL(url) { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } } updateInContentHomePanel(tab.url) } case KVOCanGoBack: let canGoBack = change[NSKeyValueChangeNewKey] as! Bool navigationToolbar.updateBackStatus(canGoBack) case KVOCanGoForward: let canGoForward = change[NSKeyValueChangeNewKey] as! Bool navigationToolbar.updateForwardStatus(canGoForward) default: assertionFailure("Unhandled KVO key: \(keyPath)") } } private func isWhitelistedUrl(url: NSURL) -> Bool { for entry in WhiteListedUrls { if let match = url.absoluteString!.rangeOfString(entry, options: .RegularExpressionSearch) { return UIApplication.sharedApplication().canOpenURL(url) } } return false } /// Updates the URL bar text and button states. /// Call this whenever the page URL changes. private func updateURLBarDisplayURL(tab: Browser) { urlBar.currentURL = tab.displayURL let isPage = (tab.displayURL != nil) ? isWebPage(tab.displayURL!) : false navigationToolbar.updatePageStatus(isWebPage: isPage) if let url = tab.displayURL?.absoluteString { profile.bookmarks.isBookmarked(url, success: { bookmarked in self.navigationToolbar.updateBookmarkStatus(bookmarked) }, failure: { err in log.error("Error getting bookmark status: \(err).") }) } } func openURLInNewTab(url: NSURL) { let tab = tabManager.addTab(request: NSURLRequest(URL: url)) tabManager.selectTab(tab) } } /** * History visit management. * TODO: this should be expanded to track various visit types; see Bug 1166084. */ extension BrowserViewController { func ignoreNavigationInTab(tab: Browser, navigation: WKNavigation) { self.ignoredNavigation.insert(navigation) } func recordNavigationInTab(tab: Browser, navigation: WKNavigation, visitType: VisitType) { self.typedNavigation[navigation] = visitType } /** * Untrack and do the right thing. */ func getVisitTypeForTab(tab: Browser, navigation: WKNavigation?) -> VisitType? { if let navigation = navigation { if let ignored = self.ignoredNavigation.remove(navigation) { return nil } return self.typedNavigation.removeValueForKey(navigation) ?? VisitType.Link } else { // See https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/NavigationState.mm#L390 return VisitType.Link } } } extension BrowserViewController: URLBarDelegate { func urlBarDidPressReload(urlBar: URLBarView) { tabManager.selectedTab?.reload() } func urlBarDidPressStop(urlBar: URLBarView) { tabManager.selectedTab?.stop() } func urlBarDidPressTabs(urlBar: URLBarView) { let tabTrayController = TabTrayController() tabTrayController.profile = profile tabTrayController.tabManager = tabManager if let tab = tabManager.selectedTab { tab.screenshot = screenshotHelper.takeScreenshot(tab, aspectRatio: 0, quality: 1) } self.navigationController?.pushViewController(tabTrayController, animated: true) self.tabTrayController = tabTrayController } func urlBarDidPressReaderMode(urlBar: URLBarView) { if let tab = tabManager.selectedTab { if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode { switch readerMode.state { case .Available: enableReaderMode() case .Active: disableReaderMode() case .Unavailable: break } } } } func urlBarDidLongPressReaderMode(urlBar: URLBarView) -> Bool { if let tab = tabManager.selectedTab, url = tab.displayURL, absoluteString = url.absoluteString, result = profile.readingList?.createRecordWithURL(absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().name) { switch result { case .Success: UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Added page to Reading List", comment: "Accessibility message e.g. spoken by VoiceOver after the current page gets added to the Reading List using the Reader View button, e.g. by long-pressing it or by its accessibility custom action.")) // TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=1158503 provide some form of 'this has been added' visual feedback? case .Failure(let error): UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading List. Maybe it's already there?", comment: "Accessibility message e.g. spoken by VoiceOver after the user wanted to add current page to the Reading List and this was not done, likely because it already was in the Reading List, but perhaps also because of real failures.")) log.error("readingList.createRecordWithURL(url: \"\(absoluteString)\", ...) failed with error: \(error)") } return true } UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading list", comment: "Accessibility message e.g. spoken by VoiceOver after adding current webpage to the Reading List failed.")) return false } func locationActionsForURLBar(urlBar: URLBarView) -> [AccessibleAction] { if UIPasteboard.generalPasteboard().string != nil { return [pasteGoAction, pasteAction, copyAddressAction] } else { return [copyAddressAction] } } func urlBarDidLongPressLocation(urlBar: URLBarView) { let longPressAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) for action in locationActionsForURLBar(urlBar) { longPressAlertController.addAction(action.alertAction(style: .Default)) } let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel alert view"), style: .Cancel, handler: { (alert: UIAlertAction!) -> Void in }) longPressAlertController.addAction(cancelAction) if let popoverPresentationController = longPressAlertController.popoverPresentationController { popoverPresentationController.sourceView = urlBar popoverPresentationController.sourceRect = urlBar.frame popoverPresentationController.permittedArrowDirections = .Any } self.presentViewController(longPressAlertController, animated: true, completion: nil) } func urlBarDidPressScrollToTop(urlBar: URLBarView) { if let selectedTab = tabManager.selectedTab { // Only scroll to top if we are not showing the home view controller if homePanelController == nil { selectedTab.webView?.scrollView.setContentOffset(CGPointZero, animated: true) } } } func urlBarLocationAccessibilityActions(urlBar: URLBarView) -> [UIAccessibilityCustomAction]? { return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction } } func urlBar(urlBar: URLBarView, didEnterText text: String) { searchLoader.query = text if text.isEmpty { hideSearchController() } else { showSearchController() searchController!.searchQuery = text } } func urlBar(urlBar: URLBarView, didSubmitText text: String) { var url = uriFixup.getURL(text) // If we can't make a valid URL, do a search query. if url == nil { url = profile.searchEngines.defaultEngine.searchURLForQuery(text) } // If we still don't have a valid URL, something is broken. Give up. if url == nil { log.error("Error handling URL entry: \"\(text)\".") return } finishEditingAndSubmit(url!, visitType: VisitType.Typed) } func urlBarDidEnterOverlayMode(urlBar: URLBarView) { showHomePanelController(inline: false) } func urlBarDidLeaveOverlayMode(urlBar: URLBarView) { hideSearchController() updateInContentHomePanel(tabManager.selectedTab?.url) } } extension BrowserViewController: BrowserToolbarDelegate { func browserToolbarDidPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goBack() } func browserToolbarDidLongPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) { // See 1159373 - Disable long press back/forward for backforward list // let controller = BackForwardListViewController() // controller.listData = tabManager.selectedTab?.backList // controller.tabManager = tabManager // presentViewController(controller, animated: true, completion: nil) } func browserToolbarDidPressReload(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.reload() } func browserToolbarDidPressStop(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.stop() } func browserToolbarDidPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goForward() } func browserToolbarDidLongPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) { // See 1159373 - Disable long press back/forward for backforward list // let controller = BackForwardListViewController() // controller.listData = tabManager.selectedTab?.forwardList // controller.tabManager = tabManager // presentViewController(controller, animated: true, completion: nil) } func browserToolbarDidPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) { if let tab = tabManager.selectedTab, let url = tab.displayURL?.absoluteString { profile.bookmarks.isBookmarked(url, success: { isBookmarked in if isBookmarked { self.removeBookmark(url) } else { self.addBookmark(url, title: tab.title) } }, failure: { err in log.error("Bookmark error: \(err).") } ) } else { log.error("Bookmark error: No tab is selected, or no URL in tab.") } } func browserToolbarDidLongPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) { } func browserToolbarDidPressShare(browserToolbar: BrowserToolbarProtocol, button: UIButton) { if let selected = tabManager.selectedTab { if let url = selected.displayURL { let printInfo = UIPrintInfo(dictionary: nil) printInfo.jobName = url.absoluteString printInfo.outputType = .General let renderer = BrowserPrintPageRenderer(browser: selected) let activityItems = [printInfo, renderer, selected.title ?? url.absoluteString!, url] var activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) // Hide 'Add to Reading List' which currently uses Safari. // Also hide our own View Later… after all, you're in the browser! let viewLater = NSBundle.mainBundle().bundleIdentifier! + ".ViewLater" activityViewController.excludedActivityTypes = [ UIActivityTypeAddToReadingList, viewLater, // Doesn't work: rdar://19430419 ] activityViewController.completionWithItemsHandler = { activityType, completed, _, _ in log.debug("Selected activity type: \(activityType).") if completed { if let selectedTab = self.tabManager.selectedTab { // We don't know what share action the user has chosen so we simply always // update the toolbar and reader mode bar to refelect the latest status. self.updateURLBarDisplayURL(selectedTab) self.updateReaderModeBar() } } } if let popoverPresentationController = activityViewController.popoverPresentationController { // Using the button for the sourceView here results in this not showing on iPads. popoverPresentationController.sourceView = toolbar ?? urlBar popoverPresentationController.sourceRect = button.frame ?? button.frame popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.Up popoverPresentationController.delegate = self } presentViewController(activityViewController, animated: true, completion: nil) } } } } extension BrowserViewController: BrowserDelegate { func browser(browser: Browser, didCreateWebView webView: WKWebView) { webViewContainer.insertSubview(webView, atIndex: 0) webView.snp_makeConstraints { make in make.edges.equalTo(self.webViewContainer) } // Observers that live as long as the tab. Make sure these are all cleared // in willDeleteWebView below! webView.addObserver(self, forKeyPath: KVOEstimatedProgress, options: .New, context: nil) webView.addObserver(self, forKeyPath: KVOLoading, options: .New, context: nil) webView.addObserver(self, forKeyPath: KVOURL, options: .New, context: nil) webView.addObserver(self, forKeyPath: KVOCanGoBack, options: .New, context: nil) webView.addObserver(self, forKeyPath: KVOCanGoForward, options: .New, context: nil) webView.UIDelegate = self let readerMode = ReaderMode(browser: browser) readerMode.delegate = self browser.addHelper(readerMode, name: ReaderMode.name()) let favicons = FaviconManager(browser: browser, profile: profile) browser.addHelper(favicons, name: FaviconManager.name()) // Temporarily disable password support until the new code lands let logins = LoginsHelper(browser: browser, profile: profile) browser.addHelper(logins, name: LoginsHelper.name()) let contextMenuHelper = ContextMenuHelper(browser: browser) contextMenuHelper.delegate = self browser.addHelper(contextMenuHelper, name: ContextMenuHelper.name()) let errorHelper = ErrorPageHelper() browser.addHelper(errorHelper, name: ErrorPageHelper.name()) } func browser(browser: Browser, willDeleteWebView webView: WKWebView) { webView.removeObserver(self, forKeyPath: KVOEstimatedProgress) webView.removeObserver(self, forKeyPath: KVOLoading) webView.removeObserver(self, forKeyPath: KVOURL) webView.removeObserver(self, forKeyPath: KVOCanGoBack) webView.removeObserver(self, forKeyPath: KVOCanGoForward) webView.UIDelegate = nil webView.scrollView.delegate = nil webView.removeFromSuperview() } private func findSnackbar(barToFind: SnackBar) -> Int? { let bars = snackBars.subviews for (index, bar) in enumerate(bars) { if bar === barToFind { return index } } return nil } private func adjustFooterSize(top: UIView? = nil) { snackBars.snp_remakeConstraints({ make in let bars = self.snackBars.subviews // if the keyboard is showing then ensure that the snackbars are positioned above it, otherwise position them above the toolbar/view bottom if bars.count > 0 { let view = bars[bars.count-1] as! UIView make.top.equalTo(view.snp_top) if let state = keyboardState { make.bottom.equalTo(-(state.intersectionHeightForView(self.view))) } else { make.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom) } } else { make.top.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom) } if traitCollection.horizontalSizeClass != .Regular { make.leading.trailing.equalTo(self.footer) self.snackBars.layer.borderWidth = 0 } else { make.centerX.equalTo(self.footer) make.width.equalTo(SnackBarUX.MaxWidth) self.snackBars.layer.borderColor = UIConstants.BorderColor.CGColor self.snackBars.layer.borderWidth = 1 } }) } // This removes the bar from its superview and updates constraints appropriately private func finishRemovingBar(bar: SnackBar) { // If there was a bar above this one, we need to remake its constraints. if let index = findSnackbar(bar) { // If the bar being removed isn't on the top of the list let bars = snackBars.subviews if index < bars.count-1 { // Move the bar above this one var nextbar = bars[index+1] as! SnackBar nextbar.snp_updateConstraints { make in // If this wasn't the bottom bar, attach to the bar below it if index > 0 { let bar = bars[index-1] as! SnackBar nextbar.bottom = make.bottom.equalTo(bar.snp_top).constraint } else { // Otherwise, we attach it to the bottom of the snackbars nextbar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).constraint } } } } // Really remove the bar bar.removeFromSuperview() } private func finishAddingBar(bar: SnackBar) { snackBars.addSubview(bar) bar.snp_remakeConstraints({ make in // If there are already bars showing, add this on top of them let bars = self.snackBars.subviews // Add the bar on top of the stack // We're the new top bar in the stack, so make sure we ignore ourself if bars.count > 1 { let view = bars[bars.count - 2] as! UIView bar.bottom = make.bottom.equalTo(view.snp_top).offset(0).constraint } else { bar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).offset(0).constraint } make.leading.trailing.equalTo(self.snackBars) }) } func showBar(bar: SnackBar, animated: Bool) { finishAddingBar(bar) adjustFooterSize(top: bar) bar.hide() view.layoutIfNeeded() UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in bar.show() self.view.layoutIfNeeded() }) } func removeBar(bar: SnackBar, animated: Bool) { let index = findSnackbar(bar)! UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in bar.hide() self.view.layoutIfNeeded() }) { success in // Really remove the bar self.finishRemovingBar(bar) // Adjust the footer size to only contain the bars self.adjustFooterSize() } } func removeAllBars() { let bars = snackBars.subviews for bar in bars { if let bar = bar as? SnackBar { bar.removeFromSuperview() } } self.adjustFooterSize() } func browser(browser: Browser, didAddSnackbar bar: SnackBar) { showBar(bar, animated: true) } func browser(browser: Browser, didRemoveSnackbar bar: SnackBar) { removeBar(bar, animated: true) } } extension BrowserViewController: HomePanelViewControllerDelegate { func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectURL url: NSURL, visitType: VisitType) { finishEditingAndSubmit(url, visitType: visitType) } func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectPanel panel: Int) { if AboutUtils.isAboutHomeURL(tabManager.selectedTab?.url) { tabManager.selectedTab?.webView?.evaluateJavaScript("history.replaceState({}, '', '#panel=\(panel)')", completionHandler: nil) } } func homePanelViewControllerDidRequestToCreateAccount(homePanelViewController: HomePanelViewController) { presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same } func homePanelViewControllerDidRequestToSignIn(homePanelViewController: HomePanelViewController) { presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same } } extension BrowserViewController: SearchViewControllerDelegate { func searchViewController(searchViewController: SearchViewController, didSelectURL url: NSURL) { finishEditingAndSubmit(url, visitType: VisitType.Typed) } func presentSearchSettingsController() { let settingsNavigationController = SearchSettingsTableViewController() settingsNavigationController.model = self.profile.searchEngines let navController = UINavigationController(rootViewController: settingsNavigationController) self.presentViewController(navController, animated: true, completion: nil) } } extension BrowserViewController: TabManagerDelegate { func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) { // Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it // and having multiple views with the same label confuses tests. if let wv = previous?.webView { wv.endEditing(true) wv.accessibilityLabel = nil wv.accessibilityElementsHidden = true wv.accessibilityIdentifier = nil // due to screwy handling within iOS, the scrollToTop handling does not work if there are // more than one scroll view in the view hierarchy // we therefore have to hide all the scrollViews that we are no actually interesting in interacting with // to ensure that scrollsToTop actually works wv.scrollView.hidden = true } if let tab = selected, webView = tab.webView { // if we have previously hidden this scrollview in order to make scrollsToTop work then // we should ensure that it is not hidden now that it is our foreground scrollView if webView.scrollView.hidden { webView.scrollView.hidden = false } updateURLBarDisplayURL(tab) scrollController.browser = selected webViewContainer.addSubview(webView) webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.accessibilityIdentifier = "contentView" webView.accessibilityElementsHidden = false if let url = webView.URL?.absoluteString { profile.bookmarks.isBookmarked(url, success: { bookmarked in self.toolbar?.updateBookmarkStatus(bookmarked) self.urlBar.updateBookmarkStatus(bookmarked) }, failure: { err in log.error("Error getting bookmark status: \(err).") }) } else { // The web view can go gray if it was zombified due to memory pressure. // When this happens, the URL is nil, so try restoring the page upon selection. webView.reload() } } removeAllBars() if let bars = selected?.bars { for bar in bars { showBar(bar, animated: true) } } navigationToolbar.updateReloadStatus(selected?.loading ?? false) navigationToolbar.updateBackStatus(selected?.canGoBack ?? false) navigationToolbar.updateForwardStatus(selected?.canGoForward ?? false) self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0)) if let readerMode = selected?.getHelper(name: ReaderMode.name()) as? ReaderMode { urlBar.updateReaderModeState(readerMode.state) if readerMode.state == .Active { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } } else { urlBar.updateReaderModeState(ReaderModeState.Unavailable) } updateInContentHomePanel(selected?.url) } func tabManager(tabManager: TabManager, didCreateTab tab: Browser, restoring: Bool) { } func tabManager(tabManager: TabManager, didAddTab tab: Browser, atIndex: Int, restoring: Bool) { // If we are restoring tabs then we update the count once at the end if !restoring { urlBar.updateTabCount(tabManager.count) } tab.browserDelegate = self } func tabManager(tabManager: TabManager, didRemoveTab tab: Browser, atIndex: Int) { urlBar.updateTabCount(tabManager.count) // browserDelegate is a weak ref (and the tab's webView may not be destroyed yet) // so we don't expcitly unset it. } func tabManagerDidAddTabs(tabManager: TabManager) { urlBar.updateTabCount(tabManager.count) } func tabManagerDidRestoreTabs(tabManager: TabManager) { urlBar.updateTabCount(tabManager.count) } private func isWebPage(url: NSURL) -> Bool { let httpSchemes = ["http", "https"] if let scheme = url.scheme, index = find(httpSchemes, scheme) { return true } return false } } extension BrowserViewController: WKNavigationDelegate { func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { if tabManager.selectedTab?.webView !== webView { return } // If we are going to navigate to a new page, hide the reader mode button. Unless we // are going to a about:reader page. Then we keep it on screen: it will change status // (orange color) as soon as the page has loaded. if let url = webView.URL { if !ReaderModeUtils.isReaderModeURL(url) { urlBar.updateReaderModeState(ReaderModeState.Unavailable) hideReaderModeBar(animated: false) } } } private func openExternal(url: NSURL, prompt: Bool = true) { if prompt { // Ask the user if it's okay to open the url with UIApplication. let alert = UIAlertController( title: String(format: NSLocalizedString("Opening %@", comment:"Opening an external URL"), url), message: NSLocalizedString("This will open in another application", comment: "Opening an external app"), preferredStyle: UIAlertControllerStyle.Alert ) alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Alert Cancel Button"), style: UIAlertActionStyle.Cancel, handler: { (action: UIAlertAction!) in })) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment:"Alert OK Button"), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in UIApplication.sharedApplication().openURL(url) })) presentViewController(alert, animated: true, completion: nil) } else { UIApplication.sharedApplication().openURL(url) } } private func callExternal(url: NSURL) { if let phoneNumber = url.resourceSpecifier?.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { let alert = UIAlertController(title: phoneNumber, message: nil, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Alert Cancel Button"), style: UIAlertActionStyle.Cancel, handler: nil)) alert.addAction(UIAlertAction(title: NSLocalizedString("Call", comment:"Alert Call Button"), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in UIApplication.sharedApplication().openURL(url) })) presentViewController(alert, animated: true, completion: nil) } } func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) { if let url = navigationAction.request.URL { if let scheme = url.scheme { switch scheme { case "about", "http", "https": if isWhitelistedUrl(url) { // If the url is whitelisted, we open it without prompting. openExternal(url, prompt: false) decisionHandler(WKNavigationActionPolicy.Cancel) } else { decisionHandler(WKNavigationActionPolicy.Allow) } case "tel": callExternal(url) decisionHandler(WKNavigationActionPolicy.Cancel) default: if UIApplication.sharedApplication().canOpenURL(url) { openExternal(url) } decisionHandler(WKNavigationActionPolicy.Cancel) } } } else { decisionHandler(WKNavigationActionPolicy.Cancel) } } func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic || challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest { if let tab = tabManager[webView] { let helper = tab.getHelper(name: LoginsHelper.name()) as! LoginsHelper helper.handleAuthRequest(self, challenge: challenge).uponQueue(dispatch_get_main_queue()) { res in if let credentials = res.successValue { completionHandler(.UseCredential, credentials.credentials) } else { completionHandler(NSURLSessionAuthChallengeDisposition.RejectProtectionSpace, nil) } } } } else { completionHandler(NSURLSessionAuthChallengeDisposition.PerformDefaultHandling, nil) } } func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { let tab: Browser! = tabManager[webView] tab.expireSnackbars() if let url = webView.URL where !ErrorPageHelper.isErrorPageURL(url) && !AboutUtils.isAboutHomeURL(url) { let notificationCenter = NSNotificationCenter.defaultCenter() var info = [NSObject: AnyObject]() info["url"] = tab.displayURL info["title"] = tab.title if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue { info["visitType"] = visitType } notificationCenter.postNotificationName("LocationChange", object: self, userInfo: info) // The screenshot immediately after didFinishNavigation is actually a screenshot of the // previous page, presumably due to some iOS bug. Adding a small delay seems to fix this, // and the current page gets captured as expected. let time = dispatch_time(DISPATCH_TIME_NOW, Int64(100 * NSEC_PER_MSEC)) dispatch_after(time, dispatch_get_main_queue()) { if webView.URL != url { // The page changed during the delay, so we missed our chance to get a thumbnail. return } if let screenshot = self.screenshotHelper.takeScreenshot(tab, aspectRatio: CGFloat(ThumbnailCellUX.ImageAspectRatio), quality: 0.5) { let thumbnail = Thumbnail(image: screenshot) self.profile.thumbnails.set(url, thumbnail: thumbnail, complete: nil) } } // Fire the readability check. This is here and not in the pageShow event handler in ReaderMode.js anymore // because that event wil not always fire due to unreliable page caching. This will either let us know that // the currently loaded page can be turned into reading mode or if the page already is in reading mode. We // ignore the result because we are being called back asynchronous when the readermode status changes. webView.evaluateJavaScript("_firefox_ReaderMode.checkReadability()", completionHandler: nil) } if tab === tabManager.selectedTab { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // must be followed by LayoutChanged, as ScreenChanged will make VoiceOver // cursor land on the correct initial element, but if not followed by LayoutChanged, // VoiceOver will sometimes be stuck on the element, not allowing user to move // forward/backward. Strange, but LayoutChanged fixes that. UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } } } extension BrowserViewController: WKUIDelegate { func webView(webView: WKWebView, createWebViewWithConfiguration configuration: WKWebViewConfiguration, forNavigationAction navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if let currentTab = tabManager.selectedTab { currentTab.screenshot = screenshotHelper.takeScreenshot(currentTab, aspectRatio: 0, quality: 1) } // If the page uses window.open() or target="_blank", open the page in a new tab. // TODO: This doesn't work for window.open() without user action (bug 1124942). let tab = tabManager.addTab(request: navigationAction.request, configuration: configuration) tabManager.selectTab(tab) return tab.webView } func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) { tabManager.selectTab(tabManager[webView]) // Show JavaScript alerts. let title = frame.request.URL!.host let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in completionHandler() })) presentViewController(alertController, animated: true, completion: nil) } func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) { tabManager.selectTab(tabManager[webView]) // Show JavaScript confirm dialogs. let title = frame.request.URL!.host let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in completionHandler(true) })) alertController.addAction(UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: { _ in completionHandler(false) })) presentViewController(alertController, animated: true, completion: nil) } func webView(webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: (String!) -> Void) { tabManager.selectTab(tabManager[webView]) // Show JavaScript input dialogs. let title = frame.request.URL!.host let alertController = UIAlertController(title: title, message: prompt, preferredStyle: UIAlertControllerStyle.Alert) var input: UITextField! alertController.addTextFieldWithConfigurationHandler({ (textField: UITextField!) in textField.text = defaultText input = textField }) alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in completionHandler(input.text) })) alertController.addAction(UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: { _ in completionHandler(nil) })) presentViewController(alertController, animated: true, completion: nil) } /// Invoked when an error occurs during a committed main frame navigation. func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) { if error.code == Int(CFNetworkErrors.CFURLErrorCancelled.rawValue) { return } // Ignore the "Plug-in handled load" error. Which is more like a notification than an error. // Note that there are no constants in the SDK for the WebKit domain or error codes. if error.domain == "WebKitErrorDomain" && error.code == 204 { return } if let url = error.userInfo?["NSErrorFailingURLKey"] as? NSURL { ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView) } } /// Invoked when an error occurs while starting to load data for the main frame. func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { if error.code == Int(CFNetworkErrors.CFURLErrorCancelled.rawValue) { if let browser = tabManager[webView] where browser === tabManager.selectedTab { urlBar.currentURL = browser.displayURL } return } if let url = error.userInfo?["NSErrorFailingURLKey"] as? NSURL { ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView) } } func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) { if navigationResponse.canShowMIMEType { decisionHandler(WKNavigationResponsePolicy.Allow) return } let error = NSError(domain: ErrorPageHelper.MozDomain, code: Int(ErrorPageHelper.MozErrorDownloadsNotEnabled), userInfo: [NSLocalizedDescriptionKey: "Downloads aren't supported in Firefox yet (but we're working on it)."]) ErrorPageHelper().showPage(error, forUrl: navigationResponse.response.URL!, inWebView: webView) decisionHandler(WKNavigationResponsePolicy.Allow) } } extension BrowserViewController: ReaderModeDelegate, UIPopoverPresentationControllerDelegate { func readerMode(readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forBrowser browser: Browser) { // If this reader mode availability state change is for the tab that we currently show, then update // the button. Otherwise do nothing and the button will be updated when the tab is made active. if tabManager.selectedTab === browser { log.debug("New readerModeState: \(state.rawValue)") urlBar.updateReaderModeState(state) } } func readerMode(readerMode: ReaderMode, didDisplayReaderizedContentForBrowser browser: Browser) { self.showReaderModeBar(animated: true) browser.showContent(animated: true) } // Returning None here makes sure that the Popover is actually presented as a Popover and // not as a full-screen modal, which is the default on compact device classes. func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.None } } extension BrowserViewController: ReaderModeStyleViewControllerDelegate { func readerModeStyleViewController(readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle) { // Persist the new style to the profile let encodedStyle: [String:AnyObject] = style.encode() profile.prefs.setObject(encodedStyle, forKey: ReaderModeProfileKeyStyle) // Change the reader mode style on all tabs that have reader mode active for tabIndex in 0..<tabManager.count { if let tab = tabManager[tabIndex] { if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode { if readerMode.state == ReaderModeState.Active { readerMode.style = style } } } } } } extension BrowserViewController { func updateReaderModeBar() { if let readerModeBar = readerModeBar { if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { readerModeBar.unread = record.unread readerModeBar.added = true } else { readerModeBar.unread = true readerModeBar.added = false } } else { readerModeBar.unread = true readerModeBar.added = false } } } func showReaderModeBar(#animated: Bool) { if self.readerModeBar == nil { let readerModeBar = ReaderModeBarView(frame: CGRectZero) readerModeBar.delegate = self view.insertSubview(readerModeBar, belowSubview: header) self.readerModeBar = readerModeBar } updateReaderModeBar() self.updateViewConstraints() } func hideReaderModeBar(#animated: Bool) { if let readerModeBar = self.readerModeBar { readerModeBar.removeFromSuperview() self.readerModeBar = nil self.updateViewConstraints() } } /// There are two ways we can enable reader mode. In the simplest case we open a URL to our internal reader mode /// and be done with it. In the more complicated case, reader mode was already open for this page and we simply /// navigated away from it. So we look to the left and right in the BackForwardList to see if a readerized version /// of the current page is there. And if so, we go there. func enableReaderMode() { if let tab = tabManager.selectedTab, let webView = tab.webView, let backList = webView.backForwardList.backList as? [WKBackForwardListItem], let forwardList = webView.backForwardList.forwardList as? [WKBackForwardListItem] { if let currentURL = webView.backForwardList.currentItem?.URL { if let readerModeURL = ReaderModeUtils.encodeURL(currentURL) { if backList.count > 1 && backList.last?.URL == readerModeURL { webView.goToBackForwardListItem(backList.last!) } else if forwardList.count > 0 && forwardList.first?.URL == readerModeURL { webView.goToBackForwardListItem(forwardList.first!) } else { // Store the readability result in the cache and load it. This will later move to the ReadabilityHelper. webView.evaluateJavaScript("\(ReaderModeNamespace).readerize()", completionHandler: { (object, error) -> Void in if let readabilityResult = ReadabilityResult(object: object) { ReaderModeCache.sharedInstance.put(currentURL, readabilityResult, error: nil) if let nav = webView.loadRequest(NSURLRequest(URL: readerModeURL)) { self.ignoreNavigationInTab(tab, navigation: nav) } } }) } } } } } /// Disabling reader mode can mean two things. In the simplest case we were opened from the reading list, which /// means that there is nothing in the BackForwardList except the internal url for the reader mode page. In that /// case we simply open a new page with the original url. In the more complicated page, the non-readerized version /// of the page is either to the left or right in the BackForwardList. If that is the case, we navigate there. func disableReaderMode() { if let tab = tabManager.selectedTab, let webView = tab.webView { let backList = webView.backForwardList.backList as! [WKBackForwardListItem] let forwardList = webView.backForwardList.forwardList as! [WKBackForwardListItem] if let currentURL = webView.backForwardList.currentItem?.URL { if let originalURL = ReaderModeUtils.decodeURL(currentURL) { if backList.count > 1 && backList.last?.URL == originalURL { webView.goToBackForwardListItem(backList.last!) } else if forwardList.count > 0 && forwardList.first?.URL == originalURL { webView.goToBackForwardListItem(forwardList.first!) } else { if let nav = webView.loadRequest(NSURLRequest(URL: originalURL)) { self.ignoreNavigationInTab(tab, navigation: nav) } } } } } } } extension BrowserViewController: ReaderModeBarViewDelegate { func readerModeBar(readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) { switch buttonType { case .Settings: if let readerMode = tabManager.selectedTab?.getHelper(name: "ReaderMode") as? ReaderMode where readerMode.state == ReaderModeState.Active { var readerModeStyle = DefaultReaderModeStyle if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) { if let style = ReaderModeStyle(dict: dict) { readerModeStyle = style } } let readerModeStyleViewController = ReaderModeStyleViewController() readerModeStyleViewController.delegate = self readerModeStyleViewController.readerModeStyle = readerModeStyle readerModeStyleViewController.modalPresentationStyle = UIModalPresentationStyle.Popover let popoverPresentationController = readerModeStyleViewController.popoverPresentationController popoverPresentationController?.backgroundColor = UIColor.whiteColor() popoverPresentationController?.delegate = self popoverPresentationController?.sourceView = readerModeBar popoverPresentationController?.sourceRect = CGRect(x: readerModeBar.frame.width/2, y: UIConstants.ToolbarHeight, width: 1, height: 1) popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.Up self.presentViewController(readerModeStyleViewController, animated: true, completion: nil) } case .MarkAsRead: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { profile.readingList?.updateRecord(record, unread: false) // TODO Check result, can this fail? readerModeBar.unread = false } } case .MarkAsUnread: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { profile.readingList?.updateRecord(record, unread: true) // TODO Check result, can this fail? readerModeBar.unread = true } } case .AddToReadingList: if let tab = tabManager.selectedTab, let url = tab.url where ReaderModeUtils.isReaderModeURL(url) { if let url = ReaderModeUtils.decodeURL(url), let absoluteString = url.absoluteString { let result = profile.readingList?.createRecordWithURL(absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().name) // TODO Check result, can this fail? readerModeBar.added = true } } case .RemoveFromReadingList: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { profile.readingList?.deleteRecord(record) // TODO Check result, can this fail? readerModeBar.added = false } } } } } private class BrowserScreenshotHelper: ScreenshotHelper { private weak var controller: BrowserViewController? init(controller: BrowserViewController) { self.controller = controller } func takeScreenshot(tab: Browser, aspectRatio: CGFloat, quality: CGFloat) -> UIImage? { if let url = tab.url { if url == UIConstants.AboutHomeURL { if let homePanel = controller?.homePanelController { return homePanel.view.screenshot(aspectRatio, quality: quality) } } else { let offset = CGPointMake(0, -(tab.webView?.scrollView.contentInset.top ?? 0)) return tab.webView?.screenshot(aspectRatio, offset: offset, quality: quality) } } return nil } } extension BrowserViewController: IntroViewControllerDelegate { func presentIntroViewController(force: Bool = false) { if force || profile.prefs.intForKey(IntroViewControllerSeenProfileKey) == nil { let introViewController = IntroViewController() introViewController.delegate = self // On iPad we present it modally in a controller if UIDevice.currentDevice().userInterfaceIdiom == .Pad { introViewController.preferredContentSize = CGSize(width: IntroViewControllerUX.Width, height: IntroViewControllerUX.Height) introViewController.modalPresentationStyle = UIModalPresentationStyle.FormSheet } presentViewController(introViewController, animated: true) { self.profile.prefs.setInt(1, forKey: IntroViewControllerSeenProfileKey) } } } func introViewControllerDidFinish(introViewController: IntroViewController) { introViewController.dismissViewControllerAnimated(true) { finished in if self.navigationController?.viewControllers.count > 1 { self.navigationController?.popToRootViewControllerAnimated(true) } } } func presentSignInViewController() { // TODO When bug 1161151 has been resolved we can jump directly to the sign in screen let settingsNavigationController = SettingsNavigationController() settingsNavigationController.profile = self.profile settingsNavigationController.tabManager = self.tabManager settingsNavigationController.modalPresentationStyle = .FormSheet self.presentViewController(settingsNavigationController, animated: true, completion: nil) } func introViewControllerDidRequestToLogin(introViewController: IntroViewController) { introViewController.dismissViewControllerAnimated(true, completion: { () -> Void in self.presentSignInViewController() }) } } extension BrowserViewController: ContextMenuHelperDelegate { func contextMenuHelper(contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UILongPressGestureRecognizer) { let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) var dialogTitle: String? if let url = elements.link { dialogTitle = url.absoluteString let newTabTitle = NSLocalizedString("Open In New Tab", comment: "Context menu item for opening a link in a new tab") let openNewTabAction = UIAlertAction(title: newTabTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) in self.scrollController.showToolbars(animated: !self.scrollController.toolbarsShowing, completion: { _ in self.tabManager.addTab(request: NSURLRequest(URL: url)) }) } actionSheetController.addAction(openNewTabAction) let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard") let copyAction = UIAlertAction(title: copyTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in var pasteBoard = UIPasteboard.generalPasteboard() pasteBoard.string = url.absoluteString } actionSheetController.addAction(copyAction) } if let url = elements.image { if dialogTitle == nil { dialogTitle = url.absoluteString } let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus() let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu item for saving an image") let saveImageAction = UIAlertAction(title: saveImageTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in if photoAuthorizeStatus == PHAuthorizationStatus.Authorized || photoAuthorizeStatus == PHAuthorizationStatus.NotDetermined { self.getImage(url) { UIImageWriteToSavedPhotosAlbum($0, nil, nil, nil) } } else { let accessDenied = UIAlertController(title: NSLocalizedString("Firefox would like to access your Photos", comment: "See http://mzl.la/1G7uHo7"), message: NSLocalizedString("This allows you to save the image to your Camera Roll.", comment: "See http://mzl.la/1G7uHo7"), preferredStyle: UIAlertControllerStyle.Alert) let dismissAction = UIAlertAction(title: CancelString, style: UIAlertActionStyle.Default, handler: nil) accessDenied.addAction(dismissAction) let settingsAction = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "See http://mzl.la/1G7uHo7"), style: UIAlertActionStyle.Default ) { (action: UIAlertAction!) -> Void in UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) } accessDenied.addAction(settingsAction) self.presentViewController(accessDenied, animated: true, completion: nil) } } actionSheetController.addAction(saveImageAction) let copyImageTitle = NSLocalizedString("Copy Image", comment: "Context menu item for copying an image to the clipboard") let copyAction = UIAlertAction(title: copyImageTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in let pasteBoard = UIPasteboard.generalPasteboard() pasteBoard.string = url.absoluteString! // TODO: put the actual image on the clipboard } actionSheetController.addAction(copyAction) } // If we're showing an arrow popup, set the anchor to the long press location. if let popoverPresentationController = actionSheetController.popoverPresentationController { popoverPresentationController.sourceView = view popoverPresentationController.sourceRect = CGRect(origin: gestureRecognizer.locationInView(view), size: CGSizeMake(0, 16)) popoverPresentationController.permittedArrowDirections = .Any } actionSheetController.title = dialogTitle?.ellipsize(maxLength: ActionSheetTitleMaxLength) var cancelAction = UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: nil) actionSheetController.addAction(cancelAction) self.presentViewController(actionSheetController, animated: true, completion: nil) } private func getImage(url: NSURL, success: UIImage -> ()) { Alamofire.request(.GET, url) .validate(statusCode: 200..<300) .response { _, _, data, _ in if let data = data as? NSData, let image = UIImage(data: data) { success(image) } } } } extension BrowserViewController: KeyboardHelperDelegate { func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { keyboardState = state // if we are already showing snack bars, adjust them so they sit above the keyboard if snackBars.subviews.count > 0 { adjustFooterSize(top: nil) } } func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) { } func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { keyboardState = nil // if we are showing snack bars, adjust them so they are no longer sitting above the keyboard if snackBars.subviews.count > 0 { adjustFooterSize(top: nil) } } } private struct CrashPromptMessaging { static let CrashPromptTitle = NSLocalizedString("Well, this is embarrassing.", comment: "Restore Tabs Prompt Title") static let CrashPromptDescription = NSLocalizedString("Looks like Firefox crashed previously. Would you like to restore your tabs?", comment: "Restore Tabs Prompt Description") static let CrashPromptAffirmative = NSLocalizedString("Okay", comment: "Restore Tabs Affirmative Action") static let CrashPromptNegative = NSLocalizedString("No", comment: "Restore Tabs Negative Action") } extension BrowserViewController: UIAlertViewDelegate { private enum CrashPromptIndex: Int { case Cancel = 0 case Restore = 1 } func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { if buttonIndex == CrashPromptIndex.Restore.rawValue { tabManager.restoreTabs() } // In case restore fails, launch at least one tab if tabManager.count == 0 { let tab = tabManager.addTab() tabManager.selectTab(tab) } } }
mpl-2.0
6a5cb34993225d850611f97156c7fdb8
44.391871
410
0.650051
5.901158
false
false
false
false
JadenGeller/Generational
Sources/LazyTake.swift
1
1907
// // LazyTakeSequence.swift // Generational // // Created by Jaden Geller on 12/28/15. // Copyright © 2015 Jaden Geller. All rights reserved. // public struct LazyTakeSequence<Base: SequenceType>: SequenceType { public let base: Base public let takeCondition: Base.Generator.Element -> Bool public init(_ base: Base, takeCondition: Base.Generator.Element -> Bool) { self.base = base self.takeCondition = takeCondition } public func generate() -> LazyTakeGenerator<Base.Generator> { return LazyTakeGenerator(base.generate(), takeCondition: takeCondition) } } public struct LazyTakeGenerator<Base: GeneratorType>: GeneratorType { public var base: Base public var taking = true public let takeCondition: Base.Element -> Bool public init(_ base: Base, takeCondition: Base.Element -> Bool) { self.base = base self.takeCondition = takeCondition } public mutating func next() -> Base.Element? { guard taking else { return nil } guard let element = base.next() else { return nil } if takeCondition(element) { return element } else { taking = false return nil } } } extension SequenceType { func takeWhile(takeCondition: Generator.Element -> Bool) -> LazyTakeSequence<Self> { return LazyTakeSequence(self, takeCondition: takeCondition) } func takeUntil(stopCondition: Generator.Element -> Bool) -> LazyTakeSequence<Self> { return takeWhile { !stopCondition($0) } } } extension SequenceType where Generator.Element: Equatable { func takeWhile(element: Generator.Element) -> LazyTakeSequence<Self> { return takeWhile { $0 == element } } func takeUntil(element: Generator.Element) -> LazyTakeSequence<Self> { return takeUntil { $0 == element } } }
mit
2c3c9e2fa1b7d8b42bd95547af63e038
28.323077
88
0.651626
4.422274
false
false
false
false
jianghongbing/APIReferenceDemo
Swift/Syntax/Optional.playground/Contents.swift
1
3689
//: Playground - noun: a place where people can play import UIKit //1.可选类型:表示值可能缺失的情况,如果有值则为该值,如果没有值,就表示没有值,用nil表示,和Objective-C中的nil不一样,在Objective-C中,不存在没有值的概念,nil表示一个不合法的对象,只能作用于NSObject类型,不能作用于基本类型和结构体类型,在Swift中,类,结构体,枚举都可以使用nil来一个可选值,其没有指向到任何对象或者变量 //可选类型变量的声明,如果没有给可选类型变量赋值,其表示没有值,用nil表示 var number: Int? //没有值,为nil number = 5 //值为5 var stringToNumber = Int("23") //值为23 stringToNumber = Int("abc") //没有值,为nil //判断可选类型变量是否有值和强制解析 //强制解析:通过在可选类型变量后面加上一个!来表示强制解析,如果变量不存在值,强制解析会产生运行时错误导致程序终止,所以在不确定可选变量是否有值的情况下,不要使用强制解析 if number != nil { print("number:\(number!)") }else { print("number is nil"); } //可选绑定:判断可选类型变量是否有值,如果有值就将值赋值给其他变量,可选绑定用于if和while语句中,作为条件,如果不存在值,条件为false if let binding = number { print("number:\(binding)") }else { print("number is nil"); } //2.可选链式调用:在一个可选类型变量或者常量上使用属性,方法,下标,如果可选类型有值,调用就会成功,如果没有值,则返回nil,多个调用可以连接在一起形成一个调用链,如果其中任何一个节点为nil,整个调用链都会失败,即返回nil //多层可选链式调用:可以通过连接多个可选链式调用在更深的模型层级中访问属性、方法以及下标,多层可选链式调用不会增加返回值的可选层级 //多层可选链式调用规则: //2.1.如果你访问的值不是可选的,可选链式调用将会返回可选值。 //2.2如果你访问的值就是可选的,可选链式调用不会让可选返回值变得“更可选",实际上还是一个可选值,通过可选链式调用访问一个Int值,将会返回Int?,无论使用了多少层可选链式调用,类似的,通过可选链式调用访问Int?值,依旧会返回Int?值,并不会返回Int??。 struct Point { var x: Double var y: Double } struct Size { var width: Double var height: Double init?(width: Double, height: Double) { guard width >= 0 && height >= 0 else { return nil } self.width = width self.height = height } } struct Rect { var x: Double var y: Double var width: Double var height: Double var origin: Point { return Point(x: x, y: y) } var size: Size? { return Size(width: width, height: height) } func area() -> Double? { guard width >= 0 && height >= 0 else { return nil } return width * height } func logRectInfo() { print("x:\(x), y:\(y), width:\(width), height:\(height)") } } let aRect:Rect? = Rect(x: 10, y: 10, width: 100, height: 100); if let point = aRect?.origin { print("x:\(point.x), y:\(point.y)") }else { print("point is nil") } if aRect?.logRectInfo() != nil { print("can log rect info") }else { print("can not log rect info") } let bRect = Rect(x: 10, y: 10, width: -10, height: 9) if let area = bRect.area() { print(area) }else { print("area is nil") } //多个可选绑定同时使用 if let width = bRect.size?.width, let height = bRect.size?.height { print(width, height) }
mit
0d3d0121c47896757f1911ee2571e4d0
25.117021
185
0.659063
2.774011
false
false
false
false
ealeksandrov/SomaFM-miniplayer
Source/AppDelegate.swift
1
1972
// // AppDelegate.swift // // Copyright © 2017 Evgeny Aleksandrov. All rights reserved. import Cocoa import MediaKeyTap @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, MediaKeyTapDelegate { let menubarController = MenubarController() var mediaKeyTap: MediaKeyTap? private var prefsWindowController: NSWindowController? var preferencesWindowController: NSWindowController? { if prefsWindowController == nil { let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) prefsWindowController = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "PreferencesWindow")) as? NSWindowController } return prefsWindowController } static let bundleId: String = Bundle.main.bundleIdentifier ?? "unknown" static let bundleShortVersion: String = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "" static let bundleVersion: String = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "" func applicationDidFinishLaunching(_ aNotification: Notification) { Log.info("Starting \(AppDelegate.bundleId) v\(AppDelegate.bundleShortVersion) (\(AppDelegate.bundleVersion))") UserDefaults.standard.register(defaults: ["RadioPlayer.NotificationsEnabled": true]) mediaKeyTap = MediaKeyTap(delegate: self) mediaKeyTap?.start() } // MARK: - NSWindowDelegate func windowWillClose(_ notification: Notification) { prefsWindowController = nil } // MARK: - NSWindowDelegate func handle(mediaKey: MediaKey, event: KeyEvent) { switch mediaKey { case .playPause: menubarController.togglePlay() case .previous, .rewind: menubarController.previousTap() case .next, .fastForward: menubarController.nextTap() } } }
mit
d418166fd0f87eeb2e836e63532260b2
34.196429
118
0.701167
5.270053
false
false
false
false
andyshep/CoreDataPlayground
events-ios.playground/Sources/CoreDataHelpers.swift
1
789
import CoreData public enum CoreDataError: Error { case modelNotFound case modelNotCreated } public func createManagedObjectContext() throws -> NSManagedObjectContext { guard let modelURL = Bundle.main.url(forResource: "Model", withExtension: "mom") else { throw CoreDataError.modelNotFound } guard let model = NSManagedObjectModel(contentsOf: modelURL) else { throw CoreDataError.modelNotCreated } let psc = NSPersistentStoreCoordinator(managedObjectModel: model) try psc.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil) let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.persistentStoreCoordinator = psc return context }
mit
66daa0fb9a4d79fab1398a4a467ba09e
31.875
106
0.74398
5.517483
false
false
false
false
manish-1988/MPAudioRecorder
AudioFunctions/SplitAudioFile.swift
1
4480
// // SplitAudioFile.swift // AudioFunctions // // Created by iDevelopers on 6/19/17. // Copyright © 2017 iDevelopers. All rights reserved. // import UIKit import AVFoundation class SplitAudioFile: UIViewController, AVAudioPlayerDelegate { @IBOutlet weak var label_lengthFAudio: UILabel! @IBOutlet weak var txt_start: UITextField! @IBOutlet weak var txt_end: UITextField! @IBOutlet weak var btn_Split: UIButton! @IBOutlet weak var btn_Play: UIButton! @IBOutlet weak var audioSlider: UISlider! @IBOutlet weak var lblStart: UILabel! @IBOutlet weak var lblEnd: UILabel! var audioFileOutput:URL! var fileURL:URL! var audioFile:AnyObject! var filecount:Int = 0 var audioPlayer : AVAudioPlayer! override func viewDidLoad() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } func dismissKeyboard() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } override func viewWillAppear(_ animated: Bool) { self.audioPlayer = try! AVAudioPlayer(contentsOf: fileURL!) label_lengthFAudio.text = "\(self.audioPlayer.duration)" lblEnd.text = "\(audioPlayer.duration)" } @IBAction func click_Split(_ sender: Any) { let fileManager = FileManager.default let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask) let documentDirectory = urls[0] as NSURL audioFileOutput = documentDirectory.appendingPathComponent("abcdf.m4a") print("\(audioFileOutput!)") do { try FileManager.default.removeItem(at: audioFileOutput) } catch let error as NSError { print(error.debugDescription) } let asset = AVAsset.init(url: fileURL) let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) let startTrimTime: Float = Float(txt_start.text!)! let endTrimTime: Float = Float(txt_end.text!)! let startTime: CMTime = CMTimeMake(value: Int64(Int(floor(startTrimTime * 100))), timescale: 100) let stopTime: CMTime = CMTimeMake(value: Int64(Int(ceil(endTrimTime * 100))), timescale: 100) let exportTimeRange: CMTimeRange = CMTimeRangeFromTimeToTime(start: startTime, end: stopTime) exportSession?.outputURL = audioFileOutput exportSession?.outputFileType = .m4a exportSession?.timeRange = exportTimeRange exportSession?.exportAsynchronously(completionHandler: {() -> Void in if AVAssetExportSession.Status.completed == exportSession?.status { print("Success!") self.audioPlayer = try! AVAudioPlayer(contentsOf: self.audioFileOutput) self.lblEnd.text = "\(self.audioPlayer.duration)" let alert = UIAlertController(title: "Alert", message: "File Trimmed Successfuly. Click on play to check", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } else if AVAssetExportSession.Status.failed == exportSession?.status { print("failed") } }) } @IBAction func click_Play(_ sender: Any) { self.audioPlayer.prepareToPlay() self.audioPlayer.delegate = self self.audioPlayer.play() audioSlider.maximumValue = Float(audioPlayer.duration) Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(playerTimeIntervalSplitController), userInfo: nil, repeats: true) } @objc func playerTimeIntervalSplitController() { audioSlider.value = Float(audioPlayer.currentTime) lblStart.text = "\(audioSlider.value)" } func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { print(flag) } func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?){ print(error.debugDescription) } internal func audioPlayerBeginInterruption(_ player: AVAudioPlayer){ print(player.debugDescription) } }
mit
fcf52356c242e5a2f00b785a1f340537
36.638655
146
0.654387
4.949171
false
false
false
false
AndersonSKM/SwiftFormValidator
SwiftFormValidator/CharacterSetRules.swift
2
1407
// // CharacterSetRules.swift // SwiftFormValidator // // Created by Anderson Macedo on 14/04/17. // Copyright © 2017 AndersonSKM. All rights reserved. // import UIKit // MARK: - CharacterSet Rules public protocol CharacterSetRule: Rule { var characterSet: CharacterSet { get set } init(characterSet: CharacterSet) init(message: String, characterSet: CharacterSet) } extension Rule where Self: CharacterSetRule { public init(characterSet: CharacterSet) { self.init() self.characterSet = characterSet } public init(message: String, characterSet: CharacterSet) { self.init(message: message) self.characterSet = characterSet } public func validate(_ text: String) -> Bool { if text.rangeOfCharacter(from: characterSet.inverted ) != nil { return false } return true } } // MARK: - Alpha Rule public class AlphaRule: CharacterSetRule { public var errorMsg: String? = "Enter valid alphabetic characters" public var characterSet: CharacterSet = CharacterSet.letters required public init() { } } // MARK: - Alpha Numeric Rule public class AlphaNumericRule: CharacterSetRule { public var errorMsg: String? = "Enter valid numeric characters" public var characterSet: CharacterSet = CharacterSet.alphanumerics required public init() { } }
mit
03cf7c60857d1d87bac78ea49a38689b
24.107143
71
0.674253
4.640264
false
false
false
false
loudnate/LoopKit
LoopKit/CarbKit/CarbMath.swift
1
38695
// // CarbMath.swift // CarbKit // // Created by Nathan Racklyeft on 1/16/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import HealthKit struct CarbModelSettings { var absorptionModel: CarbAbsorptionComputable var initialAbsorptionTimeOverrun: Double var adaptiveAbsorptionRateEnabled: Bool var adaptiveRateStandbyIntervalFraction: Double init(absorptionModel: CarbAbsorptionComputable, initialAbsorptionTimeOverrun: Double, adaptiveAbsorptionRateEnabled: Bool, adaptiveRateStandbyIntervalFraction: Double = 0.2) { self.absorptionModel = absorptionModel self.initialAbsorptionTimeOverrun = initialAbsorptionTimeOverrun self.adaptiveAbsorptionRateEnabled = adaptiveAbsorptionRateEnabled self.adaptiveRateStandbyIntervalFraction = adaptiveRateStandbyIntervalFraction } } protocol CarbAbsorptionComputable { /// Returns the percentage of total carbohydrates absorbed as blood glucose at a specified interval after eating. /// /// - Parameters: /// - percentTime: The percentage of the total absorption time /// - Returns: The percentage of the total carbohydrates that have been absorbed as blood glucose func percentAbsorptionAtPercentTime(_ percentTime: Double) -> Double /// Returns the percent of total absorption time for a percentage of total carbohydrates absorbed /// /// The is the inverse of perecentAbsorptionAtPercentTime( :percentTime: ) /// /// - Parameters: /// - percentAbsorption: The percentage of the total carbohydrates that have been absorbed as blood glucose /// - Returns: The percentage of the absorption time needed to absorb the percentage of the total carbohydrates func percentTimeAtPercentAbsorption(_ percentAbsorption: Double) -> Double /// Returns the total absorption time for a percentage of total carbohydrates absorbed as blood glucose at a specified interval after eating. /// /// - Parameters: /// - percentAbsorption: The percentage of the total carbohydrates that have been absorbed as blood glucose /// - time: The interval after the carbohydrates were eaten /// - Returns: The total time of carbohydrates absorption func absorptionTime(forPercentAbsorption percentAbsorption: Double, atTime time: TimeInterval) -> TimeInterval /// Returns the number of total carbohydrates absorbed as blood glucose at a specified interval after eating /// /// - Parameters: /// - total: The total number of carbohydrates eaten /// - time: The interval after carbohydrates were eaten /// - absorptionTime: The total time of carbohydrates absorption /// - Returns: The number of total carbohydrates that have been absorbed as blood glucose func absorbedCarbs(of total: Double, atTime time: TimeInterval, absorptionTime: TimeInterval) -> Double /// Returns the number of total carbohydrates not yet absorbed as blood glucose at a specified interval after eating /// /// - Parameters: /// - total: The total number of carbs eaten /// - time: The interval after carbohydrates were eaten /// - absorptionTime: The total time of carb absorption /// - Returns: The number of total carbohydrates that have not yet been absorbed as blood glucose func unabsorbedCarbs(of total: Double, atTime time: TimeInterval, absorptionTime: TimeInterval) -> Double /// Returns the normalized rate of carbohydrates absorption at a specified percentage of the absorption time /// /// - Parameters: /// - percentTime: The percentage of absorption time elapsed since the carbohydrates were eaten /// - Returns: The percentage absorption rate at the percentage of absorption time func percentRateAtPercentTime(forPercentTime percentTime: Double) -> Double } extension CarbAbsorptionComputable { func absorbedCarbs(of total: Double, atTime time: TimeInterval, absorptionTime: TimeInterval) -> Double { let percentTime = time / absorptionTime return total * percentAbsorptionAtPercentTime(percentTime) } func unabsorbedCarbs(of total: Double, atTime time: TimeInterval, absorptionTime: TimeInterval) -> Double { let percentTime = time / absorptionTime return total * (1.0 - percentAbsorptionAtPercentTime(percentTime)) } func absorptionTime(forPercentAbsorption percentAbsorption: Double, atTime time: TimeInterval) -> TimeInterval { let percentTime = max(percentTimeAtPercentAbsorption(percentAbsorption), .ulpOfOne) return time / percentTime } func timeToAbsorb(forPercentAbsorbed percentAbsorption: Double, absorptionTime: TimeInterval) -> TimeInterval { let percentTime = percentTimeAtPercentAbsorption(percentAbsorption) return percentTime * absorptionTime } } // MARK: - Parabolic absorption as described by Scheiner // This is the integral approximation of the Scheiner GI curve found in Think Like a Pancreas, Fig 7-8, which first appeared in [GlucoDyn](https://github.com/kenstack/GlucoDyn) struct ParabolicAbsorption: CarbAbsorptionComputable { func percentAbsorptionAtPercentTime(_ percentTime: Double) -> Double { switch percentTime { case let t where t < 0.0: return 0.0 case let t where t <= 0.5: return 2.0 * pow(t, 2) case let t where t < 1.0: return -1.0 + 2.0 * t * (2.0 - t) default: return 1.0 } } func percentTimeAtPercentAbsorption(_ percentAbsorption: Double) -> Double { switch percentAbsorption { case let a where a <= 0: return 0 case let a where a <= 0.5: return sqrt(0.5 * a) case let a where a < 1.0: return 1.0 - sqrt(0.5 * (1.0 - a)) default: return 1.0 } } func percentRateAtPercentTime(forPercentTime percentTime: Double) -> Double { switch percentTime { case let t where t > 0 && t <= 0.5: return 4.0 * t case let t where t > 0.5 && t < 1.0: return 4.0 - 4.0 * t default: return 0.0 } } } // MARK: - Linear absorption as a factor of reported duration struct LinearAbsorption: CarbAbsorptionComputable { func percentAbsorptionAtPercentTime(_ percentTime: Double) -> Double { switch percentTime { case let t where t <= 0.0: return 0.0 case let t where t < 1.0: return t default: return 1.0 } } func percentTimeAtPercentAbsorption(_ percentAbsorption: Double) -> Double { switch percentAbsorption { case let a where a <= 0.0: return 0.0 case let a where a < 1.0: return a default: return 1.0 } } func percentRateAtPercentTime(forPercentTime percentTime: Double) -> Double { switch percentTime { case let t where t > 0.0 && t <= 1.0: return 1.0 default: return 0.0 } } } // MARK: - Piecewise linear absorption as a factor of reported duration /// Nonlinear carb absorption model where absorption rate increases linearly from zero to a maximum value at a fraction of absorption time equal to percentEndOfRise, then remains constant until a fraction of absorption time equal to percentStartOfFall, and then decreases linearly to zero at the end of absorption time /// - Parameters: /// - percentEndOfRise: the percentage of absorption time when absorption rate reaches maximum, must be strictly between 0 and 1 /// - percentStartOfFall: the percentage of absorption time when absorption rate starts to decay, must be stritctly between 0 and 1 and greater than percentEndOfRise struct PiecewiseLinearAbsorption: CarbAbsorptionComputable { let percentEndOfRise = 0.15 let percentStartOfFall = 0.5 var scale: Double { return(2.0 / (1.0 + percentStartOfFall - percentEndOfRise)) } func percentAbsorptionAtPercentTime(_ percentTime: Double) -> Double { switch percentTime { case let t where t <= 0.0: return 0.0 case let t where t < percentEndOfRise: return 0.5 * scale * pow(t, 2.0) / percentEndOfRise case let t where t >= percentEndOfRise && t < percentStartOfFall: return scale * (t - 0.5 * percentEndOfRise) case let t where t >= percentStartOfFall && t < 1.0: return scale * (percentStartOfFall - 0.5 * percentEndOfRise + (t - percentStartOfFall) * (1.0 - 0.5 * (t - percentStartOfFall) / (1.0 - percentStartOfFall))) default: return 1.0 } } func percentTimeAtPercentAbsorption(_ percentAbsorption: Double) -> Double { switch percentAbsorption { case let a where a <= 0: return 0 case let a where a > 0.0 && a < 0.5 * scale * percentEndOfRise: return sqrt(2.0 * percentEndOfRise * a / scale) case let a where a >= 0.5 * scale * percentEndOfRise && a < scale * (percentStartOfFall - 0.5 * percentEndOfRise): return 0.5 * percentEndOfRise + a / scale case let a where a >= scale * (percentStartOfFall - 0.5 * percentEndOfRise) && a < 1.0: return 1.0 - sqrt((1.0 - percentStartOfFall) * (1.0 + percentStartOfFall - percentEndOfRise) * (1.0 - a)) default: return 1.0 } } func percentRateAtPercentTime(forPercentTime percentTime: Double) -> Double { switch percentTime { case let t where t <= 0: return 0.0 case let t where t > 0 && t < percentEndOfRise: return scale * t / percentEndOfRise case let t where t >= percentEndOfRise && t < percentStartOfFall: return scale case let t where t >= percentStartOfFall && t < 1.0: return scale * ((1.0 - t) / (1.0 - percentStartOfFall)) case let t where t == 1.0: return 0.0 default: return 0.0 } } } extension CarbEntry { func carbsOnBoard(at date: Date, defaultAbsorptionTime: TimeInterval, delay: TimeInterval, absorptionModel: CarbAbsorptionComputable) -> Double { let time = date.timeIntervalSince(startDate) let value: Double if time >= 0 { value = absorptionModel.unabsorbedCarbs(of: quantity.doubleValue(for: HKUnit.gram()), atTime: time - delay, absorptionTime: absorptionTime ?? defaultAbsorptionTime) } else { value = 0 } return value } // g func absorbedCarbs( at date: Date, absorptionTime: TimeInterval, delay: TimeInterval, absorptionModel: CarbAbsorptionComputable ) -> Double { let time = date.timeIntervalSince(startDate) return absorptionModel.absorbedCarbs( of: quantity.doubleValue(for: .gram()), atTime: time - delay, absorptionTime: absorptionTime ) } // mg/dL / g * g fileprivate func glucoseEffect( at date: Date, carbRatio: HKQuantity, insulinSensitivity: HKQuantity, defaultAbsorptionTime: TimeInterval, delay: TimeInterval, absorptionModel: CarbAbsorptionComputable ) -> Double { return insulinSensitivity.doubleValue(for: HKUnit.milligramsPerDeciliter) / carbRatio.doubleValue(for: .gram()) * absorbedCarbs(at: date, absorptionTime: absorptionTime ?? defaultAbsorptionTime, delay: delay, absorptionModel: absorptionModel) } fileprivate func estimatedAbsorptionTime(forAbsorbedCarbs carbs: Double, at date: Date, absorptionModel: CarbAbsorptionComputable) -> TimeInterval { let time = date.timeIntervalSince(startDate) return max(time, absorptionModel.absorptionTime(forPercentAbsorption: carbs / quantity.doubleValue(for: .gram()), atTime: time)) } } extension Collection where Element: CarbEntry { fileprivate func simulationDateRange( from start: Date? = nil, to end: Date? = nil, defaultAbsorptionTime: TimeInterval, delay: TimeInterval, delta: TimeInterval ) -> (start: Date, end: Date)? { guard count > 0 else { return nil } if let start = start, let end = end { return (start: start.dateFlooredToTimeInterval(delta), end: end.dateCeiledToTimeInterval(delta)) } else { var minDate = first!.startDate var maxDate = minDate for sample in self { if sample.startDate < minDate { minDate = sample.startDate } let endDate = sample.endDate.addingTimeInterval(sample.absorptionTime ?? defaultAbsorptionTime).addingTimeInterval(delay) if endDate > maxDate { maxDate = endDate } } return ( start: (start ?? minDate).dateFlooredToTimeInterval(delta), end: (end ?? maxDate).dateCeiledToTimeInterval(delta) ) } } /// Creates groups of entries that have overlapping absorption date intervals /// /// - Parameters: /// - defaultAbsorptionTime: The default absorption time value, if not set on the entry /// - Returns: An array of arrays representing groups of entries, in chronological order by entry startDate func groupedByOverlappingAbsorptionTimes( defaultAbsorptionTime: TimeInterval ) -> [[Iterator.Element]] { var batches: [[Iterator.Element]] = [] for entry in sorted(by: { $0.startDate < $1.startDate }) { if let lastEntry = batches.last?.last, lastEntry.startDate.addingTimeInterval(lastEntry.absorptionTime ?? defaultAbsorptionTime) > entry.startDate { batches[batches.count - 1].append(entry) } else { batches.append([entry]) } } return batches } func carbsOnBoard( from start: Date? = nil, to end: Date? = nil, defaultAbsorptionTime: TimeInterval, absorptionModel: CarbAbsorptionComputable, delay: TimeInterval = TimeInterval(minutes: 10), delta: TimeInterval = TimeInterval(minutes: 5) ) -> [CarbValue] { guard let (startDate, endDate) = simulationDateRange(from: start, to: end, defaultAbsorptionTime: defaultAbsorptionTime, delay: delay, delta: delta) else { return [] } var date = startDate var values = [CarbValue]() repeat { let value = reduce(0.0) { (value, entry) -> Double in return value + entry.carbsOnBoard(at: date, defaultAbsorptionTime: defaultAbsorptionTime, delay: delay, absorptionModel: absorptionModel) } values.append(CarbValue(startDate: date, quantity: HKQuantity(unit: HKUnit.gram(), doubleValue: value))) date = date.addingTimeInterval(delta) } while date <= endDate return values } func glucoseEffects( from start: Date? = nil, to end: Date? = nil, carbRatios: CarbRatioSchedule, insulinSensitivities: InsulinSensitivitySchedule, defaultAbsorptionTime: TimeInterval, absorptionModel: CarbAbsorptionComputable, delay: TimeInterval = TimeInterval(minutes: 10), delta: TimeInterval = TimeInterval(minutes: 5) ) -> [GlucoseEffect] { guard let (startDate, endDate) = simulationDateRange(from: start, to: end, defaultAbsorptionTime: defaultAbsorptionTime, delay: delay, delta: delta) else { return [] } var date = startDate var values = [GlucoseEffect]() let unit = HKUnit.milligramsPerDeciliter repeat { let value = reduce(0.0) { (value, entry) -> Double in return value + entry.glucoseEffect( at: date, carbRatio: carbRatios.quantity(at: entry.startDate), insulinSensitivity: insulinSensitivities.quantity(at: entry.startDate), defaultAbsorptionTime: defaultAbsorptionTime, delay: delay, absorptionModel: absorptionModel ) } values.append(GlucoseEffect(startDate: date, quantity: HKQuantity(unit: unit, doubleValue: value))) date = date.addingTimeInterval(delta) } while date <= endDate return values } var totalCarbs: CarbValue? { guard count > 0 else { return nil } let unit = HKUnit.gram() var startDate = Date.distantFuture var totalGrams: Double = 0 for entry in self { totalGrams += entry.quantity.doubleValue(for: unit) if entry.startDate < startDate { startDate = entry.startDate } } return CarbValue(startDate: startDate, quantity: HKQuantity(unit: unit, doubleValue: totalGrams)) } } // MARK: - Dyanamic absorption overrides extension Collection { func dynamicCarbsOnBoard<T>( from start: Date? = nil, to end: Date? = nil, defaultAbsorptionTime: TimeInterval, absorptionModel: CarbAbsorptionComputable, delay: TimeInterval = TimeInterval(minutes: 10), delta: TimeInterval = TimeInterval(minutes: 5) ) -> [CarbValue] where Element == CarbStatus<T> { guard let (startDate, endDate) = simulationDateRange(from: start, to: end, defaultAbsorptionTime: defaultAbsorptionTime, delay: delay, delta: delta) else { return [] } var date = startDate var values = [CarbValue]() repeat { let value = reduce(0.0) { (value, entry) -> Double in return value + entry.dynamicCarbsOnBoard( at: date, defaultAbsorptionTime: defaultAbsorptionTime, delay: delay, delta: delta, absorptionModel: absorptionModel ) } values.append(CarbValue(startDate: date, quantity: HKQuantity(unit: HKUnit.gram(), doubleValue: value))) date = date.addingTimeInterval(delta) } while date <= endDate return values } func dynamicGlucoseEffects<T>( from start: Date? = nil, to end: Date? = nil, carbRatios: CarbRatioSchedule, insulinSensitivities: InsulinSensitivitySchedule, defaultAbsorptionTime: TimeInterval, absorptionModel: CarbAbsorptionComputable, delay: TimeInterval = TimeInterval(minutes: 10), delta: TimeInterval = TimeInterval(minutes: 5) ) -> [GlucoseEffect] where Element == CarbStatus<T> { guard let (startDate, endDate) = simulationDateRange(from: start, to: end, defaultAbsorptionTime: defaultAbsorptionTime, delay: delay, delta: delta) else { return [] } var date = startDate var values = [GlucoseEffect]() let mgdL = HKUnit.milligramsPerDeciliter let gram = HKUnit.gram() repeat { let value = reduce(0.0) { (value, entry) -> Double in let csf = insulinSensitivities.quantity(at: entry.startDate).doubleValue(for: mgdL) / carbRatios.quantity(at: entry.startDate).doubleValue(for: gram) return value + csf * entry.dynamicAbsorbedCarbs( at: date, absorptionTime: entry.absorptionTime ?? defaultAbsorptionTime, delay: delay, delta: delta, absorptionModel: absorptionModel ) } values.append(GlucoseEffect(startDate: date, quantity: HKQuantity(unit: mgdL, doubleValue: value))) date = date.addingTimeInterval(delta) } while date <= endDate return values } /// The quantity of carbs expected to still absorb at the last date of absorption public func getClampedCarbsOnBoard<T>() -> CarbValue? where Element == CarbStatus<T> { guard let firstAbsorption = first?.absorption else { return nil } let gram = HKUnit.gram() var maxObservedEndDate = firstAbsorption.observedDate.end var remainingTotalGrams: Double = 0 for entry in self { guard let absorption = entry.absorption else { continue } maxObservedEndDate = Swift.max(maxObservedEndDate, absorption.observedDate.end) remainingTotalGrams += absorption.remaining.doubleValue(for: gram) } return CarbValue(startDate: maxObservedEndDate, quantity: HKQuantity(unit: gram, doubleValue: remainingTotalGrams)) } } /// Aggregates and computes data about the absorption of a CarbEntry to create a CarbStatus value. /// /// There are three key components managed by this builder: /// - The entry data as reported by the user /// - The observed data as calculated from glucose changes relative to insulin curves /// - The minimum/maximum amounts of absorption used to clamp our observation data within reasonable bounds fileprivate class CarbStatusBuilder<T: CarbEntry> { // MARK: Model settings private var absorptionModel: CarbAbsorptionComputable private var adaptiveAbsorptionRateEnabled: Bool private var adaptiveRateStandbyIntervalFraction: Double private var adaptiveRateStandbyInterval: TimeInterval { return initialAbsorptionTime * adaptiveRateStandbyIntervalFraction } // MARK: User-entered data /// The carb entry input let entry: T /// The unit used for carb values let carbUnit: HKUnit /// The total grams entered for this entry let entryGrams: Double /// The total glucose effect expected for this entry, in glucose units let entryEffect: Double /// The carbohydrate-sensitivity factor for this entry, in glucose units per gram let carbohydrateSensitivityFactor: Double /// The absorption time for this entry before any absorption is observed let initialAbsorptionTime: TimeInterval // MARK: Minimum/maximum bounding factors /// The maximum absorption time allowed for this entry, determining the minimum absorption rate let maxAbsorptionTime: TimeInterval /// An amount of time to wait after the entry date before minimum absorption is assumed to begin let delay: TimeInterval /// The maximum end date allowed for this entry's absorption let maxEndDate: Date /// The last date we have effects observed, or "now" in real-time analysis. private let lastEffectDate: Date /// The minimum-required carb absorption rate for this entry, in g/s var minAbsorptionRate: Double { return entryGrams / maxAbsorptionTime } /// The minimum amount of carbs we assume must have absorbed at the last observation date private var minPredictedGrams: Double { // We incorporate a delay when calculating minimum absorption values let time = lastEffectDate.timeIntervalSince(entry.startDate) - delay return absorptionModel.absorbedCarbs(of: entryGrams, atTime: time, absorptionTime: maxAbsorptionTime) } // MARK: Incremental observation /// The date at which we observe all the carbs were absorbed. or nil if carb absorption has not finished private var observedCompletionDate: Date? /// The total observed effect for each entry, in glucose units private(set) var observedEffect: Double = 0 /// The timeline of absorption amounts credited to this carb entry, in grams, for computation of historical COB and effect history private(set) var observedTimeline: [CarbValue] = [] /// The amount of carbs we've observed absorbing private var observedGrams: Double { return observedEffect / carbohydrateSensitivityFactor } /// The amount of effect remaining until 100% of entry absorption is observed var remainingEffect: Double { return max(entryEffect - observedEffect, 0) } /// The dates over which we observed absorption, from start until 100% or last observed effect. private var observedAbsorptionDates: DateInterval { return DateInterval(start: entry.startDate, end: observedCompletionDate ?? lastEffectDate) } // MARK: Clamped results /// The number of carbs absorbed, suitable for use in calculations. /// This is bounded by minimumPredictedGrams and the entry total. private var clampedGrams: Double { let minPredictedGrams = self.minPredictedGrams return min(entryGrams, max(minPredictedGrams, observedGrams)) } private var percentAbsorbed: Double { return clampedGrams / entryGrams } /// The amount of time needed to absorb observed grams private var timeToAbsorbObservedCarbs: TimeInterval { let time = lastEffectDate.timeIntervalSince(entry.startDate) - delay guard time > 0 else { return 0.0 } var timeToAbsorb: TimeInterval if adaptiveAbsorptionRateEnabled && time > adaptiveRateStandbyInterval { // If adaptive absorption rate is enabled, and if the time since start of absorption is greater than the standby interval, the time to absorb observed carbs equals the obervation time timeToAbsorb = time } else { // If adaptive absorption rate is disabled, or if the time since start of absorption is less than the standby interval, the time to absorb observed carbs is calculated based on the absorption model timeToAbsorb = absorptionModel.timeToAbsorb(forPercentAbsorbed: percentAbsorbed, absorptionTime: initialAbsorptionTime) } return min(timeToAbsorb, maxAbsorptionTime) } /// The amount of time needed for the remaining entry grams to absorb private var estimatedTimeRemaining: TimeInterval { let time = lastEffectDate.timeIntervalSince(entry.startDate) - delay guard time > 0 else { return initialAbsorptionTime } let notToExceedTimeRemaining = max(maxAbsorptionTime - time, 0.0) guard notToExceedTimeRemaining > 0 else { return 0.0 } var dynamicTimeRemaining: TimeInterval if adaptiveAbsorptionRateEnabled && time > adaptiveRateStandbyInterval { // If adaptive absorption rate is enabled, and if the time since start of absorption is greater than the standby interval, the remaining time is estimated assuming the observed relative absorption rate persists for the remaining carbs let dynamicAbsorptionTime = absorptionModel.absorptionTime(forPercentAbsorption: percentAbsorbed, atTime: time) dynamicTimeRemaining = dynamicAbsorptionTime - time } else { // If adaptive absorption rate is disabled, or if the time since start of absorption is less than the standby interval, the remaining time is estimated assuming the modeled absorption rate dynamicTimeRemaining = initialAbsorptionTime - timeToAbsorbObservedCarbs } // time remaining must not extend beyond the maximum absorption time let estimatedTimeRemaining = min(dynamicTimeRemaining, notToExceedTimeRemaining) return(estimatedTimeRemaining) } /// The timeline of observed absorption, if greater than the minimum required absorption. private var clampedTimeline: [CarbValue]? { return observedGrams >= minPredictedGrams ? observedTimeline : nil } /// Configures a new builder /// /// - Parameters: /// - entry: The carb entry input /// - carbUnit: The unit used for carb values /// - carbohydrateSensitivityFactor: The carbohydrate-sensitivity factor for the entry, in glucose units per gram /// - initialAbsorptionTime: The absorption initially assigned to this entry before any absorption is observed /// - maxAbsorptionTime: The maximum absorption time allowed for this entry, determining the minimum absorption rate /// - delay: An amount of time to wait after the entry date before minimum absorption is assumed to begin /// - lastEffectDate: The last recorded date of effect observation, used to initialize absorption at model defined rate /// - initialObservedEffect: The initial amount of observed effect, in glucose units. Defaults to 0. init(entry: T, carbUnit: HKUnit, carbohydrateSensitivityFactor: Double, initialAbsorptionTime: TimeInterval, maxAbsorptionTime: TimeInterval, delay: TimeInterval, lastEffectDate: Date?, absorptionModel: CarbAbsorptionComputable, adaptiveAbsorptionRateEnabled: Bool, adaptiveRateStandbyIntervalFraction: Double, initialObservedEffect: Double = 0) { self.entry = entry self.carbUnit = carbUnit self.carbohydrateSensitivityFactor = carbohydrateSensitivityFactor self.initialAbsorptionTime = initialAbsorptionTime self.maxAbsorptionTime = maxAbsorptionTime self.delay = delay self.observedEffect = initialObservedEffect self.absorptionModel = absorptionModel self.adaptiveAbsorptionRateEnabled = adaptiveAbsorptionRateEnabled self.adaptiveRateStandbyIntervalFraction = adaptiveRateStandbyIntervalFraction self.entryGrams = entry.quantity.doubleValue(for: carbUnit) self.entryEffect = entryGrams * carbohydrateSensitivityFactor self.maxEndDate = entry.startDate.addingTimeInterval(maxAbsorptionTime + delay) self.lastEffectDate = min( maxEndDate, Swift.max(lastEffectDate ?? entry.startDate, entry.startDate) ) } /// Increments the builder state with the next glucose effect. /// /// This function should only be called with values in ascending date order. /// /// - Parameters: /// - effect: The effect value, in glucose units corresponding to `carbohydrateSensitivityFactor` /// - start: The start date of the effect /// - end: The end date of the effect func addNextEffect(_ effect: Double, start: Date, end: Date) { guard start >= entry.startDate else { return } observedEffect += effect if observedCompletionDate == nil { // Continue recording the timeline until 100% of the carbs have been observed observedTimeline.append(CarbValue( startDate: start, endDate: end, quantity: HKQuantity( unit: carbUnit, doubleValue: effect / carbohydrateSensitivityFactor ) )) // Once 100% of the carbs are observed, track the endDate if observedEffect + Double(Float.ulpOfOne) >= entryEffect { observedCompletionDate = end } } } /// The resulting CarbStatus value var result: CarbStatus<T> { let absorption = AbsorbedCarbValue( observed: HKQuantity(unit: carbUnit, doubleValue: observedGrams), clamped: HKQuantity(unit: carbUnit, doubleValue: clampedGrams), total: entry.quantity, remaining: HKQuantity(unit: carbUnit, doubleValue: entryGrams - clampedGrams), observedDate: observedAbsorptionDates, estimatedTimeRemaining: estimatedTimeRemaining, timeToAbsorbObservedCarbs: timeToAbsorbObservedCarbs ) return CarbStatus( entry: entry, absorption: absorption, observedTimeline: clampedTimeline ) } func absorptionRateAtTime(t: TimeInterval) -> Double { let dynamicAbsorptionTime = min(observedAbsorptionDates.duration + estimatedTimeRemaining, maxAbsorptionTime) guard dynamicAbsorptionTime > 0 else { return(0.0) } // time t nomalized to absorption time let percentTime = t / dynamicAbsorptionTime let averageAbsorptionRate = entryGrams / dynamicAbsorptionTime return averageAbsorptionRate * absorptionModel.percentRateAtPercentTime(forPercentTime: percentTime) } } // MARK: - Sorted collections of CarbEntries extension Collection where Element: CarbEntry { /// Maps a sorted timeline of carb entries to the observed absorbed carbohydrates for each, from a timeline of glucose effect velocities. /// /// This makes some important assumptions: /// - insulin effects, used with glucose to calculate counteraction, are "correct" /// - carbs are absorbed completely in the order they were eaten without mixing or overlapping effects /// /// - Parameters: /// - effectVelocities: A timeline of glucose effect velocities, ordered by start date /// - carbRatio: The schedule of carb ratios, in grams per unit /// - insulinSensitivity: The schedule of insulin sensitivities, in units of insulin per glucose-unit /// - absorptionTimeOverrun: A multiplier for determining the minimum absorption time from the specified absorption time /// - defaultAbsorptionTime: The absorption time to use for unspecified carb entries /// - delay: The time to delay the dose effect /// - Returns: A new array of `CarbStatus` values describing the absorbed carb quantities func map( to effectVelocities: [GlucoseEffectVelocity], carbRatio: CarbRatioSchedule?, insulinSensitivity: InsulinSensitivitySchedule?, absorptionTimeOverrun: Double, defaultAbsorptionTime: TimeInterval, delay: TimeInterval, initialAbsorptionTimeOverrun: Double, absorptionModel: CarbAbsorptionComputable, adaptiveAbsorptionRateEnabled: Bool, adaptiveRateStandbyIntervalFraction: Double ) -> [CarbStatus<Element>] { guard count > 0 else { // TODO: Apply unmatched effects to meal prediction return [] } guard let carbRatios = carbRatio, let insulinSensitivities = insulinSensitivity else { return map { (entry) in CarbStatus(entry: entry, absorption: nil, observedTimeline: nil) } } // for computation let glucoseUnit = HKUnit.milligramsPerDeciliter let carbUnit = HKUnit.gram() let builders: [CarbStatusBuilder<Element>] = map { (entry) in let carbRatio = carbRatios.quantity(at: entry.startDate) let insulinSensitivity = insulinSensitivities.quantity(at: entry.startDate) let initialAbsorptionTimeOverrun = initialAbsorptionTimeOverrun return CarbStatusBuilder( entry: entry, carbUnit: carbUnit, carbohydrateSensitivityFactor: insulinSensitivity.doubleValue(for: glucoseUnit) / carbRatio.doubleValue(for: carbUnit), initialAbsorptionTime: (entry.absorptionTime ?? defaultAbsorptionTime) * initialAbsorptionTimeOverrun, maxAbsorptionTime: (entry.absorptionTime ?? defaultAbsorptionTime) * absorptionTimeOverrun, delay: delay, lastEffectDate: effectVelocities.last?.endDate, absorptionModel: absorptionModel, adaptiveAbsorptionRateEnabled: adaptiveAbsorptionRateEnabled, adaptiveRateStandbyIntervalFraction: adaptiveRateStandbyIntervalFraction ) } for dxEffect in effectVelocities { guard dxEffect.endDate > dxEffect.startDate else { assertionFailure() continue } // calculate instantanous absorption rate for all active entries // Apply effect to all active entries // Select only the entries whose dates overlap the current date interval. // These are not necessarily contiguous as maxEndDate varies between entries let activeBuilders = builders.filter { (builder) -> Bool in return dxEffect.startDate < builder.maxEndDate && dxEffect.startDate >= builder.entry.startDate } // Ignore velocities < 0 when estimating carb absorption. // These are most likely the result of insulin absorption increases such as // during activity var effectValue = Swift.max(0, dxEffect.effect.quantity.doubleValue(for: glucoseUnit)) // Sum the current absorption rates of each active entry to determine how to split the active effects var totalRate = activeBuilders.reduce(0) { (totalRate, builder) -> Double in let effectTime = dxEffect.startDate.timeIntervalSince(builder.entry.startDate) let absorptionRateAtEffectTime = builder.absorptionRateAtTime(t: effectTime) return totalRate + absorptionRateAtEffectTime } for builder in activeBuilders { // Apply a portion of the effect to this entry let effectTime = dxEffect.startDate.timeIntervalSince(builder.entry.startDate) let absorptionRateAtEffectTime = builder.absorptionRateAtTime(t: effectTime) // If total rate is zero, assign zero to partial effect var partialEffectValue: Double = 0.0 if totalRate > 0 { partialEffectValue = Swift.min(builder.remainingEffect, (absorptionRateAtEffectTime / totalRate) * effectValue) totalRate -= absorptionRateAtEffectTime effectValue -= partialEffectValue } builder.addNextEffect(partialEffectValue, start: dxEffect.startDate, end: dxEffect.endDate) // If there's still remainder effects with no additional entries to account them to, count them as overrun on the final entry if effectValue > Double(Float.ulpOfOne) && builder === activeBuilders.last! { builder.addNextEffect(effectValue, start: dxEffect.startDate, end: dxEffect.endDate) } } // We have remaining effect and no activeBuilders (otherwise we would have applied the effect to the last one) if effectValue > Double(Float.ulpOfOne) { // TODO: Track "phantom meals" } } return builders.map { $0.result } } }
mit
77b8bb58cb0d7e3af035d2b8a823aeca
41.850498
351
0.658061
4.943025
false
false
false
false
hujiaweibujidao/Gank
Gank/Extension/Extension.swift
1
2110
// // Extension.swift // Gank // // Created by AHuaner on 2017/2/26. // Copyright © 2017年 CoderAhuan. All rights reserved. // import UIKit // MARK: - Bundle - Extension extension Bundle { static var releaseVersion: String? { return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String } static var buildVersion: String? { return Bundle.main.infoDictionary?["CFBundleVersion"] as? String } static var appName: String { return Bundle.main.infoDictionary?["CFBundleName"] as! String } } // MARK: - UIDevice - Extension extension UIDevice { static func getUUID() -> String { // let UUID = Foundation.UUID().uuidString return UIDevice.current.identifierForVendor!.uuidString } } // MARK: - DispatchTime - Extension extension DispatchTime: ExpressibleByIntegerLiteral { public init(integerLiteral value: Int) { self = DispatchTime.now() + .seconds(value) } } extension DispatchTime: ExpressibleByFloatLiteral { public init(floatLiteral value: Double) { self = DispatchTime.now() + .milliseconds(Int(value * 1000)) } } // MARK: - NSObject - Extension extension NSObject { static var className: String { let name = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String let reaName = name + "." return NSStringFromClass(self).substring(from: reaName.endIndex) } } // MARK: - CGFloat - Extension extension CGFloat { func format(f: Int) -> String { return NSString(format:"%.\(f)f" as NSString, self) as String } } // MARK: - Date - Extension extension Date { func toString(WithFormat format: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.string(from: self) } } // MARK: - CALayer - Extension extension CALayer { var XibBorderColor: UIColor? { get { return UIColor(cgColor: self.borderColor!) } set(boderColor) { self.borderColor = boderColor?.cgColor } } }
mit
a077e10d3d26b395e5a610de5f01aebe
24.695122
83
0.648315
4.389583
false
false
false
false
ashfurrow/pragma-2015-rx-workshop
Session 4/Signup Demo/Pods/RxSwift/RxSwift/Observable+Extensions.swift
12
4230
// // Observable+Extensions.swift // Rx // // Created by Krunoslav Zaher on 2/21/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation extension ObservableType { /** Subscribes an event handler to an observable sequence. - parameter on: Action to invoke for each event in the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ @warn_unused_result public func subscribe(on: (event: Event<E>) -> Void) -> Disposable { let observer = AnonymousObserver { e in on(event: e) } return self.subscribeSafe(observer) } /** Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence. - parameter next: Action to invoke for each element in the observable sequence. - parameter error: Action to invoke upon errored termination of the observable sequence. - parameter completed: Action to invoke upon graceful termination of the observable sequence. - parameter disposed: Action to invoke upon any type of termination of sequence (if the sequence has gracefully completed, errored, or if the generation is cancelled by disposing subscription) - returns: Subscription object used to unsubscribe from the observable sequence. */ @warn_unused_result public func subscribe(next next: ((E) -> Void)? = nil, error: ((ErrorType) -> Void)? = nil, completed: (() -> Void)? = nil, disposed: (() -> Void)? = nil) -> Disposable { let disposable: Disposable if let disposed = disposed { disposable = AnonymousDisposable(disposed) } else { disposable = NopDisposable.instance } let observer = AnonymousObserver<E> { e in switch e { case .Next(let value): next?(value) case .Error(let e): error?(e) disposable.dispose() case .Completed: completed?() disposable.dispose() } } return BinaryDisposable( self.subscribeSafe(observer), disposable ) } /** Subscribes an element handler to an observable sequence. - parameter onNext: Action to invoke for each element in the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ @warn_unused_result public func subscribeNext(onNext: (E) -> Void) -> Disposable { let observer = AnonymousObserver<E> { e in if case .Next(let value) = e { onNext(value) } } return self.subscribeSafe(observer) } /** Subscribes an error handler to an observable sequence. - parameter onRrror: Action to invoke upon errored termination of the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ @warn_unused_result public func subscribeError(onError: (ErrorType) -> Void) -> Disposable { let observer = AnonymousObserver<E> { e in if case .Error(let error) = e { onError(error) } } return self.subscribeSafe(observer) } /** Subscribes a completion handler to an observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ @warn_unused_result public func subscribeCompleted(onCompleted: () -> Void) -> Disposable { let observer = AnonymousObserver<E> { e in if case .Completed = e { onCompleted() } } return self.subscribeSafe(observer) } } public extension ObservableType { /** All internal subscribe calls go through this method */ func subscribeSafe<O: ObserverType where O.E == E>(observer: O) -> Disposable { return self.subscribe(observer) } }
mit
99a014c2da143d1fe8a1e778e00e8d61
32.314961
158
0.616785
5.078031
false
false
false
false
LoopKit/LoopKit
LoopKitUI/Views/SegmentedGaugeBarView.swift
1
6708
// // SegmentedGaugeBarView.swift // LoopKitUI // // Created by Michael Pangburn on 3/22/19. // Copyright © 2019 LoopKit Authors. All rights reserved. // import UIKit public protocol SegmentedGaugeBarViewDelegate: AnyObject { /// Invoked only when `progress` is updated via gesture. func segmentedGaugeBarView(_ view: SegmentedGaugeBarView, didUpdateProgressFrom oldValue: Double, to newValue: Double) } @IBDesignable public class SegmentedGaugeBarView: UIView { @IBInspectable public var numberOfSegments: Int { get { return gaugeLayer.numberOfSegments } set { gaugeLayer.numberOfSegments = newValue } } @IBInspectable public var startColor: UIColor { get { return UIColor(cgColor: gaugeLayer.startColor) } set { gaugeLayer.startColor = newValue.cgColor } } @IBInspectable public var endColor: UIColor { get { return UIColor(cgColor: gaugeLayer.endColor) } set { gaugeLayer.endColor = newValue.cgColor } } @IBInspectable public var borderWidth: CGFloat { get { return gaugeLayer.gaugeBorderWidth } set { gaugeLayer.gaugeBorderWidth = newValue } } @IBInspectable public var borderColor: UIColor { get { return UIColor(cgColor: gaugeLayer.gaugeBorderColor) } set { gaugeLayer.gaugeBorderColor = newValue.cgColor } } @IBInspectable public var progress: Double { get { if displaysThumb { return Double(fractionThrough(thumb.center.x, in: thumbCenterXRange)) } else { return visualProgress } } set { if displaysThumb { thumb.center.x = interpolatedValue(at: CGFloat(newValue), through: thumbCenterXRange).clamped(to: thumbCenterXRange) // Push the gauge progress behind the thumb, ensuring the cap rounding is not visible. let gaugeX = thumb.center.x + 0.25 * thumb.frame.width visualProgress = newValue == 0 ? 0 : Double(fractionThrough(gaugeX, in: gaugeXRange)) } else { visualProgress = newValue } } } private var visualProgress: Double { get { Double(gaugeLayer.progress) } set { gaugeLayer.progress = CGFloat(newValue) } } public weak var delegate: SegmentedGaugeBarViewDelegate? override public class var layerClass: AnyClass { return SegmentedGaugeBarLayer.self } private var gaugeLayer: SegmentedGaugeBarLayer { return layer as! SegmentedGaugeBarLayer } override public init(frame: CGRect) { super.init(frame: frame) setupPanGestureRecognizer() } required init?(coder: NSCoder) { super.init(coder: coder) setupPanGestureRecognizer() } private lazy var thumb = ThumbView() public var displaysThumb = false { didSet { if displaysThumb { assert(numberOfSegments == 1, "Thumb only supported for single-segment gauges") if thumb.superview == nil { addSubview(thumb) } } else { thumb.removeFromSuperview() } } } private var panGestureRecognizer: UIPanGestureRecognizer? private func setupPanGestureRecognizer() { let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:))) panGestureRecognizer = pan addGestureRecognizer(pan) } @objc private func handlePan(_ recognizer: UIPanGestureRecognizer) { switch recognizer.state { case .began, .changed: guard recognizer.numberOfTouches == 1 else { break } let location = recognizer.location(ofTouch: 0, in: self) let gaugeFillFraction = fractionThrough(location.x, in: gaugeXRange) let oldValue = progress let newValue = (Double(gaugeFillFraction) * Double(numberOfSegments)).clamped(to: 0...Double(numberOfSegments)) CATransaction.withoutActions { progress = newValue } delegate?.segmentedGaugeBarView(self, didUpdateProgressFrom: oldValue, to: newValue) case .ended: uglyWorkaroundToForceRedraw() default: break } } private func uglyWorkaroundToForceRedraw() { // Resolves an issue--most of the time--where dragging _very_ rapidly then releasing // can cause the gauge layer to fall behind a cycle in rendering. // - `setNeedsDisplay()` is insufficient. // - Adding additional executions (delay times) catches the issue with a greater probability, // with diminishing returns after four executions (by observation). for (index, delayMS) in [10, 25, 50, 100].enumerated() { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(delayMS)) { CATransaction.withoutActions { self.progress = index % 2 == 0 ? self.progress.nextUp : self.progress.nextDown } } } } override public func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = frame.height / 2 updateThumbPosition() } private var gaugeXRange: ClosedRange<CGFloat> { (bounds.minX + 2 * borderWidth)...(bounds.maxX - 2 * borderWidth) } private var thumbCenterXRange: ClosedRange<CGFloat> { let radius = thumb.bounds.width / 2 return (gaugeXRange.lowerBound + radius)...(gaugeXRange.upperBound - radius) } private func updateThumbPosition() { guard displaysThumb else { return } let diameter = bounds.height - 2 * borderWidth thumb.bounds.size = CGSize(width: diameter, height: diameter) let xPosition = interpolatedValue(at: CGFloat(progress), through: thumbCenterXRange) thumb.center = CGPoint(x: xPosition, y: bounds.midY) } public func cancelActiveTouches() { guard panGestureRecognizer?.isEnabled == true else { return } panGestureRecognizer?.isEnabled = false panGestureRecognizer?.isEnabled = true } } fileprivate extension CATransaction { static func withoutActions(_ execute: () -> Void) { begin() setValue(true, forKey: kCATransactionDisableActions) execute() commit() } }
mit
2fa619c07948e9584f7feeb05a716f33
29.486364
132
0.605785
5.127676
false
false
false
false
imfree-jdcastro/Evrythng-iOS-SDK
Evrythng-iOS/EvrythngUserAuthenticator.swift
1
2783
// // EvrythngUserAuthenticator.swift // EvrythngiOS // // Created by JD Castro on 29/05/2017. // Copyright © 2017 ImFree. All rights reserved. // import UIKit import Moya import MoyaSugar import Moya_SwiftyJSONMapper public class EvrythngUserAuthenticator: EvrythngNetworkExecutableProtocol { private var email: String! private var password: String! private init() { } internal init(email: String, password: String) { self.email = email self.password = password } public func getDefaultProvider() -> EvrythngMoyaProvider<EvrythngNetworkService> { return EvrythngMoyaProvider<EvrythngNetworkService>() } public func execute(completionHandler: @escaping (Credentials?, Swift.Error?) -> Void) { let creds = Credentials(email: self.email, password: self.password) let authenticateUserRepo = EvrythngNetworkService.authenticateUser(credentials: creds) self.getDefaultProvider().request(authenticateUserRepo) { result in switch result { case let .success(moyaResponse): let data = moyaResponse.data let statusCode = moyaResponse.statusCode let datastring = NSString(data: data, encoding: String.Encoding.utf8.rawValue) print("Data: \(datastring!) Status Code: \(statusCode)") if(200..<300 ~= statusCode) { do { let credentials = try moyaResponse.map(to: Credentials.self) completionHandler(credentials, nil) } catch { print(error) completionHandler(nil, error) } } else { do { let err = try moyaResponse.map(to: EvrythngNetworkErrorResponse.self) print("EvrythngNetworkErrorResponse: \(err.jsonData?.rawString())") completionHandler(nil, EvrythngNetworkError.ResponseError(response: err)) } catch { print(error) completionHandler(nil, error) } } case let .failure(error): print("Error: \(error)") // this means there was a network failure - either the request // wasn't sent (connectivity), or no response was received (server // timed out). If the server responds with a 4xx or 5xx error, that // will be sent as a ".success"-ful response. completionHandler(nil, error) break } } } }
apache-2.0
a805982e0d546304dea18b24cc6c5f43
35.605263
97
0.551761
5.190299
false
false
false
false
bnickel/StackedDrafts
StackedDrafts/StackedDrafts/DraftTransitioningDelegate.swift
1
4266
// // DraftTransitioningDelegate.swift // StackedDrafts // // Created by Brian Nickel on 4/21/16. // Copyright © 2016 Stack Exchange. All rights reserved. // import UIKit /** This class manages animation, presentation, and interactive dismissal of view controllers conforming to `DraftViewControllerProtocol`. Before being presented, draft view controllers should set their `transitioningDelegate` to an instance of this class and `modalPresentationStyle` to `.Custom`. - Note: When the presentation animation is completed, the presenting view controller is replaced with a view that simulates its color and navigation bar appearance. Subclasses may override `simulatedPresentingView(for:)` to handle complex view controller styles. */ @objc(SEUIDraftTransitioningDelegate) open class DraftTransitioningDelegate : NSObject, UIViewControllerTransitioningDelegate { private let openDraftsIndicatorSource: OpenDraftsIndicatorSource @objc public init(openDraftsIndicatorSource: OpenDraftsIndicatorSource) { self.openDraftsIndicatorSource = openDraftsIndicatorSource super.init() } open func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { return DraftPresentationController(presentedViewController: presented, presenting: presenting, openDraftsIndicatorSource: openDraftsIndicatorSource) } open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return SingleDraftPresentationAnimatedTransitioning() } open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return DraftDismissalAnimatedTransitioning(interactiveTransitioning: dismissed.draftPresentationController?.interactiveTransitioning) } open func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return (animator as? DraftDismissalAnimatedTransitioning)?.interactiveTransitioning } /** This method is called by the presentation controller when the animation completes in order to show what appears to be the top of the presenting view controller behind the presented view controller. The view controller is obscured in such a way that no more than the top 20pt should be visible in when the status bar is visible and 5pt when the status bar is hidden. This should cause most or all navigation bar content hidden so a solid background would be sufficient. The default implementation of this method renders either a solid background for a presenting UIViewController or a matching navigation bar for a presenting UINavigationController. This method can be overwritten in a subclass to handle more complex requirements. - Parameter presentingViewController: The view controller that should be simulated. - Returns: The UIView to display. */ @objc open func simulatedPresentingView(for presentingViewController: UIViewController) -> UIView { let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) view.backgroundColor = presentingViewController.view.backgroundColor if let navigationController = presentingViewController as? UINavigationController , !navigationController.isNavigationBarHidden { let sourceNavigationBar = navigationController.navigationBar let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: 100, height: 64)) navigationBar.backgroundColor = sourceNavigationBar.backgroundColor navigationBar.barTintColor = sourceNavigationBar.barTintColor navigationBar.isTranslucent = sourceNavigationBar.isTranslucent navigationBar.autoresizingMask = [.flexibleBottomMargin, .flexibleWidth] view.backgroundColor = navigationController.visibleViewController?.view.backgroundColor ?? navigationController.view.backgroundColor view.addSubview(navigationBar) } return view } }
mit
61a4ad49d88cdfacb73bf7e51cb173e1
62.656716
475
0.776788
6.136691
false
false
false
false
Awalz/ark-ios-monitor
ArkMonitor/Home /TransactionDetailViewController.swift
1
5311
// Copyright (c) 2016 Ark // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit import SwiftyArk class TransactionDetailViewController: ArkViewController { fileprivate let transaction : Transaction fileprivate var tableView : ArkTableView! init(_ transaction: Transaction) { self.transaction = transaction super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Detail" tableView = ArkTableView(CGRect.zero) tableView.delegate = self tableView.dataSource = self view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.left.right.top.bottom.equalToSuperview() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(false, animated: true) } } // MARK: UITableViewDelegate extension TransactionDetailViewController : UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 35.0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: _screenWidth, height: 35.0)) headerView.backgroundColor = ArkPalette.secondaryBackgroundColor let headerLabel = UILabel(frame: CGRect(x: 12.5, y: 0.0, width: _screenWidth - 12.5, height: 35.0)) headerLabel.textColor = ArkPalette.highlightedTextColor headerLabel.textAlignment = .center headerLabel.font = UIFont.systemFont(ofSize: 15.0, weight: .semibold) switch section { case 0: headerLabel.text = "Transaction ID" case 1: headerLabel.text = "Time" case 2: headerLabel.text = "From" case 3: headerLabel.text = "To" case 4: headerLabel.text = "Amount" case 5: headerLabel.text = "Fee" case 6: headerLabel.text = "Confirmations" default: headerLabel.text = "Vendor Field" } headerView.addSubview(headerLabel) return headerView } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0 { return 65.0 } return 45.0 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return CGFloat.leastNormalMagnitude } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return nil } } // MARK: UITableViewDelegate extension TransactionDetailViewController : UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { if transaction.vendorField != nil { return 8 } else { return 7 } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var titleString = "" var numberOfLines = 1 switch indexPath.section { case 0: titleString = transaction.id numberOfLines = 2 case 1: titleString = transaction.timestamp.longStyleDateString case 2: titleString = transaction.senderId case 3: titleString = transaction.recipientId case 4: titleString = String(transaction.amount) case 5: titleString = String(transaction.fee) case 6: titleString = String(transaction.confirmations) default: titleString = transaction.vendorField ?? "" } let cell = ArkDetailTableViewCell(titleString, numberOfLines: numberOfLines) return cell } }
mit
d9f7a85bf2aea777d5c2193f1d06a7d2
33.940789
137
0.643947
5.237673
false
false
false
false
Draveness/NightNight
NightNight/Classes/Dictionary+AttributedStringKeys.swift
1
478
// // Dictionary+AttributedStringKeys.swift // NightNight // // Created by Weiran Zhang on 08/10/2017. // import Foundation extension Dictionary where Key == String, Value == AnyObject { public func withAttributedStringKeys() -> [NSAttributedString.Key: AnyObject] { var mappedDictionary = [NSAttributedString.Key: AnyObject]() self.forEach { mappedDictionary[MixedColorAttributeNamesDictionary[$0.0]!] = $0.1 } return mappedDictionary } }
mit
c6700c81a1d5e6c648c101a3d2286270
27.117647
91
0.707113
4.385321
false
false
false
false
transparentmask/CheckIn
CheckIn/CIAppInfo.swift
1
3260
// // CIAppInfo.swift // CheckIn // // Created by Martin Yin on 10/05/2017. // Copyright © 2017 Martin Yin. All rights reserved. // import UIKit import SDWebImage import SwiftyJSON class CIAppInfo: NSObject, NSCoding { var id: String? = nil var name: String? = nil var icon: UIImage? = nil var iconURL: String? = nil { didSet { if let iconURL = iconURL, let url = URL(string: iconURL) { SDWebImageManager.shared().downloadImage(with: url, options: .avoidAutoSetImage, progress: nil, completed: { (image, error, cacheType, finished, _) in self.icon = image }) } } } var url: String? = nil var alreadyOpen: Bool { get { return Calendar.current.isDateInToday(Date(timeIntervalSince1970: checkinTime)) } } var checkinTime: TimeInterval = 0 override var description: String { return "id: \(id!); name: \(name!); icon: \(iconURL!); url: \(url!)" } override var debugDescription: String { return description } override init() { super.init() } convenience init(_ appJSON: JSON) { self.init() id = appJSON["id"].string name = appJSON["name"].string iconURL = appJSON["icon"].string url = appJSON["url"].string if let time = appJSON["checkinTime"].double { checkinTime = time } } required init?(coder aDecoder: NSCoder) { self.id = aDecoder.decodeObject(forKey: "id") as? String self.name = aDecoder.decodeObject(forKey: "name") as? String self.iconURL = aDecoder.decodeObject(forKey: "iconURL") as? String self.url = aDecoder.decodeObject(forKey: "url") as? String self.checkinTime = aDecoder.decodeObject(forKey: "checkinTime") as! TimeInterval } func encode(with aCoder: NSCoder) { if let id = id { aCoder.encode(id, forKey: "id") } if let name = name { aCoder.encode(name, forKey: "name") } if let iconURL = iconURL { aCoder.encode(iconURL, forKey: "iconURL") } if let url = url { aCoder.encode(url, forKey: "url") } aCoder.encode(checkinTime, forKey: "checkinTime") } func dictionary() -> Dictionary<String, Any> { return ["id": id!, "name": name!, "icon": iconURL!, "url": url!, "checkinTime": checkinTime] } func open(_ completion: ((Bool) -> Swift.Void)? = nil) { if let url = url, let appURL = URL(string: url) { UIApplication.shared.open(appURL, completionHandler: { result in if result { self.checkinTime = Date().timeIntervalSince1970 } if let completion = completion { completion(result) } }) } } static func ==(lhs: CIAppInfo, rhs: CIAppInfo) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name && lhs.iconURL == rhs.iconURL && lhs.url == rhs.url } static func !=(lhs: CIAppInfo, rhs: CIAppInfo) -> Bool { return !(lhs == rhs) } }
apache-2.0
6ca8fe05ebef85aea4a04cc73114c891
29.457944
166
0.548328
4.271298
false
false
false
false
OrielBelzer/StepCoin
Controllers/UserController.swift
1
1439
// // UserController.swift // StepCoin // // Created by Oriel Belzer on 12/23/16. // import Haneke import SwiftyJSON open class UserController { let cache = Shared.dataCache let defaults = UserDefaults.standard func calcUserQuantities() { var sumOfUserCoinsValue = 0.0 var uniqueStoreIDs = Set<Int>() cache.fetch(key: "user").onSuccess { data in if let user = NSKeyedUnarchiver.unarchiveObject(with: data) as? User { for coin in (user.coins)! { if !uniqueStoreIDs.contains(coin.storeId!) { uniqueStoreIDs.insert(coin.storeId!) } sumOfUserCoinsValue += Double(coin.value!)! } self.defaults.set(user.coins?.count, forKey: "userNumberOfCoins") self.defaults.set(sumOfUserCoinsValue, forKey: "userSumOfCoinsValue") self.defaults.set(uniqueStoreIDs.count, forKey: "userSumOfCoinsStores") self.defaults.synchronize() } } } func sendLocationToServer(userId: String, latitude: String, longitude: String) { ConnectionController.sharedInstance.sendLocationToServer(userId: userId, longitude: longitude, latitude: latitude) { (responseObject:SwiftyJSON.JSON, error:String) in if (error == "") { } else { print(error) } } } }
mit
a14268a86406e18ba2ef25dfe24889a5
31.704545
176
0.594163
4.468944
false
false
false
false
RocketChat/Rocket.Chat.iOS
Pods/OAuthSwift/Sources/String+OAuthSwift.swift
3
4241
// // String+OAuthSwift.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation extension String { var parametersFromQueryString: [String: String] { return dictionaryBySplitting("&", keyValueSeparator: "=") } /// Encodes url string making it ready to be passed as a query parameter. This encodes pretty much everything apart from /// alphanumerics and a few other characters compared to standard query encoding. var urlEncoded: String { let customAllowedSet = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~") return self.addingPercentEncoding(withAllowedCharacters: customAllowedSet)! } var urlQueryEncoded: String? { return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) } /// Returns new url query string by appending query parameter encoding it first, if specified. func urlQueryByAppending(parameter name: String, value: String, encode: Bool = true, _ encodeError: ((String, String) -> Void)? = nil) -> String? { if value.isEmpty { return self } else if let value = encode ? value.urlQueryEncoded : value { return "\(self)\(self.isEmpty ? "" : "&")\(name)=\(value)" } else { encodeError?(name, value) return nil } } /// Returns new url string by appending query string at the end. func urlByAppending(query: String) -> String { return "\(self)\(self.contains("?") ? "&" : "?")\(query)" } fileprivate func dictionaryBySplitting(_ elementSeparator: String, keyValueSeparator: String) -> [String: String] { var string = self if hasPrefix(elementSeparator) { string = String(dropFirst(1)) } var parameters = [String: String]() let scanner = Scanner(string: string) var key: NSString? var value: NSString? while !scanner.isAtEnd { key = nil scanner.scanUpTo(keyValueSeparator, into: &key) scanner.scanString(keyValueSeparator, into: nil) value = nil scanner.scanUpTo(elementSeparator, into: &value) scanner.scanString(elementSeparator, into: nil) if let key = key as String? { if let value = value as String? { if key.contains(elementSeparator) { var keys = key.components(separatedBy: elementSeparator) if let key = keys.popLast() { parameters.updateValue(value, forKey: String(key)) } for flag in keys { parameters.updateValue("", forKey: flag) } } else { parameters.updateValue(value, forKey: key) } } else { parameters.updateValue("", forKey: key) } } } return parameters } public var headerDictionary: OAuthSwift.Headers { return dictionaryBySplitting(",", keyValueSeparator: "=") } var safeStringByRemovingPercentEncoding: String { return self.removingPercentEncoding ?? self } mutating func dropLast() { self.remove(at: self.index(before: self.endIndex)) } subscript (bounds: CountableClosedRange<Int>) -> String { let start = index(startIndex, offsetBy: bounds.lowerBound) let end = index(startIndex, offsetBy: bounds.upperBound) return String(self[start...end]) } subscript (bounds: CountableRange<Int>) -> String { let start = index(startIndex, offsetBy: bounds.lowerBound) let end = index(startIndex, offsetBy: bounds.upperBound) return String(self[start..<end]) } } extension String.Encoding { var charset: String { let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.rawValue)) // swiftlint:disable:next force_cast return charset! as String } }
mit
11b5b1d698187b48c1778e15ce463c06
33.479675
151
0.604574
5.229346
false
false
false
false
frootloops/swift
stdlib/public/SDK/Metal/Metal.swift
2
9699
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Metal // Clang module @available(swift 4) @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLBlitCommandEncoder { public func fill(buffer: MTLBuffer, range: Range<Int>, value: UInt8) { __fill(buffer, range: NSRange(location: range.lowerBound, length: range.count), value: value) } } @available(swift 4) @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLBuffer { #if os(macOS) @available(macOS, introduced: 10.11) public func didModifyRange(_ range: Range<Int>) { __didModifyRange(NSRange(location: range.lowerBound, length: range.count)) } #endif @available(macOS 10.12, iOS 10.0, tvOS 10.0, *) public func addDebugMarker(_ marker: String, range: Range<Int>) { __addDebugMarker(marker, range: NSRange(location: range.lowerBound, length: range.count)) } } @available(swift 4) @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLComputeCommandEncoder { @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func useResources(_ resources: [MTLResource], usage: MTLResourceUsage) { __use(resources, count: resources.count, usage: usage) } @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func useHeaps(_ heaps: [MTLHeap]) { __use(heaps, count: heaps.count) } public func setBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) { __setBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) } public func setTextures(_ textures: [MTLTexture?], range: Range<Int>) { __setTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) } public func setSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) { __setSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) } public func setSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) { __setSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) } } @available(swift 4) @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLDevice { @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func getDefaultSamplePositions(sampleCount: Int) -> [MTLSamplePosition] { var positions = [MTLSamplePosition](repeating: MTLSamplePosition(x: 0,y: 0), count: sampleCount) __getDefaultSamplePositions(&positions, count: sampleCount) return positions } } #if os(macOS) @available(swift 4) @available(macOS 10.13, *) public func MTLCopyAllDevicesWithObserver(handler: @escaping MTLDeviceNotificationHandler) -> (devices:[MTLDevice], observer:NSObject) { var resultTuple: (devices:[MTLDevice], observer:NSObject) resultTuple.observer = NSObject() resultTuple.devices = __MTLCopyAllDevicesWithObserver(AutoreleasingUnsafeMutablePointer<NSObjectProtocol?>(&resultTuple.observer), handler) return resultTuple } #endif @available(swift 4) @available(macOS 10.12, iOS 10.0, tvOS 10.0, *) extension MTLFunctionConstantValues { public func setConstantValues(_ values: UnsafeRawPointer, type: MTLDataType, range: Range<Int>) { __setConstantValues(values, type: type, with: NSRange(location: range.lowerBound, length: range.count)) } } @available(swift 4) @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) extension MTLArgumentEncoder { public func setBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) { __setBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) } public func setTextures(_ textures: [MTLTexture?], range: Range<Int>) { __setTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) } public func setSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) { __setSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) } } @available(swift 4) @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLRenderCommandEncoder { @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func useResources(_ resources: [MTLResource], usage: MTLResourceUsage) { __use(resources, count: resources.count, usage: usage) } @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func useHeaps(_ heaps: [MTLHeap]) { __use(heaps, count: heaps.count) } #if os(macOS) @available(macOS 10.13, *) public func setViewports(_ viewports: [MTLViewport]) { __setViewports(viewports, count: viewports.count) } @available(macOS 10.13, *) public func setScissorRects(_ scissorRects: [MTLScissorRect]) { __setScissorRects(scissorRects, count: scissorRects.count) } #endif public func setVertexBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) { __setVertexBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) } public func setVertexTextures(_ textures: [MTLTexture?], range: Range<Int>) { __setVertexTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) } public func setVertexSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) { __setVertexSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) } public func setVertexSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) { __setVertexSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) } public func setFragmentBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) { __setFragmentBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) } public func setFragmentTextures(_ textures: [MTLTexture?], range: Range<Int>) { __setFragmentTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) } public func setFragmentSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) { __setFragmentSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) } public func setFragmentSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) { __setFragmentSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) } #if os(iOS) @available(iOS 11.0, *) public func setTileBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) { __setTileBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) } @available(iOS 11.0, *) public func setTileTextures(_ textures: [MTLTexture?], range: Range<Int>) { __setTileTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) } @available(iOS 11.0, *) public func setTileSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) { __setTileSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) } @available(iOS 11.0, *) public func setTileSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) { __setTileSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) } #endif } @available(swift 4) @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLRenderPassDescriptor { @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func setSamplePositions(_ positions: [MTLSamplePosition]) { __setSamplePositions(positions, count: positions.count) } @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) public func getSamplePositions() -> [MTLSamplePosition] { let numPositions = __getSamplePositions(nil, count: 0) var positions = [MTLSamplePosition](repeating: MTLSamplePosition(x: 0,y: 0), count: numPositions) __getSamplePositions(&positions, count: numPositions) return positions } } @available(swift 4) @available(macOS 10.11, iOS 8.0, tvOS 8.0, *) extension MTLTexture { @available(macOS 10.11, iOS 9.0, tvOS 9.0, *) public func makeTextureView(pixelFormat: MTLPixelFormat, textureType: MTLTextureType, levels levelRange: Range<Int>, slices sliceRange: Range<Int>) -> MTLTexture? { return __newTextureView(with: pixelFormat, textureType: textureType, levels: NSRange(location: levelRange.lowerBound, length: levelRange.count), slices: NSRange(location: sliceRange.lowerBound, length: sliceRange.count)) } }
apache-2.0
eff1d6c77abdda13458e44992c06e03a
40.987013
228
0.679451
4.198701
false
false
false
false
google/JacquardSDKiOS
Tests/FakeImplementations/FakeComponent.swift
1
2078
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation @testable import JacquardSDK struct FakeGearComponent: Component { var componentID: ComponentID var vendor: GearMetadata.GearData.Vendor var product: GearMetadata.GearData.Product var isAttached: Bool var version: Version? var uuid: String? } struct FakeTagComponent: Component { var componentID: ComponentID var vendor: GearMetadata.GearData.Vendor var product: GearMetadata.GearData.Product var isAttached: Bool var version: Version? var uuid: String? } class FakeComponentHelper { private static func fetchGearMetadata() -> GearMetadata.GearData { let url = GearCapabilities.jsonURL! let data = try! Data(contentsOf: url) let gearData = try! GearMetadata.GearData(jsonUTF8Data: data) return gearData } static func gearData(vendorID: String, productID: String) -> ( vendor: GearMetadata.GearData.Vendor, product: GearMetadata.GearData.Product ) { let gearMetadata = fetchGearMetadata() let vendorData = gearMetadata.vendors.filter({ $0.id == vendorID }).first! let productData = vendorData.products.filter({ $0.id == productID }).first! return (vendorData, productData) } static func capabilities(vendorID: String, productID: String) -> [GearMetadata.Capability] { let gearMetadata = fetchGearMetadata() let capabilityIDs = gearMetadata.vendors.filter({ $0.id == vendorID }).first! .products.filter({ $0.id == productID }).first! .capabilities return capabilityIDs } }
apache-2.0
34030d6b506a94000b03fb9f55bca3ba
32.516129
94
0.737729
3.988484
false
false
false
false
cplaverty/KeitaiWaniKani
AlliCrab/View/ProgressBarView.swift
1
1964
// // ProgressBarView.swift // AlliCrab // // Copyright © 2019 Chris Laverty. All rights reserved. // import UIKit @IBDesignable class ProgressBarView: UIView, XibLoadable { private static let percentFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .percent formatter.roundingMode = .down formatter.roundingIncrement = 0.01 return formatter }() // MARK: - Properties @IBInspectable var title: String? { get { return titleLabel.text } set { titleLabel.text = newValue } } @IBInspectable var progress: Float { get { return progressView.progress } set { progressView.setProgress(newValue, animated: false) let formattedFractionComplete = type(of: self).percentFormatter.string(from: newValue as NSNumber) percentCompleteLabel.text = formattedFractionComplete } } @IBInspectable var totalCount: Int = 0 { didSet { totalItemCountLabel.text = NumberFormatter.localizedString(from: totalCount as NSNumber, number: .decimal) } } // MARK: - Outlets var contentView : UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var percentCompleteLabel: UILabel! @IBOutlet weak var totalItemCountLabel: UILabel! @IBOutlet weak var progressView: UIProgressView! // MARK: - Initialisers override init(frame: CGRect) { super.init(frame: frame) contentView = setupContentViewFromXib() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) contentView = setupContentViewFromXib() } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() contentView.prepareForInterfaceBuilder() } }
mit
baae41d53cf9502bf62878165ae3639f
25.173333
118
0.623535
5.363388
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/SpeechToTextV1/SpeechToTextSession.swift
2
12804
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import AVFoundation /** The IBM Watson Speech to Text service enables you to add speech transcription capabilities to your application. It uses machine intelligence to combine information about grammar and language structure to generate an accurate transcription. Transcriptions are supported for various audio formats and languages. This class enables fine-tuned control of a WebSockets session with the Speech to Text service. Although it is a more complex interface than the `SpeechToText` class, it provides more control and customizability of the session. */ public class SpeechToTextSession { /// The base URL of the Speech to Text service. public var serviceURL = "https://stream.watsonplatform.net/speech-to-text/api" /// The URL that shall be used to obtain a token. public var tokenURL = "https://stream.watsonplatform.net/authorization/api/v1/token" /// The URL that shall be used to stream audio for transcription. public var websocketsURL = "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize" /// The default HTTP headers for all requests to the service. public var defaultHeaders = [String: String]() /// The results of the most recent recognition request. public var results: SpeechRecognitionResults { get { return socket.results } } /// Invoked when the session connects to the Speech to Text service. public var onConnect: ((Void) -> Void)? { get { return socket.onConnect } set { socket.onConnect = newValue } } /// Invoked with microphone audio when a recording audio queue buffer has been filled. /// If microphone audio is being compressed, then the audio data is in Opus format. /// If uncompressed, then the audio data is in 16-bit mono PCM format at 16 kHZ. public var onMicrophoneData: ((Data) -> Void)? /// Invoked every 0.025s when recording with the average dB power of the microphone. public var onPowerData: ((Float32) -> Void)? { get { return recorder.onPowerData } set { recorder.onPowerData = newValue } } /// Invoked when transcription results are received for a recognition request. public var onResults: ((SpeechRecognitionResults) -> Void)? { get { return socket.onResults } set { socket.onResults = newValue } } /// Invoked when an error or warning occurs. public var onError: ((Error) -> Void)? { get { return socket.onError } set { socket.onError = newValue } } /// Invoked when the session disconnects from the Speech to Text service. public var onDisconnect: ((Void) -> Void)? private lazy var socket: SpeechToTextSocket = { var socket = SpeechToTextSocket( username: self.username, password: self.password, model: self.model, customizationID: self.customizationID, learningOptOut: self.learningOptOut, serviceURL: self.serviceURL, tokenURL: self.tokenURL, websocketsURL: self.websocketsURL, defaultHeaders: self.defaultHeaders ) socket.onDisconnect = { if self.recorder.isRecording { self.stopMicrophone() } self.onDisconnect?() } return socket }() private var recorder: SpeechToTextRecorder private var encoder: SpeechToTextEncoder private var compress: Bool = true private let domain = "com.ibm.watson.developer-cloud.SpeechToTextV1" private let username: String private let password: String private let model: String? private let customizationID: String? private let learningOptOut: Bool? /** Create a `SpeechToTextSession` object. - parameter username: The username used to authenticate with the service. - parameter password: The password used to authenticate with the service. - parameter model: The language and sample rate of the audio. For supported models, visit https://www.ibm.com/watson/developercloud/doc/speech-to-text/input.shtml#models. - parameter customizationID: The GUID of a custom language model that is to be used with the request. The base language model of the specified custom language model must match the model specified with the `model` parameter. By default, no custom model is used. - parameter learningOptOut: If `true`, then this request will not be logged for training. */ public init(username: String, password: String, model: String? = nil, customizationID: String? = nil, learningOptOut: Bool? = nil) { self.username = username self.password = password self.model = model self.customizationID = customizationID self.learningOptOut = learningOptOut recorder = SpeechToTextRecorder() encoder = try! SpeechToTextEncoder( format: recorder.format, opusRate: Int32(recorder.format.mSampleRate), application: .voip ) } /** Connect to the Speech to Text service. If set, the `onConnect()` callback will be invoked after the session connects to the service. */ public func connect() { socket.connect() } /** Start a recognition request. - parameter settings: The configuration to use for this recognition request. */ public func startRequest(settings: RecognitionSettings) { socket.writeStart(settings: settings) } /** Send an audio file to transcribe. - parameter audio: The audio file to transcribe. */ public func recognize(audio: URL) { do { let data = try Data(contentsOf: audio) recognize(audio: data) } catch { let failureReason = "Could not load audio data from \(audio)." let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: domain, code: 0, userInfo: userInfo) onError?(error) return } } /** Send audio data to transcribe. - parameter audio: The audio data to transcribe. */ public func recognize(audio: Data) { socket.writeAudio(audio: audio) } /** Start streaming microphone audio data to transcribe. Knowing when to stop the microphone depends upon the recognition request's continuous setting: - If `false`, then the service ends the recognition request at the first end-of-speech incident (denoted by a half-second of non-speech or when the stream terminates). This will coincide with a `final` transcription result. So the `success` callback should be configured to stop the microphone when a final transcription result is received. - If `true`, then you will typically stop the microphone based on user-feedback. For example, your application may have a button to start/stop the request, or you may stream the microphone for the duration of a long press on a UI element. By default, microphone audio data is compressed to Opus format to reduce latency and bandwidth. To disable Opus compression and send linear PCM data instead, set `compress` to `false`. If compression is enabled, the recognitions request's `contentType` setting should be set to `AudioMediaType.Opus`. If compression is disabled, then the `contentType` settings should be set to `AudioMediaType.L16(rate: 16000, channels: 1)`. This function may cause the system to automatically prompt the user for permission to access the microphone. Use `AVAudioSession.requestRecordPermission(_:)` if you would rather prefer to ask for the user's permission in advance. - parameter compress: Should microphone audio be compressed to Opus format? (Opus compression reduces latency and bandwidth.) */ public func startMicrophone(compress: Bool = true) { self.compress = compress // reset encoder encoder = try! SpeechToTextEncoder( format: recorder.format, opusRate: Int32(recorder.format.mSampleRate), application: .voip ) // request recording permission recorder.session.requestRecordPermission { granted in guard granted else { let failureReason = "Permission was not granted to access the microphone." let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: self.domain, code: 0, userInfo: userInfo) self.onError?(error) return } // callback if uncompressed let onMicrophoneDataPCM = { (pcm: Data) in guard pcm.count > 0 else { return } self.socket.writeAudio(audio: pcm) self.onMicrophoneData?(pcm) } // callback if compressed let onMicrophoneDataOpus = { (pcm: Data) in guard pcm.count > 0 else { return } try! self.encoder.encode(pcm: pcm) let opus = self.encoder.bitstream(flush: true) guard opus.count > 0 else { return } self.socket.writeAudio(audio: opus) self.onMicrophoneData?(opus) } // set callback if compress { self.recorder.onMicrophoneData = onMicrophoneDataOpus } else { self.recorder.onMicrophoneData = onMicrophoneDataPCM } // start recording do { try self.recorder.startRecording() } catch { let failureReason = "Failed to start recording." let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: self.domain, code: 0, userInfo: userInfo) self.onError?(error) return } } } /** Stop streaming microphone audio data to transcribe. */ public func stopMicrophone() { do { try recorder.stopRecording() } catch { let failureReason = "Failed to stop recording." let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: self.domain, code: 0, userInfo: userInfo) self.onError?(error) return } if compress { let opus = try! encoder.endstream() guard opus.count > 0 else { return } self.socket.writeAudio(audio: opus) } } /** Stop the recognition request. */ public func stopRequest() { socket.writeStop() } /** Send a message to prevent the service from automatically disconnecting due to inactivity. As described in the service documentation, the Speech to Text service terminates the session and closes the connection if the inactivity or session timeout is reached. The inactivity timeout occurs if audio is being sent by the client but the service detects no speech. The inactivity timeout is 30 seconds by default, but can be configured by specifying a value for the `inactivityTimeout` setting. The session timeout occurs if the service receives no data from the client or sends no interim results for 30 seconds. You cannot change the length of this timeout; however, you can extend the session by sending a message. This function sends a `no-op` message to touch the session and reset the session timeout in order to keep the connection alive. */ public func keepAlive() { socket.writeNop() } /** Wait for any queued recognition requests to complete then disconnect from the service. */ public func disconnect() { socket.waitForResults() socket.disconnect() } }
mit
3642dbf7bf4357c6e04fed127d851473
38.763975
136
0.644642
5.056872
false
false
false
false
varkor/firefox-ios
Client/Frontend/Browser/Tab.swift
1
17924
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import Storage import Shared import XCGLogger private let log = Logger.browserLogger protocol TabHelper { static func name() -> String func scriptMessageHandlerName() -> String? func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) } @objc protocol TabDelegate { func tab(tab: Tab, didAddSnackbar bar: SnackBar) func tab(tab: Tab, didRemoveSnackbar bar: SnackBar) func tab(tab: Tab, didSelectFindInPageForSelection selection: String) optional func tab(tab: Tab, didCreateWebView webView: WKWebView) optional func tab(tab: Tab, willDeleteWebView webView: WKWebView) } struct TabState { var isPrivate: Bool = false var desktopSite: Bool = false var isBookmarked: Bool = false var url: NSURL? var title: String? var favicon: Favicon? } class Tab: NSObject { private var _isPrivate: Bool = false internal private(set) var isPrivate: Bool { get { if #available(iOS 9, *) { return _isPrivate } else { return false } } set { if _isPrivate != newValue { _isPrivate = newValue self.updateAppState() } } } var tabState: TabState { return TabState(isPrivate: _isPrivate, desktopSite: desktopSite, isBookmarked: isBookmarked, url: url, title: displayTitle, favicon: displayFavicon) } var webView: WKWebView? = nil var tabDelegate: TabDelegate? = nil weak var appStateDelegate: AppStateDelegate? var bars = [SnackBar]() var favicons = [Favicon]() var lastExecutedTime: Timestamp? var sessionData: SessionData? private var lastRequest: NSURLRequest? = nil var pendingScreenshot = false var url: NSURL? /// The last title shown by this tab. Used by the tab tray to show titles for zombie tabs. var lastTitle: String? /// Whether or not the desktop site was requested with the last request, reload or navigation. Note that this property needs to /// be managed by the web view's navigation delegate. var desktopSite: Bool = false { didSet { if oldValue != desktopSite { self.updateAppState() } } } var isBookmarked: Bool = false { didSet { if oldValue != isBookmarked { self.updateAppState() } } } private(set) var screenshot: UIImage? var screenshotUUID: NSUUID? // If this tab has been opened from another, its parent will point to the tab from which it was opened var parent: Tab? = nil private var helperManager: HelperManager? = nil private var configuration: WKWebViewConfiguration? = nil /// Any time a tab tries to make requests to display a Javascript Alert and we are not the active /// tab instance, queue it for later until we become foregrounded. private var alertQueue = [JSAlertInfo]() init(configuration: WKWebViewConfiguration) { self.configuration = configuration } @available(iOS 9, *) init(configuration: WKWebViewConfiguration, isPrivate: Bool) { self.configuration = configuration super.init() self.isPrivate = isPrivate } class func toTab(tab: Tab) -> RemoteTab? { if let displayURL = tab.displayURL where RemoteTab.shouldIncludeURL(displayURL) { let history = Array(tab.historyList.filter(RemoteTab.shouldIncludeURL).reverse()) return RemoteTab(clientGUID: nil, URL: displayURL, title: tab.displayTitle, history: history, lastUsed: NSDate.now(), icon: nil) } else if let sessionData = tab.sessionData where !sessionData.urls.isEmpty { let history = Array(sessionData.urls.filter(RemoteTab.shouldIncludeURL).reverse()) if let displayURL = history.first { return RemoteTab(clientGUID: nil, URL: displayURL, title: tab.displayTitle, history: history, lastUsed: sessionData.lastUsedTime, icon: nil) } } return nil } private func updateAppState() { let state = mainStore.updateState(.Tab(tabState: self.tabState)) self.appStateDelegate?.appDidUpdateState(state) } weak var navigationDelegate: WKNavigationDelegate? { didSet { if let webView = webView { webView.navigationDelegate = navigationDelegate } } } func createWebview() { if webView == nil { assert(configuration != nil, "Create webview can only be called once") configuration!.userContentController = WKUserContentController() configuration!.preferences = WKPreferences() configuration!.preferences.javaScriptCanOpenWindowsAutomatically = false let webView = TabWebView(frame: CGRectZero, configuration: configuration!) webView.delegate = self configuration = nil webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.allowsBackForwardNavigationGestures = true webView.backgroundColor = UIColor.lightGrayColor() // Turning off masking allows the web content to flow outside of the scrollView's frame // which allows the content appear beneath the toolbars in the BrowserViewController webView.scrollView.layer.masksToBounds = false webView.navigationDelegate = navigationDelegate helperManager = HelperManager(webView: webView) restore(webView) self.webView = webView self.webView?.addObserver(self, forKeyPath: "URL", options: .New, context: nil) tabDelegate?.tab?(self, didCreateWebView: webView) } } func restore(webView: WKWebView) { if let sessionData = self.sessionData { // If the tab has session data, load the last selected URL. // We don't try to restore full session history due to bug 1238006. let updatedURLs = sessionData.urls.flatMap { WebServer.sharedInstance.updateLocalURL($0) } // currentPage is a number from -N+1 to 0, where N is the number of URLs. // In other words, currentPage represents the offset from the last page // in session history to the page that was selected. var selectedIndex = updatedURLs.count + sessionData.currentPage - 1 self.sessionData = nil guard !updatedURLs.isEmpty else { log.warning("Restore data has no tabs!") return } if !(0..<updatedURLs.count ~= selectedIndex) { assertionFailure("Restore index outside of page count") selectedIndex = updatedURLs.count - 1 } webView.loadRequest(PrivilegedRequest(URL: updatedURLs[selectedIndex])) } else if let request = lastRequest { // We're unzombifying a tab opened in the background, so load the pending request. webView.loadRequest(request) } else { log.error("creating webview with no lastRequest and no session data: \(self.url)") } } deinit { if let webView = webView { tabDelegate?.tab?(self, willDeleteWebView: webView) webView.removeObserver(self, forKeyPath: "URL") } } var loading: Bool { return webView?.loading ?? false } var estimatedProgress: Double { return webView?.estimatedProgress ?? 0 } var backList: [WKBackForwardListItem]? { return webView?.backForwardList.backList } var forwardList: [WKBackForwardListItem]? { return webView?.backForwardList.forwardList } var historyList: [NSURL] { func listToUrl(item: WKBackForwardListItem) -> NSURL { return item.URL } var tabs = self.backList?.map(listToUrl) ?? [NSURL]() tabs.append(self.url!) return tabs } var title: String? { return webView?.title } var displayTitle: String { if let title = webView?.title { if !title.isEmpty { return title } } guard let lastTitle = lastTitle where !lastTitle.isEmpty else { return displayURL?.absoluteString ?? "" } return lastTitle } var currentInitialURL: NSURL? { get { let initalURL = self.webView?.backForwardList.currentItem?.initialURL return initalURL } } var displayFavicon: Favicon? { var width = 0 var largest: Favicon? for icon in favicons { if icon.width > width { width = icon.width! largest = icon } } return largest } var displayURL: NSURL? { if let url = url { if ReaderModeUtils.isReaderModeURL(url) { return ReaderModeUtils.decodeURL(url) } if ErrorPageHelper.isErrorPageURL(url) { let decodedURL = ErrorPageHelper.originalURLFromQuery(url) if !AboutUtils.isAboutURL(decodedURL) { return decodedURL } else { return nil } } if let urlComponents = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) where (urlComponents.user != nil) || (urlComponents.password != nil) { urlComponents.user = nil urlComponents.password = nil return urlComponents.URL } if !AboutUtils.isAboutURL(url) { return url } } return nil } var canGoBack: Bool { return webView?.canGoBack ?? false } var canGoForward: Bool { return webView?.canGoForward ?? false } func goBack() { webView?.goBack() } func goForward() { webView?.goForward() } func goToBackForwardListItem(item: WKBackForwardListItem) { webView?.goToBackForwardListItem(item) } func loadRequest(request: NSURLRequest) -> WKNavigation? { if let webView = webView { lastRequest = request return webView.loadRequest(request) } return nil } func stop() { webView?.stopLoading() } func reload() { if #available(iOS 9.0, *) { let userAgent: String? = desktopSite ? UserAgent.desktopUserAgent() : nil if (userAgent ?? "") != webView?.customUserAgent, let currentItem = webView?.backForwardList.currentItem { webView?.customUserAgent = userAgent // Reload the initial URL to avoid UA specific redirection loadRequest(PrivilegedRequest(URL: currentItem.initialURL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 60)) return } } if let _ = webView?.reloadFromOrigin() { log.info("reloaded zombified tab from origin") return } if let webView = self.webView { log.info("restoring webView from scratch") restore(webView) } } func addHelper(helper: TabHelper, name: String) { helperManager!.addHelper(helper, name: name) } func getHelper(name name: String) -> TabHelper? { return helperManager?.getHelper(name: name) } func hideContent(animated: Bool = false) { webView?.userInteractionEnabled = false if animated { UIView.animateWithDuration(0.25, animations: { () -> Void in self.webView?.alpha = 0.0 }) } else { webView?.alpha = 0.0 } } func showContent(animated: Bool = false) { webView?.userInteractionEnabled = true if animated { UIView.animateWithDuration(0.25, animations: { () -> Void in self.webView?.alpha = 1.0 }) } else { webView?.alpha = 1.0 } } func addSnackbar(bar: SnackBar) { bars.append(bar) tabDelegate?.tab(self, didAddSnackbar: bar) } func removeSnackbar(bar: SnackBar) { if let index = bars.indexOf(bar) { bars.removeAtIndex(index) tabDelegate?.tab(self, didRemoveSnackbar: bar) } } func removeAllSnackbars() { // Enumerate backwards here because we'll remove items from the list as we go. for i in (0..<bars.count).reverse() { let bar = bars[i] removeSnackbar(bar) } } func expireSnackbars() { // Enumerate backwards here because we may remove items from the list as we go. for i in (0..<bars.count).reverse() { let bar = bars[i] if !bar.shouldPersist(self) { removeSnackbar(bar) } } } func setScreenshot(screenshot: UIImage?, revUUID: Bool = true) { self.screenshot = screenshot if revUUID { self.screenshotUUID = NSUUID() } } @available(iOS 9, *) func toggleDesktopSite() { desktopSite = !desktopSite reload() } func queueJavascriptAlertPrompt(alert: JSAlertInfo) { alertQueue.append(alert) } func dequeueJavascriptAlertPrompt() -> JSAlertInfo? { guard !alertQueue.isEmpty else { return nil } return alertQueue.removeFirst() } func cancelQueuedAlerts() { alertQueue.forEach { alert in alert.cancel() } } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String: AnyObject]?, context: UnsafeMutablePointer<Void>) { guard let webView = object as? WKWebView where webView == self.webView, let path = keyPath where path == "URL" else { return assertionFailure("Unhandled KVO key: \(keyPath)") } updateAppState() } func isDescendentOf(ancestor: Tab) -> Bool { var tab = parent while tab != nil { if tab! == ancestor { return true } tab = tab?.parent } return false } func setNoImageMode(enabled: Bool = false, force: Bool) { if enabled || force { webView?.evaluateJavaScript("window.__firefox__.NoImageMode.setEnabled(\(enabled))", completionHandler: nil) } } func setNightMode(enabled: Bool) { webView?.evaluateJavaScript("window.__firefox__.NightMode.setEnabled(\(enabled))", completionHandler: nil) } } extension Tab: TabWebViewDelegate { private func tabWebView(tabWebView: TabWebView, didSelectFindInPageForSelection selection: String) { tabDelegate?.tab(self, didSelectFindInPageForSelection: selection) } } private class HelperManager: NSObject, WKScriptMessageHandler { private var helpers = [String: TabHelper]() private weak var webView: WKWebView? init(webView: WKWebView) { self.webView = webView } @objc func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { for helper in helpers.values { if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { if scriptMessageHandlerName == message.name { helper.userContentController(userContentController, didReceiveScriptMessage: message) return } } } } func addHelper(helper: TabHelper, name: String) { if let _ = helpers[name] { assertionFailure("Duplicate helper added: \(name)") } helpers[name] = helper // If this helper handles script messages, then get the handler name and register it. The Browser // receives all messages and then dispatches them to the right TabHelper. if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { webView?.configuration.userContentController.addScriptMessageHandler(self, name: scriptMessageHandlerName) } } func getHelper(name name: String) -> TabHelper? { return helpers[name] } } private protocol TabWebViewDelegate: class { func tabWebView(tabWebView: TabWebView, didSelectFindInPageForSelection selection: String) } private class TabWebView: WKWebView, MenuHelperInterface { private weak var delegate: TabWebViewDelegate? override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { return action == MenuHelper.SelectorFindInPage } @objc func menuHelperFindInPage(sender: NSNotification) { evaluateJavaScript("getSelection().toString()") { result, _ in let selection = result as? String ?? "" self.delegate?.tabWebView(self, didSelectFindInPageForSelection: selection) } } private override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { // The find-in-page selection menu only appears if the webview is the first responder. becomeFirstResponder() return super.hitTest(point, withEvent: event) } }
mpl-2.0
d174c7323dee666a8aaae796efd1cccb
31.471014
163
0.608179
5.344067
false
false
false
false
khizkhiz/swift
test/expr/cast/set_bridge.swift
1
3407
// RUN: %target-parse-verify-swift // REQUIRES: objc_interop class Root : Hashable { var hashValue: Int { return 0 } } func ==(x: Root, y: Root) -> Bool { return true } class ObjC : Root { var x = 0 } class DerivesObjC : ObjC { } struct BridgedToObjC : Hashable, _ObjectiveCBridgeable { static func _isBridgedToObjectiveC() -> Bool { return true } static func _getObjectiveCType() -> Any.Type { return ObjC.self } func _bridgeToObjectiveC() -> ObjC { return ObjC() } static func _forceBridgeFromObjectiveC( x: ObjC, result: inout BridgedToObjC? ) { } static func _conditionallyBridgeFromObjectiveC( x: ObjC, result: inout BridgedToObjC? ) -> Bool { return true } var hashValue: Int { return 0 } } func ==(x: BridgedToObjC, y: BridgedToObjC) -> Bool { return true } func testUpcastBridge() { var setR = Set<Root>() var setO = Set<ObjC>() var setD = Set<DerivesObjC>() var setB = Set<BridgedToObjC>() // Upcast to object types. setR = setB; _ = setR setO = setB; _ = setO // Upcast object to bridged type setB = setO // expected-error{{cannot assign value of type 'Set<ObjC>' to type 'Set<BridgedToObjC>'}} // Failed upcast setD = setB // expected-error{{cannot assign value of type 'Set<BridgedToObjC>' to type 'Set<DerivesObjC>'}} _ = setD } func testForcedDowncastBridge() { let setR = Set<Root>() let setO = Set<ObjC>() let setD = Set<DerivesObjC>() let setB = Set<BridgedToObjC>() setR as! Set<BridgedToObjC> setO as! Set<BridgedToObjC> setD as! Set<BridgedToObjC> // expected-error {{'ObjC' is not a subtype of 'DerivesObjC'}} // expected-note @-1 {{in cast from type 'Set<DerivesObjC>' to 'Set<BridgedToObjC>'}} // TODO: the diagnostic for the below two examples should indicate that 'as' // should be used instead of 'as!' setB as! Set<Root> // expected-error {{'Root' is not a subtype of 'BridgedToObjC'}} // expected-note @-1 {{in cast from type 'Set<BridgedToObjC>' to 'Set<Root>'}} setB as! Set<ObjC> // expected-error {{'ObjC' is not a subtype of 'BridgedToObjC'}} // expected-note @-1 {{in cast from type 'Set<BridgedToObjC>' to 'Set<ObjC>'}} setB as! Set<DerivesObjC> // expected-error {{'DerivesObjC' is not a subtype of 'BridgedToObjC'}} // expected-note @-1 {{in cast from type 'Set<BridgedToObjC>' to 'Set<DerivesObjC>'}} } func testConditionalDowncastBridge() { var setR = Set<Root>() var setO = Set<ObjC>() var setD = Set<DerivesObjC>() var setB = Set<BridgedToObjC>() if let s = setR as? Set<BridgedToObjC> { } if let s = setO as? Set<BridgedToObjC> { } if let s = setD as? Set<BridgedToObjC> { } // expected-error {{'ObjC' is not a subtype of 'DerivesObjC'}} // expected-note @-1 {{in cast from type 'Set<DerivesObjC>' to 'Set<BridgedToObjC>'}} if let s = setB as? Set<Root> { } // expected-error {{'Root' is not a subtype of 'BridgedToObjC'}} // expected-note @-1 {{in cast from type 'Set<BridgedToObjC>' to 'Set<Root>'}} if let s = setB as? Set<ObjC> { } // expected-error {{'ObjC' is not a subtype of 'BridgedToObjC'}} // expected-note @-1 {{in cast from type 'Set<BridgedToObjC>' to 'Set<ObjC>'}} if let s = setB as? Set<DerivesObjC> { } // expected-error {{'DerivesObjC' is not a subtype of 'BridgedToObjC'}} // expected-note @-1 {{in cast from type 'Set<BridgedToObjC>' to 'Set<DerivesObjC>'}} }
apache-2.0
a5ed043c208a6096701f7aa92286babe
30.256881
114
0.655415
3.519628
false
false
false
false
tkremenek/swift
test/AutoDiff/compiler_crashers_fixed/sr12548-siloptimizer-rewrite-partial-apply-convention-method.swift
11
1028
// RUN: %target-build-swift -O %s // SR-12548: SIL verification error regarding // `CapturePropagation::rewritePartialApply` for `partial_apply` with // `@convention(method)` callee. import _Differentiation protocol Protocol: Differentiable { @differentiable(reverse) func method() -> Self } extension Protocol { @differentiable(reverse) func method() -> Self { self } } struct Struct: Protocol {} let _: @differentiable(reverse) (Struct) -> Struct = { $0.method() } // SIL verification failed: operand of thin_to_thick_function must be thin: opFTy->getRepresentation() == SILFunctionType::Representation::Thin // Verifying instruction: // // function_ref specialized Protocol.method() // %5 = function_ref @$s7crasher8ProtocolPAAE6methodxyFAA6StructV_TG5 : $@convention(method) (@in_guaranteed Struct) -> @out Struct // user: %6 // -> %6 = thin_to_thick_function %5 : $@convention(method) (@in_guaranteed Struct) -> @out Struct to $@callee_guaranteed (@in_guaranteed Struct) -> @out Struct // user: %11
apache-2.0
af1eb3fc9cde9fdf082c999d90d3132d
37.074074
175
0.710117
3.711191
false
false
false
false
AlanAherne/BabyTunes
BabyTunes/BabyTunes/Modules/Main/Home/Interaction controllers/SwipeInteractionController.swift
1
3200
///// 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 class SwipeInteractionController: UIPercentDrivenInteractiveTransition { var interactionInProgress = false private var shouldCompleteTransition = false private weak var viewController: UIViewController! init(viewController: UIViewController) { super.init() self.viewController = viewController prepareGestureRecognizer(in: viewController.view) } private func prepareGestureRecognizer(in view: UIView) { let gesture = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handleGesture(_:))) gesture.edges = .left view.addGestureRecognizer(gesture) } @objc func handleGesture(_ gestureRecognizer: UIScreenEdgePanGestureRecognizer) { // 1 let translation = gestureRecognizer.translation(in: gestureRecognizer.view!.superview!) var progress = (translation.x / 200) progress = CGFloat(fminf(fmaxf(Float(progress), 0.0), 1.0)) switch gestureRecognizer.state { // 2 case .began: interactionInProgress = true viewController.dismiss(animated: true, completion: nil) // 3 case .changed: shouldCompleteTransition = progress > 0.5 update(progress) // 4 case .cancelled: interactionInProgress = false cancel() // 5 case .ended: interactionInProgress = false if shouldCompleteTransition { finish() } else { cancel() } default: break } } }
mit
b6e0b5e8375eeea73172b0ee6994c602
36.209302
91
0.70625
5.111821
false
false
false
false
joehour/ScratchCard
Example/Example/ViewController.swift
1
2340
// // ViewController.swift // Example // // Created by JoeJoe on 2016/12/13. // Copyright © 2016年 Joe. All rights reserved. // import UIKit import ScratchCard class ViewController: UIViewController, ScratchUIViewDelegate { var scratchCard: ScratchUIView! @IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. scratchCard = ScratchUIView(frame: CGRect(x:50, y:80, width:320, height:480), Coupon: "image.jpg", MaskImage: "mask.png", ScratchWidth: CGFloat(40)) scratchCard.delegate = self self.view.addSubview(scratchCard) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func getScratchPercent(_ sender: Any) { let scratchPercent: Double = scratchCard.getScratchPercent() textField.text = String(format: "%.2f", scratchPercent * 100) + "%" } //Scratch Began Event(optional) func scratchBegan(_ view: ScratchUIView) { print("scratchBegan") ////Get the Scratch Position in ScratchCard(coordinate origin is at the lower left corner) let position = Int(view.scratchPosition.x).description + "," + Int(view.scratchPosition.y).description print(position) } //Scratch Moved Event(optional) func scratchMoved(_ view: ScratchUIView) { let scratchPercent: Double = self.scratchCard.getScratchPercent() self.textField.text = String(format: "%.2f", scratchPercent * 100) + "%" print("scratchMoved") ////Get the Scratch Position in ScratchCard(coordinate origin is at the lower left corner) let position = Int(view.scratchPosition.x).description + "," + Int(view.scratchPosition.y).description print(position) } //Scratch Ended Event(optional) func scratchEnded(_ view: ScratchUIView) { print("scratchEnded") ////Get the Scratch Position in ScratchCard(coordinate origin is at the lower left corner) let position = Int(view.scratchPosition.x).description + "," + Int(view.scratchPosition.y).description print(position) } }
mit
dfd7ca8b6dff281100c0bf586c24c6ac
34.409091
156
0.65982
4.368224
false
false
false
false
naokits/my-programming-marathon
BondYTPlayerDemo/RACPlayground/ViewController.swift
1
10044
// // ViewController.swift // RACPlayground // // Created by Naoki Tsutsui on 8/2/16. // Copyright © 2016 Naoki Tsutsui. All rights reserved. // import UIKit import Bond import youtube_ios_player_helper import ObjectiveC class ViewController: UIViewController, UIWebViewDelegate { let viewModel = ViewModel() // MARK: - YouTubeDataApi_iOS myKey // let YouTubeApiKey = "AIzaSyCBGyBYhnXtLV1A6VPEvrbOw8Vg9_NyYiQ" // MARK: - ディスプレイサイズ取得 let displayWidth = UIScreen.mainScreen().bounds.size.width let displayHeight = UIScreen.mainScreen().bounds.size.height // MARK: - Properties @IBOutlet weak var playerView: YTPlayerView! @IBOutlet weak var TitleLabel: UILabel! @IBOutlet weak var PlayerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var playtimeSlider: UISlider! @IBOutlet weak var nextButton: UIButton! @IBOutlet weak var previousButton: UIButton! @IBOutlet weak var shuffleButton: UIButton! @IBOutlet weak var repeatButton: UIButton! // var shuffledVideoList: [String]? // var videoList = ["YvzB97ge80g"] var PlayerWidth: String! // Playerの幅 var PlayerHeight: String! // Playerの高さ // 自動的にunsubscribeする場合に使用する let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.playerView.delegate = self self.loadCurrentVideo() } override func viewDidAppear(animated: Bool) { self.setup() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Misc func loadVideo(moveID: String) { self.playerView.loadWithVideoId(moveID, playerVars: [ "playsinline":0, "rel": 0, "controls": 1, "showinfo": 0, "autoplay": 0, "autohide": 1, "modestbranding": 1, "origin": "https://www.youtube.com/" ]) } // MARK: - Setup func setup() { self.setupUI() self.setupObserver() self.setupBind() } func setupBind() { self.viewModel.playerState.map { (state) -> String in var str = "" switch state { case .Unstarted: // str = "停止中" str = "▶️" self.playButton.enabled = true case .Ended: // str = "再生終了" str = "▶️" if self.viewModel.repeatButtonState.value == RepeatStateType.One { self.loadCurrentVideo() // self.playerView.stopVideo() // self.playerView.playVideo() } else { if self.viewModel.repeatButtonState.value == RepeatStateType.All { self.viewModel.nextVideoIndex() } } case .Playing: self.playButton.enabled = true self.playButton.tintColor = UIColor.redColor() // return "再生中" return "⏸" case .Paused: // str = "一時停止中" str = "▶️" // if self.isBackgroundPlay { // log.debug("バックグラウンドで再生する") // playerView.playVideo() // self.isBackgroundPlay = false // } case .Buffering: self.playButton.enabled = false // str = "読込中" str = "🔄" case .Queued: str = "キュー" default: str = "デフォルト" } return str }.bindTo(self.playButton.bnd_title) self.viewModel.shuffleButtonState.map { (state) -> String in if self.viewModel.isShuffle() { self.viewModel.shufflePlaylist() return "🔀" } else { return String("S:\(state)") } }.bindTo(self.shuffleButton.bnd_title) self.viewModel.repeatButtonState.map({ (state) -> String in print(state) if state == RepeatStateType.One { return "🔂" } else if state == RepeatStateType.All { return "🔁" } else { return String("R:\(state)") } }).bindTo(self.repeatButton.bnd_title) } func setupObserver() { self.playButton.bnd_tap.observe { _ in print("再生ボタンがタップされた: \(self.viewModel.playerState.value.rawValue)") if self.viewModel.isPlayingVideo() { self.playerView.pauseVideo() } else if self.viewModel.isEndedVideo() { self.loadCurrentVideo() self.playerView.playVideo() } else { self.playerView.playVideo() } } self.shuffleButton.bnd_tap.observe { _ in self.viewModel.updateShuffleState() } self.repeatButton.bnd_tap.observe { _ in self.viewModel.updateRepeatState() } self.previousButton.bnd_tap.observe { (_) in self.viewModel.previousVideoIndex() } self.nextButton.bnd_tap.observe { (_) in self.viewModel.nextVideoIndex() } self.viewModel.currentPlayListIndex.observeNew { (index) in log.debug("インデックス: \(index)") log.info("再生中のビデオを停止してから、\(self.viewModel.playlist.value[index]) のビデオをローディング") self.playerView.stopVideo() let videoid = self.viewModel.playlist.value[index] self.loadVideo(videoid) } self.viewModel.playlist.observe { (playlist) in print("プレイリスト: \(playlist)") } } func setupUI() { // self.setupPlayerSize() self.allDisablePlayerButton() } func setupPlayerSize() { // Playerのサイズを計算 let width: Int = Int(displayWidth) self.PlayerWidth = String(width) let Height = displayWidth / 1.77777777777778 let height: Int = Int(Height) self.PlayerHeight = String(height) } // 現在の再生インデックスの動画をロードする func loadCurrentVideo() { let index = self.viewModel.currentPlayListIndex.value let videoid = self.viewModel.playlist.value[index] self.loadVideo(videoid) } private func allDisablePlayerButton() { self.playButton.enabled = false self.previousButton.enabled = false self.nextButton.enabled = false self.shuffleButton.enabled = false self.repeatButton.enabled = false } } // MARK: - YTPlayerViewDelegate /** * A delegate for ViewControllers to respond to YouTube player events outside * of the view, such as changes to video playback state or playback errors. * The callback functions correlate to the events fired by the IFrame API. * For the full documentation, see the IFrame documentation here: * https://developers.google.com/youtube/iframe_api_reference#Events */ extension ViewController: YTPlayerViewDelegate { /** * Invoked when the player view is ready to receive API calls. * * @param playerView The YTPlayerView instance that has become ready. */ func playerViewDidBecomeReady(playerView: YTPlayerView) { log.debug("準備完了") self.playButton.enabled = true if self.viewModel.playlist.value.count > 0 { self.previousButton.enabled = true self.nextButton.enabled = true self.repeatButton.enabled = true self.shuffleButton.enabled = true } self.playerView.playVideo() } /** * Callback invoked when player state has changed, e.g. stopped or started playback. * * @param playerView The YTPlayerView instance where playback state has changed. * @param state YTPlayerState designating the new playback state. */ func playerView(playerView: YTPlayerView, didChangeToState state: YTPlayerState) { log.debug(state.rawValue) self.viewModel.updatePlayState(state) } /** * Callback invoked when an error has occured. * * @param playerView The YTPlayerView instance where the error has occurred. * @param error YTPlayerError containing the error state. */ func playerView(playerView: YTPlayerView, receivedError error: YTPlayerError) { log.error(error.rawValue) } /** * Callback invoked when playback quality has changed. * * @param playerView The YTPlayerView instance where playback quality has changed. * @param quality YTPlaybackQuality designating the new playback quality. */ func playerView(playerView: YTPlayerView, didChangeToQuality quality: YTPlaybackQuality) { // log.debug(quality.rawValue) } /** * Callback invoked frequently when playBack is plaing. * * @param playerView The YTPlayerView instance where the error has occurred. * @param playTime float containing curretn playback time. */ func playerView(playerView: YTPlayerView, didPlayTime playTime: Float) { // let progress = NSTimeInterval(playTime) / self.playerView.duration() // log.debug("再生時間: \(progress)") // self.playtimeSlider.value = Float(progress) } }
mit
e1803b8c412c1ab23d2d694beef7a215
31.262458
94
0.577386
4.619886
false
false
false
false
ustwo/videoplayback-ios
Source/Manager/Utils/VPKTableViewPrefetchSynchronizer.swift
1
3437
// // VPKTableViewPrefetchSynchronizer.swift // DemoVideoPlaybackKit //s// Created by Sonam on 7/5/17. // Copyright © 2017 ustwo. All rights reserved. // import Foundation import UIKit public extension UITableView { func vpk_setPrefetchOptimizer(for videoItems:[VPKVideoType]) { self.prefetchDataSource = VPKTableViewPrefetchSynchronizer(videoItems: videoItems) } } protocol VPKPrefetchVideoDownloader: class { var videoItems: [VPKVideoType] { get set } var tasks: [URLSessionTask] { get set } func downloadVideo(forItemAtIndex index: Int) func cancelDownloadingVideo(forItemAtIndex index: Int) } public class VPKTableViewPrefetchSynchronizer: NSObject, VPKPrefetchVideoDownloader, UITableViewDataSourcePrefetching { var videoItems = [VPKVideoType]() var tasks = [URLSessionTask]() convenience public init(videoItems: [VPKVideoType]) { self.init() self.videoItems = videoItems } //MARK: Prefetch public func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) { let filteredVideoItems = indexPaths.map{ self.videoItems[$0.row] } VPKVideoPlaybackManager.shared.preloadURLsForFeed(with: filteredVideoItems) } public func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) { let filteredVideoItems = indexPaths.map{ self.videoItems[$0.row] } VPKVideoPlaybackManager.shared.cancelPreload(of: filteredVideoItems) } //MARK: Download func downloadVideo(forItemAtIndex index: Int) { //TODO: (SONAM) /* guard let url = videoItems[index].videoUrl else { return } guard tasks.index(where: { $0.originalRequest?.url == url }) == nil else { // We're already downloading the video. return } let resorceDelegate = VPKAssetResourceLoaderDelegate(customLoadingScheme: "VPKPlayback", resourcesDirectory: VPKVideoPlaybackManager.defaultDirectory, defaults: UserDefaults.standard) let asset = resorceDelegate.prefetchAssetData(for: url) //Configure asset, set resource delegate. Let resource delegate handle download. let task = URLSession.shared.dataTask(with: url) { (data, response, error) in //download Video data on a background thread //Perform UI changes only on main thread. DispatchQueue.main.async { update UI If need be // Reload cell with fade animation. let indexPath = IndexPath(row: index, section: 0) if self.tableView.indexPathsForVisibleRows?.contains(indexPath) ?? false { self.tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .fade) } } } } task.resume() tasks.append(task)*/ } func cancelDownloadingVideo(forItemAtIndex index: Int) { //TODO: (SONAM) /*guard let url = videoItems[index].videoUrl else { return } // Find a task with given URL, cancel it and delete from `tasks` array. guard let taskIndex = tasks.index(where: { $0.originalRequest?.url == url }) else { return } let task = tasks[taskIndex] task.cancel() tasks.remove(at: taskIndex)*/ } }
mit
464e600b7a1625423d6f458297e7df54
33.36
192
0.644936
4.70041
false
false
false
false
csnu17/My-Blognone-apps
myblognone/Common/Extensions/MyFontExtension.swift
1
2247
// // MyFontExtension.swift // myblognone // // Created by Kittisak Phetrungnapha on 12/25/2559 BE. // Copyright © 2559 Kittisak Phetrungnapha. All rights reserved. // import Foundation import UIKit extension UIFont { private enum MyFont: String { case SFUIDisplayBold = "SFUIDisplay-Bold" case SFUITextLight = "SFUIText-Light" case SFUITextRegular = "SFUIText-Regular" case SFUIDisplayMedium = "SFUIDisplay-Medium" } private static let defaultFont = UIFont.systemFont(ofSize: 17) static func printAllPossibleFonts() { UIFont.familyNames.sorted().forEach({ UIFont.fontNames(forFamilyName: $0).sorted().forEach({ print($0) }) }) } static func fontForNavigationBarTitle() -> UIFont { return UIFont(name: MyFont.SFUIDisplayMedium.rawValue, size: 21) ?? defaultFont } static func fontForLargeNavigationBarTitle() -> UIFont { return UIFont(name: MyFont.SFUIDisplayMedium.rawValue, size: 32) ?? defaultFont } static func fontForNewsTitle() -> UIFont { return UIFont(name: MyFont.SFUIDisplayBold.rawValue, size: 21) ?? defaultFont } static func fontForNewsCreator() -> UIFont { return UIFont(name: MyFont.SFUITextLight.rawValue, size: 17) ?? defaultFont } static func fontForNewsPubDate() -> UIFont { return UIFont(name: MyFont.SFUITextRegular.rawValue, size: 15) ?? defaultFont } static func fontFotLastUpdateTime() -> UIFont { return UIFont(name: MyFont.SFUITextLight.rawValue, size: 14) ?? defaultFont } static func fontForVersionTitle() -> UIFont { return UIFont(name: MyFont.SFUITextRegular.rawValue, size: 17) ?? defaultFont } static func fontForVersionValue() -> UIFont { return UIFont(name: MyFont.SFUITextRegular.rawValue, size: 17) ?? defaultFont } static func fontForSendEmailFeedback() -> UIFont { return UIFont(name: MyFont.SFUITextRegular.rawValue, size: 17) ?? defaultFont } static func fontForRateApps() -> UIFont { return UIFont(name: MyFont.SFUITextRegular.rawValue, size: 17) ?? defaultFont } }
mit
ddbe6a87f3c8d240a877bcba4d715fe9
31.085714
87
0.654052
4.352713
false
false
false
false
inacioferrarini/OMDBSpy
OMDBSpy/ViewControllers/MovieSearch/MovieSearchTableViewController.swift
1
7224
import UIKit import SDWebImage enum SearchBarStatus { case Normal case Searching } class MovieSearchTableViewController: BaseTableViewController, UITextFieldDelegate { // MARK: - Properties @IBOutlet weak var leftBarButtonItem: UIBarButtonItem! @IBOutlet weak var rightBarButtonItem: UIBarButtonItem! @IBOutlet weak var searchTextField: UITextField! @IBOutlet weak var searchInfoView: UIView! @IBOutlet weak var containerView: UIView! var resultHeader: MovieListTableViewHeader! var status:SearchBarStatus! // MARK: - BaseTableViewController Override Methods override func viewDidLoad() { super.viewDidLoad() self.status = .Normal self.resultHeader = MovieListTableViewHeader() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.registerForKeyboardNotifications() } override func viewWillDisappear(animated: Bool) { self.deregisterFromKeyboardNotifications() super.viewWillDisappear(animated) } override func shouldSyncData() -> Bool { return false } override func createDataSource() -> UITableViewDataSource? { let presenter = TableViewCellPresenter<MovieListTableViewCell, OmdbMovie> ( configureCellBlock: { (cell: MovieListTableViewCell, entity: OmdbMovie) -> Void in if let posterUrl = entity.poster, let url = NSURL(string: posterUrl) { cell.posterImage.sd_setImageWithURL(url) } cell.movieTitle.text = entity.title ?? "" cell.movieDescription.text = entity.plot ?? "" }, cellReuseIdentifier: MovieListTableViewCell.simpleClassName()) let sortDescriptors:[NSSortDescriptor] = [] let context = self.appContext.coreDataStack.managedObjectContext let logger = appContext.logger let dataSource = FetcherDataSource<MovieListTableViewCell, OmdbMovie>( targetingTableView: self.tableView!, presenter: presenter, entityName: OmdbMovie.simpleClassName(), sortDescriptors: sortDescriptors, managedObjectContext: context, logger: logger) dataSource.refreshData() return dataSource } override func createDelegate() -> UITableViewDelegate? { let itemSelectionBlock = { (indexPath:NSIndexPath) -> Void in if let dataSource = self.dataSource as? FetcherDataSource<MovieListTableViewCell, OmdbMovie> { let selectedValue = dataSource.objectAtIndexPath(indexPath) if let title = selectedValue.title { self.searchMovie(title) } } } let delegate = TableViewBlockDelegate(tableView: self.tableView!, itemSelectionBlock: itemSelectionBlock, loadMoreDataBlock: nil) delegate.heightForHeaderInSectionBlock = { (section: Int) -> CGFloat in return 24 } delegate.viewForHeaderInSectionBlock = { (section: Int) -> UIView? in return self.resultHeader } return delegate } // MARK: - Keyboard Notifications func registerForKeyboardNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWasShown:"), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillBeHidden:"), name: UIKeyboardWillHideNotification, object: nil) } func deregisterFromKeyboardNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidHideNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } func keyboardWasShown(notification: NSNotification) { UIView.animateWithDuration(0.3) { () -> Void in self.containerView.frame.origin.y = 35 } } func keyboardWillBeHidden(notification: NSNotification) { UIView.animateWithDuration(0.3) { () -> Void in self.containerView.frame.origin.y = 126 } } // MARK: - Actions @IBAction func leftBarButtonAction(sender: UIBarButtonItem) { if self.status == .Searching { self.status = .Normal; self.updateSearchBarForStatus(self.status) } } @IBAction func rightBarButtonAction(sender: UIBarButtonItem) { if self.status == .Normal { self.status = .Searching } else if self.status == .Searching { self.status = .Normal } self.updateSearchBarForStatus(self.status) } private func updateSearchBarForStatus(status: SearchBarStatus) { switch status { case .Normal: self.leftBarButtonItem.image = UIImage(named: "ic_menu_white") self.rightBarButtonItem.image = UIImage(named: "ic_search_white") self.searchTextField.hidden = true self.searchTextField.resignFirstResponder() case .Searching: self.leftBarButtonItem.image = UIImage(named: "ic_arrow_back_white") self.rightBarButtonItem.image = UIImage(named: "ic_close_white") self.searchTextField.hidden = false self.searchTextField.becomeFirstResponder() } } func textFieldShouldReturn(textField: UITextField) -> Bool { if let movieName = textField.text { self.searchMovies(movieName) } textField.resignFirstResponder() return true } func refreshData(totalResults: Int) { if let dataSource = self.dataSource as? FetcherDataSource<MovieListTableViewCell, OmdbMovie> { dataSource.refreshData() self.tableView!.reloadData() // count results if totalResults > 0 { self.searchInfoView.hidden = true self.resultHeader.sectionTitle.text = "Encontramos \(totalResults) resultados:" } } } func searchMovies(title: String) { OmdbApiClient(appContext: self.appContext).searchMovie(title, atPage: 0, completionBlock: { (totalResults: Int, movies:[OmdbMovie]?) -> Void in self.refreshData(totalResults) }) { (error: NSError) -> Void in self.appContext.logger.logError(error) } } func searchMovie(title: String) { OmdbApiClient(appContext: self.appContext).fetchMovie(title,completionBlock: { (movie:OmdbMovie?) -> Void in if let movie = movie { let imdbId = movie.imdbID ?? "" let route = Routes().showMovieUrl(imdbId) self.appContext.router.navigateInternal(route) } }) { (error: NSError) -> Void in self.appContext.logger.logError(error) } } }
mit
0cb22d231e4e9a73ce68028565e53aff
34.239024
158
0.623893
5.510297
false
false
false
false
weijingyunIOS/JYAutoLayout
JYAutoLayout-Swift/DemoListViewController.swift
1
1855
// // DemoViewController.swift // JYAutoLayout-Swift // // Created by weijingyun on 16/5/5. // Copyright © 2015年 joyios. All rights reserved. // import UIKit struct ExampleInfo { var name: String var cls: AnyClass } class DemoListViewController: UITableViewController { lazy var exampleList: [ExampleInfo] = { return [ ExampleInfo(name: "Alignment Demo 1", cls: AlignDemoView1.self), ExampleInfo(name: "Alignment Demo 2", cls: AlignDemoView2.self), ExampleInfo(name: "Alignment Demo 3", cls: AlignDemoView3.self), ExampleInfo(name: "AnimDemoView Demo 1", cls: AnimDemoView1.self), ExampleInfo(name: "AnimDemoView Demo 2", cls: AnimDemoView2.self), ExampleInfo(name: "HVAlignmentDemoView Demo", cls: HVAlignmentDemoView.self), ExampleInfo(name: "WideHightAlignment Demo", cls: WideHightAlignment.self), ] }() override func viewDidLoad() { super.viewDidLoad() title = "JYAutoLayout Demo" tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return exampleList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = exampleList[(indexPath as NSIndexPath).row].name return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = DemoViewController() vc.exampleInfo = exampleList[(indexPath as NSIndexPath).row] navigationController?.pushViewController(vc, animated: true) } }
apache-2.0
b0989b0e0edcd3290a30ebe5e1c6f2b9
33.296296
109
0.677106
4.506083
false
false
false
false
rshuston/ClosestPointsWorkshop
ClosestPoints/ClosestPoints/DivideAndConquerSolver.swift
1
10878
// // DivideAndConquerSolver.swift // ClosestPoints // // Created by Robert Huston on 12/11/16. // Copyright © 2016 Pinpoint Dynamics. All rights reserved. // import Cocoa class DivideAndConquerSolver: Solver { var maxSimpleRegionSize = 3 struct PointRegion { var lower: Int // Lower index into points array, -1 if not defined var upper: Int // Upper index into points array, -1 if not defined } struct PointPairAndDistance { var pointPair: (Point, Point) var distanceSquared: CGFloat } class SolutionCarryOn { var checkRect: NSRect? var checkPoints: (Point, Point)? var closestPoints: (Point, Point)? var monitor: ((NSRect?, (Point, Point)?, (Point, Point)?) -> Bool)? var keepRunning = true var closestDistanceSquared: CGFloat = CGFloat.greatestFiniteMagnitude func monitorPointRegion(points: [Point], pointRegion: PointRegion) -> Bool { // Note: This is a bit messy, but it's for monitoring so I don't care right now let loPoint = points[pointRegion.lower] let hiPoint = points[pointRegion.upper] checkRect = AppUtils.NSRectFromNSPoints(loPoint.getAsNSPoint(), hiPoint.getAsNSPoint()) checkRect?.origin.y = 0 checkRect?.size.height = 512 // Not exact, but it's big enough and it'll clip anyway // Don't need to set checkPoints because we're doing the region keepRunning = monitor?(checkRect, checkPoints, closestPoints) ?? true return keepRunning } func monitorPointPair(pointPair: (Point, Point), distanceSquared: CGFloat) -> Bool { checkRect = AppUtils.NSRectFromNSPoints(pointPair.0.getAsNSPoint(), pointPair.1.getAsNSPoint()) checkPoints = pointPair if distanceSquared < closestDistanceSquared { closestDistanceSquared = distanceSquared closestPoints = checkPoints } keepRunning = monitor?(checkRect, checkPoints, closestPoints) ?? true return keepRunning } func monitorRectForPoint(point: Point, withAxisDistance: CGFloat) -> Bool { checkRect = NSRect(x: point.x - withAxisDistance, y: point.y - withAxisDistance, width: withAxisDistance, height: 2 * withAxisDistance) checkPoints = nil keepRunning = monitor?(checkRect, checkPoints, closestPoints) ?? true return keepRunning } } override func findClosestPoints(points: [Point], monitor: ((NSRect?, (Point, Point)?, (Point, Point)?) -> Bool)?, completion: (((Point, Point)?) -> Void)?) { var closestPoints: (Point, Point)? let solutionCarryOn = SolutionCarryOn() solutionCarryOn.monitor = monitor if points.count >= 2 { let sortedPoints = points.sorted(by: { (lhs: Point, rhs: Point) -> Bool in return lhs.x <= rhs.x }) let N = sortedPoints.count let pointRegion = PointRegion(lower: 0, upper: N - 1) if solutionCarryOn.keepRunning { let result = findClosestPointsInRegion(points: sortedPoints, pointRegion: pointRegion, withCarryOn: solutionCarryOn) closestPoints = result?.pointPair } } completion?(closestPoints) } internal func squaredEuclideanDistance(_ pt1: Point, _ pt2: Point) -> CGFloat { let dx = pt2.x - pt1.x let dy = pt2.y - pt1.y return dx * dx + dy * dy } internal func dividePointRegion(region: PointRegion) -> (PointRegion, PointRegion) { let midPoint = (region.upper - region.lower) / 2 + region.lower let lowerRegion = PointRegion(lower: region.lower, upper: midPoint) let upperRegion = PointRegion(lower: midPoint + 1, upper: region.upper) return (lowerRegion, upperRegion) } internal func findClosestPointsInSimpleRegion(points: [Point], pointRegion: PointRegion, withCarryOn: SolutionCarryOn) -> PointPairAndDistance? { var result: PointPairAndDistance? let count = pointRegion.upper - pointRegion.lower + 1 switch count { case 2: let pointPair = (points[pointRegion.lower], points[pointRegion.upper]) let distanceSquared = squaredEuclideanDistance(points[pointRegion.lower], points[pointRegion.upper]) result = PointPairAndDistance(pointPair: pointPair, distanceSquared: distanceSquared) _ = withCarryOn.monitorPointPair(pointPair: pointPair, distanceSquared: distanceSquared) break default: // Use simple combinatorial search var keepRunning = true for ptA_index in pointRegion.lower..<pointRegion.upper { let ptA = points[ptA_index] for ptB_index in (ptA_index+1)...pointRegion.upper { let ptB = points[ptB_index] let distanceSquared = squaredEuclideanDistance(ptA, ptB) if result == nil { result = PointPairAndDistance(pointPair: (ptA, ptB), distanceSquared: distanceSquared) } else if distanceSquared < result!.distanceSquared { result!.pointPair = (ptA, ptB) result!.distanceSquared = distanceSquared } keepRunning = withCarryOn.monitorPointPair(pointPair: result!.pointPair, distanceSquared: distanceSquared) if !keepRunning { break } } if !keepRunning { break } } break } return result } internal func findClosestPointInBorderRegions(points: [Point], lowerRegion: PointRegion, upperRegion: PointRegion, withinAxisDistance: CGFloat, withCarryOn: SolutionCarryOn) -> PointPairAndDistance? { var result: PointPairAndDistance? var keepRunning = true let midPt = points[lowerRegion.upper] for leftIdx in (lowerRegion.lower...lowerRegion.upper).reversed() { let leftPt = points[leftIdx] if midPt.x - leftPt.x > withinAxisDistance { break } for rightIdx in upperRegion.lower...upperRegion.upper { let rightPt = points[rightIdx] if rightPt.x - midPt.x > withinAxisDistance { break } let dx = rightPt.x - leftPt.x let dy = rightPt.y - leftPt.y if abs(dx) <= withinAxisDistance && abs(dy) <= withinAxisDistance { let distanceSquared = dx * dx + dy * dy if result == nil { result = PointPairAndDistance(pointPair: (leftPt, rightPt), distanceSquared: distanceSquared) } else if distanceSquared < result!.distanceSquared { result!.pointPair = (leftPt, rightPt) result!.distanceSquared = distanceSquared } keepRunning = withCarryOn.monitorPointPair(pointPair: result!.pointPair, distanceSquared: distanceSquared) } else { keepRunning = withCarryOn.monitorRectForPoint(point: leftPt, withAxisDistance: withinAxisDistance) } if !keepRunning { break } } if !keepRunning { break } } return result } // Recursive worker function to find closest points internal func findClosestPointsInRegion(points: [Point], pointRegion: PointRegion, withCarryOn: SolutionCarryOn) -> PointPairAndDistance? { var result: PointPairAndDistance? = nil let keepRunning = withCarryOn.monitorPointRegion(points: points, pointRegion: pointRegion) if keepRunning { let count = pointRegion.upper - pointRegion.lower + 1 if count <= maxSimpleRegionSize { result = findClosestPointsInSimpleRegion(points: points, pointRegion: pointRegion, withCarryOn: withCarryOn) } else { let regions = dividePointRegion(region: pointRegion) let lowerRegion = regions.0 let upperRegion = regions.1 if withCarryOn.keepRunning { if let lowerResult = findClosestPointsInRegion(points: points, pointRegion: lowerRegion, withCarryOn: withCarryOn) { result = lowerResult } } if withCarryOn.keepRunning { if let upperResult = findClosestPointsInRegion(points: points, pointRegion: upperRegion, withCarryOn: withCarryOn) { if result == nil { result = upperResult } else { if upperResult.distanceSquared < result!.distanceSquared { result = upperResult } } } } if withCarryOn.keepRunning { let axisDistance: CGFloat if result != nil { axisDistance = sqrt(result!.distanceSquared) } else { axisDistance = CGFloat.greatestFiniteMagnitude } if let middleResult = findClosestPointInBorderRegions(points: points, lowerRegion: lowerRegion, upperRegion: upperRegion, withinAxisDistance: axisDistance, withCarryOn: withCarryOn) { if result == nil { result = middleResult } else { if middleResult.distanceSquared < result!.distanceSquared { result = middleResult } } } } } } return result } }
mit
b51a5c03017bc703bfcf71b9d77cfd61
42.508
203
0.535993
5.179524
false
false
false
false
lacyrhoades/CasualUX
Transitions/CasualSwipeDismiss/CasualSwipeStartingViewController.swift
1
1738
// // CasualSwipeStartingViewController.swift // CasualUX // // Created by Lacy Rhoades on 2/25/16. // Copyright © 2016 Lacy Rhoades. All rights reserved. // import UIKit class CasualSwipeStartingViewController: UIViewController { var animationTransitioner: CasualSwipeDetailTransitioner! var tappableView: UIView! override func viewDidLoad() { let label = UILabel(frame: self.view.bounds) label.numberOfLines = 0 label.font = UIFont(name: "Helvetica", size: 88.0) label.textColor = UIColor.whiteColor() label.text = "Testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest" self.view.addSubview(label) let width = self.view.bounds.size.width / 2.0 let height = self.view.bounds.size.height / 2.0 let x = (self.view.bounds.size.width - width) / 2.0 let y = (self.view.bounds.size.height - height) / 2.0 self.tappableView = UIView(frame: CGRect(x: x, y: y, width: width, height:height)) self.tappableView.backgroundColor = UIColor.yellowColor() self.view.addSubview(self.tappableView) let tap = UITapGestureRecognizer(target: self, action: "didTap") self.tappableView.addGestureRecognizer(tap) } func didTap() { self.animationTransitioner = CasualSwipeDetailTransitioner() self.animationTransitioner.interactive = false self.animationTransitioner.fromView = self.tappableView let vc = CasualSwipeDetailViewController() vc.transitioningDelegate = self.animationTransitioner self.presentViewController(vc, animated: true) { () -> Void in // done } } }
mit
e2696aac02ccc119f23a1ff68e15c612
33.74
95
0.66494
4.135714
false
true
false
false
coodly/laughing-adventure
Source/UI/InputValidation.swift
1
1697
/* * Copyright 2015 Coodly LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit public protocol InputValidation: class { weak var attached: UITextField? { get set } func textField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool } public class DecimalInputValidation: InputValidation { public weak var attached: UITextField? public init() { } public func textField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if string == " " { return false } if string != "." && string != "," { return true } guard let original = textField.text else { return true } if let _ = original.range(of: ".") { return false } guard let range = original.range(from: range) else { return true } var replaced = original replaced.replaceSubrange(range, with: ".") textField.text = replaced return false } }
apache-2.0
48d1a1863c32c415fb46220dc07ec506
28.258621
141
0.632882
4.961988
false
false
false
false
ewhitley/CDAKit
CDAKit/health-data-standards/lib/models/organization.swift
1
2828
// // organization.swift // CDAKit // // Created by Eric Whitley on 11/30/15. // Copyright © 2015 Eric Whitley. All rights reserved. // import Foundation import Mustache /** Organization */ public class CDAKOrganization: CDAKJSONInstantiable, CustomStringConvertible, Equatable, Hashable { // MARK: CDA properties ///organization name public var name: String? ///OIds etc. for organization public var ids: [CDAKCDAIdentifier] = [] //not used in original model. Merged from QRDA ORG model ///physical address public var addresses: [CDAKAddress] = [CDAKAddress]() ///telecoms public var telecoms: [CDAKTelecom] = [CDAKTelecom]() // MARK: - Initializers public init() { } // MARK: - Deprecated - Do not use ///Do not use - will be removed. Was used in HDS Ruby. required public init(event: [String:Any?]) { initFromEventList(event) } ///Do not use - will be removed. Was used in HDS Ruby. private func initFromEventList(event: [String:Any?]) { for (key, value) in event { CDAKUtility.setProperty(self, property: key, value: value) } } // MARK: Standard properties ///Debugging description public var description: String { return "CDAKOrganization => name: \(name), addresses: \(addresses), telecoms: \(telecoms)" } } extension CDAKOrganization { public var hashValue: Int { var hv: Int hv = "\(name)".hashValue if addresses.count > 0 { hv = hv ^ "\(addresses)".hashValue } if telecoms.count > 0 { hv = hv ^ "\(telecoms)".hashValue } return hv } } public func == (lhs: CDAKOrganization, rhs: CDAKOrganization) -> Bool { return lhs.hashValue == rhs.hashValue && CDAKCommonUtility.classNameAsString(lhs) == CDAKCommonUtility.classNameAsString(rhs) } extension CDAKOrganization: MustacheBoxable { // MARK: - Mustache marshalling var boxedValues: [String:MustacheBox] { var vals: [String:MustacheBox] = [:] vals = [ "name" : Box(name), "ids": Box(ids) ] if addresses.count > 0 { vals["addresses"] = Box(addresses) } if telecoms.count > 0 { vals["telecoms"] = Box(telecoms) } return vals } public var mustacheBox: MustacheBox { return Box(boxedValues) } } extension CDAKOrganization: CDAKJSONExportable { // MARK: - JSON Generation ///Dictionary for JSON data public var jsonDict: [String: AnyObject] { var dict: [String: AnyObject] = [:] if let name = name { dict["name"] = name } if ids.count > 0 { dict["ids"] = ids.map({$0.jsonDict}) } if telecoms.count > 0 { dict["telecoms"] = telecoms.map({$0.jsonDict}) } if addresses.count > 0 { dict["addresses"] = addresses.map({$0.jsonDict}) } return dict } }
mit
68bad3f006e38dd474020202a0d77cd2
22.172131
127
0.629996
3.937326
false
false
false
false
Chaosspeeder/YourGoals
YourGoalsTests/TodayScheduleCalculatorTests.swift
1
5227
// // TodayScheduleCalculatorTests.swift // YourGoalsTests // // Created by André Claaßen on 11.01.18. // Copyright © 2018 André Claaßen. All rights reserved. // import XCTest @testable import YourGoals class TodayScheduleCalculatorTests: StorageTestCase { let testDateTime = Date.dateTimeWithYear(2018, month: 01, day: 11, hour: 13, minute: 00, second: 00) let commitmentDate = Date.dateWithYear(2018, month: 01, day: 11) fileprivate func createTasks(infos: [TaskInfoTuple]) -> [Task] { let goal = super.testDataCreator.createGoalWithTasks(infos: infos) try! self.manager.saveContext() let orderManager = TaskOrderManager(manager: self.manager) return try! orderManager.tasksByOrder(forGoal: goal) } /// calculate a list of starting times func testCalulateStartingTimesWithoutActiveTask() { // setup let actionables = self.createTasks(infos:[ ("Task 30 Minutes", 1, 30.0,nil , self.commitmentDate, nil, nil), ("Task 90 Minutes", 2, 90.0,nil , self.commitmentDate, nil, nil) ]) // act let scheduleCalculator = TodayScheduleCalculator(manager: self.manager) let times = try! scheduleCalculator.calculateTimeInfos(forTime: self.testDateTime, actionables: actionables) // test XCTAssertEqual(2, times.count) XCTAssertEqual(ActionableTimeInfo(hour: 13, minute: 00, second: 00, remainingMinutes: 30.0, conflicting: false, fixed: false, actionable: actionables[0]), times[0]) XCTAssertEqual(ActionableTimeInfo(hour: 13, minute: 30, second: 00, remainingMinutes: 90.0, conflicting: false, fixed: false, actionable: actionables[1]), times[1]) } /// calculate a list of starti3ng times func testCalulateStartingTimesWithActiveTask() { // setup let actionables = self.createTasks(infos:[ ("Task 30 Minutes", 1, 30.0,nil , self.commitmentDate, nil, nil), ("Task 90 Minutes", 2, 90.0,nil , self.commitmentDate, nil, nil) ]) let activeTask = actionables.first! // task is progressing since 15 Minutes try! TaskProgressManager(manager: self.manager).startProgress(forTask: activeTask, atDate: self.testDateTime.addingTimeInterval(60.0 * 15.0 * -1.0)) // act let scheduleCalculator = TodayScheduleCalculator(manager: self.manager) let times = try! scheduleCalculator.calculateTimeInfos(forTime: self.testDateTime, actionables: actionables) // test XCTAssertEqual(2, times.count) XCTAssertEqual(ActionableTimeInfo(hour: 12, minute: 45, second: 00, end: Date.timeWith(hour: 13, minute: 15, second: 00), remainingMinutes: 15.0, conflicting: false, fixed: false, actionable: actionables[0]), times[0]) XCTAssertEqual(ActionableTimeInfo(hour: 13, minute: 15, second: 00, remainingMinutes: 90.0, conflicting: false, fixed: false, actionable: actionables[1]), times[1]) } /// calculate a list of starting times with a fixed time in betwee func testCalulateStartingTimesWithFixedBeginTime() { // setup let actionables = self.createTasks(infos:[ ("Task 30 Minutes", 1, 30.0,nil , self.commitmentDate, nil,nil), ("Task 90 Minutes", 2, 90.0,nil , self.commitmentDate, Date.timeWith(hour: 14, minute: 00, second: 00), nil) ]) // act let scheduleCalculator = TodayScheduleCalculator(manager: self.manager) let times = try! scheduleCalculator.calculateTimeInfos(forTime: self.testDateTime, actionables: actionables) // test XCTAssertEqual(2, times.count) XCTAssertEqual(ActionableTimeInfo(hour: 13, minute: 00, second: 00, remainingMinutes: 30.0, conflicting: false, fixed: false, actionable: actionables[0]), times[0]) XCTAssertEqual(ActionableTimeInfo(hour: 14, minute: 00, second: 00, remainingMinutes: 90.0, conflicting: false, fixed: true, actionable: actionables[1]), times[1]) } /// calculate a list of starting times with a fixed time in betwee func testCalulateStartingTimesWithFixedBeginTimeInDanger() { // setup let actionables = self.createTasks(infos:[ ("Task 30 Minutes", 1, 90.0,nil , self.commitmentDate, nil, nil), // going from 13:00 til 14:30 ("Task 90 Minutes", 2, 90.0,nil , self.commitmentDate, Date.timeWith(hour: 14, minute: 00, second: 00), nil) ]) // act let scheduleCalculator = TodayScheduleCalculator(manager: self.manager) let times = try! scheduleCalculator.calculateTimeInfos(forTime: self.testDateTime, actionables: actionables) // test XCTAssertEqual(2, times.count) XCTAssertEqual(ActionableTimeInfo(hour: 13, minute: 00, second: 00, remainingMinutes: 90.0, conflicting: false, fixed: false, actionable: actionables[0]), times[0]) XCTAssertEqual(ActionableTimeInfo(hour: 14, minute: 00, second: 00, remainingMinutes: 90.0, conflicting: true, fixed: true, actionable: actionables[1]), times[1]) } }
lgpl-3.0
15aacf18dc47bb1e1e0f4e852e281c1c
50.70297
172
0.66239
4.160956
false
true
false
false
milseman/swift
test/IDE/complete_dynamic_lookup.swift
11
31014
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -disable-objc-attr-requires-foundation-module -o %t %S/Inputs/AnyObject/foo_swift_module.swift // RUN: %target-swift-frontend -emit-module -disable-objc-attr-requires-foundation-module -o %t %S/Inputs/AnyObject/bar_swift_module.swift // RUN: cp %S/Inputs/AnyObject/baz_clang_module.h %t // RUN: cp %S/Inputs/AnyObject/module.map %t // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_FUNC_PARAM_NO_DOT_1 > %t.dl.txt // RUN: %FileCheck %s -check-prefix=DL_INSTANCE_NO_DOT < %t.dl.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_FUNC_PARAM_DOT_1 > %t.dl.txt // RUN: %FileCheck %s -check-prefix=DL_INSTANCE_DOT < %t.dl.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_VAR_NO_DOT_1 > %t.dl.txt // RUN: %FileCheck %s -check-prefix=DL_INSTANCE_NO_DOT < %t.dl.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_VAR_DOT_1 > %t.dl.txt // RUN: %FileCheck %s -check-prefix=DL_INSTANCE_DOT < %t.dl.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_RETURN_VAL_NO_DOT_1 > %t.dl.txt // RUN: %FileCheck %s -check-prefix=DL_INSTANCE_NO_DOT < %t.dl.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_RETURN_VAL_DOT_1 > %t.dl.txt // RUN: %FileCheck %s -check-prefix=DL_INSTANCE_DOT < %t.dl.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_CALL_RETURN_VAL_NO_DOT_1 > %t.dl.txt // RUN: %FileCheck %s -check-prefix=TLOC_MEMBERS_NO_DOT < %t.dl.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_CALL_RETURN_VAL_DOT_1 > %t.dl.txt // RUN: %FileCheck %s -check-prefix=TLOC_MEMBERS_DOT < %t.dl.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_FUNC_NAME_1 > %t.dl.txt // RUN: %FileCheck %s -check-prefix=DL_FUNC_NAME_1 < %t.dl.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_FUNC_NAME_PAREN_1 > %t.dl.txt // RUN: %FileCheck %s -check-prefix=DL_FUNC_NAME_PAREN_1 < %t.dl.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_FUNC_NAME_DOT_1 > %t.dl.txt // RUN: %FileCheck %s -check-prefix=DL_FUNC_NAME_DOT_1 < %t.dl.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_FUNC_NAME_BANG_1 > %t.dl.txt // RUN: %FileCheck %s -check-prefix=DL_FUNC_NAME_BANG_1 < %t.dl.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_CLASS_NO_DOT_1 > %t.dl.txt // RUN: %FileCheck %s -check-prefix=DL_CLASS_NO_DOT < %t.dl.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -I %t -disable-objc-attr-requires-foundation-module -code-completion-token=DL_CLASS_DOT_1 > %t.dl.txt // RUN: %FileCheck %s -check-prefix=DL_CLASS_DOT < %t.dl.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.dl.txt // REQUIRES: objc_interop import foo_swift_module import class bar_swift_module.Bar_ImportedObjcClass import baz_clang_module //===--- //===--- Helper types that are used in this test. //===--- @objc class Base {} @objc class Derived : Base {} protocol Foo { func foo() } protocol Bar { func bar() } //===--- //===--- Types that contain members accessible by dynamic lookup. //===--- // GLOBAL_NEGATIVE-NOT: ERROR // DL_INSTANCE_NO_DOT: Begin completions // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[bar_swift_module]: .bar_ImportedObjcClass_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[bar_swift_module]: .bar_ImportedObjcClass_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc2!({#(a): Derived#})[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc3!({#(a): Derived#})[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc4!()[#Base#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: .base1_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: .base1_Property2[#Base?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: .baz_Class_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: .baz_Protocol_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_Nested1_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: .foo_Nested1_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_Nested2_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: .foo_Nested2_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_TopLevelClass_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: .foo_TopLevelClass_ObjcProperty1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_TopLevelObjcClass_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: .foo_TopLevelObjcClass_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_TopLevelObjcProtocol_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: .foo_TopLevelObjcProtocol_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .nested1_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: .nested1_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .nested2_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: .nested2_Property[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .returnsObjcClass!({#(i): Int#})[#TopLevelObjcClass#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .topLevelClass_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: .topLevelClass_ObjcProperty1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .topLevelObjcClass_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: .topLevelObjcClass_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .topLevelObjcProtocol_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: .topLevelObjcProtocol_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[bar_swift_module]: [{#Bar_ImportedObjcClass#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[foo_swift_module]: [{#Foo_TopLevelObjcProtocol#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[swift_ide_test]: [{#Int16#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[foo_swift_module]: [{#Int32#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[foo_swift_module]: [{#Int64#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[swift_ide_test]: [{#Int8#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[swift_ide_test]: [{#TopLevelObjcClass#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[swift_ide_test]: [{#TopLevelObjcProtocol#}][#Int?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[baz_clang_module]: [{#Int32#}][#Any!?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT-DAG: Decl[Subscript]/OtherModule[baz_clang_module]: [{#Any!#}][#Any!?#]{{; name=.+$}} // DL_INSTANCE_NO_DOT: End completions // GLOBAL_NEGATIVE-NOT:.objectAtIndexedSubscript // DL_INSTANCE_DOT: Begin completions // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[bar_swift_module]: bar_ImportedObjcClass_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[bar_swift_module]: bar_ImportedObjcClass_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc2!({#(a): Derived#})[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc3!({#(a): Derived#})[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc4!()[#Base#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: base1_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: base1_Property2[#Base?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: baz_Class_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[baz_clang_module]: baz_Class_Property1[#Baz_Class!?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[baz_clang_module]: baz_Class_Property2[#Baz_Class!?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: baz_Protocol_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_Nested1_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: foo_Nested1_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_Nested2_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: foo_Nested2_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_TopLevelClass_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: foo_TopLevelClass_ObjcProperty1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_TopLevelObjcClass_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: foo_TopLevelObjcClass_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_TopLevelObjcProtocol_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[foo_swift_module]: foo_TopLevelObjcProtocol_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: nested1_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: nested1_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: nested2_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: nested2_Property[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: returnsObjcClass!({#(i): Int#})[#TopLevelObjcClass#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: topLevelClass_ObjcInstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: topLevelClass_ObjcProperty1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: topLevelObjcClass_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: topLevelObjcClass_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: topLevelObjcProtocol_InstanceFunc1!()[#Void#]{{; name=.+$}} // DL_INSTANCE_DOT-DAG: Decl[InstanceVar]/OtherModule[swift_ide_test]: topLevelObjcProtocol_Property1[#Int?#]{{; name=.+$}} // DL_INSTANCE_DOT: End completions // DL_CLASS_NO_DOT: Begin completions // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[bar_swift_module]: .bar_ImportedObjcClass_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[bar_swift_module]: .bar_ImportedObjcClass_InstanceFunc1({#self: Bar_ImportedObjcClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc1({#self: Base1#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc2({#self: Base1#})[#(Derived) -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc3({#self: Base1#})[#(Derived) -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .base1_InstanceFunc4({#self: Base1#})[#() -> Base#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[baz_clang_module]: .baz_Class_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: .baz_Class_InstanceFunc1({#self: Baz_Class#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[baz_clang_module]: .baz_Protocol_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: .baz_Protocol_InstanceFunc1({#self: Self#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: .foo_Nested1_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_Nested1_ObjcInstanceFunc1({#self: Foo_ContainerForNestedClass1.Foo_Nested1#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: .foo_Nested2_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_Nested2_ObjcInstanceFunc1({#self: Foo_ContainerForNestedClass2.Foo_Nested2#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: .foo_TopLevelClass_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_TopLevelClass_ObjcInstanceFunc1({#self: Foo_TopLevelClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: .foo_TopLevelObjcClass_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_TopLevelObjcClass_InstanceFunc1({#self: Foo_TopLevelObjcClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: .foo_TopLevelObjcProtocol_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: .foo_TopLevelObjcProtocol_InstanceFunc1({#self: Self#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: .nested1_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .nested1_ObjcInstanceFunc1({#self: ContainerForNestedClass1.Nested1#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: .nested2_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .nested2_ObjcInstanceFunc1({#self: ContainerForNestedClass2.Nested2#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .returnsObjcClass({#self: TopLevelObjcClass#})[#(Int) -> TopLevelObjcClass#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: .topLevelClass_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .topLevelClass_ObjcInstanceFunc1({#self: TopLevelClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: .topLevelObjcClass_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .topLevelObjcClass_InstanceFunc1({#self: TopLevelObjcClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: .topLevelObjcProtocol_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_NO_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: .topLevelObjcProtocol_InstanceFunc1({#self: Self#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_NO_DOT: End completions // DL_CLASS_DOT: Begin completions // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[bar_swift_module]: bar_ImportedObjcClass_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[bar_swift_module]: bar_ImportedObjcClass_InstanceFunc1({#self: Bar_ImportedObjcClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc1({#self: Base1#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc2({#self: Base1#})[#(Derived) -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc3({#self: Base1#})[#(Derived) -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: base1_InstanceFunc4({#self: Base1#})[#() -> Base#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[baz_clang_module]: baz_Class_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: baz_Class_InstanceFunc1({#self: Baz_Class#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[baz_clang_module]: baz_Protocol_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[baz_clang_module]: baz_Protocol_InstanceFunc1({#self: Self#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: foo_Nested1_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_Nested1_ObjcInstanceFunc1({#self: Foo_ContainerForNestedClass1.Foo_Nested1#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: foo_Nested2_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_Nested2_ObjcInstanceFunc1({#self: Foo_ContainerForNestedClass2.Foo_Nested2#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: foo_TopLevelClass_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_TopLevelClass_ObjcInstanceFunc1({#self: Foo_TopLevelClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: foo_TopLevelObjcClass_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_TopLevelObjcClass_InstanceFunc1({#self: Foo_TopLevelObjcClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[foo_swift_module]: foo_TopLevelObjcProtocol_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[foo_swift_module]: foo_TopLevelObjcProtocol_InstanceFunc1({#self: Self#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: nested1_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: nested1_ObjcInstanceFunc1({#self: ContainerForNestedClass1.Nested1#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: nested2_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: nested2_ObjcInstanceFunc1({#self: ContainerForNestedClass2.Nested2#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: returnsObjcClass({#self: TopLevelObjcClass#})[#(Int) -> TopLevelObjcClass#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: topLevelClass_ObjcClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: topLevelClass_ObjcInstanceFunc1({#self: TopLevelClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: topLevelObjcClass_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: topLevelObjcClass_InstanceFunc1({#self: TopLevelObjcClass#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[StaticMethod]/OtherModule[swift_ide_test]: topLevelObjcProtocol_ClassFunc1()[#Void#]{{; name=.+$}} // DL_CLASS_DOT-DAG: Decl[InstanceMethod]/OtherModule[swift_ide_test]: topLevelObjcProtocol_InstanceFunc1({#self: Self#})[#() -> Void#]{{; name=.+$}} // DL_CLASS_DOT: End completions // TLOC_MEMBERS_NO_DOT: Begin completions // TLOC_MEMBERS_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .returnsObjcClass({#(i): Int#})[#TopLevelObjcClass#]{{; name=.+$}} // TLOC_MEMBERS_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .topLevelObjcClass_InstanceFunc1()[#Void#]{{; name=.+$}} // TLOC_MEMBERS_NO_DOT-NEXT: Decl[Subscript]/CurrNominal: [{#Int8#}][#Int#]{{; name=.+$}} // TLOC_MEMBERS_NO_DOT-NEXT: Decl[InstanceVar]/CurrNominal: .topLevelObjcClass_Property1[#Int#]{{; name=.+$}} // TLOC_MEMBERS_NO_DOT-NEXT: Decl[InfixOperatorFunction]/OtherModule[Swift]: === {#AnyObject?#}[#Bool#]; // TLOC_MEMBERS_NO_DOT-NEXT: Decl[InfixOperatorFunction]/OtherModule[Swift]: !== {#AnyObject?#}[#Bool#]; // TLOC_MEMBERS_NO_DOT-NEXT: End completions // TLOC_MEMBERS_DOT: Begin completions // TLOC_MEMBERS_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: returnsObjcClass({#(i): Int#})[#TopLevelObjcClass#]{{; name=.+$}} // TLOC_MEMBERS_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: topLevelObjcClass_InstanceFunc1()[#Void#]{{; name=.+$}} // TLOC_MEMBERS_DOT-NEXT: Decl[InstanceVar]/CurrNominal: topLevelObjcClass_Property1[#Int#]{{; name=.+$}} // TLOC_MEMBERS_DOT-NEXT: End completions // FIXME: Properties in Clang modules. // There's a test already: baz_Protocol_Property1. // Blocked by: rdar://15136550 Properties in protocols not implemented @objc class TopLevelObjcClass { func returnsObjcClass(_ i: Int) -> TopLevelObjcClass {} func topLevelObjcClass_InstanceFunc1() {} class func topLevelObjcClass_ClassFunc1() {} subscript(i: Int8) -> Int { get { return 0 } } var topLevelObjcClass_Property1: Int } @objc class TopLevelObjcClass_DuplicateMembers { func topLevelObjcClass_InstanceFunc1() {} class func topLevelObjcClass_ClassFunc1() {} subscript(i: Int8) -> Int { get { return 0 } } var topLevelObjcClass_Property1: Int } class TopLevelClass { @objc func topLevelClass_ObjcInstanceFunc1() {} @objc class func topLevelClass_ObjcClassFunc1() {} @objc subscript (i: Int16) -> Int { get { return 0 } } @objc var topLevelClass_ObjcProperty1: Int func ERROR() {} typealias ERROR = Int subscript (i: ERROR) -> Int { get { return 0 } } var ERROR_Property: Int } @objc protocol TopLevelObjcProtocol { func topLevelObjcProtocol_InstanceFunc1() class func topLevelObjcProtocol_ClassFunc1() subscript (i: TopLevelObjcClass) -> Int { get set } var topLevelObjcProtocol_Property1: Int { get set } } class ContainerForNestedClass1 { class Nested1 { @objc func nested1_ObjcInstanceFunc1() {} @objc class func nested1_ObjcClassFunc1() {} @objc var nested1_Property1: Int func ERROR() {} typealias ERROR = Int subscript (i: ERROR) -> Int { get { return 0 } } var ERROR_Property: Int } func ERROR() {} } struct ContainerForNestedClass2 { class Nested2 { @objc func nested2_ObjcInstanceFunc1() {} @objc class func nested2_ObjcClassFunc1() {} @objc subscript (i: TopLevelObjcProtocol) -> Int { get { return 0 } } @objc var nested2_Property: Int func ERROR() {} var ERROR_Property: Int } func ERROR() {} } class GenericContainerForNestedClass1<T> { class Nested3 { @objc func ERROR1() {} func ERROR2() {} class func ERROR3() {} typealias ERROR = Int subscript (i: ERROR) -> Int { get { return 0 } } var ERROR_Property: Int } func ERROR() {} } struct GenericContainerForNestedClass2<T> { class Nested3 { @objc func ERROR1() {} func ERROR2() {} class func ERROR3() {} typealias ERROR = Int subscript (i: ERROR) -> Int { get { return 0 } } var ERROR_Property: Int } func ERROR() {} } @objc class Base1 { func base1_InstanceFunc1() {} func base1_InstanceFunc2(_ a: Derived) {} func base1_InstanceFunc3(_ a: Derived) {} func base1_InstanceFunc4() -> Base {} var base1_Property1: Int var base1_Property2: Base } @objc class Derived1 : Base1 { func base1_InstanceFunc1() {} func base1_InstanceFunc2(_ a: Derived) {} func base1_InstanceFunc3(_ a: Base) {} func base1_InstanceFunc4() -> Derived {} var base1_Property1: Int { get { return 0 } set {} } var base1_Property2: Derived { get { return Derived() } set {} } } func returnsAnyObject() -> AnyObject { return TopLevelClass() } func testAnyObject1(_ dl: AnyObject) { dl#^DL_FUNC_PARAM_NO_DOT_1^# } func testAnyObject2(_ dl: AnyObject) { dl.#^DL_FUNC_PARAM_DOT_1^# } func testAnyObject3() { var dl: AnyObject = TopLevelClass() dl#^DL_VAR_NO_DOT_1^# } func testAnyObject4() { var dl: AnyObject = TopLevelClass() dl.#^DL_VAR_DOT_1^# } func testAnyObject5() { returnsAnyObject()#^DL_RETURN_VAL_NO_DOT_1^# } func testAnyObject6() { returnsAnyObject().#^DL_RETURN_VAL_DOT_1^# } func testAnyObject7(_ dl: AnyObject) { dl.returnsObjcClass!(42)#^DL_CALL_RETURN_VAL_NO_DOT_1^# } func testAnyObject8(_ dl: AnyObject) { dl.returnsObjcClass!(42).#^DL_CALL_RETURN_VAL_DOT_1^# } func testAnyObject9() { // FIXME: this syntax is not implemented yet. // dl.returnsObjcClass?(42)#^DL_CALL_RETURN_OPTIONAL_NO_DOT_1^# } func testAnyObject10() { // FIXME: this syntax is not implemented yet. // dl.returnsObjcClass?(42).#^DL_CALL_RETURN_OPTIONAL_DOT_1^# } func testAnyObject11(_ dl: AnyObject) { dl.returnsObjcClass#^DL_FUNC_NAME_1^# } // FIXME: it would be nice if we produced a call pattern here. // DL_FUNC_NAME_1: Begin completions // DL_FUNC_NAME_1-DAG: Decl[InstanceVar]/CurrNominal: .description[#String#]{{; name=.+$}} // DL_FUNC_NAME_1: End completions func testAnyObject11_(_ dl: AnyObject) { dl.returnsObjcClass!(#^DL_FUNC_NAME_PAREN_1^# } // DL_FUNC_NAME_PAREN_1: Begin completions // DL_FUNC_NAME_PAREN_1-DAG: Pattern/ExprSpecific: ['(']{#Int#})[#TopLevelObjcClass#]{{; name=.+$}} // DL_FUNC_NAME_PAREN_1: End completions func testAnyObject12(_ dl: AnyObject) { dl.returnsObjcClass.#^DL_FUNC_NAME_DOT_1^# } // FIXME: it would be nice if we produced a call pattern here. // DL_FUNC_NAME_DOT_1: Begin completions // DL_FUNC_NAME_DOT_1-DAG: Decl[InstanceVar]/CurrNominal: description[#String#]{{; name=.+$}} // DL_FUNC_NAME_DOT_1: End completions func testAnyObject13(_ dl: AnyObject) { dl.returnsObjcClass!#^DL_FUNC_NAME_BANG_1^# } // DL_FUNC_NAME_BANG_1: Begin completions // DL_FUNC_NAME_BANG_1-NEXT: Pattern/ExprSpecific: ({#Int#})[#TopLevelObjcClass#] // DL_FUNC_NAME_BANG_1-NEXT: End completions func testAnyObject14() { // FIXME: this syntax is not implemented yet. // dl.returnsObjcClass?#^DL_FUNC_QUESTION_1^# } func testAnyObjectClassMethods1(_ dl: AnyObject) { type(of: dl)#^DL_CLASS_NO_DOT_1^# } func testAnyObjectClassMethods2(_ dl: AnyObject) { type(of: dl).#^DL_CLASS_DOT_1^# }
apache-2.0
af7bc5a0be9830d5a08d460dd3837a78
61.277108
186
0.686593
3.378799
false
true
false
false
notohiro/NowCastMapView
NowCastMapView/Overlay.swift
1
1070
// // Overlay.swift // NowCastMapView // // Created by Hiroshi Noto on 6/20/15. // Copyright (c) 2015 Hiroshi Noto. All rights reserved. // import Foundation import MapKit public class Overlay: NSObject, MKOverlay { public var coordinate: CLLocationCoordinate2D { let latitude = (Constants.originLatitude + Constants.terminalLatitude) / 2 let longitude = (Constants.originLongitude + Constants.terminalLongitude) / 2 return CLLocationCoordinate2DMake(latitude, longitude) } public var boundingMapRect: MKMapRect { let origin = MKMapPoint(CLLocationCoordinate2DMake(Constants.originLatitude, Constants.originLongitude)) let end = MKMapPoint(CLLocationCoordinate2DMake(Constants.terminalLatitude, Constants.terminalLongitude)) let size = MKMapSize(width: end.x - origin.x, height: end.y - origin.y) return MKMapRect(x: origin.x, y: origin.y, width: size.width, height: size.height) } public func intersects(_ mapRect: MKMapRect) -> Bool { return mapRect.intersects(TileModel.serviceAreaMapRect) } }
mit
b74a47407ff08421b7b30b0c8f9740ed
34.666667
110
0.737383
4.28
false
false
false
false
mindz-eye/MYTableViewIndex
Example/MYTableViewIndex/TableViewController.swift
1
6075
// // TableViewController.swift // TableViewIndex // // Created by Makarov Yury on 30/04/16. // Copyright © 2016 Makarov Yury. All rights reserved. // import UIKit import MYTableViewIndex class TableViewController : UITableViewController, UITextFieldDelegate, TableViewIndexDelegate, ExampleContainer { var example: Example! fileprivate var dataSource: DataSource! lazy fileprivate var searchController = UISearchController(searchResultsController: nil) fileprivate var tableViewIndexController: TableViewIndexController! override func viewDidLoad() { super.viewDidLoad() dataSource = example.dataSource tableViewIndexController = TableViewIndexController(scrollView: tableView) tableViewIndexController.tableViewIndex.delegate = self example.setupTableIndexController(tableViewIndexController) if example.hasSearchIndex { tableView.tableHeaderView = searchController.searchBar tableView.sectionIndexColor = UIColor.clear tableView.sectionIndexBackgroundColor = UIColor.clear tableView.sectionIndexTrackingBackgroundColor = UIColor.clear searchController.hidesNavigationBarDuringPresentation = false } } // MARK: - UITableView override func numberOfSections(in tableView: UITableView) -> Int { return dataSource.numberOfSections() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.numberOfItemsInSection(section) } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return dataSource.titleForHeaderInSection(section) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) if let dataCell = cell as? TableCell { dataCell.setupWithItem(dataSource.itemAtIndexPath(indexPath)!) } return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return TableCell.heightForItem(dataSource.itemAtIndexPath(indexPath)!) } override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { return NSNotFound } override func sectionIndexTitles(for tableView: UITableView) -> [String]? { return example.hasSearchIndex ? [dummyItemForNativeTableIndex()] : nil } // MARK: - UIScrollView override func scrollViewDidScroll(_ scrollView: UIScrollView) { updateIndexVisibility() updateHighlightedItems() } // MARK: - TableViewIndex func tableViewIndex(_ tableViewIndex: TableViewIndex, didSelect item: UIView, at index: Int) -> Bool { let originalOffset = tableView.contentOffset if item is SearchItem { tableView.scrollRectToVisible(searchController.searchBar.frame, animated: false) } else { let sectionIndex = example.mapIndexItemToSection(item, index: index) if sectionIndex != NSNotFound { let rowCount = tableView.numberOfRows(inSection: sectionIndex) let indexPath = IndexPath(row: rowCount > 0 ? 0 : NSNotFound, section: sectionIndex) tableView.scrollToRow(at: indexPath, at: .top, animated: false) } else { tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false) } } return tableView.contentOffset != originalOffset } // MARK: - Helpers fileprivate func uncoveredTableViewFrame() -> CGRect { return CGRect(x: tableView.bounds.origin.x, y: tableView.bounds.origin.y + topLayoutGuide.length, width: tableView.bounds.width, height: tableView.bounds.height - topLayoutGuide.length) } fileprivate func updateIndexVisibility() { guard let visibleIndexes = tableView.indexPathsForVisibleRows else { return } for indexPath in visibleIndexes { if (dataSource.titleForHeaderInSection((indexPath as NSIndexPath).section)) != nil { continue } let cellFrame = view.convert(tableView.rectForRow(at: indexPath), to: nil) if view.convert(uncoveredTableViewFrame(), to: nil).intersects(cellFrame) { tableViewIndexController.setHidden(true, animated: true) return } } tableViewIndexController.setHidden(false, animated: true) } fileprivate func updateHighlightedItems() { let frame = uncoveredTableViewFrame() var visibleSections = Set<Int>() for section in 0..<tableView.numberOfSections { if (frame.intersects(tableView.rect(forSection: section)) || frame.intersects(tableView.rectForHeader(inSection: section))) { visibleSections.insert(section) } } example.trackSelectedSections(visibleSections) } fileprivate func dummyItemForNativeTableIndex() -> String { let maxLetterWidth = self.tableViewIndexController.tableViewIndex.font.lineHeight var str = ""; var size = CGSize() while size.width < maxLetterWidth { str += "i" size = str.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: [.usesFontLeading, .usesLineFragmentOrigin], attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 11.0)], context: nil).size } return str } }
mit
a7ff1841920ec9422616769cfd2e03c1
38.441558
130
0.647185
5.784762
false
false
false
false
ymsheng/ReachabilitySwift
ReachabilitySwift/MNReachability/FSM/ReachStateWIFI.swift
1
1028
// // ReachStateWIFI.swift // ReachabilitySwift // // Created by mosn on 2/25/16. // Copyright © 2016 com.*. All rights reserved. // import Foundation open class ReachStateWIFI:ReachState { override open func onEventWithError(_ event: NSDictionary) throws -> RRStateID { var resStateID = RRStateID.rrStateWIFI let eventID = Int((event[kEventKeyID] as! Int)) switch eventID { case RREventID.rrEventUnLoad.rawValue: resStateID = RRStateID.rrStateUnloaded case RREventID.rrEventPingCallback.rawValue: let eventParam = (event[kEventKeyParam]! as AnyObject).boolValue resStateID = FSMStateUtil.RRStateFromPingFlag(eventParam!) case RREventID.rrEventLocalConnectionCallback.rawValue: resStateID = FSMStateUtil.RRStateFromValue(event[kEventKeyParam] as! String) default: throw NSError(domain: "FSM", code: kFSMErrorNotAccept, userInfo: nil) } return resStateID; } }
mit
ae589d82b5cfa2872a3e08c087656e97
33.233333
88
0.667965
3.98062
false
false
false
false
someoneAnyone/PageCollectionViewLayout
Pod/Classes/PageCollectionViewLayoutAttributes.swift
1
991
// // PageCollectionViewLayoutAttributes.swift // PageCollectionViewLayout // // Created by Peter Ina on 10/30/15. // Copyright © 2015 Peter Ina. All rights reserved. // import UIKit public class PageCollectionViewLayoutAttributes: UICollectionViewLayoutAttributes { public var numberOfPages: Int = 0 public var currentPage: Int = 0 // MARK: NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! PageCollectionViewLayoutAttributes copy.numberOfPages = self.numberOfPages copy.currentPage = self.currentPage return copy } public override func isEqual(object: AnyObject?) -> Bool { if let rhs = object as? PageCollectionViewLayoutAttributes { if currentPage != rhs.currentPage { return false } return super.isEqual(object) } else { return false } } }
mit
75f3f8360de7fcd70d5ba53c5f7b113c
27.285714
83
0.641414
5.238095
false
false
false
false
OneBusAway/onebusaway-iphone
Carthage/Checkouts/SwiftEntryKit/Source/Model/EntryAttributes/EKAttributes+Shadow.swift
3
941
// // EKAttributes+Shadow.swift // SwiftEntryKit // // Created by Daniel Huri on 4/21/18. // Copyright (c) 2018 [email protected]. All rights reserved. // import Foundation import UIKit public extension EKAttributes { /** The shadow around the entry */ enum Shadow { /** No shadow */ case none /** Shadow with value */ case active(with: Value) /** The shadow properties */ public struct Value { public let radius: CGFloat public let opacity: Float public let color: UIColor public let offset: CGSize public init(color: UIColor = .black, opacity: Float, radius: CGFloat, offset: CGSize = .zero) { self.color = color self.radius = radius self.offset = offset self.opacity = opacity } } } }
apache-2.0
da214d366cf59c245496d495f9b87613
22.525
107
0.529224
4.901042
false
false
false
false
Za1006/TIY-Assignments
Counter/Counter/ViewController.swift
1
4428
// // ViewController.swift // Swift-Counter // // Created by Ben Gohlke on 8/17/15. // Copyright (c) 2015 The Iron Yard. All rights reserved. // import UIKit class ViewController: UIViewController { // The following variables and constants are called properties; they hold values that can be accessed from any method in this class // This allows the app to set its current count when the app first loads. // The line below simply generates a random number and then makes sure it falls within the bounds 1-100. var currentCount: Int = Int(arc4random() % 100) // These are called IBOutlets and are a kind of property; they connect elements in the storyboard with the code so you can update the UI elements from code. @IBOutlet weak var countTextField: UITextField! @IBOutlet weak var slider: UISlider! @IBOutlet weak var stepper: UIStepper! override func viewDidLoad() { super.viewDidLoad() // // 1. Once the currentCount variable is set, each of the UI elements on the screen need to be updated to match the currentCount. // There is a method below that performs these steps. All you need to do perform a method call in the line below. // updateViewsWithCurrentCount() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateViewsWithCurrentCount() { // Here we are updating the different subviews in our main view with the current count. // // 2. The textfield needs to always show the current count. Fill in the blank below to set the text value of the textfield. // countTextField.text = "\(currentCount)" // // 3. Here we are setting the value property of the UISlider in the view. This causes the slider to set its handle to the // appropriate position. Fill in the blank below. // slider.value = Float(currentCount) // // 4. We also need to update the value of the UIStepper. The user will not see any change to the stepper, but it needs to have a // current value nonetheless, so when + or - is tapped, it will know what value to increment. Fill in the blanks below. // stepper.value = Double(currentCount) } // MARK: - Gesture recognizers @IBAction func viewTapped(sender: UITapGestureRecognizer) { // This method is run whenever the user taps on the blank, white view (meaning they haven't tapped any of the controls on the // view). It hides the keyboard if the user has edited the count textfield, and also updates the currentCount variable. if countTextField.isFirstResponder() { countTextField.resignFirstResponder() currentCount = Int(countTextField) // // 8. Hopefully you're seeing a pattern here. After we update the currentCount variable, what do we need to do next? Fill in // the blank below. // updateViewsWithCurrentCount() } } // MARK: - Action handlers @IBAction func sliderValueChanged(sender: UISlider) { // // 5. This method will run whenever the value of the slider is changed by the user. The "sender" object passed in as an argument // to this method represents the slider from the view. We need to take the value of the slider and use it to update the // value of our "currentCount" instance variable. Fill in the blank below. // currentCount = Int(sender.value) // // 6. Once we update the value of currentCount, we need to make sure all the UI elements on the screen are updated to keep // everything in sync. We have previously done this (look in viewDidLoad). Fill in the blank below. // updateViewsWithCurrentCount() } @IBAction func stepperValueChanged(sender: UIStepper) { // // 7. This method is run when the value of the stepper is changed by the user. If you've done steps 5 and 6 already, these steps // should look pretty familiar, hint, hint. ;) Fill in the blanks below. // currentCount = <#What goes here?#> } }
cc0-1.0
cb645b5e53ebd8e63fd98c2808f160d9
39.623853
160
0.642276
4.947486
false
false
false
false
february29/Learning
swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observables/Switch.swift
49
7523
// // Switch.swift // RxSwift // // Created by Krunoslav Zaher on 3/12/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Projects each element of an observable sequence into a new sequence of observable sequences and then transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. It is a combination of `map` + `switchLatest` operator - seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) - parameter selector: A transform function to apply to each element. - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ public func flatMapLatest<O: ObservableConvertibleType>(_ selector: @escaping (E) throws -> O) -> Observable<O.E> { return FlatMapLatest(source: asObservable(), selector: selector) } } extension ObservableType where E : ObservableConvertibleType { /** Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. Each time a new inner observable sequence is received, unsubscribe from the previous inner observable sequence. - seealso: [switch operator on reactivex.io](http://reactivex.io/documentation/operators/switch.html) - returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ public func switchLatest() -> Observable<E.E> { return Switch(source: asObservable()) } } fileprivate class SwitchSink<SourceType, S: ObservableConvertibleType, O: ObserverType> : Sink<O> , ObserverType , LockOwnerType , SynchronizedOnType where S.E == O.E { typealias E = SourceType fileprivate let _subscriptions: SingleAssignmentDisposable = SingleAssignmentDisposable() fileprivate let _innerSubscription: SerialDisposable = SerialDisposable() let _lock = RecursiveLock() // state fileprivate var _stopped = false fileprivate var _latest = 0 fileprivate var _hasLatest = false override init(observer: O, cancel: Cancelable) { super.init(observer: observer, cancel: cancel) } func run(_ source: Observable<SourceType>) -> Disposable { let subscription = source.subscribe(self) _subscriptions.setDisposable(subscription) return Disposables.create(_subscriptions, _innerSubscription) } func on(_ event: Event<E>) { synchronizedOn(event) } func performMap(_ element: SourceType) throws -> S { rxAbstractMethod() } func _synchronized_on(_ event: Event<E>) { switch event { case .next(let element): do { let observable = try performMap(element).asObservable() _hasLatest = true _latest = _latest &+ 1 let latest = _latest let d = SingleAssignmentDisposable() _innerSubscription.disposable = d let observer = SwitchSinkIter(parent: self, id: latest, _self: d) let disposable = observable.subscribe(observer) d.setDisposable(disposable) } catch let error { forwardOn(.error(error)) dispose() } case .error(let error): forwardOn(.error(error)) dispose() case .completed: _stopped = true _subscriptions.dispose() if !_hasLatest { forwardOn(.completed) dispose() } } } } final fileprivate class SwitchSinkIter<SourceType, S: ObservableConvertibleType, O: ObserverType> : ObserverType , LockOwnerType , SynchronizedOnType where S.E == O.E { typealias E = S.E typealias Parent = SwitchSink<SourceType, S, O> fileprivate let _parent: Parent fileprivate let _id: Int fileprivate let _self: Disposable var _lock: RecursiveLock { return _parent._lock } init(parent: Parent, id: Int, _self: Disposable) { _parent = parent _id = id self._self = _self } func on(_ event: Event<E>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<E>) { switch event { case .next: break case .error, .completed: _self.dispose() } if _parent._latest != _id { return } switch event { case .next: _parent.forwardOn(event) case .error: _parent.forwardOn(event) _parent.dispose() case .completed: _parent._hasLatest = false if _parent._stopped { _parent.forwardOn(event) _parent.dispose() } } } } // MARK: Specializations final fileprivate class SwitchIdentitySink<S: ObservableConvertibleType, O: ObserverType> : SwitchSink<S, S, O> where O.E == S.E { override init(observer: O, cancel: Cancelable) { super.init(observer: observer, cancel: cancel) } override func performMap(_ element: S) throws -> S { return element } } final fileprivate class MapSwitchSink<SourceType, S: ObservableConvertibleType, O: ObserverType> : SwitchSink<SourceType, S, O> where O.E == S.E { typealias Selector = (SourceType) throws -> S fileprivate let _selector: Selector init(selector: @escaping Selector, observer: O, cancel: Cancelable) { _selector = selector super.init(observer: observer, cancel: cancel) } override func performMap(_ element: SourceType) throws -> S { return try _selector(element) } } // MARK: Producers final fileprivate class Switch<S: ObservableConvertibleType> : Producer<S.E> { fileprivate let _source: Observable<S> init(source: Observable<S>) { _source = source } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { let sink = SwitchIdentitySink<S, O>(observer: observer, cancel: cancel) let subscription = sink.run(_source) return (sink: sink, subscription: subscription) } } final fileprivate class FlatMapLatest<SourceType, S: ObservableConvertibleType> : Producer<S.E> { typealias Selector = (SourceType) throws -> S fileprivate let _source: Observable<SourceType> fileprivate let _selector: Selector init(source: Observable<SourceType>, selector: @escaping Selector) { _source = source _selector = selector } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { let sink = MapSwitchSink<SourceType, S, O>(selector: _selector, observer: observer, cancel: cancel) let subscription = sink.run(_source) return (sink: sink, subscription: subscription) } }
mit
bac12194e8710b4150eb5b73edef07fb
31.991228
160
0.633741
4.856036
false
true
false
false
keyOfVv/KEYExtension
KEYExtension-macOS/Sources/DebugLog.swift
1
1061
// // DebugLog.swift // KEYExtension-macOS // // Created by Ke Yang on 18/01/2018. // Copyright © 2018 com.keyofvv. All rights reserved. // import Foundation public struct KEYExtension { public static var enabledDebugLog: Bool = false } /// 向控制台打印调试日志 /// /// - 如果`KEYExtension.enabledDebugLog`为`true`, 该函数将向控制台输出日志; 反之则不执行任何操作; /// - Parameters: /// - any: 待打印的对象/值; /// - function: 当前所在的函数, 建议使用默认值`#function`; /// - file: 当前所在的文件, 建议使用默认值`#file`; /// - line: 当前所在的行号, 建议使用默认值`#line`; public func dog(_ any: Any?, function: String = #function, file: String = #file, line: Int = #line) { guard KEYExtension.enabledDebugLog else { return } let dateFormat = DateFormatter() dateFormat.dateFormat = "HH:mm:ss.SSS" let time = dateFormat.string(from: NSDate() as Date) print("[\(time)] <\((file as NSString).lastPathComponent)> \(function) LINE(\(line)): \(any ?? "")") }
mit
d3f1f14dde8cf963d2e53c96f2550a12
29.758621
101
0.66704
2.915033
false
false
false
false
nathawes/swift
test/Driver/macabi-environment.swift
9
8504
// Tests to check that the driver finds standard library in the macabi environment. // UNSUPPORTED: windows // RUN: %swiftc_driver -sdk "" -sdk "" -driver-print-jobs -target x86_64-apple-ios13.0-macabi -sdk %S/../Inputs/clang-importer-sdk %s | %FileCheck -check-prefix=IOS13-MACABI %s // IOS13-MACABI: bin/swift // IOS13-MACABI: -target x86_64-apple-ios13.0-macabi // IOS13-MACABI: bin/ld // IOS13-MACABI-DAG: -L [[MACCATALYST_STDLIB_PATH:[^ ]+/lib/swift/maccatalyst]] // IOS13-MACABI-DAG: -L [[MACOSX_STDLIB_PATH:[^ ]+/lib/swift/macosx]] // IOS13-MACABI-DAG: -L [[MACCATALYST_SDK_STDLIB_PATH:[^ ]+/clang-importer-sdk/System/iOSSupport/usr/lib/swift]] // IOS13-MACABI-DAG: -L [[MACOSX_SDK_STDLIB_PATH:[^ ]+/clang-importer-sdk/usr/lib/swift]] // IOS13-MACABI-DAG: -rpath [[MACCATALYST_STDLIB_PATH]] // IOS13-MACABI-DAG: -rpath [[MACOSX_STDLIB_PATH]] // IOS13-MACABI-DAG: -rpath [[MACCATALYST_SDK_STDLIB_PATH]] // IOS13-MACABI-DAG: -rpath [[MACOSX_SDK_STDLIB_PATH]] // IOS13-MACABI-DAG: -platform_version mac-catalyst 13.0.0 0.0.0 // Adjust iOS versions < 13.0 to 13.0 for the linker's sake. // RUN: %swiftc_driver -sdk "" -sdk "" -driver-print-jobs -target x86_64-apple-ios12.0-macabi -sdk %S/../Inputs/clang-importer-sdk %s | %FileCheck -check-prefix=IOS12-MACABI %s // IOS12-MACABI: bin/swift // IOS12-MACABI: -target x86_64-apple-ios12.0-macabi // IOS12-MACABI: bin/ld // IOS12-MACABI-DAG: -L [[MACCATALYST_STDLIB_PATH:[^ ]+/lib/swift/maccatalyst]] // IOS12-MACABI-DAG: -L [[MACOSX_STDLIB_PATH:[^ ]+/lib/swift/macosx]] // IOS12-MACABI-DAG: -L [[MACCATALYST_SDK_STDLIB_PATH:[^ ]+/clang-importer-sdk/System/iOSSupport/usr/lib/swift]] // IOS12-MACABI-DAG: -L [[MACOSX_SDK_STDLIB_PATH:[^ ]+/clang-importer-sdk/usr/lib/swift]] // IOS12-MACABI-DAG: -rpath [[MACCATALYST_STDLIB_PATH]] // IOS12-MACABI-DAG: -rpath [[MACOSX_STDLIB_PATH]] // IOS12-MACABI-DAG: -rpath [[MACCATALYST_SDK_STDLIB_PATH]] // IOS12-MACABI-DAG: -rpath [[MACOSX_SDK_STDLIB_PATH]] // IOS12-MACABI-DAG: -platform_version mac-catalyst 13.0.0 0.0.0 // RUN: %swiftc_driver -driver-print-jobs -target arm64-apple-ios12.0-macabi -sdk %S/../Inputs/clang-importer-sdk %s | %FileCheck -check-prefix=IOS14-MACABI %s // IOS14-MACABI: -platform_version mac-catalyst 14.0.0 0.0.0 // Test using target-variant to build zippered outputs // RUN: %swiftc_driver -sdk "" -driver-print-jobs -c -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi %s | %FileCheck -check-prefix=ZIPPERED-VARIANT-OBJECT %s // ZIPPERED-VARIANT-OBJECT: bin/swift // ZIPPERED-VARIANT-OBJECT: -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi // RUN: %swiftc_driver -sdk "" -sdk "" -driver-print-jobs -emit-library -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi -module-name foo %s | %FileCheck -check-prefix=ZIPPERED-VARIANT-LIBRARY %s // ZIPPERED-VARIANT-LIBRARY: bin/swift // ZIPPERED-VARIANT-LIBRARY: -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi // ZIPPERED-VARIANT-LIBRARY: bin/ld // ZIPPERED-VARIANT-LIBRARY: -platform_version macos 10.14.0 0.0.0 -platform_version mac-catalyst 13.0.0 0.0.0 // Make sure we pass the -target-variant when creating the pre-compiled header. // RUN: %swiftc_driver -sdk "" -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi -enable-bridging-pch -import-objc-header %S/Inputs/bridging-header.h %s | %FileCheck -check-prefix=ZIPPERED-VARIANT-PCH %s // ZIPPERED-VARIANT-PCH: bin/swift // ZIPPERED-VARIANT-PCH: -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi // ZIPPERED_VARIANT-PCH -emit-pch // ZIPPERED-VARIANT-PCH: bin/swift // ZIPPERED-VARIANT-PCH: -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi // ZIPPERED-VARIANT-PCH: bin/ld // ZIPPERED-VARIANT-PCH: -platform_version macos 10.14.0 0.0.0 -platform_version mac-catalyst 13.0.0 0.0.0 // Test using 'reverse' target-variant to build zippered outputs when the primary // target is ios-macabi // RUN: %swiftc_driver -sdk "" -driver-print-jobs -c -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 %s | %FileCheck -check-prefix=REVERSE-ZIPPERED-VARIANT-OBJECT %s // REVERSE-ZIPPERED-VARIANT-OBJECT: bin/swift // REVERSE-ZIPPERED-VARIANT-OBJECT: -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 // RUN: %swiftc_driver -sdk "" -sdk "" -driver-print-jobs -emit-library -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 -module-name foo %s | %FileCheck -check-prefix=REVERSE-ZIPPERED-VARIANT-LIBRARY %s // REVERSE-ZIPPERED-VARIANT-LIBRARY: bin/swift // REVERSE-ZIPPERED-VARIANT-LIBRARY: -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 // REVERSE-ZIPPERED-VARIANT-LIBRARY: bin/ld // REVERSE-ZIPPERED-VARIANT-LIBRARY: -platform_version mac-catalyst 13.0.0 0.0.0 -platform_version macos 10.14.0 // Make sure we pass the -target-variant when creating the pre-compiled header. // RUN: %swiftc_driver -sdk "" -sdk "" -driver-print-jobs -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 -enable-bridging-pch -import-objc-header %S/Inputs/bridging-header.h %s | %FileCheck -check-prefix=REVERSE-ZIPPERED-VARIANT-PCH %s // REVERSE-ZIPPERED-VARIANT-PCH: bin/swift // REVERSE-ZIPPERED-VARIANT-PCH: -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 // REVERSE-ZIPPERED_VARIANT-PCH -emit-pch // REVERSE-ZIPPERED-VARIANT-PCH: bin/swift // REVERSE-ZIPPERED-VARIANT-PCH: -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 // REVERSE-ZIPPERED-VARIANT-PCH: bin/ld // REVERSE-ZIPPERED-VARIANT-PCH: -platform_version mac-catalyst 13.0.0 0.0.0 -platform_version macos 10.14.0 0.0.0 // RUN: not %swiftc_driver -sdk "" -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0 %s 2>&1 | %FileCheck --check-prefix=UNSUPPORTED-TARGET-VARIANT %s // RUN: not %swiftc_driver -sdk "" -target x86_64-apple-ios13.0 -target-variant x86_64-apple-macosx10.14 %s 2>&1 | %FileCheck --check-prefix=UNSUPPORTED-TARGET %s // UNSUPPORTED-TARGET-VARIANT: error: unsupported '-target-variant' value {{.*}}; use 'ios-macabi' instead // UNSUPPORTED-TARGET: error: unsupported '-target' value {{.*}}; use 'ios-macabi' instead // When compiling for iOS, pass iphoneos_version_min to the linker, not maccatalyst_version_min. // RUN: %swiftc_driver -sdk "" -driver-print-jobs -target arm64-apple-ios13.0 -sdk %S/../Inputs/clang-importer-sdk %s | %FileCheck -check-prefix=IOS13-NO-MACABI -implicit-check-not=mac-catalyst %s // IOS13-NO-MACABI: bin/swift // IOS13-NO-MACABI: -target arm64-apple-ios13.0 // IOS13-NO-MACABI: bin/ld // IOS13-NO-MACABI-DAG: -L {{[^ ]+/lib/swift/iphoneos}} // IOS13-NO-MACABI-DAG: -L {{[^ ]+/clang-importer-sdk/usr/lib/swift}} // IOS13-NO-MACABI-DAG: -platform_version ios 13.0.0 // Check reading the SDKSettings.json from an SDK and using it to map Catalyst // SDK version information. // RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi -sdk %S/Inputs/MacOSX10.15.versioned.sdk %s 2>&1 | %FileCheck -check-prefix MACOS_10_15_ZIPPERED %s // MACOS_10_15_ZIPPERED: -target-sdk-version 10.15 // MACOS_10_15_ZIPPERED: -target-variant-sdk-version 13.1 // MACOS_10_15_ZIPPERED: -platform_version macos 10.14.0 10.15.0 // MACOS_10_15_ZIPPERED: -platform_version mac-catalyst 13.0.0 13.1.0 // RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi -sdk %S/Inputs/MacOSX10.15.4.versioned.sdk %s 2>&1 | %FileCheck -check-prefix MACOS_10_15_4_ZIPPERED %s // MACOS_10_15_4_ZIPPERED: -target-sdk-version 10.15.4 // MACOS_10_15_4_ZIPPERED: -target-variant-sdk-version 13.4 // MACOS_10_15_4_ZIPPERED: -platform_version macos 10.14.0 10.15.4 // MACOS_10_15_4_ZIPPERED: -platform_version mac-catalyst 13.0.0 13.4.0 // RUN: %swiftc_driver -sdk "" -driver-print-jobs -target-variant x86_64-apple-macosx10.14 -target x86_64-apple-ios13.0-macabi -sdk %S/Inputs/MacOSX10.15.4.versioned.sdk %s 2>&1 | %FileCheck -check-prefix MACOS_10_15_4_REVERSE_ZIPPERED %s // MACOS_10_15_4_REVERSE_ZIPPERED: -target-sdk-version 13.4 // MACOS_10_15_4_REVERSE_ZIPPERED: -target-variant-sdk-version 10.15.4 // MACOS_10_15_4_REVERSE_ZIPPERED: -platform_version mac-catalyst 13.0.0 13.4.0 // MACOS_10_15_4_REVERSE_ZIPPERED: -platform_version macos 10.14.0 10.15.4
apache-2.0
f2fdf306736f694dc0f135cd4df55eb7
67.580645
265
0.731538
2.658331
false
false
false
false
alexhillc/AXPhotoViewer
Source/Integrations/SDWebImageIntegration.swift
1
3479
// // SDWebImageIntegration.swift // AXPhotoViewer // // Created by Alex Hill on 5/20/17. // Copyright © 2017 Alex Hill. All rights reserved. // #if canImport(SDWebImage) import SDWebImage class SDWebImageIntegration: NSObject, AXNetworkIntegrationProtocol { weak var delegate: AXNetworkIntegrationDelegate? fileprivate var downloadOperations = NSMapTable<AXPhotoProtocol, SDWebImageOperation>(keyOptions: .strongMemory, valueOptions: .strongMemory) func loadPhoto(_ photo: AXPhotoProtocol) { if photo.imageData != nil || photo.image != nil { AXDispatchUtils.executeInBackground { [weak self] in guard let `self` = self else { return } self.delegate?.networkIntegration(self, loadDidFinishWith: photo) } return } guard let url = photo.url else { return } let progress: SDWebImageDownloaderProgressBlock = { [weak self] (receivedSize, expectedSize, targetURL) in AXDispatchUtils.executeInBackground { [weak self] in guard let `self` = self else { return } self.delegate?.networkIntegration?(self, didUpdateLoadingProgress: CGFloat(receivedSize) / CGFloat(expectedSize), for: photo) } } let completion: SDInternalCompletionBlock = { [weak self] (image, data, error, cacheType, finished, imageURL) in guard let `self` = self else { return } self.downloadOperations.removeObject(forKey: photo) if let data = data, data.containsGIF() { photo.imageData = data AXDispatchUtils.executeInBackground { [weak self] in guard let `self` = self else { return } self.delegate?.networkIntegration(self, loadDidFinishWith: photo) } } else if let image = image { photo.image = image AXDispatchUtils.executeInBackground { [weak self] in guard let `self` = self else { return } self.delegate?.networkIntegration(self, loadDidFinishWith: photo) } } else { let error = NSError( domain: AXNetworkIntegrationErrorDomain, code: AXNetworkIntegrationFailedToLoadErrorCode, userInfo: nil ) AXDispatchUtils.executeInBackground { [weak self] in guard let `self` = self else { return } self.delegate?.networkIntegration(self, loadDidFailWith: error, for: photo) } } } guard let operation = SDWebImageManager.shared.loadImage(with: url, options: [], progress: progress, completed: completion) else { return } self.downloadOperations.setObject(operation, forKey: photo) } func cancelLoad(for photo: AXPhotoProtocol) { guard let downloadOperation = self.downloadOperations.object(forKey: photo) else { return } downloadOperation.cancel() } func cancelAllLoads() { let enumerator = self.downloadOperations.objectEnumerator() while let downloadOperation = enumerator?.nextObject() as? SDWebImageOperation { downloadOperation.cancel() } self.downloadOperations.removeAllObjects() } } #endif
mit
8d58981285b4a61b8ba0147cf5572b0a
39.44186
147
0.598045
5.425897
false
false
false
false
kuangniaokuang/Cocktail-Pro
smartmixer/smartmixer/Home/HomeDirectionSync.swift
1
6490
// // HomeDirectionsSync.swift // smartmixer // // Created by 姚俊光 on 14/10/8. // Copyright (c) 2014年 smarthito. All rights reserved. // import UIKit /** * 该类是用于处理获取主页更新信息的网络处理部分, * 该部分的工作首先获取一个当前服务器的版本号与本地匹配, * 若本地版本与服务器不一致都进行下载更新 */ //自定义一个搜索设置完毕开始搜索的消息 protocol HomeDirectionSyncDelegate:NSObjectProtocol{ func homeDirectionSync(sender:HomeDirectionSync,NeedRefresh refresh:Bool) } class HomeDirectionSync { init(){ } //代理 var delegate:HomeDirectionSyncDelegate! //主页数据存储的基地址 let baseUrl:String="http://???????/cocktailpro/homedirections/" //是否是强制更新 var byForce:Bool = false //子线程的数量 var subthread:Int=0 //更新数据的调用 func UpdateHomeSync(){ //第一种 新建线程 NSThread.detachNewThreadSelector("getServerVersionSync:", toTarget:self,withObject:self) } @objc func getServerVersionSync(sender:AnyObject){ var owner = sender as HomeDirectionSync var request = HTTPTask() request.GET(owner.baseUrl+"version.txt", parameters: nil, success: {(response: HTTPResponse) in if response.responseObject != nil { var localVersion:String?=NSUserDefaults.standardUserDefaults().stringForKey("HomeDirection") if(localVersion==nil){ localVersion="" } let data = response.responseObject as NSData let remoteVersion = NSString(data: data, encoding: NSUTF8StringEncoding) if(localVersion != remoteVersion || owner.byForce){//两地的版本字符串不匹配或是强制更新,开始下载新的 let fileManager = NSFileManager.defaultManager() var isDir:ObjCBool=false if !fileManager.fileExistsAtPath(applicationDocumentsPath + "/homedirections/",isDirectory: &isDir) { fileManager.createDirectoryAtPath(applicationDocumentsPath + "/homedirections/", withIntermediateDirectories: true, attributes: nil, error: nil) } NSUserDefaults.standardUserDefaults().setObject(remoteVersion, forKey: "HomeDirection") self.getLatestSync(owner) }else{ if(owner.delegate != nil){ owner.delegate.homeDirectionSync(owner, NeedRefresh: false) } } } },failure: {(error: NSError, response: HTTPResponse?) in if(owner.delegate != nil){ owner.delegate.homeDirectionSync(owner, NeedRefresh: false) } }) } //获取最新的文件 func getLatestSync(sender:HomeDirectionSync){ var request = HTTPTask() request.download(sender.baseUrl+"latest.zip", parameters: nil, progress: {(complete: Double) in }, success: {(response: HTTPResponse) in if response.responseObject != nil { //数据下载成功,将数据解压到用户牡蛎中 var zip = ZipArchive() zip.UnzipOpenFile((response.responseObject! as NSURL).path) needRefresh=zip.UnzipFileTo(applicationDocumentsPath+"/homedirections/", overWrite: true) if(needRefresh && sender.delegate != nil){//唯一的操作成功的返回 sender.delegate.homeDirectionSync(sender, NeedRefresh: true) return } } if(sender.delegate != nil){ sender.delegate.homeDirectionSync(sender, NeedRefresh: false) } } ,failure: {(error: NSError, response: HTTPResponse?) in if(sender.delegate != nil){ sender.delegate.homeDirectionSync(sender, NeedRefresh: false) } }) } /* //分析文件,开始下载数据信息 func analysisDescription(tmpUrl:NSURL,MainThread sender:HomeDirectionSync){ let jsonData = NSData(contentsOfURL: tmpUrl) let rootDescription = NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary let version:NSString = rootDescription["version"] as NSString NSUserDefaults.standardUserDefaults().setObject(version, forKey: "HomeDirection") let databody:NSArray = rootDescription["data"] as NSArray sender.subthread = databody.count for item in databody { var str=item["image"] as String if(str != ""){ getImageSync(str,MainThread:sender) }else{ sender.subthread-- } } } //异步下载图片信息 func getImageSync(image:String,MainThread sender:HomeDirectionSync){ var request = HTTPTask() request.download(sender.baseUrl+image, parameters: nil, progress: {(complete: Double) in }, success: {(response: HTTPResponse) in if response.responseObject != nil { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let newPath = NSURL(fileURLWithPath:applicationDocumentsPath+"/homedirections/"+image) NSLog("\(newPath)") let fileManager = NSFileManager.defaultManager() fileManager.removeItemAtURL(newPath!, error: nil) var error:NSError?=nil if !fileManager.moveItemAtURL(response.responseObject! as NSURL, toURL: newPath!, error: &error) { NSLog(error!.localizedDescription) } sender.subthread-- if(sender.subthread==0 && sender.delegate != nil){ sender.delegate.homeDirectionSync(sender, NeedRefresh: true) } } } ,failure: {(error: NSError) in if(sender.delegate != nil){ sender.delegate.homeDirectionSync(sender, NeedRefresh: false) } }) } */ }
apache-2.0
9842575c09f1323fa615eb91d1111068
40.013514
168
0.582372
4.922952
false
false
false
false
mpangburn/RayTracer
RayTracer/View Controllers/AboutTableViewController.swift
1
2368
// // AboutTableViewController.swift // RayTracer // // Created by Michael Pangburn on 7/27/17. // Copyright © 2017 Michael Pangburn. All rights reserved. // import UIKit private let aboutCellReuseIdentifier = "AboutCell" final class AboutTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: aboutCellReuseIdentifier) } enum Row: Int { case howItWorks // case tipsAndTricks case frequentlyAskedQuestions static let count = 2 } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Row.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: aboutCellReuseIdentifier, for: indexPath) cell.accessoryType = .disclosureIndicator switch Row(rawValue: indexPath.row)! { case .howItWorks: cell.textLabel?.text = NSLocalizedString("How It Works", comment: "The title text for the cell describing how ray tracing works") // case .tipsAndTricks: // cell.textLabel?.text = NSLocalizedString("Tips and Tricks", comment: "The title text for the cell describing tips and tricks for using the application") case .frequentlyAskedQuestions: cell.textLabel?.text = NSLocalizedString("Frequently Asked Questions (FAQs)", comment: "The title text the cell describing frequently asked questions in using the application") } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let sender = tableView.cellForRow(at: indexPath) switch Row(rawValue: indexPath.row)! { case .howItWorks: self.show(HowItWorksTableViewController(), sender: sender) // case .tipsAndTricks: // self.show(TipsAndTricksTableViewController(), sender: sender) case .frequentlyAskedQuestions: self.show(FrequentlyAskedQuestionsTableViewController(), sender: sender) } } }
mit
a70649e04b2a03e8f4380271a48108c4
34.328358
188
0.690325
4.983158
false
false
false
false
huonw/swift
test/IRGen/objc_properties.swift
3
14779
// This file is also used by objc_properties_ios.swift. // RUN: %swift -target x86_64-apple-macosx10.11 %s -disable-target-os-checking -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-NEW %s // RUN: %swift -target x86_64-apple-macosx10.10 %s -disable-target-os-checking -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-OLD %s // REQUIRES: OS=macosx // REQUIRES: objc_interop @objc class SomeObject { var readonly : SomeObject { get { return self } } var readwrite : SomeObject { get { return bareIvar } set { bareIvar = newValue } } var bareIvar : SomeObject @objc(wobble) var wibble : SomeObject init() { bareIvar = SomeObject() wibble = SomeObject() } static var sharedProp: Int64 = 0 } extension SomeObject { var extensionProperty : SomeObject { get { return self } set { bareIvar = self } } class var extensionClassProp : SomeObject.Type { return self } } // <rdar://problem/16952186> Crash with @lazy in @objc class @objc class LazyPropertyCrash { lazy var applicationFilesDirectory: LazyPropertyCrash = LazyPropertyCrash() } // <rdar://16909436> @objc class Tree { weak var parent: Tree? } // <rdar://problem/17127126> swift compiler segfaults trying to generate a setter for a @lazy property in a subclass of NSObject func test17127126(f : Class17127126) { f.x = 2 // this is the problem } @objc class Class17127126 { lazy var x = 1 } @objc protocol Proto { var value: Int { get } static var sharedInstance: AnyObject { get set } } // CHECK-NEW: [[SHARED_NAME:@.*]] = private unnamed_addr constant [11 x i8] c"sharedProp\00" // CHECK-NEW: [[SHARED_ATTRS:@.*]] = private unnamed_addr constant [17 x i8] c"Tq,N,VsharedProp\00" // CHECK-NEW: @_CLASS_PROPERTIES__TtC15objc_properties10SomeObject = private constant { {{.*}}] } { // CHECK-NEW: i32 16, // CHECK-NEW: i32 1, // CHECK-NEW: [1 x { i8*, i8* }] [{ // CHECK-NEW: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SHARED_NAME]], i64 0, i64 0), // CHECK-NEW: i8* getelementptr inbounds ([17 x i8], [17 x i8]* [[SHARED_ATTRS]], i64 0, i64 0) // CHECK-NEW: }] // CHECK-NEW: }, section "__DATA, __objc_const", align 8 // CHECK: @_METACLASS_DATA__TtC15objc_properties10SomeObject = private constant { {{.*}} } { // CHECK-SAME: i32 {{[0-9]+}}, i32 {{[0-9]+}}, i32 {{[0-9]+}}, i32 {{[0-9]+}}, // CHECK-SAME: i8* null, // CHECK-SAME: i8* getelementptr inbounds ([{{.+}} x i8], [{{.+}} x i8]* {{@.+}}, i64 0, i64 0), // CHECK-SAME: { {{.+}} }* @_CLASS_METHODS__TtC15objc_properties10SomeObject, // CHECK-SAME: i8* null, i8* null, i8* null, // CHECK-NEW-SAME: { {{.+}} }* @_CLASS_PROPERTIES__TtC15objc_properties10SomeObject // CHECK-OLD-SAME: i8* null // CHECK-SAME: }, section "__DATA, __objc_const", align 8 // CHECK: [[GETTER_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00" // CHECK: [[SETTER_SIGNATURE:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00" // CHECK: @_INSTANCE_METHODS__TtC15objc_properties10SomeObject = private constant { {{.*}}] } { // CHECK: i32 24, // CHECK: i32 8, // CHECK: [8 x { i8*, i8*, i8* }] [{ // CHECK: i8* getelementptr inbounds ([9 x i8], [9 x i8]* @"\01L_selector_data(readonly)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE0:%.*]]* ([[OPAQUE1:%.*]]*, i8*)* @"$S15objc_properties10SomeObjectC8readonlyACvgTo" to i8*) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(readwrite)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE0]]* ([[OPAQUE1]]*, i8*)* @"$S15objc_properties10SomeObjectC9readwriteACvgTo" to i8*) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(setReadwrite:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE3:%.*]]*, i8*, [[OPAQUE4:%.*]]*)* @"$S15objc_properties10SomeObjectC9readwriteACvsTo" to i8*) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([9 x i8], [9 x i8]* @"\01L_selector_data(bareIvar)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE0]]* ([[OPAQUE1]]*, i8*)* @"$S15objc_properties10SomeObjectC8bareIvarACvgTo" to i8*) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([13 x i8], [13 x i8]* @"\01L_selector_data(setBareIvar:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE3]]*, i8*, [[OPAQUE4]]*)* @"$S15objc_properties10SomeObjectC8bareIvarACvsTo" to i8*) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(wobble)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (%0* (%0*, i8*)* @"$S15objc_properties10SomeObjectC6wibbleACvgTo" to i8*) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"\01L_selector_data(setWobble:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void (%0*, i8*, %0*)* @"$S15objc_properties10SomeObjectC6wibbleACvsTo" to i8*) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE5:%.*]]* ([[OPAQUE6:%.*]]*, i8*)* @"$S15objc_properties10SomeObjectCACycfcTo" to i8*) // CHECK: }] // CHECK: }, section "__DATA, __objc_const", align 8 // This appears earlier because it's also used in an ivar description. // CHECK: [[BAREIVAR_NAME:@.*]] = private unnamed_addr constant [9 x i8] c"bareIvar\00" // CHECK: [[READONLY_NAME:@.*]] = private unnamed_addr constant [9 x i8] c"readonly\00" // CHECK: [[READONLY_ATTRS:@.*]] = private unnamed_addr constant [42 x i8] c"T@\22_TtC15objc_properties10SomeObject\22,N,R\00" // CHECK: [[READWRITE_NAME:@.*]] = private unnamed_addr constant [10 x i8] c"readwrite\00" // CHECK: [[READWRITE_ATTRS:@.*]] = private unnamed_addr constant [42 x i8] c"T@\22_TtC15objc_properties10SomeObject\22,N,&\00" // CHECK: [[BAREIVAR_ATTRS:@.*]] = private unnamed_addr constant [52 x i8] c"T@\22_TtC15objc_properties10SomeObject\22,N,&,VbareIvar\00" // CHECK: [[WIBBLE_NAME:@.*]] = private unnamed_addr constant [7 x i8] c"wobble\00" // CHECK: [[WIBBLE_ATTRS:@.*]] = private unnamed_addr constant [50 x i8] c"T@\22_TtC15objc_properties10SomeObject\22,N,&,Vwibble\00" // CHECK: @_PROPERTIES__TtC15objc_properties10SomeObject = private constant { {{.*}}] } { // CHECK: i32 16, // CHECK: i32 4, // CHECK: [4 x { i8*, i8* }] [{ // CHECK: i8* getelementptr inbounds ([9 x i8], [9 x i8]* [[READONLY_NAME]], i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([42 x i8], [42 x i8]* [[READONLY_ATTRS]], i64 0, i64 0) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([10 x i8], [10 x i8]* [[READWRITE_NAME]], i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([42 x i8], [42 x i8]* [[READWRITE_ATTRS]], i64 0, i64 0) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([9 x i8], [9 x i8]* [[BAREIVAR_NAME]], i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([52 x i8], [52 x i8]* [[BAREIVAR_ATTRS]], i64 0, i64 0) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[WIBBLE_NAME]], i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([50 x i8], [50 x i8]* [[WIBBLE_ATTRS]], i64 0, i64 0) // CHECK: }] // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK: @_DATA__TtC15objc_properties10SomeObject = private constant { {{.+}} } { // CHECK: i32 {{[0-9]+}}, i32 {{[0-9]+}}, i32 {{[0-9]+}}, i32 {{[0-9]+}}, // CHECK: i8* null, // CHECK: i8* getelementptr inbounds ([{{.+}} x i8], [{{.+}} x i8]* {{@.+}}, i64 0, i64 0), // CHECK: { {{.+}} }* @_INSTANCE_METHODS__TtC15objc_properties10SomeObject, // CHECK: i8* null, // CHECK: { {{.+}} }* @_IVARS__TtC15objc_properties10SomeObject, // CHECK: i8* null, // CHECK: { {{.+}} }* @_PROPERTIES__TtC15objc_properties10SomeObject // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC15objc_properties10SomeObject_$_objc_properties" = private constant { {{.*}}] } { // CHECK: i32 24, // CHECK: i32 2, // CHECK: [2 x { i8*, i8*, i8* }] [{ // CHECK: { i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(extensionProperty)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE0]]* ([[OPAQUE1]]*, i8*)* @"$S15objc_properties10SomeObjectC17extensionPropertyACvgTo" to i8*) // CHECK: }, { // CHECK: i8* getelementptr inbounds ([22 x i8], [22 x i8]* @"\01L_selector_data(setExtensionProperty:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE3]]*, i8*, [[OPAQUE4]]*)* @"$S15objc_properties10SomeObjectC17extensionPropertyACvsTo" to i8*) // CHECK: }] // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK: [[EXTENSIONPROPERTY_NAME:@.*]] = private unnamed_addr constant [18 x i8] c"extensionProperty\00" // CHECK: @"_CATEGORY_PROPERTIES__TtC15objc_properties10SomeObject_$_objc_properties" = private constant { {{.*}}] } { // CHECK: i32 16, // CHECK: i32 1, // CHECK: [1 x { i8*, i8* }] [{ // CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* [[EXTENSIONPROPERTY_NAME]], i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([42 x i8], [42 x i8]* [[READWRITE_ATTRS]], i64 0, i64 0) // CHECK: }] // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK-NEW: [[EXTENSIONCLASSPROPERTY_NAME:@.*]] = private unnamed_addr constant [19 x i8] c"extensionClassProp\00" // CHECK-NEW: [[EXTENSIONCLASSPROPERTY_ATTRS:@.*]] = private unnamed_addr constant [7 x i8] c"T#,N,R\00" // CHECK-NEW: @"_CATEGORY_CLASS_PROPERTIES__TtC15objc_properties10SomeObject_$_objc_properties" = private constant { {{.*}}] } { // CHECK-NEW: i32 16, // CHECK-NEW: i32 1, // CHECK-NEW: [1 x { i8*, i8* }] [{ // CHECK-NEW: i8* getelementptr inbounds ([19 x i8], [19 x i8]* [[EXTENSIONCLASSPROPERTY_NAME]], i64 0, i64 0), // CHECK-NEW: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[EXTENSIONCLASSPROPERTY_ATTRS]], i64 0, i64 0) // CHECK-NEW: }] // CHECK-NEW: }, section "__DATA, __objc_const", align 8 // CHECK: @"_CATEGORY__TtC15objc_properties10SomeObject_$_objc_properties" = private constant { {{.+}} } { // CHECK: i8* getelementptr inbounds ([{{.+}} x i8], [{{.+}} x i8]* {{@.+}}, i64 0, i64 0), // CHECK: %swift.type* bitcast (i64* getelementptr inbounds (<{ {{.+}} }>* @"$S15objc_properties10SomeObjectCMf", i32 0, i32 2) to %swift.type*), // CHECK: { {{.+}} }* @"_CATEGORY_INSTANCE_METHODS__TtC15objc_properties10SomeObject_$_objc_properties", // CHECK: { {{.+}} }* @"_CATEGORY_CLASS_METHODS__TtC15objc_properties10SomeObject_$_objc_properties", // CHECK: i8* null, // CHECK: { {{.+}} }* @"_CATEGORY_PROPERTIES__TtC15objc_properties10SomeObject_$_objc_properties", // CHECK-NEW: { {{.+}} }* @"_CATEGORY_CLASS_PROPERTIES__TtC15objc_properties10SomeObject_$_objc_properties", // CHECK-OLD: i8* null, // CHECK: i32 60 // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK: @_INSTANCE_METHODS__TtC15objc_properties4Tree = // CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(parent)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (%2* (%2*, i8*)* @"$S15objc_properties4TreeC6parentACSgXwvgTo" to i8*) // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"\01L_selector_data(setParent:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void (%2*, i8*, %2*)* @"$S15objc_properties4TreeC6parentACSgXwvsTo" to i8*) // CHECK: @_PROTOCOL__TtP15objc_properties5Proto_ = private constant { {{.+}} } { // CHECK: i8* null, // CHECK: i8* getelementptr inbounds ([{{.+}} x i8], [{{.+}} x i8]* {{@.+}}, i64 0, i64 0), // CHECK: i8* null, // CHECK: { {{.+}} }* @_PROTOCOL_INSTANCE_METHODS__TtP15objc_properties5Proto_, // CHECK: { {{.+}} }* @_PROTOCOL_CLASS_METHODS__TtP15objc_properties5Proto_, // CHECK: i8* null, // CHECK: i8* null, // CHECK: { {{.+}} }* @_PROTOCOL_PROPERTIES__TtP15objc_properties5Proto_, // CHECK: i32 96, i32 1, // CHECK: [{{.+}}]* @_PROTOCOL_METHOD_TYPES__TtP15objc_properties5Proto_, // CHECK: i8* null, // CHECK-NEW: { {{.+}} }* @_PROTOCOL_CLASS_PROPERTIES__TtP15objc_properties5Proto_ // CHECK-OLD: i8* null // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK: [[PROTOCOLPROPERTY_NAME:@.+]] = private unnamed_addr constant [6 x i8] c"value\00" // CHECK: [[PROTOCOLPROPERTY_ATTRS:@.+]] = private unnamed_addr constant [7 x i8] c"Tq,N,R\00" // CHECK: @_PROTOCOL_PROPERTIES__TtP15objc_properties5Proto_ = private constant { {{.*}}] } { // CHECK: i32 16, // CHECK: i32 1, // CHECK: [1 x { i8*, i8* }] [{ // CHECK: i8* getelementptr inbounds ([6 x i8], [6 x i8]* [[PROTOCOLPROPERTY_NAME]], i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[PROTOCOLPROPERTY_ATTRS]], i64 0, i64 0) // CHECK: }] // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK-NEW: [[PROTOCOLCLASSPROPERTY_NAME:@.+]] = private unnamed_addr constant [15 x i8] c"sharedInstance\00" // CHECK-NEW: [[PROTOCOLCLASSPROPERTY_ATTRS:@.+]] = private unnamed_addr constant [7 x i8] c"T@,N,&\00" // CHECK-NEW: @_PROTOCOL_CLASS_PROPERTIES__TtP15objc_properties5Proto_ = private constant { {{.*}}] } { // CHECK-NEW: i32 16, // CHECK-NEW: i32 1, // CHECK-NEW: [1 x { i8*, i8* }] [{ // CHECK-NEW: i8* getelementptr inbounds ([15 x i8], [15 x i8]* [[PROTOCOLCLASSPROPERTY_NAME]], i64 0, i64 0), // CHECK-NEW: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[PROTOCOLCLASSPROPERTY_ATTRS]], i64 0, i64 0) // CHECK-NEW: }] // CHECK-NEW: }, section "__DATA, __objc_const", align 8
apache-2.0
886d161f73d21c2186804dfb2f6345e4
51.407801
193
0.61858
2.98928
false
false
false
false
BigxMac/firefox-ios
Client/Frontend/Browser/BrowserViewController.swift
1
89701
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import WebKit import Shared import Storage import SnapKit import XCGLogger import Alamofire private let log = XCGLogger.defaultInstance() private let OKString = NSLocalizedString("OK", comment: "OK button") private let CancelString = NSLocalizedString("Cancel", comment: "Cancel button") private let KVOLoading = "loading" private let KVOEstimatedProgress = "estimatedProgress" private struct BrowserViewControllerUX { private static let ToolbarBaseAnimationDuration: CGFloat = 0.3 private static let BackgroundColor = UIConstants.AppBackgroundColor private static let ShowHeaderTapAreaHeight: CGFloat = 32 } class BrowserViewController: UIViewController { private var urlBar: URLBarView! private var readerModeBar: ReaderModeBarView? private var statusBarOverlay: UIView! private var toolbar: BrowserToolbar? private var homePanelController: HomePanelViewController? private var searchController: SearchViewController? private var webViewContainer: UIView! private let uriFixup = URIFixup() private var screenshotHelper: ScreenshotHelper! private var homePanelIsInline = false private var searchLoader: SearchLoader! private let snackBars = UIView() private let auralProgress = AuralProgressBar() private weak var tabTrayController: TabTrayController! private let profile: Profile private let tabManager: TabManager // These views wrap the urlbar and toolbar to provide background effects on them private var header: UIView! private var footer: UIView! private var footerBackground: UIView! private var topTouchArea: UIButton! // Scroll management properties private var previousScroll: CGPoint? private var headerConstraint: Constraint? private var headerConstraintOffset: CGFloat = 0 private var footerConstraint: Constraint? private var footerConstraintOffset: CGFloat = 0 private var readerConstraint: Constraint? private var readerConstraintOffset: CGFloat = 0 private var keyboardState: KeyboardState? let WhiteListedUrls = ["\\/\\/itunes\\.apple\\.com\\/"] // Tracking navigation items to record history types. // TODO: weak references? var ignoredNavigation = Set<WKNavigation>() var typedNavigation = [WKNavigation: VisitType]() var navigationToolbar: BrowserToolbarProtocol { return toolbar ?? urlBar } init(profile: Profile, tabManager: TabManager) { self.profile = profile self.tabManager = tabManager super.init(nibName: nil, bundle: nil) didInit() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } private func didInit() { screenshotHelper = BrowserScreenshotHelper(controller: self) tabManager.addDelegate(self) tabManager.addNavigationDelegate(self) } override func preferredStatusBarStyle() -> UIStatusBarStyle { if header == nil { return UIStatusBarStyle.LightContent } if header.transform.ty == 0 { return UIStatusBarStyle.LightContent } return UIStatusBarStyle.Default } func shouldShowToolbarForTraitCollection(previousTraitCollection: UITraitCollection) -> Bool { return previousTraitCollection.verticalSizeClass != .Compact && previousTraitCollection.horizontalSizeClass != .Regular } private func updateToolbarStateForTraitCollection(newCollection: UITraitCollection) { let showToolbar = shouldShowToolbarForTraitCollection(newCollection) urlBar.setShowToolbar(!showToolbar) toolbar?.removeFromSuperview() toolbar?.browserToolbarDelegate = nil footerBackground?.removeFromSuperview() footerBackground = nil toolbar = nil if showToolbar { toolbar = BrowserToolbar() toolbar?.browserToolbarDelegate = self footerBackground = wrapInEffect(toolbar!, parent: footer) } view.setNeedsUpdateConstraints() if let home = homePanelController { home.view.setNeedsUpdateConstraints() } if let tab = tabManager.selectedTab { updateNavigationToolbarStates(tab, webView: tab.webView!) let isPage = (tab.displayURL != nil) ? isWebPage(tab.displayURL!) : false navigationToolbar.updatePageStatus(isWebPage: isPage) navigationToolbar.updateReloadStatus(tab.loading ?? false) } } override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator) updateToolbarStateForTraitCollection(newCollection) // WKWebView looks like it has a bug where it doesn't invalidate it's visible area when the user // performs a device rotation. Since scrolling calls // _updateVisibleContentRects (https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/API/Cocoa/WKWebView.mm#L1430) // this method nudges the web view's scroll view by a single pixel to force it to invalidate. if let scrollView = self.tabManager.selectedTab?.webView?.scrollView { let contentOffset = scrollView.contentOffset coordinator.animateAlongsideTransition({ context in self.updateHeaderFooterConstraintsAndAlpha( headerOffset: 0, footerOffset: 0, readerOffset: 0, alpha: 1) self.view.layoutIfNeeded() scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y + 1), animated: true) }, completion: { context in scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y), animated: false) }) } } func SELstatusBarFrameWillChange(notification: NSNotification) { if let statusBarFrame = notification.userInfo![UIApplicationStatusBarFrameUserInfoKey] as? NSValue { showToolbars(animated: false) self.view.setNeedsUpdateConstraints() } } func SELtappedTopArea() { showToolbars(animated: true, completion: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillChangeStatusBarFrameNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: BookmarkStatusChangedNotification, object: nil) } override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELstatusBarFrameWillChange:", name: UIApplicationWillChangeStatusBarFrameNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELBookmarkStatusDidChange:", name: BookmarkStatusChangedNotification, object: nil) KeyboardHelper.defaultHelper.addDelegate(self) webViewContainer = UIView() view.addSubview(webViewContainer) // Temporary work around for covering the non-clipped web view content statusBarOverlay = UIView() statusBarOverlay.backgroundColor = BrowserViewControllerUX.BackgroundColor view.addSubview(statusBarOverlay) topTouchArea = UIButton() topTouchArea.addTarget(self, action: "SELtappedTopArea", forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(topTouchArea) // Setup the URL bar, wrapped in a view to get transparency effect urlBar = URLBarView() urlBar.setTranslatesAutoresizingMaskIntoConstraints(false) urlBar.delegate = self urlBar.browserToolbarDelegate = self header = wrapInEffect(urlBar, parent: view, backgroundColor: nil) searchLoader = SearchLoader(history: profile.history, urlBar: urlBar) footer = UIView() self.view.addSubview(footer) footer.addSubview(snackBars) snackBars.backgroundColor = UIColor.clearColor() self.updateToolbarStateForTraitCollection(self.traitCollection) } func loadQueuedTabs() { log.debug("Loading queued tabs.") // This assumes that the DB returns rows in some kind of sane order. // It does in practice, so WFM. self.profile.queue.getQueuedTabs() >>== { c in log.debug("Queue. Count: \(c.count).") if c.count > 0 { var urls = [NSURL]() for (let r) in c { if let url = r?.url.asURL { log.debug("Queuing \(url).") urls.append(url) } } if !urls.isEmpty { dispatch_async(dispatch_get_main_queue()) { self.tabManager.addTabsForURLs(urls, zombie: false) } } } // Clear *after* making an attempt to open. We're making a bet that // it's better to run the risk of perhaps opening twice on a crash, // rather than losing data. self.profile.queue.clearQueuedTabs() } } func startTrackingAccessibilityStatus() { NSNotificationCenter.defaultCenter().addObserverForName(UIAccessibilityVoiceOverStatusChanged, object: nil, queue: nil) { (notification) -> Void in self.auralProgress.hidden = !UIAccessibilityIsVoiceOverRunning() } auralProgress.hidden = !UIAccessibilityIsVoiceOverRunning() } func stopTrackingAccessibilityStatus() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIAccessibilityVoiceOverStatusChanged, object: nil) auralProgress.hidden = true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // On iPhone, if we are about to show the On-Boarding, blank out the browser so that it does // not flash before we present. This change of alpha also participates in the animation when // the intro view is dismissed. if UIDevice.currentDevice().userInterfaceIdiom == .Phone { self.view.alpha = (profile.prefs.intForKey(IntroViewControllerSeenProfileKey) != nil) ? 1.0 : 0.0 } if tabManager.count == 0 { // Restore tabs if not disabled by the TestAppDelegate or because we crashed previously if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate where appDelegate.shouldRestoreTabs() { tabManager.restoreTabs() } // If restoring tabs failed, was disable, or there was nothing to restore, create an initial tab if tabManager.count == 0 { let tab = tabManager.addTab() tabManager.selectTab(tab) } } } override func viewDidAppear(animated: Bool) { startTrackingAccessibilityStatus() presentIntroViewController() super.viewDidAppear(animated) } override func viewDidDisappear(animated: Bool) { stopTrackingAccessibilityStatus() } override func updateViewConstraints() { super.updateViewConstraints() statusBarOverlay.snp_remakeConstraints { make in make.left.right.equalTo(self.view) make.height.equalTo(UIApplication.sharedApplication().statusBarFrame.height) make.bottom.equalTo(header.snp_top) } topTouchArea.snp_remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight) } urlBar.snp_remakeConstraints { make in make.edges.equalTo(self.header) } header.snp_remakeConstraints { make in let topLayoutGuide = self.topLayoutGuide as! UIView self.headerConstraint = make.top.equalTo(topLayoutGuide.snp_bottom).constraint make.height.equalTo(UIConstants.ToolbarHeight) make.left.right.equalTo(self.view) } header.setNeedsUpdateConstraints() readerModeBar?.snp_remakeConstraints { make in self.readerConstraint = make.top.equalTo(self.header.snp_bottom).constraint make.height.equalTo(UIConstants.ToolbarHeight) make.leading.trailing.equalTo(self.view) } webViewContainer.snp_remakeConstraints { make in make.left.right.equalTo(self.view) if let readerModeBarBottom = readerModeBar?.snp_bottom { make.top.equalTo(readerModeBarBottom) } else { make.top.equalTo(self.header.snp_bottom) } if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp_top) } else { make.bottom.equalTo(self.view) } } // Setup the bottom toolbar toolbar?.snp_remakeConstraints { make in make.edges.equalTo(self.footerBackground!) make.height.equalTo(UIConstants.ToolbarHeight) } footer.snp_remakeConstraints { [unowned self] make in self.footerConstraint = make.bottom.equalTo(self.view.snp_bottom).constraint make.top.equalTo(self.snackBars.snp_top) make.leading.trailing.equalTo(self.view) } adjustFooterSize(top: nil) footerBackground?.snp_remakeConstraints { make in make.bottom.left.right.equalTo(self.footer) make.height.equalTo(UIConstants.ToolbarHeight) } urlBar.setNeedsUpdateConstraints() // Remake constraints even if we're already showing the home controller. // The home controller may change sizes if we tap the URL bar while on about:home. homePanelController?.view.snp_remakeConstraints { make in make.top.equalTo(self.urlBar.snp_bottom) make.left.right.equalTo(self.view) if self.homePanelIsInline { make.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom) } else { make.bottom.equalTo(self.view.snp_bottom) } } } private func wrapInEffect(view: UIView, parent: UIView) -> UIView { return self.wrapInEffect(view, parent: parent, backgroundColor: UIColor.clearColor()) } private func wrapInEffect(view: UIView, parent: UIView, backgroundColor: UIColor?) -> UIView { let effect = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight)) effect.setTranslatesAutoresizingMaskIntoConstraints(false) if let background = backgroundColor { view.backgroundColor = backgroundColor } effect.addSubview(view) parent.addSubview(effect) return effect } private func showHomePanelController(#inline: Bool) { homePanelIsInline = inline if homePanelController == nil { homePanelController = HomePanelViewController() homePanelController!.profile = profile homePanelController!.delegate = self homePanelController!.url = tabManager.selectedTab?.displayURL homePanelController!.view.alpha = 0 view.addSubview(homePanelController!.view) addChildViewController(homePanelController!) } var panelNumber = tabManager.selectedTab?.url?.fragment var numberArray = panelNumber?.componentsSeparatedByString("=") homePanelController?.selectedButtonIndex = numberArray?.last?.toInt() ?? 0 // We have to run this animation, even if the view is already showing because there may be a hide animation running // and we want to be sure to override its results. UIView.animateWithDuration(0.2, animations: { () -> Void in self.homePanelController!.view.alpha = 1 }, completion: { finished in if finished { self.webViewContainer.accessibilityElementsHidden = true self.stopTrackingAccessibilityStatus() UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } }) toolbar?.hidden = !inline view.setNeedsUpdateConstraints() } private func hideHomePanelController() { if let controller = homePanelController { UIView.animateWithDuration(0.2, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in controller.view.alpha = 0 }, completion: { finished in if finished { controller.view.removeFromSuperview() controller.removeFromParentViewController() self.homePanelController = nil self.webViewContainer.accessibilityElementsHidden = false self.toolbar?.hidden = false self.startTrackingAccessibilityStatus() UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // Refresh the reading view toolbar since the article record may have changed if let readerMode = self.tabManager.selectedTab?.getHelper(name: ReaderMode.name()) as? ReaderMode where readerMode.state == .Active { self.showReaderModeBar(animated: false) } } }) } } private func updateInContentHomePanel(url: NSURL?) { if !urlBar.isEditing { if AboutUtils.isAboutHomeURL(url){ showHomePanelController(inline: (tabManager.selectedTab?.canGoForward ?? false || tabManager.selectedTab?.canGoBack ?? false)) } else { hideHomePanelController() } } } private func showSearchController() { if searchController != nil { return } urlBar.locationView.inputMode = .Search searchController = SearchViewController() searchController!.searchEngines = profile.searchEngines searchController!.searchDelegate = self searchController!.profile = self.profile searchLoader.addListener(searchController!) view.addSubview(searchController!.view) searchController!.view.snp_makeConstraints { make in make.top.equalTo(self.urlBar.snp_bottom) make.left.right.bottom.equalTo(self.view) return } homePanelController?.view?.hidden = true addChildViewController(searchController!) } private func hideSearchController() { if let searchController = searchController { searchController.view.removeFromSuperview() searchController.removeFromParentViewController() self.searchController = nil urlBar.locationView.inputMode = .URL homePanelController?.view?.hidden = false } } private func finishEditingAndSubmit(var url: NSURL, visitType: VisitType) { urlBar.currentURL = url urlBar.finishEditing() if let tab = tabManager.selectedTab, let nav = tab.loadRequest(NSURLRequest(URL: url)) { self.recordNavigationInTab(tab, navigation: nav, visitType: visitType) } } func addBookmark(url: String, title: String?) { let shareItem = ShareItem(url: url, title: title, favicon: nil) profile.bookmarks.shareItem(shareItem) // Dispatch to the main thread to update the UI dispatch_async(dispatch_get_main_queue()) { _ in self.toolbar?.updateBookmarkStatus(true) self.urlBar.updateBookmarkStatus(true) } } private func removeBookmark(url: String) { profile.bookmarks.removeByURL(url, success: { success in self.toolbar?.updateBookmarkStatus(!success) self.urlBar.updateBookmarkStatus(!success) }, failure: { err in log.error("Error removing bookmark: \(err).") }) } func SELBookmarkStatusDidChange(notification: NSNotification) { if let bookmark = notification.object as? BookmarkItem { if bookmark.url == urlBar.currentURL?.absoluteString { if let userInfo = notification.userInfo as? Dictionary<String, Bool>{ if let added = userInfo["added"]{ self.toolbar?.updateBookmarkStatus(added) self.urlBar.updateBookmarkStatus(added) } } } } } override func accessibilityPerformEscape() -> Bool { if urlBar.isEditing { urlBar.SELdidClickCancel() return true } else if let selectedTab = tabManager.selectedTab where selectedTab.canGoBack { selectedTab.goBack() return true } return false } override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject: AnyObject], context: UnsafeMutablePointer<Void>) { if object as? WKWebView !== tabManager.selectedTab?.webView { return } switch keyPath { case KVOEstimatedProgress: let progress = change[NSKeyValueChangeNewKey] as! Float urlBar.updateProgressBar(progress) // when loading is stopped, KVOLoading is fired first, and only then KVOEstimatedProgress with progress 1.0 which would leave the progress bar running if progress != 1.0 || tabManager.selectedTab?.loading ?? false { auralProgress.progress = Double(progress) } case KVOLoading: let loading = change[NSKeyValueChangeNewKey] as! Bool toolbar?.updateReloadStatus(loading) urlBar.updateReloadStatus(loading) auralProgress.progress = loading ? 0 : nil default: assertionFailure("Unhandled KVO key: \(keyPath)") } } private func isWhitelistedUrl(url: NSURL) -> Bool { for entry in WhiteListedUrls { if let match = url.absoluteString!.rangeOfString(entry, options: .RegularExpressionSearch) { return UIApplication.sharedApplication().canOpenURL(url) } } return false } private func updateNavigationToolbarStates(tab: Browser, webView: WKWebView) { urlBar.currentURL = tab.displayURL navigationToolbar.updateBackStatus(webView.canGoBack) navigationToolbar.updateForwardStatus(webView.canGoForward) if let url = tab.displayURL?.absoluteString { profile.bookmarks.isBookmarked(url, success: { bookmarked in self.navigationToolbar.updateBookmarkStatus(bookmarked) }, failure: { err in log.error("Error getting bookmark status: \(err).") }) } } func openURLInNewTab(url: NSURL) { let tab = tabManager.addTab(request: NSURLRequest(URL: url)) tabManager.selectTab(tab) } } /** * History visit management. * TODO: this should be expanded to track various visit types; see Bug 1166084. */ extension BrowserViewController { func ignoreNavigationInTab(tab: Browser, navigation: WKNavigation) { self.ignoredNavigation.insert(navigation) } func recordNavigationInTab(tab: Browser, navigation: WKNavigation, visitType: VisitType) { self.typedNavigation[navigation] = visitType } /** * Untrack and do the right thing. */ func getVisitTypeForTab(tab: Browser, navigation: WKNavigation?) -> VisitType? { if let navigation = navigation { if let ignored = self.ignoredNavigation.remove(navigation) { return nil } return self.typedNavigation.removeValueForKey(navigation) ?? VisitType.Link } else { // See https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/NavigationState.mm#L390 return VisitType.Link } } } extension BrowserViewController: URLBarDelegate { func urlBarDidPressReload(urlBar: URLBarView) { tabManager.selectedTab?.reload() } func urlBarDidPressStop(urlBar: URLBarView) { tabManager.selectedTab?.stop() } func urlBarDidPressTabs(urlBar: URLBarView) { let tabTrayController = TabTrayController() tabTrayController.profile = profile tabTrayController.tabManager = tabManager tabTrayController.transitioningDelegate = self tabTrayController.modalPresentationStyle = .Custom if let tab = tabManager.selectedTab { tab.screenshot = screenshotHelper.takeScreenshot(tab, aspectRatio: 0, quality: 1) } presentViewController(tabTrayController, animated: true, completion: nil) self.tabTrayController = tabTrayController } func dismissTabTrayController(#animated: Bool, completion: () -> Void) { if let tabTrayController = tabTrayController { tabTrayController.dismissViewControllerAnimated(animated) { completion() self.tabTrayController = nil } } } func urlBarDidPressReaderMode(urlBar: URLBarView) { if let tab = tabManager.selectedTab { if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode { switch readerMode.state { case .Available: enableReaderMode() case .Active: disableReaderMode() case .Unavailable: break } } } } func urlBarDidLongPressReaderMode(urlBar: URLBarView) { if let tab = tabManager.selectedTab { if var url = tab.displayURL { if let absoluteString = url.absoluteString { let result = profile.readingList?.createRecordWithURL(absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().name) // TODO Check result, can this fail? // TODO Followup bug, provide some form of 'this has been added' feedback? } } } } func urlBarDidLongPressLocation(urlBar: URLBarView) { let longPressAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) let pasteboardContents = UIPasteboard.generalPasteboard().string // Check if anything is on the pasteboard if pasteboardContents != nil { let pasteAndGoAction = UIAlertAction(title: NSLocalizedString("Paste & Go", comment: "Paste the URL into the location bar and visit"), style: .Default, handler: { (alert: UIAlertAction!) -> Void in self.urlBar(urlBar, didSubmitText: pasteboardContents!) }) longPressAlertController.addAction(pasteAndGoAction) let pasteAction = UIAlertAction(title: NSLocalizedString("Paste", comment: "Paste the URL into the location bar"), style: .Default, handler: { (alert: UIAlertAction!) -> Void in urlBar.updateURLBarText(pasteboardContents!) }) longPressAlertController.addAction(pasteAction) } let copyAddressAction = UIAlertAction(title: NSLocalizedString("Copy Address", comment: "Copy the URL from the location bar"), style: .Default, handler: { (alert: UIAlertAction!) -> Void in UIPasteboard.generalPasteboard().string = urlBar.currentURL?.absoluteString }) longPressAlertController.addAction(copyAddressAction) let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel alert view"), style: .Cancel, handler: nil) longPressAlertController.addAction(cancelAction) if let popoverPresentationController = longPressAlertController.popoverPresentationController { popoverPresentationController.sourceView = urlBar popoverPresentationController.sourceRect = urlBar.frame popoverPresentationController.permittedArrowDirections = .Any } self.presentViewController(longPressAlertController, animated: true, completion: nil) } func urlBarDidPressScrollToTop(urlBar: URLBarView) { if let selectedTab = tabManager.selectedTab { // Only scroll to top if we are not showing the home view controller if homePanelController == nil { selectedTab.webView?.scrollView.setContentOffset(CGPointZero, animated: true) } } } func urlBar(urlBar: URLBarView, didEnterText text: String) { searchLoader.query = text if text.isEmpty { hideSearchController() } else { showSearchController() searchController!.searchQuery = text } } func urlBar(urlBar: URLBarView, didSubmitText text: String) { var url = uriFixup.getURL(text) // If we can't make a valid URL, do a search query. if url == nil { url = profile.searchEngines.defaultEngine.searchURLForQuery(text) } // If we still don't have a valid URL, something is broken. Give up. if url == nil { log.error("Error handling URL entry: \"\(text)\".") return } finishEditingAndSubmit(url!, visitType: VisitType.Typed) } func urlBarDidBeginEditing(urlBar: URLBarView) { // Pass the edit message along if we are already showing the home panel if let homePanelController = self.homePanelController where homePanelController.view.alpha == 1 { homePanelController.endEditing(nil) } else { showHomePanelController(inline: false) } } func urlBarDidEndEditing(urlBar: URLBarView) { hideSearchController() updateInContentHomePanel(tabManager.selectedTab?.url) } } extension BrowserViewController: BrowserToolbarDelegate { func browserToolbarDidPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goBack() } func browserToolbarDidLongPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) { // See 1159373 - Disable long press back/forward for backforward list // let controller = BackForwardListViewController() // controller.listData = tabManager.selectedTab?.backList // controller.tabManager = tabManager // presentViewController(controller, animated: true, completion: nil) } func browserToolbarDidPressReload(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.reload() } func browserToolbarDidPressStop(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.stop() } func browserToolbarDidPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goForward() } func browserToolbarDidLongPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) { // See 1159373 - Disable long press back/forward for backforward list // let controller = BackForwardListViewController() // controller.listData = tabManager.selectedTab?.forwardList // controller.tabManager = tabManager // presentViewController(controller, animated: true, completion: nil) } func browserToolbarDidPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) { if let tab = tabManager.selectedTab, let url = tab.displayURL?.absoluteString { profile.bookmarks.isBookmarked(url, success: { isBookmarked in if isBookmarked { self.removeBookmark(url) } else { self.addBookmark(url, title: tab.title) } }, failure: { err in log.error("Bookmark error: \(err).") } ) } else { log.error("Bookmark error: No tab is selected, or no URL in tab.") } } func browserToolbarDidLongPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) { } func browserToolbarDidPressShare(browserToolbar: BrowserToolbarProtocol, button: UIButton) { if let selected = tabManager.selectedTab { if let url = selected.displayURL { var activityViewController = UIActivityViewController(activityItems: [selected.title ?? url.absoluteString!, url], applicationActivities: nil) // Hide 'Add to Reading List' which currently uses Safari activityViewController.excludedActivityTypes = [UIActivityTypeAddToReadingList] if let popoverPresentationController = activityViewController.popoverPresentationController { // Using the button for the sourceView here results in this not showing on iPads. popoverPresentationController.sourceView = toolbar ?? urlBar popoverPresentationController.sourceRect = button.frame ?? button.frame popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.Up } presentViewController(activityViewController, animated: true, completion: nil) } } } } extension BrowserViewController: BrowserDelegate { func browser(browser: Browser, didCreateWebView webView: WKWebView) { webView.scrollView.delegate = self webViewContainer.insertSubview(webView, atIndex: 0) webView.snp_makeConstraints { make in make.edges.equalTo(self.webViewContainer) } // Observers that live as long as the tab. Make sure these are all cleared // in willDeleteWebView below! webView.addObserver(self, forKeyPath: KVOEstimatedProgress, options: .New, context: nil) webView.addObserver(self, forKeyPath: KVOLoading, options: .New, context: nil) webView.UIDelegate = self let readerMode = ReaderMode(browser: browser) readerMode.delegate = self browser.addHelper(readerMode, name: ReaderMode.name()) let favicons = FaviconManager(browser: browser, profile: profile) browser.addHelper(favicons, name: FaviconManager.name()) // Temporarily disable password support until the new code lands let logins = LoginsHelper(browser: browser, profile: profile) browser.addHelper(logins, name: LoginsHelper.name()) let contextMenuHelper = ContextMenuHelper(browser: browser) contextMenuHelper.delegate = self browser.addHelper(contextMenuHelper, name: ContextMenuHelper.name()) let hashchangeHelper = HashchangeHelper(browser: browser) hashchangeHelper.delegate = self browser.addHelper(hashchangeHelper, name: HashchangeHelper.name()) let errorHelper = ErrorPageHelper() browser.addHelper(errorHelper, name: ErrorPageHelper.name()) } func browser(browser: Browser, willDeleteWebView webView: WKWebView) { webView.removeObserver(self, forKeyPath: KVOEstimatedProgress) webView.removeObserver(self, forKeyPath: KVOLoading) webView.UIDelegate = nil webView.scrollView.delegate = nil webView.removeFromSuperview() } private func findSnackbar(barToFind: SnackBar) -> Int? { let bars = snackBars.subviews for (index, bar) in enumerate(bars) { if bar === barToFind { return index } } return nil } private func adjustFooterSize(top: UIView? = nil) { snackBars.snp_remakeConstraints({ make in let bars = self.snackBars.subviews // if the keyboard is showing then ensure that the snackbars are positioned above it, otherwise position them above the toolbar/view bottom if let state = keyboardState { make.bottom.equalTo(-(state.height + 20)) } else { make.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom) } if traitCollection.horizontalSizeClass != .Regular { make.leading.trailing.equalTo(self.footer) self.snackBars.layer.borderWidth = 0 } else { make.centerX.equalTo(self.footer) make.width.equalTo(SnackBarUX.MaxWidth) self.snackBars.layer.borderColor = UIConstants.BorderColor.CGColor self.snackBars.layer.borderWidth = 1 } if bars.count > 0 { let view = bars[bars.count-1] as! UIView make.top.equalTo(view.snp_top) } else { make.top.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom) } }) } // This removes the bar from its superview and updates constraints appropriately private func finishRemovingBar(bar: SnackBar) { // If there was a bar above this one, we need to remake its constraints. if let index = findSnackbar(bar) { // If the bar being removed isn't on the top of the list let bars = snackBars.subviews if index < bars.count-1 { // Move the bar above this one var nextbar = bars[index+1] as! SnackBar nextbar.snp_updateConstraints { make in // If this wasn't the bottom bar, attach to the bar below it if index > 0 { let bar = bars[index-1] as! SnackBar nextbar.bottom = make.bottom.equalTo(bar.snp_top).constraint } else { // Otherwise, we attach it to the bottom of the snackbars nextbar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).constraint } } } } // Really remove the bar bar.removeFromSuperview() } private func finishAddingBar(bar: SnackBar) { snackBars.addSubview(bar) bar.snp_remakeConstraints({ make in // If there are already bars showing, add this on top of them let bars = self.snackBars.subviews // Add the bar on top of the stack // We're the new top bar in the stack, so make sure we ignore ourself if bars.count > 1 { let view = bars[bars.count - 2] as! UIView bar.bottom = make.bottom.equalTo(view.snp_top).offset(0).constraint } else { bar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).offset(0).constraint } make.leading.trailing.equalTo(self.snackBars) }) } func showBar(bar: SnackBar, animated: Bool) { finishAddingBar(bar) adjustFooterSize(top: bar) bar.hide() view.layoutIfNeeded() UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in bar.show() self.view.layoutIfNeeded() }) } func removeBar(bar: SnackBar, animated: Bool) { let index = findSnackbar(bar)! UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in bar.hide() self.view.layoutIfNeeded() }) { success in // Really remove the bar self.finishRemovingBar(bar) // Adjust the footer size to only contain the bars self.adjustFooterSize() } } func removeAllBars() { let bars = snackBars.subviews for bar in bars { if let bar = bar as? SnackBar { bar.removeFromSuperview() } } self.adjustFooterSize() } func browser(browser: Browser, didAddSnackbar bar: SnackBar) { showBar(bar, animated: true) } func browser(browser: Browser, didRemoveSnackbar bar: SnackBar) { removeBar(bar, animated: true) } } extension BrowserViewController: HomePanelViewControllerDelegate { func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectURL url: NSURL, visitType: VisitType) { finishEditingAndSubmit(url, visitType: visitType) } func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectPanel panel: Int) { if AboutUtils.isAboutHomeURL(tabManager.selectedTab?.url) { tabManager.selectedTab?.webView?.evaluateJavaScript("history.replaceState({}, '', '#panel=\(panel)')", completionHandler: nil) } } func homePanelViewControllerDidRequestToCreateAccount(homePanelViewController: HomePanelViewController) { presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same } func homePanelViewControllerDidRequestToSignIn(homePanelViewController: HomePanelViewController) { presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same } } extension BrowserViewController: SearchViewControllerDelegate { func searchViewController(searchViewController: SearchViewController, didSelectURL url: NSURL) { finishEditingAndSubmit(url, visitType: VisitType.Typed) } func presentSearchSettingsController() { let settingsNavigationController = SearchSettingsTableViewController() settingsNavigationController.model = self.profile.searchEngines let navController = UINavigationController(rootViewController: settingsNavigationController) self.presentViewController(navController, animated: true, completion: nil) } func searchViewControllerWillAppear(searchViewController: SearchViewController) { self.urlBar.locationView.editTextField.becomeFirstResponder() } } extension BrowserViewController : UIScrollViewDelegate { func scrollViewWillBeginDragging(scrollView: UIScrollView) { previousScroll = scrollView.contentOffset } func scrollViewDidScroll(scrollView: UIScrollView) { if let tab = tabManager.selectedTab, let prev = self.previousScroll { var totalToolbarHeight = header.frame.size.height let offset = scrollView.contentOffset let dy = prev.y - offset.y let scrollingSize = scrollView.contentSize.height - scrollView.frame.size.height totalToolbarHeight += readerModeBar?.frame.size.height ?? 0 totalToolbarHeight += self.toolbar?.frame.size.height ?? 0 // Only scroll away our toolbars if, if !tab.loading && // There is enough web content to fill the screen if the scroll bars are fulling animated out scrollView.contentSize.height > (scrollView.frame.size.height + totalToolbarHeight) && // The user is scrolling through the content and not because of the bounces that // happens when you pull up past the content scrollView.contentOffset.y > 0 && // Only scroll away the toolbars if we are NOT pinching to zoom, only when we are dragging !scrollView.zooming { scrollFooter(dy) scrollHeader(dy) scrollReader(dy) } else { // Force toolbars to be in open state showToolbars(animated: false) } self.previousScroll = offset } } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if previousScroll != nil { endDragging() } } private func endDragging() { self.previousScroll = nil let headerHeight = header.frame.size.height let totalOffset = headerHeight if headerConstraintOffset > -totalOffset { // Whenever we try running an animation from the scrollViewWillEndDragging delegate method, // it calls layoutSubviews so many times that it ends up clobbering any animations we want to // run from here. This dispatch_async places the animation onto the main queue for processing after // the scrollView has placed it's work on it already dispatch_async(dispatch_get_main_queue()) { self.showToolbars(animated: true) } } } } // Functions for scrolling the urlbar and footers. extension BrowserViewController { func scrollViewShouldScrollToTop(scrollView: UIScrollView) -> Bool { showToolbars(animated: true) return true } private func scrollHeader(dy: CGFloat) { let totalOffset = self.header.frame.size.height let newOffset = self.clamp(self.headerConstraintOffset + dy, min: -totalOffset, max: 0) self.headerConstraint?.updateOffset(newOffset) self.headerConstraintOffset = newOffset let alpha = 1 - (abs(newOffset) / totalOffset) self.urlBar.updateAlphaForSubviews(alpha) } private func scrollFooter(dy: CGFloat) { let newOffset = self.clamp(self.footerConstraintOffset - dy, min: 0, max: footer.frame.size.height) self.footerConstraint?.updateOffset(newOffset) self.footerConstraintOffset = newOffset } private func scrollReader(dy: CGFloat) { let totalOffset = UIConstants.ToolbarHeight let newOffset = self.clamp(self.readerConstraintOffset + dy, min: -totalOffset, max: 0) self.readerConstraint?.updateOffset(newOffset) self.readerConstraintOffset = newOffset } private func clamp(y: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat { if y >= max { return max } else if y <= min { return min } return y } private func showToolbars(#animated: Bool, completion: ((finished: Bool) -> Void)? = nil) { let animationDistance = self.headerConstraintOffset let totalOffset = self.header.frame.size.height let durationRatio = abs(animationDistance / totalOffset) let actualDuration = NSTimeInterval(BrowserViewControllerUX.ToolbarBaseAnimationDuration * durationRatio) self.animateToolbarsWithOffsets( animated: animated, duration: actualDuration, headerOffset: 0, footerOffset: 0, readerOffset: 0, alpha: 1, completion: completion) } private func hideToolbars(#animated: Bool, completion: ((finished: Bool) -> Void)? = nil) { let totalOffset = self.header.frame.size.height let animationDistance = totalOffset - abs(self.headerConstraintOffset) let durationRatio = abs(animationDistance / totalOffset) let actualDuration = NSTimeInterval(BrowserViewControllerUX.ToolbarBaseAnimationDuration * durationRatio) self.animateToolbarsWithOffsets( animated: animated, duration: actualDuration, headerOffset: -self.header.frame.size.height, footerOffset: self.footer.frame.height, readerOffset: -(readerModeBar?.frame.size.height ?? 0), alpha: 0, completion: completion) } private func animateToolbarsWithOffsets(#animated: Bool, duration: NSTimeInterval, headerOffset: CGFloat, footerOffset: CGFloat, readerOffset: CGFloat, alpha: CGFloat, completion: ((finished: Bool) -> Void)?) { let animation: () -> Void = { self.updateHeaderFooterConstraintsAndAlpha(headerOffset: headerOffset, footerOffset: footerOffset, readerOffset: readerOffset, alpha: alpha) self.view.layoutIfNeeded() } if animated { UIView.animateWithDuration(duration, animations: animation, completion: completion) } else { animation() completion?(finished: true) } } private func updateHeaderFooterConstraintsAndAlpha(#headerOffset: CGFloat, footerOffset: CGFloat, readerOffset: CGFloat, alpha: CGFloat) { self.headerConstraint?.updateOffset(headerOffset) self.footerConstraint?.updateOffset(footerOffset) self.readerConstraint?.updateOffset(readerOffset) self.headerConstraintOffset = headerOffset self.footerConstraintOffset = footerOffset self.readerConstraintOffset = readerOffset self.urlBar.updateAlphaForSubviews(alpha) } } extension BrowserViewController: TabManagerDelegate { func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) { // Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it // and having multiple views with the same label confuses tests. if let wv = previous?.webView { wv.accessibilityLabel = nil wv.accessibilityElementsHidden = true wv.accessibilityIdentifier = nil // due to screwy handling within iOS, the scrollToTop handling does not work if there are // more than one scroll view in the view hierarchy // we therefore have to hide all the scrollViews that we are no actually interesting in interacting with // to ensure that scrollsToTop actually works wv.scrollView.hidden = true } if let webView = selected?.webView { // if we have previously hidden this scrollview in order to make scrollsToTop work then // we should ensure that it is not hidden now that it is our foreground scrollView if webView.scrollView.hidden { webView.scrollView.hidden = false } webViewContainer.addSubview(webView) webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.accessibilityIdentifier = "contentView" webView.accessibilityElementsHidden = false if let url = webView.URL?.absoluteString { profile.bookmarks.isBookmarked(url, success: { bookmarked in self.toolbar?.updateBookmarkStatus(bookmarked) self.urlBar.updateBookmarkStatus(bookmarked) }, failure: { err in log.error("Error getting bookmark status: \(err).") }) } else { // The web view can go gray if it was zombified due to memory pressure. // When this happens, the URL is nil, so try restoring the page upon selection. webView.reload() } } removeAllBars() urlBar.currentURL = selected?.displayURL if let bars = selected?.bars { for bar in bars { showBar(bar, animated: true) } } toolbar?.updateBackStatus(selected?.canGoBack ?? false) toolbar?.updateForwardStatus(selected?.canGoForward ?? false) toolbar?.updateReloadStatus(selected?.loading ?? false) let isPage = (selected?.displayURL != nil) ? isWebPage(selected!.displayURL!) : false toolbar?.updatePageStatus(isWebPage: isPage) self.urlBar.updateBackStatus(selected?.canGoBack ?? false) self.urlBar.updateForwardStatus(selected?.canGoForward ?? false) self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0)) if let readerMode = selected?.getHelper(name: ReaderMode.name()) as? ReaderMode { urlBar.updateReaderModeState(readerMode.state) if readerMode.state == .Active { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } } else { urlBar.updateReaderModeState(ReaderModeState.Unavailable) } updateInContentHomePanel(selected?.url) } func tabManager(tabManager: TabManager, didCreateTab tab: Browser, restoring: Bool) { } func tabManager(tabManager: TabManager, didAddTab tab: Browser, atIndex: Int, restoring: Bool) { // If we are restoring tabs then we update the count once at the end if !restoring { urlBar.updateTabCount(tabManager.count) } tab.browserDelegate = self } func tabManager(tabManager: TabManager, didRemoveTab tab: Browser, atIndex: Int) { urlBar.updateTabCount(tabManager.count) // browserDelegate is a weak ref (and the tab's webView may not be destroyed yet) // so we don't expcitly unset it. } func tabManagerDidAddTabs(tabManager: TabManager) { urlBar.updateTabCount(tabManager.count) } func tabManagerDidRestoreTabs(tabManager: TabManager) { urlBar.updateTabCount(tabManager.count) } private func isWebPage(url: NSURL) -> Bool { let httpSchemes = ["http", "https"] if let scheme = url.scheme, index = find(httpSchemes, scheme) { return true } return false } } extension BrowserViewController: WKNavigationDelegate { func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { if tabManager.selectedTab?.webView !== webView { return } // If we are going to navigate to a new page, hide the reader mode button. Unless we // are going to a about:reader page. Then we keep it on screen: it will change status // (orange color) as soon as the page has loaded. if let url = webView.URL { if !ReaderModeUtils.isReaderModeURL(url) { urlBar.updateReaderModeState(ReaderModeState.Unavailable) } } } private func openExternal(url: NSURL, prompt: Bool = true) { if prompt { // Ask the user if it's okay to open the url with UIApplication. let alert = UIAlertController( title: String(format: NSLocalizedString("Opening %@", comment:"Opening an external URL"), url), message: NSLocalizedString("This will open in another application", comment: "Opening an external app"), preferredStyle: UIAlertControllerStyle.Alert ) alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Alert Cancel Button"), style: UIAlertActionStyle.Cancel, handler: { (action: UIAlertAction!) in })) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment:"Alert OK Button"), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in UIApplication.sharedApplication().openURL(url) })) presentViewController(alert, animated: true, completion: nil) } else { UIApplication.sharedApplication().openURL(url) } } private func callExternal(url: NSURL) { if let phoneNumber = url.resourceSpecifier?.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { let alert = UIAlertController(title: phoneNumber, message: nil, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Alert Cancel Button"), style: UIAlertActionStyle.Cancel, handler: nil)) alert.addAction(UIAlertAction(title: NSLocalizedString("Call", comment:"Alert Call Button"), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in UIApplication.sharedApplication().openURL(url) })) presentViewController(alert, animated: true, completion: nil) } } func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) { if let url = navigationAction.request.URL { if let scheme = url.scheme { switch scheme { case "about", "http", "https": if isWhitelistedUrl(url) { // If the url is whitelisted, we open it without prompting. openExternal(url, prompt: false) decisionHandler(WKNavigationActionPolicy.Cancel) } else { decisionHandler(WKNavigationActionPolicy.Allow) } case "tel": callExternal(url) decisionHandler(WKNavigationActionPolicy.Cancel) default: if UIApplication.sharedApplication().canOpenURL(url) { openExternal(url) } decisionHandler(WKNavigationActionPolicy.Cancel) } } } else { decisionHandler(WKNavigationActionPolicy.Cancel) } } func webView(webView: WKWebView, didCommitNavigation navigation: WKNavigation!) { if let tab = tabManager.selectedTab { if tab.webView == webView { updateNavigationToolbarStates(tab, webView: webView) let isPage = (tab.displayURL != nil) ? isWebPage(tab.displayURL!) : false navigationToolbar.updatePageStatus(isWebPage: isPage) showToolbars(animated: false) if let url = tab.url { if ReaderModeUtils.isReaderModeURL(url) { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } } updateInContentHomePanel(tab.url) } } } func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic || challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest { if let tab = tabManager[webView] { let helper = tab.getHelper(name: LoginsHelper.name()) as! LoginsHelper helper.handleAuthRequest(self, challenge: challenge).uponQueue(dispatch_get_main_queue()) { res in if let credentials = res.successValue { completionHandler(.UseCredential, credentials.credentials) } else { completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil) } } } } else { completionHandler(NSURLSessionAuthChallengeDisposition.PerformDefaultHandling, nil) } } func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { let tab: Browser! = tabManager[webView] tab.expireSnackbars() if let url = webView.URL where !ErrorPageHelper.isErrorPageURL(url) && !AboutUtils.isAboutHomeURL(url) { let notificationCenter = NSNotificationCenter.defaultCenter() var info = [NSObject: AnyObject]() info["url"] = tab.displayURL info["title"] = tab.title if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue { info["visitType"] = visitType } notificationCenter.postNotificationName("LocationChange", object: self, userInfo: info) // The screenshot immediately after didFinishNavigation is actually a screenshot of the // previous page, presumably due to some iOS bug. Adding a small delay seems to fix this, // and the current page gets captured as expected. let time = dispatch_time(DISPATCH_TIME_NOW, Int64(100 * NSEC_PER_MSEC)) dispatch_after(time, dispatch_get_main_queue()) { if webView.URL != url { // The page changed during the delay, so we missed our chance to get a thumbnail. return } if let screenshot = self.screenshotHelper.takeScreenshot(tab, aspectRatio: CGFloat(ThumbnailCellUX.ImageAspectRatio), quality: 0.5) { let thumbnail = Thumbnail(image: screenshot) self.profile.thumbnails.set(url, thumbnail: thumbnail, complete: nil) } } // Fire the readability check. This is here and not in the pageShow event handler in ReaderMode.js anymore // because that event wil not always fire due to unreliable page caching. This will either let us know that // the currently loaded page can be turned into reading mode or if the page already is in reading mode. We // ignore the result because we are being called back asynchronous when the readermode status changes. webView.evaluateJavaScript("_firefox_ReaderMode.checkReadability()", completionHandler: nil) } if tab === tabManager.selectedTab { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // must be followed by LayoutChanged, as ScreenChanged will make VoiceOver // cursor land on the correct initial element, but if not followed by LayoutChanged, // VoiceOver will sometimes be stuck on the element, not allowing user to move // forward/backward. Strange, but LayoutChanged fixes that. UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } } } extension BrowserViewController: WKUIDelegate { func webView(webView: WKWebView, createWebViewWithConfiguration configuration: WKWebViewConfiguration, forNavigationAction navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { // If the page uses window.open() or target="_blank", open the page in a new tab. // TODO: This doesn't work for window.open() without user action (bug 1124942). let tab = tabManager.addTab(request: navigationAction.request, configuration: configuration) tabManager.selectTab(tab) return tab.webView } func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) { tabManager.selectTab(tabManager[webView]) // Show JavaScript alerts. let title = frame.request.URL!.host let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in completionHandler() })) presentViewController(alertController, animated: true, completion: nil) } func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) { tabManager.selectTab(tabManager[webView]) // Show JavaScript confirm dialogs. let title = frame.request.URL!.host let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in completionHandler(true) })) alertController.addAction(UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: { _ in completionHandler(false) })) presentViewController(alertController, animated: true, completion: nil) } func webView(webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: (String!) -> Void) { tabManager.selectTab(tabManager[webView]) // Show JavaScript input dialogs. let title = frame.request.URL!.host let alertController = UIAlertController(title: title, message: prompt, preferredStyle: UIAlertControllerStyle.Alert) var input: UITextField! alertController.addTextFieldWithConfigurationHandler({ (textField: UITextField!) in textField.text = defaultText input = textField }) alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in completionHandler(input.text) })) alertController.addAction(UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: { _ in completionHandler(nil) })) presentViewController(alertController, animated: true, completion: nil) } /// Invoked when an error occurs during a committed main frame navigation. func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) { if error.code == Int(CFNetworkErrors.CFURLErrorCancelled.rawValue) { return } // Ignore the "Plug-in handled load" error. Which is more like a notification than an error. // Note that there are no constants in the SDK for the WebKit domain or error codes. if error.domain == "WebKitErrorDomain" && error.code == 204 { return } if let url = error.userInfo?["NSErrorFailingURLKey"] as? NSURL { ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView) } } /// Invoked when an error occurs while starting to load data for the main frame. func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { if error.code == Int(CFNetworkErrors.CFURLErrorCancelled.rawValue) { return } if let url = error.userInfo?["NSErrorFailingURLKey"] as? NSURL { ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView) } } func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) { if navigationResponse.canShowMIMEType { decisionHandler(WKNavigationResponsePolicy.Allow) return } let error = NSError(domain: ErrorPageHelper.MozDomain, code: Int(ErrorPageHelper.MozErrorDownloadsNotEnabled), userInfo: [NSLocalizedDescriptionKey: "Downloads aren't supported in Firefox yet (but we're working on it)."]) ErrorPageHelper().showPage(error, forUrl: navigationResponse.response.URL!, inWebView: webView) decisionHandler(WKNavigationResponsePolicy.Allow) } } extension BrowserViewController: ReaderModeDelegate, UIPopoverPresentationControllerDelegate { func readerMode(readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forBrowser browser: Browser) { // If this reader mode availability state change is for the tab that we currently show, then update // the button. Otherwise do nothing and the button will be updated when the tab is made active. if tabManager.selectedTab === browser { log.debug("New readerModeState: \(state.rawValue)") urlBar.updateReaderModeState(state) } } func readerMode(readerMode: ReaderMode, didDisplayReaderizedContentForBrowser browser: Browser) { self.showReaderModeBar(animated: true) browser.showContent(animated: true) } // Returning None here makes sure that the Popover is actually presented as a Popover and // not as a full-screen modal, which is the default on compact device classes. func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.None } } extension BrowserViewController: ReaderModeStyleViewControllerDelegate { func readerModeStyleViewController(readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle) { // Persist the new style to the profile let encodedStyle: [String:AnyObject] = style.encode() profile.prefs.setObject(encodedStyle, forKey: ReaderModeProfileKeyStyle) // Change the reader mode style on all tabs that have reader mode active for tabIndex in 0..<tabManager.count { if let tab = tabManager[tabIndex] { if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode { if readerMode.state == ReaderModeState.Active { readerMode.style = style } } } } } } extension BrowserViewController : UIViewControllerTransitioningDelegate { func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return TransitionManager(show: false) } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return TransitionManager(show: true) } } extension BrowserViewController : Transitionable { private func headerTransformToCellFrame(frame: CGRect) -> CGAffineTransform { let scale = frame.size.width / header.frame.size.width // Since the scale will happen in the center of the frame, we move this so the centers of the two frames overlap. let tx = frame.origin.x + frame.width/2 - (header.frame.origin.x + header.frame.width/2) let ty = frame.origin.y - header.frame.origin.y * scale * 2 // Move this up a little actually keeps it above the web page. I'm not sure what you want var transform = CGAffineTransformMakeTranslation(tx, ty) return CGAffineTransformScale(transform, scale, scale) } private func footerTransformToCellFrame(frame: CGRect) -> CGAffineTransform { let tx = frame.origin.x + frame.width/2 - (footer.frame.origin.x + footer.frame.width/2) var footerTransform = CGAffineTransformMakeTranslation(tx, -footer.frame.origin.y + frame.origin.y + frame.size.height - footer.frame.size.height) let footerScale = frame.size.width / footer.frame.size.width return CGAffineTransformScale(footerTransform, footerScale, footerScale) } func transitionablePreHide(transitionable: Transitionable, options: TransitionOptions) { // Move all the webview's off screen for i in 0..<tabManager.count { if let tab = tabManager[i] { tab.webView?.hidden = true } } self.homePanelController?.view.hidden = true } func transitionablePreShow(transitionable: Transitionable, options: TransitionOptions) { // Move all the webview's off screen for i in 0..<tabManager.count { if let tab = tabManager[i] { tab.webView?.hidden = true } } // Move over the transforms to reflect where the opening tab is coming from instead of where the previous tab was if let frame = options.cellFrame { header.transform = CGAffineTransformIdentity footer.transform = CGAffineTransformIdentity header.transform = headerTransformToCellFrame(frame) footer.transform = footerTransformToCellFrame(frame) } self.homePanelController?.view.hidden = true } func transitionableWillShow(transitionable: Transitionable, options: TransitionOptions) { view.alpha = 1 header.transform = CGAffineTransformIdentity footer.transform = CGAffineTransformIdentity } func transitionableWillHide(transitionable: Transitionable, options: TransitionOptions) { view.alpha = 0 if let frame = options.cellFrame { header.transform = headerTransformToCellFrame(frame) footer.transform = footerTransformToCellFrame(frame) } } func transitionableWillComplete(transitionable: Transitionable, options: TransitionOptions) { // Move all the webview's back on screen for i in 0..<tabManager.count { if let tab = tabManager[i] { tab.webView?.hidden = false } } self.homePanelController?.view.hidden = false if options.toView === self { startTrackingAccessibilityStatus() } else { stopTrackingAccessibilityStatus() } } } extension BrowserViewController { func showReaderModeBar(#animated: Bool) { if self.readerModeBar == nil { let readerModeBar = ReaderModeBarView(frame: CGRectZero) readerModeBar.delegate = self view.insertSubview(readerModeBar, belowSubview: header) self.readerModeBar = readerModeBar } if let readerModeBar = readerModeBar { if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { readerModeBar.unread = record.unread readerModeBar.added = true } else { readerModeBar.unread = true readerModeBar.added = false } } else { readerModeBar.unread = true readerModeBar.added = false } } self.updateViewConstraints() } func hideReaderModeBar(#animated: Bool) { if let readerModeBar = self.readerModeBar { readerModeBar.removeFromSuperview() self.readerModeBar = nil self.updateViewConstraints() } } /// There are two ways we can enable reader mode. In the simplest case we open a URL to our internal reader mode /// and be done with it. In the more complicated case, reader mode was already open for this page and we simply /// navigated away from it. So we look to the left and right in the BackForwardList to see if a readerized version /// of the current page is there. And if so, we go there. func enableReaderMode() { if let tab = tabManager.selectedTab, let webView = tab.webView, let backList = webView.backForwardList.backList as? [WKBackForwardListItem], let forwardList = webView.backForwardList.forwardList as? [WKBackForwardListItem] { if let currentURL = webView.backForwardList.currentItem?.URL { if let readerModeURL = ReaderModeUtils.encodeURL(currentURL) { if backList.count > 1 && backList.last?.URL == readerModeURL { webView.goToBackForwardListItem(backList.last!) } else if forwardList.count > 0 && forwardList.first?.URL == readerModeURL { webView.goToBackForwardListItem(forwardList.first!) } else { // Store the readability result in the cache and load it. This will later move to the ReadabilityHelper. webView.evaluateJavaScript("\(ReaderModeNamespace).readerize()", completionHandler: { (object, error) -> Void in if let readabilityResult = ReadabilityResult(object: object) { ReaderModeCache.sharedInstance.put(currentURL, readabilityResult, error: nil) if let nav = webView.loadRequest(NSURLRequest(URL: readerModeURL)) { self.ignoreNavigationInTab(tab, navigation: nav) } } }) } } } } } /// Disabling reader mode can mean two things. In the simplest case we were opened from the reading list, which /// means that there is nothing in the BackForwardList except the internal url for the reader mode page. In that /// case we simply open a new page with the original url. In the more complicated page, the non-readerized version /// of the page is either to the left or right in the BackForwardList. If that is the case, we navigate there. func disableReaderMode() { if let tab = tabManager.selectedTab, let webView = tab.webView { let backList = webView.backForwardList.backList as! [WKBackForwardListItem] let forwardList = webView.backForwardList.forwardList as! [WKBackForwardListItem] if let currentURL = webView.backForwardList.currentItem?.URL { if let originalURL = ReaderModeUtils.decodeURL(currentURL) { if backList.count > 1 && backList.last?.URL == originalURL { webView.goToBackForwardListItem(backList.last!) } else if forwardList.count > 0 && forwardList.first?.URL == originalURL { webView.goToBackForwardListItem(forwardList.first!) } else { if let nav = webView.loadRequest(NSURLRequest(URL: originalURL)) { self.ignoreNavigationInTab(tab, navigation: nav) } } } } } } } extension BrowserViewController: ReaderModeBarViewDelegate { func readerModeBar(readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) { switch buttonType { case .Settings: if let readerMode = tabManager.selectedTab?.getHelper(name: "ReaderMode") as? ReaderMode where readerMode.state == ReaderModeState.Active { var readerModeStyle = DefaultReaderModeStyle if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) { if let style = ReaderModeStyle(dict: dict) { readerModeStyle = style } } let readerModeStyleViewController = ReaderModeStyleViewController() readerModeStyleViewController.delegate = self readerModeStyleViewController.readerModeStyle = readerModeStyle readerModeStyleViewController.modalPresentationStyle = UIModalPresentationStyle.Popover let popoverPresentationController = readerModeStyleViewController.popoverPresentationController popoverPresentationController?.backgroundColor = UIColor.whiteColor() popoverPresentationController?.delegate = self popoverPresentationController?.sourceView = readerModeBar popoverPresentationController?.sourceRect = CGRect(x: readerModeBar.frame.width/2, y: UIConstants.ToolbarHeight, width: 1, height: 1) popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.Up self.presentViewController(readerModeStyleViewController, animated: true, completion: nil) } case .MarkAsRead: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { profile.readingList?.updateRecord(record, unread: false) // TODO Check result, can this fail? readerModeBar.unread = false } } case .MarkAsUnread: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { profile.readingList?.updateRecord(record, unread: true) // TODO Check result, can this fail? readerModeBar.unread = true } } case .AddToReadingList: if let tab = tabManager.selectedTab, let url = tab.url where ReaderModeUtils.isReaderModeURL(url) { if let url = ReaderModeUtils.decodeURL(url), let absoluteString = url.absoluteString { let result = profile.readingList?.createRecordWithURL(absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().name) // TODO Check result, can this fail? readerModeBar.added = true } } case .RemoveFromReadingList: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { profile.readingList?.deleteRecord(record) // TODO Check result, can this fail? readerModeBar.added = false } } } } } private class BrowserScreenshotHelper: ScreenshotHelper { private weak var controller: BrowserViewController? init(controller: BrowserViewController) { self.controller = controller } func takeScreenshot(tab: Browser, aspectRatio: CGFloat, quality: CGFloat) -> UIImage? { if let url = tab.url { if url == UIConstants.AboutHomeURL { if let homePanel = controller?.homePanelController { return homePanel.view.screenshot(aspectRatio, quality: quality) } } else { let offset = CGPointMake(0, -(tab.webView?.scrollView.contentInset.top ?? 0)) return tab.webView?.screenshot(aspectRatio, offset: offset, quality: quality) } } return nil } } extension BrowserViewController: IntroViewControllerDelegate { func presentIntroViewController(force: Bool = false) { if force || profile.prefs.intForKey(IntroViewControllerSeenProfileKey) == nil { let introViewController = IntroViewController() introViewController.delegate = self // On iPad we present it modally in a controller if UIDevice.currentDevice().userInterfaceIdiom == .Pad { introViewController.preferredContentSize = CGSize(width: IntroViewControllerUX.Width, height: IntroViewControllerUX.Height) introViewController.modalPresentationStyle = UIModalPresentationStyle.FormSheet } presentViewController(introViewController, animated: false) { self.profile.prefs.setInt(1, forKey: IntroViewControllerSeenProfileKey) } } } func introViewControllerDidFinish(introViewController: IntroViewController) { introViewController.dismissViewControllerAnimated(true, completion: nil) } func presentSignInViewController() { // TODO When bug 1161151 has been resolved we can jump directly to the sign in screen let settingsNavigationController = SettingsNavigationController() settingsNavigationController.profile = self.profile settingsNavigationController.tabManager = self.tabManager settingsNavigationController.modalPresentationStyle = .FormSheet self.presentViewController(settingsNavigationController, animated: true, completion: nil) } func introViewControllerDidRequestToLogin(introViewController: IntroViewController) { introViewController.dismissViewControllerAnimated(true, completion: { () -> Void in self.presentSignInViewController() }) } } extension BrowserViewController: ContextMenuHelperDelegate { func contextMenuHelper(contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UILongPressGestureRecognizer) { let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) var dialogTitle: String? if let url = elements.link { dialogTitle = url.absoluteString let newTabTitle = NSLocalizedString("Open In New Tab", comment: "Context menu item for opening a link in a new tab") let openNewTabAction = UIAlertAction(title: newTabTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) in self.showToolbars(animated: self.headerConstraintOffset != 0, completion: { _ in self.tabManager.addTab(request: NSURLRequest(URL: url)) }) } actionSheetController.addAction(openNewTabAction) let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard") let copyAction = UIAlertAction(title: copyTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in var pasteBoard = UIPasteboard.generalPasteboard() pasteBoard.string = url.absoluteString } actionSheetController.addAction(copyAction) } if let url = elements.image { if dialogTitle == nil { dialogTitle = url.absoluteString } let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu item for saving an image") let saveImageAction = UIAlertAction(title: saveImageTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in self.getImage(url) { UIImageWriteToSavedPhotosAlbum($0, nil, nil, nil) } } actionSheetController.addAction(saveImageAction) let copyImageTitle = NSLocalizedString("Copy Image", comment: "Context menu item for copying an image to the clipboard") let copyAction = UIAlertAction(title: copyImageTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in let pasteBoard = UIPasteboard.generalPasteboard() pasteBoard.string = url.absoluteString! // TODO: put the actual image on the clipboard } actionSheetController.addAction(copyAction) } // If we're showing an arrow popup, set the anchor to the long press location. if let popoverPresentationController = actionSheetController.popoverPresentationController { popoverPresentationController.sourceView = view popoverPresentationController.sourceRect = CGRect(origin: gestureRecognizer.locationInView(view), size: CGSizeMake(0, 16)) popoverPresentationController.permittedArrowDirections = .Any } actionSheetController.title = dialogTitle var cancelAction = UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: nil) actionSheetController.addAction(cancelAction) self.presentViewController(actionSheetController, animated: true, completion: nil) } private func getImage(url: NSURL, success: UIImage -> ()) { Alamofire.request(.GET, url) .validate(statusCode: 200..<300) .response { _, _, data, _ in if let data = data as? NSData, let image = UIImage(data: data) { success(image) } } } } extension BrowserViewController: HashchangeHelperDelegate { func hashchangeHelperDidHashchange(hashchangeHelper: HashchangeHelper) { if let tab = tabManager.selectedTab, let webView = tab.webView { updateNavigationToolbarStates(tab, webView: webView) } } } extension BrowserViewController: KeyboardHelperDelegate { func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { keyboardState = state // if we are already showing snack bars, adjust them so they sit above the keyboard if snackBars.subviews.count > 0 { adjustFooterSize(top: nil) } } func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { keyboardState = nil // if we are showing snack bars, adjust them so they are no longer sitting above the keyboard if snackBars.subviews.count > 0 { adjustFooterSize(top: nil) } } }
mpl-2.0
75f7be3af98c80e831be1d28d5a6d471
42.885029
229
0.649603
5.780449
false
false
false
false
dkhamsing/osia
Swift/osia/Coordinator.swift
1
1868
// // Coordinator.swift // osia // // Created by Daniel Khamsing on 9/5/17. // Copyright © 2017 Daniel Khamsing. All rights reserved. // import UIKit final class Coordinator { let navigationController: UINavigationController init(navigationController: UINavigationController) { self.navigationController = navigationController } func start() { let v = ListController() v.delegate = self v.title = Constant.title navigationController.pushViewController(v, animated: false) DataSource.Create(url: Constant.url) { result in guard case .success(let root) = result else { return } v.category = root DispatchQueue.main.async { v.reload() } } } } private struct Constant { static let title = "OSIA" static let url = "https://raw.githubusercontent.com/dkhamsing/open-source-ios-apps/master/contents.json" } extension Coordinator: Selectable { func didSelect(_ app: App) { guard app.hasScreenshots else { didSelect(app.source) return } let s = ScreenshotsController() s.delegate = self s.title = app.title s.sourceURL = app.source s.screenshots = app.screenshots navigationController.pushViewController(s, animated: true) } func didSelect(_ category: Category) { let v = ListController() v.delegate = self v.title = category.title v.category = category navigationController.pushViewController(v, animated: true) } func didSelect(_ url: URL?) { guard let url = url else { return } UIApplication.shared.open(url) } } private extension App { var hasScreenshots: Bool { return screenshots?.count ?? 0 > 0 } }
mit
2648721f2219691926a0c9ceb39ff3aa
23.565789
108
0.610605
4.531553
false
false
false
false
jaguerr82/Swift-Matching-Card-Game
FlashMemoryCards/GameViewController.swift
1
2955
// // GameViewController.swift // FlashMemoryCards // // Created by Jorge Guerra on 7/17/17. // Copyright © 2017 Jorge Guerra. All rights reserved. // import UIKit import LTMorphingLabel import MZTimerLabel class GameViewController: UIViewController, MatchingGameDelegate { @IBOutlet weak var practiceMorphLabel: LTMorphingLabel! @IBOutlet weak var cardButton: UIButton! var counter = 1 var game = Game() var gameNumber = 1 var stopwatch: MZTimerLabel! @IBOutlet weak var timerLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() game.newGame() stopwatch = MZTimerLabel.init(label: timerLabel) stopwatch.timeFormat = "mm:ss" stopwatch?.start() game.gameDelegate = self practiceMorphLabel.morphingEffect = .burn } @IBAction func cardTapped(_ sender: UIButton) { let tagNum = sender.tag if game.flipCard(atIndexnumber: tagNum - 1) { let thisImage = UIImage(named: game.deckOfCards.dealtCards[tagNum - 1]) UIView.transition(with: sender, duration: 0.5, options: .transitionFlipFromTop, animations: { sender.setImage(thisImage, for: .normal) }, completion: nil) if game.cardsRemaining.isEmpty { displayGameOver() } } } @IBAction func newGame(_ sender: UIButton) { for tagNum in 1...12 { if let thisButton = self.view.viewWithTag(tagNum) as? UIButton { UIView.transition(with: thisButton, duration: 0.5, options: .transitionFlipFromTop, animations: { thisButton.setImage(#imageLiteral(resourceName: "CardBack"), for: .normal) }, completion: nil) } } gameNumber += 1 practiceMorphLabel.text = "Game #\(gameNumber)" game.newGame() stopwatch.reset() stopwatch.start() } func displayGameOver() { practiceMorphLabel.text = "Game Over!" stopwatch.pause() } func game(_ game: Game, hideCards cards: [Int]) { let delayTime = DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: delayTime) { for cardIndex in cards { if let thisButton = self.view.viewWithTag(cardIndex + 1) as? UIButton { UIView.transition(with: thisButton, duration: 0.5, options: .transitionFlipFromBottom, animations: { thisButton.setImage(#imageLiteral(resourceName: "CardBack"), for: .normal) }, completion: nil) } } self.game.waitingForHidingCards = false //All unmatched crds are hidden } } }
mit
9be4b9c66fb34827106b8c14546a1de1
30.763441
120
0.577522
4.733974
false
false
false
false
hovansuit/FoodAndFitness
FoodAndFitness/Controllers/SideMenu/LeftSideViewModel.swift
1
764
// // LeftSideViewModel.swift // FoodAndFitness // // Created by Mylo Ho on 4/13/17. // Copyright © 2017 SuHoVan. All rights reserved. // import UIKit import RealmS import RealmSwift final class LeftSideViewModel { let user: User? var selectedMenu: LeftSideViewController.SideMenu = .home init() { user = User.me } func dataForUserProfile() -> UserProfileCell.Data? { guard let user = user else { return nil } var url: String? if user.avatarUrl.characters.isNotEmpty { url = ApiPath.baseURL + user.avatarUrl } let bmi = "BMI: " + user.bmiValue.format(f: ".2") return UserProfileCell.Data(avatarUrl: url, userName: user.name, bmi: bmi, status: user.statusBmi) } }
mit
fbd1df770aed781d605aebcd34495c2b
24.433333
106
0.640891
3.777228
false
false
false
false
zorn/Expenses
_FINAL/Expenses/ExpenseListViewController.swift
1
2241
import UIKit class ExpenseListViewController : UITableViewController, UITableViewDataSource, UITableViewDelegate { var expenseCollection = NSMutableArray() // MARK: - UIViewController override func viewDidLoad() { self.expenseCollection.addObject(Expense(name: "Test Expense 1")) self.expenseCollection.addObject(Expense(name: "Test Expense 2")) self.expenseCollection.addObject(Expense(name: "Test Expense 3")) self.expenseCollection.addObject(Expense(name: "Test Expense 4")) super.viewDidLoad() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { if (identifier == "test") { } } } // MARK: - UITableViewDataSource override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return expenseCollection.count; } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // FIXME: What I don't like about this implementation is that I'm duplicating the "desgin" of the "Basic" cell in the storyboard and here in the else branch. I want to keep the storyboard version as it lets me make a segue. Preferably I'd have the app crash if the storyboard design was not available. I could do that by explicitly unpacking the optional I get back from dequeueReusableCellWithIdentifier but that feels "wrong" -- feedback welcome. let cellReuseID = "Basic" if let cell = tableView.dequeueReusableCellWithIdentifier(cellReuseID) as? UITableViewCell { return self.configureCell(cell, indexPath: indexPath) } else { let newCell = UITableViewCell(style: .Default, reuseIdentifier: cellReuseID); return self.configureCell(newCell, indexPath: indexPath) } } // MARK: - Private func configureCell(cell: UITableViewCell, indexPath: NSIndexPath) -> UITableViewCell { let expense = self.expenseCollection.objectAtIndex(indexPath.row) as Expense cell.textLabel.text = expense.name return cell } }
mit
ec00a9a58071ea8ce54be4a0aa6165b4
43.84
456
0.687193
5.361244
false
true
false
false
Sorix/CloudCore
Source/Classes/Save/ObjectToRecord/ObjectToRecordOperation.swift
1
2871
// // ObjectToRecordOperation.swift // CloudCore // // Created by Vasily Ulianov on 09.02.17. // Copyright © 2017 Vasily Ulianov. All rights reserved. // import CloudKit import CoreData class ObjectToRecordOperation: Operation { /// Need to set before starting operation, child context from it will be created var parentContext: NSManagedObjectContext? // Set on init let record: CKRecord private let changedAttributes: [String]? private let serviceAttributeNames: ServiceAttributeNames // var errorCompletionBlock: ((Error) -> Void)? var conversionCompletionBlock: ((CKRecord) -> Void)? init(record: CKRecord, changedAttributes: [String]?, serviceAttributeNames: ServiceAttributeNames) { self.record = record self.changedAttributes = changedAttributes self.serviceAttributeNames = serviceAttributeNames super.init() self.name = "ObjectToRecordOperation" } override func main() { if self.isCancelled { return } guard let parentContext = parentContext else { let error = CloudCoreError.coreData("CloudCore framework error") errorCompletionBlock?(error) return } let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) childContext.parent = parentContext do { try self.fillRecordWithData(using: childContext) try childContext.save() self.conversionCompletionBlock?(self.record) } catch { self.errorCompletionBlock?(error) } } private func fillRecordWithData(using context: NSManagedObjectContext) throws { guard let managedObject = try fetchObject(for: record, using: context) else { throw CloudCoreError.coreData("Unable to find managed object for record: \(record)") } let changedValues = managedObject.committedValues(forKeys: changedAttributes) for (attributeName, value) in changedValues { if attributeName == serviceAttributeNames.recordData || attributeName == serviceAttributeNames.recordID { continue } if let attribute = CoreDataAttribute(value: value, attributeName: attributeName, entity: managedObject.entity) { let recordValue = try attribute.makeRecordValue() record.setValue(recordValue, forKey: attributeName) } else if let relationship = CoreDataRelationship(value: value, relationshipName: attributeName, entity: managedObject.entity) { let references = try relationship.makeRecordValue() record.setValue(references, forKey: attributeName) } } } private func fetchObject(for record: CKRecord, using context: NSManagedObjectContext) throws -> NSManagedObject? { let entityName = record.recordType let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName) fetchRequest.predicate = NSPredicate(format: serviceAttributeNames.recordID + " == %@", record.recordID.encodedString) return try context.fetch(fetchRequest).first as? NSManagedObject } }
mit
4e0cf322af65364cddcef6dfbdd9bd96
34
131
0.76446
4.408602
false
false
false
false
remirobert/TextDrawer
TextDrawer/TextDrawer/TextDrawer.swift
1
9109
// // DrawView.swift // // // Created by Remi Robert on 11/07/15. // // //Scrux import UIKit import Masonry public class TextDrawer: UIView, TextEditViewDelegate { private var textEditView: TextEditView! private var drawTextView: DrawTextView! private var initialTransformation: CGAffineTransform! private var initialCenterDrawTextView: CGPoint! private var initialRotationTransform: CGAffineTransform! private var initialReferenceRotationTransform: CGAffineTransform! private var activieGestureRecognizer = NSMutableSet() private var activeRotationGesture: UIRotationGestureRecognizer? private var activePinchGesture: UIPinchGestureRecognizer? private lazy var tapRecognizer: UITapGestureRecognizer! = { let tapRecognizer = UITapGestureRecognizer(target: self, action: "handleTapGesture:") tapRecognizer.delegate = self return tapRecognizer }() private lazy var panRecognizer: UIPanGestureRecognizer! = { let panRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGesture:") panRecognizer.delegate = self return panRecognizer }() private lazy var rotateRecognizer: UIRotationGestureRecognizer! = { let rotateRecognizer = UIRotationGestureRecognizer(target: self, action: "handlePinchGesture:") rotateRecognizer.delegate = self return rotateRecognizer }() private lazy var zoomRecognizer: UIPinchGestureRecognizer! = { let zoomRecognizer = UIPinchGestureRecognizer(target: self, action: "handlePinchGesture:") zoomRecognizer.delegate = self return zoomRecognizer }() public func clearText() { text = "" } public func resetTransformation() { drawTextView.transform = initialTransformation drawTextView.mas_updateConstraints({ (make: MASConstraintMaker!) -> Void in make.edges.equalTo()(self) make.centerX.and().centerY().equalTo()(self) }) drawTextView.center = center //drawTextView.sizeTextLabel() } //MARK: - //MARK: Setup DrawView private func setup() { self.layer.masksToBounds = true drawTextView = DrawTextView() initialTransformation = drawTextView.transform addSubview(drawTextView) drawTextView.mas_makeConstraints { (make: MASConstraintMaker!) -> Void in make.edges.equalTo()(self) } textEditView = TextEditView() textEditView.delegate = self addSubview(textEditView) textEditView.mas_makeConstraints { (make: MASConstraintMaker!) -> Void in make.edges.equalTo()(self) } addGestureRecognizer(tapRecognizer) addGestureRecognizer(panRecognizer) addGestureRecognizer(rotateRecognizer) addGestureRecognizer(zoomRecognizer) initialReferenceRotationTransform = CGAffineTransformIdentity } //MARK: - //MARK: Initialisation init() { super.init(frame: CGRectZero) setup() drawTextView.textLabel.font = drawTextView.textLabel.font.fontWithSize(44) } override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func textEditViewFinishedEditing(text: String) { textEditView.hidden = true drawTextView.text = text } } //MARK: - //MARK: Proprety extension public extension TextDrawer { public var fontSize: CGFloat! { set { drawTextView.textLabel.font = drawTextView.textLabel.font.fontWithSize(newValue) } get { return drawTextView.textLabel.font.pointSize } } public var font: UIFont! { set { drawTextView.textLabel.font = newValue } get { return drawTextView.textLabel.font } } public var textColor: UIColor! { set { drawTextView.textLabel.textColor = newValue } get { return drawTextView.textLabel.textColor } } public var textAlignement: NSTextAlignment! { set { drawTextView.textLabel.textAlignment = newValue } get { return drawTextView.textLabel.textAlignment } } public var textBackgroundColor: UIColor! { set { drawTextView.textLabel.backgroundColor = newValue } get { return drawTextView.textLabel.backgroundColor } } public var text: String! { set { drawTextView.text = newValue } get { return drawTextView.text } } public var textSize: Int! { set { textEditView.textSize = newValue } get { return textEditView.textSize } } } //MARK: - //MARK: Gesture handler extension extension TextDrawer: UIGestureRecognizerDelegate { public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func handleTapGesture(recognizer: UITapGestureRecognizer) { textEditView.textEntry = text textEditView.isEditing = true textEditView.hidden = false } func handlePanGesture(recognizer: UIPanGestureRecognizer) { let translation = recognizer.translationInView(self) switch recognizer.state { case .Began, .Ended, .Failed, .Cancelled: initialCenterDrawTextView = drawTextView.center case .Changed: drawTextView.center = CGPointMake(initialCenterDrawTextView.x + translation.x, initialCenterDrawTextView.y + translation.y) default: return } } func handlePinchGesture(recognizer: UIGestureRecognizer) { var transform = initialRotationTransform switch recognizer.state { case .Began: if activieGestureRecognizer.count == 0 { initialRotationTransform = drawTextView.transform } activieGestureRecognizer.addObject(recognizer) break case .Changed: for currentRecognizer in activieGestureRecognizer { transform = applyRecogniser(currentRecognizer as? UIGestureRecognizer, currentTransform: transform) } drawTextView.transform = transform break case .Ended, .Failed, .Cancelled: initialRotationTransform = applyRecogniser(recognizer, currentTransform: initialRotationTransform) activieGestureRecognizer.removeObject(recognizer) default: return } } private func applyRecogniser(recognizer: UIGestureRecognizer?, currentTransform: CGAffineTransform) -> CGAffineTransform { if let recognizer = recognizer { if recognizer is UIRotationGestureRecognizer { return CGAffineTransformRotate(currentTransform, (recognizer as! UIRotationGestureRecognizer).rotation) } if recognizer is UIPinchGestureRecognizer { let scale = (recognizer as! UIPinchGestureRecognizer).scale return CGAffineTransformScale(currentTransform, scale, scale) } } return currentTransform } } //MARK: - //MARK: Render extension public extension TextDrawer { public func render() -> UIImage? { return renderTextOnView(self) } public func renderTextOnView(view: UIView) -> UIImage? { UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0) view.layer.renderInContext(UIGraphicsGetCurrentContext()!) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return renderTextOnImage(img) } public func renderTextOnImage(image: UIImage) -> UIImage? { let size = image.size let scale = size.width / CGRectGetWidth(self.bounds) let color = layer.backgroundColor UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0) image.drawInRect(CGRectMake(CGRectGetWidth(self.bounds) / 2 - (image.size.width / scale) / 2, CGRectGetHeight(self.bounds) / 2 - (image.size.height / scale) / 2, image.size.width / scale, image.size.height / scale)) layer.backgroundColor = UIColor.clearColor().CGColor layer.renderInContext(UIGraphicsGetCurrentContext()!) layer.backgroundColor = color let drawnImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return UIImage(CGImage: drawnImage.CGImage!, scale: 1, orientation: drawnImage.imageOrientation) } }
mit
04c7cb8e82d1feab2b1881f591735527
29.982993
179
0.640026
5.62979
false
false
false
false
PigDogBay/swift-utils
SwiftUtils/WordListCallback.swift
1
6727
// // WordListCallback.swift // Anagram Solver // // Created by Mark Bailey on 09/02/2015. // Copyright (c) 2015 MPD Bailey Technology. All rights reserved. // import Foundation public protocol WordListCallback { func update(_ result: String) } public class WordListFilterWrapper : WordListCallback { //should callback be weak? private let callback : WordListCallback! private var matches: [String] = [] public init(callback: WordListCallback) { self.callback = callback } public func update(_ result: String) { if (!matches.contains(result)) { matches.append(result) callback.update(result) } } } public class WordListMissingLetterWrapper : WordListCallback { private let callback : WordListCallback! private let originalWord : String! public init(callback: WordListCallback, originalWord: String) { self.callback = callback self.originalWord = originalWord } public func update(_ result: String) { let missingLetters = originalWord.subtractLetters(result) callback.update("\(result) (\(missingLetters))") } } public class BiggerThanFilter : WordListCallback { private let callback : WordListCallback private let size : Int public init(callback : WordListCallback, size : Int){ self.callback = callback self.size = size } public func update(_ result: String) { if result.count > size { callback.update(result) } } } public class LessThanFilter : WordListCallback { private let callback : WordListCallback private let size : Int public init(callback : WordListCallback, size : Int){ self.callback = callback self.size = size } public func update(_ result: String) { if result.count < size { callback.update(result) } } } public class EqualToFilter : WordListCallback { private let callback : WordListCallback private let size : Int public init(callback : WordListCallback, size : Int){ self.callback = callback self.size = size } public func update(_ result: String) { if result.count == size { callback.update(result) } } } public class StartsWithFilter : WordListCallback { private let callback : WordListCallback private let letters : String public init(callback : WordListCallback, letters : String){ self.callback = callback self.letters = letters } public func update(_ result: String) { if result.hasPrefix(letters) { callback.update(result) } } } public class EndsWithFilter : WordListCallback { private let callback : WordListCallback private let letters : String public init(callback : WordListCallback, letters : String){ self.callback = callback self.letters = letters } public func update(_ result: String) { if result.hasSuffix(letters) { callback.update(result) } } } public class ContainsFilter : WordListCallback { private let callback : WordListCallback private let letterSet : LetterSet public init(callback : WordListCallback, letters : String){ self.callback = callback self.letterSet = LetterSet(word: letters) } public func update(_ result: String) { if (letterSet.isSupergram(result)) { //contains all letters callback.update(result) } } } public class ExcludesFilter : WordListCallback { private let callback : WordListCallback private let letters : String public init(callback : WordListCallback, letters : String){ self.callback = callback self.letters = letters } public func update(_ result: String) { for c in letters.unicodeScalars { if result.unicodeScalars.contains(c){ //excluded letter found return } } //does not contain any of the excluded letters callback.update(result) } } public class ContainsWordFilter : WordListCallback { private let callback : WordListCallback private let word : String public init(callback : WordListCallback, word : String){ self.callback = callback self.word = word } public func update(_ result: String) { if result.contains(word){ callback.update(result) } } } public class ExcludesWordFilter : WordListCallback { private let callback : WordListCallback private let word : String public init(callback : WordListCallback, word : String){ self.callback = callback self.word = word } public func update(_ result: String) { if !result.contains(word){ callback.update(result) } } } public class RegexFilter : WordListCallback { private let callback : WordListCallback private let regex : NSRegularExpression? public init(callback : WordListCallback, pattern : String){ self.callback = callback //need to append word boundaries \b otherwise regex will not match the words in the wordlist //Oddly units will pass without \b, why? regex = try? NSRegularExpression(pattern: "\\b"+pattern+"\\b", options: []) } public func update(_ result: String) { let range = NSRange(location: 0, length: result.length) if 1 == regex?.numberOfMatches(in: result, options: [], range: range){ callback.update(result) } } public class func createCrosswordFilter(callback : WordListCallback, query : String) -> WordListCallback { let pattern = query .replace(".", withString: "[a-z]") .replace("@", withString: "[a-z]+") return RegexFilter(callback: callback, pattern: pattern) } } public class DistinctFilter : WordListCallback { fileprivate let callback : WordListCallback fileprivate let letterSet : LetterSet public init(callback : WordListCallback){ self.callback = callback self.letterSet = LetterSet(word: "") } open func update(_ result: String) { letterSet.clear() letterSet.add(result) if letterSet.isDistinct() { callback.update(result) } } } public class NotDistinctFilter : DistinctFilter { public override func update(_ result: String) { letterSet.clear() letterSet.add(result) if !letterSet.isDistinct() { callback.update(result) } } }
apache-2.0
e4a3fa39f640e35c152cfea4731a1ee1
25.908
110
0.625539
4.529966
false
false
false
false
RedRoster/rr-ios
RedRoster/Login/NewUserPage.swift
1
1080
// // PageOneViewController.swift // RedRoster // // Created by Daniel Li on 4/4/16. // Copyright © 2016 dantheli. All rights reserved. // import UIKit class NewUserPage: UIViewController { var isLastPage: Bool = false var topText: String! var bottomText: String! var imageName: String! @IBOutlet weak var topLabel: UILabel! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var bottomLabel: UILabel! @IBOutlet weak var proceedButton: UIButton! @IBAction func proceedButton(_ sender: UIButton) { if isLastPage { dismiss(animated: true, completion: nil) } else { } } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.rosterRed() topLabel.text = topText ?? "" bottomLabel.text = bottomText ?? "" imageView.image = UIImage(named: imageName ?? "") proceedButton.setTitle(isLastPage ? "Start using RedRoster" : "Next", for: UIControlState()) } }
apache-2.0
fe36e802926991f837f676f6f0d271a9
24.093023
100
0.610751
4.611111
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/maximum-width-of-binary-tree.swift
2
2661
/** * https://leetcode.com/problems/maximum-width-of-binary-tree/ * * */ // Date: Fri Jul 10 22:56:25 PDT 2020 /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init(_ val: Int) { * self.val = val * self.left = nil * self.right = nil * } * } */ class Solution { func widthOfBinaryTree(_ root: TreeNode?) -> Int { guard let root = root else { return 0 } var queue = [(root, 0)] var maxL: Int = 1 while queue.isEmpty == false { var size = queue.count while size > 0 { let (node, position) = queue.removeFirst() size -= 1 if let left = node.left { queue.append((left, position &* 2)) } if let right = node.right { queue.append((right, position &* 2 + 1)) } } if let first = queue.first, let last = queue.last { maxL = max(maxL, last.1 - first.1 + 1) } } return maxL } } /** * https://leetcode.com/problems/maximum-width-of-binary-tree/ * * */ // Date: Fri Jul 10 23:20:20 PDT 2020 /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init(_ val: Int) { * self.val = val * self.left = nil * self.right = nil * } * } */ class Solution { // Introduce the offset. // This solution shift all the position to left by offset. // Reference: https://www.youtube.com/watch?v=7LBdfdC8vhs func widthOfBinaryTree(_ root: TreeNode?) -> Int { guard let root = root else { return 0 } var queue = [(root, 0)] var maxL: Int = 1 while queue.isEmpty == false { var size = queue.count let offset = queue.first?.1 ?? 0 while size > 0 { let (node, position) = queue.removeFirst() size -= 1 if let left = node.left { queue.append((left, position * 2 - offset)) } if let right = node.right { queue.append((right, position * 2 - offset + 1)) } } if let first = queue.first, let last = queue.last { maxL = max(maxL, last.1 - first.1 + 1) } } return maxL } }
mit
3d54285b03115b1ea12f96b0a29c6c15
27.308511
68
0.478767
3.953938
false
false
false
false
box/box-ios-sdk
Sources/Modules/FoldersModule+Async.swift
1
14234
// // FoldersModule+Async.swift // BoxSDK-iOS // // Created by Artur Jankowski on 18/05/2022. // Copyright © 2022 box. All rights reserved. // import Foundation import UIKit @available(iOS 13.0, *) public extension FoldersModule { /// Get information about a folder. /// /// - Parameters: /// - folderId: The ID of the folder on which to retrieve information. /// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to /// include in the response. /// - Returns: Folder object /// - Throws: BoxSDKError if the parentId is invalid or if a name collision occurs. func get( folderId: String, fields: [String]? = nil ) async throws -> Folder { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<Folder>) in self.get(folderId: folderId, fields: fields, completion: callback) } } /// Create a new folder. /// /// - Parameters: /// - name: The desired name for the folder. Box supports folder names of 255 characters or /// less. Names containing non-printable ASCII characters, "/" or "\", names with trailing /// spaces, and the special names “.” and “..” are also not allowed. /// - parentId: The ID of the parent folder. /// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to /// include in the response. /// - Returns: A full folder object. /// - Throws: A BoxSDKError if the parentId is invalid or if a name collision occurs. func create( name: String, parentId: String, fields: [String]? = nil ) async throws -> Folder { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<Folder>) in self.create(name: name, parentId: parentId, fields: fields, completion: callback) } } /// Update a folder. /// /// - Parameters: /// - folderId: The ID of the file to update /// - name: The name of the folder. /// - description: The description of the folder. /// - parentId: The ID of the parent folder /// - sharedLink: Shared links provide direct, read-only access to folder on Box using a URL. /// - folderUploadEmailAccess: Can be open or collaborators /// - tags: Array of tags to be added or replaced to the folder /// - canNonOwnersInvite: If this parameter is set to false, only folder owners and co-owners can send collaborator invites /// - isCollaborationRestrictedToEnterprise: Whether to restrict future collaborations to within the enterprise. Does not affect existing collaborations. /// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to /// include in the response. /// - Returns: The updated folder is returned if the name is valid. /// - Throws: A BoxSDKError if the parentId is invalid or if a name collision occurs. func update( folderId: String, name: String? = nil, description: String? = nil, parentId: String? = nil, sharedLink: NullableParameter<SharedLinkData>? = nil, folderUploadEmailAccess: FolderUploadEmailAccess? = nil, tags: [String]? = nil, canNonOwnersInvite: Bool? = nil, isCollaborationRestrictedToEnterprise: Bool? = nil, collections: [String]? = nil, fields: [String]? = nil ) async throws -> Folder { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<Folder>) in self.update( folderId: folderId, name: name, description: description, parentId: parentId, sharedLink: sharedLink, folderUploadEmailAccess: folderUploadEmailAccess, tags: tags, canNonOwnersInvite: canNonOwnersInvite, isCollaborationRestrictedToEnterprise: isCollaborationRestrictedToEnterprise, collections: collections, fields: fields, completion: callback ) } } /// Delete a folder or move a folder to the trash. The recursive parameter must be included in /// order to delete folders that aren't empty. Depending on the [enterprise settings for this /// user](https://community.box.com/t5/Managing-Files-and-Folders/Trash/ta-p/19212), the item /// will either be actually deleted from Box or [moved to the trash] /// (https://developer.box.com/reference#get-the-items-in-the-trash). /// /// - Parameters: /// - folderId: The ID of the file to delete. /// - recursive: Whether to delete this folder if it has items inside of it. /// - Returns: An empty response will be returned upon successful deletion. /// - Throws: A BoxSDKError if the folder is not empty and the ‘recursive’ parameter is not included. func delete(folderId: String, recursive: Bool? = nil) async throws { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<Void>) in self.delete(folderId: folderId, recursive: recursive, completion: callback) } } /// Create a copy of a folder in another folder. The original version of the folder will not be altered. /// /// - Parameters: /// - folderId: The ID of the folder that will be copy. /// - destinationFolderId: The ID of the destination folder /// - name: An optional new name for the folder /// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to /// include in the response. /// - Returns: The full folder object. /// - Throws: A BoxSDKError if a name collision occurs. func copy( folderId: String, destinationFolderId: String, name: String? = nil, fields: [String]? = nil ) async throws -> Folder { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<Folder>) in self.copy( folderId: folderId, destinationFolderID: destinationFolderId, name: name, fields: fields, completion: callback ) } } /// Add folder to favorites /// /// - Parameters: /// - folderId: The ID of the folder /// - fields: Comma-separated list of folder [fields](https://developer.box.com/reference#fields) to /// include in the response. /// - Returns: The updated folder. /// - Throws: BoxSDKError. func addToFavorites( folderId: String, fields: [String]? = nil ) async throws -> Folder { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<Folder>) in self.addToFavorites(folderId: folderId, fields: fields, completion: callback) } } /// Add folder to particular collection /// /// - Parameters: /// - folderId: The ID of the folder /// - fields: Comma-separated list of folder [fields](https://developer.box.com/reference#fields) to /// include in the response. /// - Returns: The updated folder or an error /// - Throws: BoxSDKError func addToCollection( folderId: String, collectionId: String, fields: [String]? = nil ) async throws -> Folder { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<Folder>) in self.addToCollection( folderId: folderId, collectionId: collectionId, fields: fields, completion: callback ) } } /// Remove folder from favorites /// /// - Parameters: /// - folderId: The ID of the folder /// - fields: Comma-separated list of folder [fields](https://developer.box.com/reference#fields) to /// include in the response. /// - Returns: The updated folder or an error /// - Throws: BoxSDKError func removeFromFavorites( folderId: String, fields: [String]? = nil ) async throws -> Folder { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<Folder>) in self.removeFromFavorites( folderId: folderId, fields: fields, completion: callback ) } } /// Remove folder from particular collection /// /// - Parameters: /// - folderId: The ID of the folder /// - collectionId: The ID of the collection /// - fields: Comma-separated list of folder [fields](https://developer.box.com/reference#fields) to /// include in the response. /// - Returns: The updated folder /// - Throws: BoxSDKError func removeFromCollection( folderId: String, collectionId: String, fields: [String]? = nil ) async throws -> Folder { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<Folder>) in self.removeFromCollection( folderId: folderId, collectionId: collectionId, fields: fields, completion: callback ) } } /// Gets folder with updated shared link /// /// - Parameters: /// - folderId: The ID of the folder /// - Returns: The SharedLink object /// - Throws: BoxSDKError func getSharedLink(forFolder folderId: String) async throws -> SharedLink { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<SharedLink>) in self.getSharedLink(forFolder: folderId, completion: callback) } } /// Creates or updates shared link for a folder /// /// - Parameters: /// - folderId: The ID of the folder /// - access: The level of access. If you omit this field then the access level will be set to the default access level specified by the enterprise admin /// - unsharedAt: The date-time that this link will become disabled. This field can only be set by users with paid accounts /// - vanityName: The custom name of a shared link, as used in the vanityUrl field. /// It should be between 12 and 30 characters. This field can contains only letters, numbers, and hyphens. /// - password: The password required to access the shared link. Set to .null to remove the password /// - canDownload: Whether the shared link allows downloads. Applies to any items in the folder /// - Returns: The SharedLink object /// - Throws: BoxSDKError func setSharedLink( forFolder folderId: String, access: SharedLinkAccess? = nil, unsharedAt: NullableParameter<Date>? = nil, vanityName: NullableParameter<String>? = nil, password: NullableParameter<String>? = nil, canDownload: Bool? = nil ) async throws -> SharedLink { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<SharedLink>) in self.setSharedLink( forFolder: folderId, access: access, unsharedAt: unsharedAt, vanityName: vanityName, password: password, canDownload: canDownload, completion: callback ) } } /// Removes shared link for a folder /// /// - Parameters: /// - folderId: The ID of the folder /// - Throws: BoxSDKError func deleteSharedLink(forFolder folderId: String) async throws { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<Void>) in self.deleteSharedLink(forFolder: folderId, completion: callback) } } /// Retrieves the watermark on a specified folder. /// /// - Parameters: /// - folderId: The id of the folder to retrieve the watermark from. /// - Returns: The Watermark object. /// - Throws: BoxSDKError func getWatermark(folderId: String) async throws -> Watermark { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<Watermark>) in self.getWatermark(folderId: folderId, completion: callback) } } /// Apply or update the watermark on a specified folder. /// /// - Parameters: /// - folderId: The id of the folder to update the watermark for. /// - Returns: The Watermark object. /// - Throws: BoxSDKError func applyWatermark(folderId: String) async throws -> Watermark { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<Watermark>) in self.applyWatermark(folderId: folderId, completion: callback) } } /// Remove the watermark from a specified folder. /// /// - Parameters: /// - folderId: The id of the folder to remove the watermark from. /// - Throws: BoxSDKError func removeWatermark(folderId: String) async throws { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<Void>) in self.removeWatermark(folderId: folderId, completion: callback) } } /// Creates a folder lock on a folder, preventing it from being moved and/or deleted. /// /// - Parameters: /// - folderId: The ID of the folder to apply the lock to. /// - Returns: The Folder lock object /// - Throws: BoxSDKError func createLock(folderId: String) async throws -> FolderLock { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<FolderLock>) in self.createLock(folderId: folderId, completion: callback) } } /// Remove the specified folder lock. /// /// - Parameters: /// - folderLockId: The id of the folder lock to remove. /// - Throws: BoxSDKError func deleteLock(folderLockId: String) async throws { return try await AsyncHelper.asyncifyCallback { (callback: @escaping Callback<Void>) in self.deleteLock(folderLockId: folderLockId, completion: callback) } } }
apache-2.0
bf908112bc7379c299f9b378d21c43a0
40.581871
159
0.623163
4.667214
false
false
false
false
edx/edx-app-ios
Source/CourseOutlineViewController.swift
1
20545
// // CourseOutlineViewController.swift // edX // // Created by Akiva Leffert on 4/30/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation import UIKit public enum CourseOutlineMode { case full case video } public class CourseOutlineViewController : OfflineSupportViewController, CourseBlockViewController, CourseContentPageViewControllerDelegate, PullRefreshControllerDelegate, LoadStateViewReloadSupport, InterfaceOrientationOverriding { public typealias Environment = OEXAnalyticsProvider & DataManagerProvider & OEXInterfaceProvider & NetworkManagerProvider & ReachabilityProvider & OEXRouterProvider & OEXConfigProvider & OEXStylesProvider private var rootID : CourseBlockID? private var environment : Environment private let courseQuerier : CourseOutlineQuerier private let tableController : CourseOutlineTableController private let blockIDStream = BackedStream<CourseBlockID?>() private let headersLoader = BackedStream<CourseOutlineQuerier.BlockGroup>() private let rowsLoader = BackedStream<[CourseOutlineQuerier.BlockGroup]>() private let courseDateBannerLoader = BackedStream<(CourseDateBannerModel)>() private let loadController : LoadStateViewController private let insetsController : ContentInsetsController private var resumeCourseController : ResumeCourseController private(set) var courseOutlineMode: CourseOutlineMode /// Strictly a test variable used as a trigger flag. Not to be used out of the test scope fileprivate var t_hasTriggeredSetResumeCourse = false private var canDownload: Bool { return environment.dataManager.interface?.canDownload() ?? false } public var blockID : CourseBlockID? { return blockIDStream.value ?? nil } public var courseID : String { return courseQuerier.courseID } public var block: CourseBlock? { return courseQuerier.blockWithID(id: blockID).value } private var course: OEXCourse? { return environment.dataManager.enrollmentManager.enrolledCourseWithID(courseID: courseID)?.course } public init(environment: Environment, courseID : String, rootID : CourseBlockID?, forMode mode: CourseOutlineMode?) { self.rootID = rootID self.environment = environment courseQuerier = environment.dataManager.courseDataManager.querierForCourseWithID(courseID: courseID, environment: environment) loadController = LoadStateViewController() insetsController = ContentInsetsController() courseOutlineMode = mode ?? .full tableController = CourseOutlineTableController(environment: environment, courseID: courseID, forMode: courseOutlineMode, courseBlockID: rootID) resumeCourseController = ResumeCourseController(blockID: rootID , dataManager: environment.dataManager, networkManager: environment.networkManager, courseQuerier: courseQuerier, forMode: courseOutlineMode) super.init(env: environment, shouldShowOfflineSnackBar: false) addObserver() resumeCourseController.delegate = self addChild(tableController) tableController.didMove(toParent: self) tableController.delegate = self } // componentID is only being used for deeplinking to component var componentID: String? { didSet { guard componentID != nil else { return } navigateToComponentScreenIfNeeded() } } public func reloadData() { tableController.tableView.reloadData() } public required init?(coder aDecoder: NSCoder) { // required by the compiler because UIViewController implements NSCoding, // but we don't actually want to serialize these things fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil) view.backgroundColor = OEXStyles.shared().standardBackgroundColor() view.addSubview(tableController.view) loadController.setupInController(controller: self, contentView:tableController.view) tableController.refreshController.setupInScrollView(scrollView: tableController.tableView) tableController.refreshController.delegate = self insetsController.setupInController(owner: self, scrollView : tableController.tableView) view.setNeedsUpdateConstraints() addListeners() setAccessibilityIdentifiers() } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) resumeCourseController.loadResumeCourse(forMode: courseOutlineMode) loadCourseStream() if courseOutlineMode == .video { // We are doing calculations to show downloading progress on video tab, For this purpose we are observing notifications. tableController.courseVideosHeaderView?.addObservers() } } public override func viewWillDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if courseOutlineMode == .video { // As calculations are made to show progress on view. So when any other view apear we stop observing and making calculations for better performance. tableController.courseVideosHeaderView?.removeObservers() } } override public var shouldAutorotate: Bool { return true } override public var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .allButUpsideDown } override public func updateViewConstraints() { loadController.insets = UIEdgeInsets(top: view.safeAreaInsets.top, left: 0, bottom: view.safeAreaInsets.bottom, right : 0) tableController.view.snp.remakeConstraints { make in make.edges.equalTo(safeEdges) } super.updateViewConstraints() } override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() insetsController.updateInsets() } override func reloadViewData() { reload() } private func setAccessibilityIdentifiers() { view.accessibilityIdentifier = "CourseOutlineViewController:view" tableController.tableView.accessibilityIdentifier = "CourseOutlineViewController:course-outline-table-view" loadController.view.accessibilityIdentifier = "CourseOutlineViewController:load-state-controller-view" } private func setupNavigationItem(block : CourseBlock) { navigationItem.title = (courseOutlineMode == .video && rootID == nil) ? Strings.Dashboard.courseVideos : block.displayName } private func addObserver() { NotificationCenter.default.oex_addObserver(observer: self, name: NOTIFICATION_SHIFT_COURSE_DATES) { _, observer, _ in observer.refreshCourseOutlineController() } } private var courseOutlineLoaded = false private func loadCourseOutlineStream() { let courseOutlineStream = joinStreams(courseQuerier.rootID, courseQuerier.blockWithID(id: blockID)) courseOutlineStream.extendLifetimeUntilFirstResult (success : { [weak self] (rootID, block) in if self?.blockID == rootID || self?.blockID == nil { if self?.courseOutlineMode == .full { self?.courseOutlineLoaded = true self?.navigateToComponentScreenIfNeeded() self?.environment.analytics.trackScreen(withName: OEXAnalyticsScreenCourseOutline, courseID: self?.courseID, value: nil) } else { self?.environment.analytics.trackScreen(withName: AnalyticsScreenName.CourseVideos.rawValue, courseID: self?.courseID, value: nil) } } else { self?.environment.analytics.trackScreen(withName: OEXAnalyticsScreenSectionOutline, courseID: self?.courseID, value: block.internalName) self?.tableController.isSectionOutline = true } }, failure: { Logger.logError("ANALYTICS", "Unable to load block: \($0)") }) } private func loadCourseBannerStream() { let courseBannerRequest = CourseDateBannerAPI.courseDateBannerRequest(courseID: courseID) let courseBannerStream = environment.networkManager.streamForRequest(courseBannerRequest) courseDateBannerLoader.backWithStream(courseBannerStream) courseBannerStream.listen(self) { [weak self] result in switch result { case .success(let courseBanner): self?.handleDatesBanner(courseBanner: courseBanner) break case .failure(let error): self?.hideCourseBannerView() Logger.logError("DatesResetBanner", "Unable to load dates reset banner: \(error.localizedDescription)") break } } } private func handleDatesBanner(courseBanner: CourseDateBannerModel) { guard let isSelfPaced = course?.isSelfPaced else { hideCourseBannerView() return } if isSelfPaced { loadCourseDateBannerView(courseBanner: courseBanner) } else { if let status = courseBanner.bannerInfo.status, status == .upgradeToCompleteGradedBanner { loadCourseDateBannerView(courseBanner: courseBanner) } else { hideCourseBannerView() } } } private func loadCourseStream() { loadController.state = .Initial loadCourseOutlineStream() loadCourseBannerStream() reload() } private func loadCourseDateBannerView(courseBanner: CourseDateBannerModel) { if courseBanner.hasEnded { tableController.hideCourseDateBanner() } else { tableController.showCourseDateBanner(bannerInfo: courseBanner.bannerInfo) } } private func hideCourseBannerView() { tableController.hideCourseDateBanner() } private func reload() { blockIDStream.backWithStream(OEXStream(value : self.blockID)) } private func emptyState() -> LoadState { return LoadState.empty(icon: .UnknownError, message : (courseOutlineMode == .video) ? Strings.courseVideoUnavailable : Strings.coursewareUnavailable) } private func showErrorIfNecessary(error : NSError) { if loadController.state.isInitial { loadController.state = LoadState.failed(error: error) } } private func addBackStreams() { headersLoader.backWithStream(blockIDStream.transform {[weak self] blockID in if let owner = self { return owner.courseQuerier.childrenOfBlockWithID(blockID: blockID, forMode: owner.courseOutlineMode) } else { return OEXStream<CourseOutlineQuerier.BlockGroup>(error: NSError.oex_courseContentLoadError()) }} ) rowsLoader.backWithStream(headersLoader.transform {[weak self] headers in if let owner = self { let children = headers.children.map {header in return owner.courseQuerier.childrenOfBlockWithID(blockID: header.blockID, forMode: owner.courseOutlineMode) } return joinStreams(children) } else { return OEXStream(error: NSError.oex_courseContentLoadError()) }} ) blockIDStream.backWithStream(OEXStream(value: rootID)) } private func loadHeaderStream() { headersLoader.listen(self, success: { [weak self] headers in self?.setupNavigationItem(block: headers.block) }, failure: { _ in }) } private func loadRowsStream() { rowsLoader.listen(self, success : { [weak self] groups in if let owner = self { owner.tableController.groups = groups owner.tableController.tableView.reloadData() owner.loadController.state = groups.count == 0 ? owner.emptyState() : .Loaded } }, failure : {[weak self] error in self?.showErrorIfNecessary(error: error) }, finally: {[weak self] in if let active = self?.rowsLoader.active, !active { self?.tableController.refreshController.endRefreshing() } } ) } private func loadBackedStreams() { loadHeaderStream() loadRowsStream() } private func addListeners() { addBackStreams() loadBackedStreams() } func resetCourseDate(controller: CourseOutlineTableController) { trackDatesShiftTapped() hideCourseBannerView() let request = CourseDateBannerAPI.courseDatesResetRequest(courseID: courseID) environment.networkManager.taskForRequest(request) { [weak self] result in if let _ = result.error { self?.trackDatesShiftEvent(success: false) self?.showDateResetSnackBar(message: Strings.Coursedates.ResetDate.errorMessage) } else { self?.trackDatesShiftEvent(success: true) self?.showSnackBar() self?.postCourseDateResetNotification() } } } private func trackDatesShiftTapped() { guard let courseMode = environment.dataManager.enrollmentManager.enrolledCourseWithID(courseID: courseID)?.mode else { return } environment.analytics.trackDatesShiftButtonTapped(screenName: AnalyticsScreenName.CourseDashboard, courseMode: courseMode) } private func trackDatesShiftEvent(success: Bool) { guard let courseMode = environment.dataManager.enrollmentManager.enrolledCourseWithID(courseID: courseID)?.mode else { return } environment.analytics.trackDatesShiftEvent(screenName: AnalyticsScreenName.CourseDashboard, courseMode: courseMode, success: success) } private func showSnackBar() { showDateResetSnackBar(message: Strings.Coursedates.toastSuccessMessage, buttonText: Strings.Coursedates.viewAllDates, showButton: true) { [weak self] in if let weakSelf = self { weakSelf.environment.router?.showDatesTabController(controller: weakSelf) weakSelf.hideSnackBar() } } } private func postCourseDateResetNotification() { NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: NOTIFICATION_SHIFT_COURSE_DATES))) } private func refreshCourseOutlineController() { hideCourseBannerView() courseQuerier.needsRefresh = true loadBackedStreams() loadCourseStream() } func navigateToComponentScreenIfNeeded() { if courseOutlineLoaded, let componentID = componentID { self.componentID = nil environment.router?.navigateToComponentScreen(from: self, courseID: courseID, componentID: componentID) } } deinit { NotificationCenter.default.removeObserver(self) } //MARK: PullRefreshControllerDelegate public func refreshControllerActivated(controller: PullRefreshController) { refreshCourseOutlineController() } //MARK: CourseContentPageViewControllerDelegate public func courseContentPageViewController(controller: CourseContentPageViewController, enteredBlockWithID blockID: CourseBlockID, parentID: CourseBlockID) { blockIDStream.backWithStream(courseQuerier.parentOfBlockWithID(blockID: parentID)) tableController.highlightedBlockID = blockID } //MARK:- LoadStateViewReloadSupport method func loadStateViewReload() { reload() } } //MARK: ResumeCourseControllerDelegate extension CourseOutlineViewController: ResumeCourseControllerDelegate { public func resumeCourseControllerDidFetchResumeCourseItem(item: ResumeCourseItem?) { guard let resumeCourseItem = item, !resumeCourseItem.lastVisitedBlockID.isEmpty else { tableController.hideResumeCourse() return } courseQuerier.blockWithID(id: resumeCourseItem.lastVisitedBlockID).extendLifetimeUntilFirstResult(success: { [weak self] block in switch block.type { case .Course, .Chapter, .Unit, .Section: self?.tableController.hideResumeCourse() default: self?.tableController.showResumeCourse(item: resumeCourseItem) } }, failure: { [weak self] _ in self?.tableController.hideResumeCourse() }) } } extension CourseOutlineViewController: CourseOutlineTableControllerDelegate { func outlineTableControllerChoseShowDownloads(controller: CourseOutlineTableController) { environment.router?.showDownloads(from: self) } func outlineTableController(controller: CourseOutlineTableController, choseDownloadVideos videos: [OEXHelperVideoDownload], rootedAtBlock block:CourseBlock) { if canDownload { environment.dataManager.interface?.downloadVideos(videos) let courseID = self.courseID let analytics = environment.analytics courseQuerier.parentOfBlockWithID(blockID: block.blockID).listenOnce(self, success: { parentID in analytics.trackSubSectionBulkVideoDownload(parentID, subsection: block.blockID, courseID: courseID, videoCount: videos.count) }, failure: {error in Logger.logError("ANALYTICS", "Unable to find parent of block: \(block). Error: \(error.localizedDescription)") }) } else { showOverlay(withMessage: environment.interface?.networkErrorMessage() ?? Strings.noWifiMessage) } } func outlineTableController(controller: CourseOutlineTableController, choseDownloadVideoForBlock block: CourseBlock) { if canDownload { environment.dataManager.interface?.downloadVideos(withIDs: [block.blockID], courseID: courseID) environment.analytics.trackSingleVideoDownload(block.blockID, courseID: courseID, unitURL: block.webURL?.absoluteString) } else { showOverlay(withMessage: environment.interface?.networkErrorMessage() ?? Strings.noWifiMessage) } } func outlineTableController(controller: CourseOutlineTableController, resumeCourse item: ResumeCourseItem) { environment.router?.navigateToComponentScreen(from: self, courseID: courseID, componentID: item.lastVisitedBlockID) } func outlineTableController(controller: CourseOutlineTableController, choseBlock block: CourseBlock, parent: CourseBlockID) { if block.specialExamInfo != nil || (block.type == .Section && block.children.isEmpty) { environment.router?.showCourseUnknownBlock(blockID: block.blockID, courseID: courseQuerier.courseID, fromController: self) } else { environment.router?.showContainerForBlockWithID(blockID: block.blockID, type: block.displayType, parentID: parent, courseID: courseQuerier.courseID, fromController: self, forMode: courseOutlineMode) } } func outlineTableControllerReload(controller: CourseOutlineTableController) { courseQuerier.needsRefresh = true reload() } } extension CourseOutlineViewController { public func t_setup() -> OEXStream<Void> { return rowsLoader.map { _ in } } public func t_currentChildCount() -> Int { return tableController.groups.count } public func t_populateResumeCourseItem(item : ResumeCourseItem) -> Bool { tableController.showResumeCourse(item: item) return tableController.tableView.tableHeaderView != nil } public func t_didTriggerSetResumeCourse() -> Bool { return t_hasTriggeredSetResumeCourse } public func t_tableView() -> UITableView { return tableController.tableView } }
apache-2.0
be7007da326d5f130c82c2e708a5b468
39.522682
213
0.671842
5.527307
false
false
false
false
HongliYu/firefox-ios
Client/Frontend/Browser/TabToolbar.swift
1
13361
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SnapKit import Shared protocol TabToolbarProtocol: AnyObject { var tabToolbarDelegate: TabToolbarDelegate? { get set } var tabsButton: TabsButton { get } var menuButton: ToolbarButton { get } var libraryButton: ToolbarButton { get } var forwardButton: ToolbarButton { get } var backButton: ToolbarButton { get } var stopReloadButton: ToolbarButton { get } var actionButtons: [Themeable & UIButton] { get } func updateBackStatus(_ canGoBack: Bool) func updateForwardStatus(_ canGoForward: Bool) func updateReloadStatus(_ isLoading: Bool) func updatePageStatus(_ isWebPage: Bool) func updateTabCount(_ count: Int, animated: Bool) func privateModeBadge(visible: Bool) } protocol TabToolbarDelegate: AnyObject { func tabToolbarDidPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidLongPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidLongPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidLongPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressStop(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressMenu(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressLibrary(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidLongPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) } class ToolbarPrivateModeBadge: UIImageView { let privateModeBadgeSize = CGFloat(16) let privateModeBadgeOffset = CGFloat(10) init() { super.init(image: UIImage(imageLiteralResourceName: "privateModeBadge")) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func layout(forTabsButton button: UIButton) { snp.remakeConstraints { make in make.size.equalTo(privateModeBadgeSize) make.centerX.equalTo(button).offset(privateModeBadgeOffset) make.centerY.equalTo(button).offset(-privateModeBadgeOffset) } } } @objcMembers open class TabToolbarHelper: NSObject { let toolbar: TabToolbarProtocol let ImageReload = UIImage.templateImageNamed("nav-refresh") let ImageStop = UIImage.templateImageNamed("nav-stop") var loading: Bool = false { didSet { if loading { toolbar.stopReloadButton.setImage(ImageStop, for: .normal) toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Stop", comment: "Accessibility Label for the tab toolbar Stop button") } else { toolbar.stopReloadButton.setImage(ImageReload, for: .normal) toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Reload", comment: "Accessibility Label for the tab toolbar Reload button") } } } fileprivate func setTheme(forButtons buttons: [Themeable]) { buttons.forEach { $0.applyTheme() } } init(toolbar: TabToolbarProtocol) { self.toolbar = toolbar super.init() toolbar.backButton.setImage(UIImage.templateImageNamed("nav-back"), for: .normal) toolbar.backButton.accessibilityLabel = NSLocalizedString("Back", comment: "Accessibility label for the Back button in the tab toolbar.") let longPressGestureBackButton = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressBack)) toolbar.backButton.addGestureRecognizer(longPressGestureBackButton) toolbar.backButton.addTarget(self, action: #selector(didClickBack), for: .touchUpInside) toolbar.forwardButton.setImage(UIImage.templateImageNamed("nav-forward"), for: .normal) toolbar.forwardButton.accessibilityLabel = NSLocalizedString("Forward", comment: "Accessibility Label for the tab toolbar Forward button") let longPressGestureForwardButton = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressForward)) toolbar.forwardButton.addGestureRecognizer(longPressGestureForwardButton) toolbar.forwardButton.addTarget(self, action: #selector(didClickForward), for: .touchUpInside) toolbar.stopReloadButton.setImage(UIImage.templateImageNamed("nav-refresh"), for: .normal) toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Reload", comment: "Accessibility Label for the tab toolbar Reload button") let longPressGestureStopReloadButton = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressStopReload)) toolbar.stopReloadButton.addGestureRecognizer(longPressGestureStopReloadButton) toolbar.stopReloadButton.addTarget(self, action: #selector(didClickStopReload), for: .touchUpInside) toolbar.tabsButton.addTarget(self, action: #selector(didClickTabs), for: .touchUpInside) let longPressGestureTabsButton = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressTabs)) toolbar.tabsButton.addGestureRecognizer(longPressGestureTabsButton) toolbar.menuButton.contentMode = .center toolbar.menuButton.setImage(UIImage.templateImageNamed("nav-menu"), for: .normal) toolbar.menuButton.accessibilityLabel = Strings.AppMenuButtonAccessibilityLabel toolbar.menuButton.addTarget(self, action: #selector(didClickMenu), for: .touchUpInside) toolbar.menuButton.accessibilityIdentifier = "TabToolbar.menuButton" toolbar.libraryButton.contentMode = .center toolbar.libraryButton.setImage(UIImage.templateImageNamed("menu-library"), for: .normal) toolbar.libraryButton.accessibilityLabel = Strings.AppMenuButtonAccessibilityLabel toolbar.libraryButton.addTarget(self, action: #selector(didClickLibrary), for: .touchUpInside) toolbar.libraryButton.accessibilityIdentifier = "TabToolbar.libraryButton" setTheme(forButtons: toolbar.actionButtons) } func didClickBack() { toolbar.tabToolbarDelegate?.tabToolbarDidPressBack(toolbar, button: toolbar.backButton) } func didLongPressBack(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == .began { toolbar.tabToolbarDelegate?.tabToolbarDidLongPressBack(toolbar, button: toolbar.backButton) } } func didClickTabs() { toolbar.tabToolbarDelegate?.tabToolbarDidPressTabs(toolbar, button: toolbar.tabsButton) } func didLongPressTabs(_ recognizer: UILongPressGestureRecognizer) { toolbar.tabToolbarDelegate?.tabToolbarDidLongPressTabs(toolbar, button: toolbar.tabsButton) } func didClickForward() { toolbar.tabToolbarDelegate?.tabToolbarDidPressForward(toolbar, button: toolbar.forwardButton) } func didLongPressForward(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == .began { toolbar.tabToolbarDelegate?.tabToolbarDidLongPressForward(toolbar, button: toolbar.forwardButton) } } func didClickMenu() { toolbar.tabToolbarDelegate?.tabToolbarDidPressMenu(toolbar, button: toolbar.menuButton) } func didClickLibrary() { toolbar.tabToolbarDelegate?.tabToolbarDidPressLibrary(toolbar, button: toolbar.menuButton) } func didClickStopReload() { if loading { toolbar.tabToolbarDelegate?.tabToolbarDidPressStop(toolbar, button: toolbar.stopReloadButton) } else { toolbar.tabToolbarDelegate?.tabToolbarDidPressReload(toolbar, button: toolbar.stopReloadButton) } } func didLongPressStopReload(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == .began && !loading { toolbar.tabToolbarDelegate?.tabToolbarDidLongPressReload(toolbar, button: toolbar.stopReloadButton) } } func updateReloadStatus(_ isLoading: Bool) { loading = isLoading } } class ToolbarButton: UIButton { var selectedTintColor: UIColor! var unselectedTintColor: UIColor! var disabledTintColor = UIColor.Photon.Grey50 override init(frame: CGRect) { super.init(frame: frame) adjustsImageWhenHighlighted = false selectedTintColor = tintColor unselectedTintColor = tintColor imageView?.contentMode = .scaleAspectFit } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open var isHighlighted: Bool { didSet { self.tintColor = isHighlighted ? selectedTintColor : unselectedTintColor } } override open var isEnabled: Bool { didSet { self.tintColor = isEnabled ? unselectedTintColor : disabledTintColor } } override var tintColor: UIColor! { didSet { self.imageView?.tintColor = self.tintColor } } } extension ToolbarButton: Themeable { func applyTheme() { selectedTintColor = UIColor.theme.toolbarButton.selectedTint disabledTintColor = UIColor.theme.toolbarButton.disabledTint unselectedTintColor = UIColor.theme.browser.tint tintColor = isEnabled ? unselectedTintColor : disabledTintColor imageView?.tintColor = tintColor } } class TabToolbar: UIView { weak var tabToolbarDelegate: TabToolbarDelegate? let tabsButton = TabsButton() let menuButton = ToolbarButton() let libraryButton = ToolbarButton() let forwardButton = ToolbarButton() let backButton = ToolbarButton() let stopReloadButton = ToolbarButton() let actionButtons: [Themeable & UIButton] private let privateModeBadge = ToolbarPrivateModeBadge() func privateModeBadge(visible: Bool) { privateModeBadge.isHidden = !visible } var helper: TabToolbarHelper? private let contentView = UIStackView() fileprivate override init(frame: CGRect) { actionButtons = [backButton, forwardButton, stopReloadButton, tabsButton, menuButton] super.init(frame: frame) setupAccessibility() addSubview(contentView) helper = TabToolbarHelper(toolbar: self) addButtons(actionButtons) contentView.addSubview(privateModeBadge) contentView.axis = .horizontal contentView.distribution = .fillEqually } override func updateConstraints() { privateModeBadge.layout(forTabsButton: tabsButton) contentView.snp.makeConstraints { make in make.leading.trailing.top.equalTo(self) make.bottom.equalTo(self.safeArea.bottom) } super.updateConstraints() } private func setupAccessibility() { backButton.accessibilityIdentifier = "TabToolbar.backButton" forwardButton.accessibilityIdentifier = "TabToolbar.forwardButton" stopReloadButton.accessibilityIdentifier = "TabToolbar.stopReloadButton" tabsButton.accessibilityIdentifier = "TabToolbar.tabsButton" menuButton.accessibilityIdentifier = "TabToolbar.menuButton" accessibilityNavigationStyle = .combined accessibilityLabel = NSLocalizedString("Navigation Toolbar", comment: "Accessibility label for the navigation toolbar displayed at the bottom of the screen.") } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addButtons(_ buttons: [UIButton]) { buttons.forEach { contentView.addArrangedSubview($0) } } override func draw(_ rect: CGRect) { if let context = UIGraphicsGetCurrentContext() { drawLine(context, start: .zero, end: CGPoint(x: frame.width, y: 0)) } } fileprivate func drawLine(_ context: CGContext, start: CGPoint, end: CGPoint) { context.setStrokeColor(UIColor.black.withAlphaComponent(0.05).cgColor) context.setLineWidth(2) context.move(to: CGPoint(x: start.x, y: start.y)) context.addLine(to: CGPoint(x: end.x, y: end.y)) context.strokePath() } } extension TabToolbar: TabToolbarProtocol { func updateBackStatus(_ canGoBack: Bool) { backButton.isEnabled = canGoBack } func updateForwardStatus(_ canGoForward: Bool) { forwardButton.isEnabled = canGoForward } func updateReloadStatus(_ isLoading: Bool) { helper?.updateReloadStatus(isLoading) } func updatePageStatus(_ isWebPage: Bool) { stopReloadButton.isEnabled = isWebPage } func updateTabCount(_ count: Int, animated: Bool) { tabsButton.updateTabCount(count, animated: animated) } } extension TabToolbar: Themeable, PrivateModeUI { func applyTheme() { backgroundColor = UIColor.theme.browser.background helper?.setTheme(forButtons: actionButtons) } func applyUIMode(isPrivate: Bool) { privateModeBadge(visible: isPrivate) } }
mpl-2.0
4d67b104385140749af1b98a03df368e
38.883582
166
0.716413
5.400566
false
false
false
false
ethan605/SwiftVD
swiftvd/swiftvd/Test.playground/section-1.swift
1
780
// Playground - noun: a place where people can play import Cocoa import Foundation //class MTopic: NSObject { // var title: String? // var absWidgetImage: String? // var photos: String[] = [] //} // //var m = MTopic() //var d1 = NSDictionary(object: "http://photo.depvd.com/14/124/13/ph_WMuMK5wY8w_zJFxJzJ3_no.jpg", forKey: "absNormal") //var d = NSDictionary( // objects: ["Giận rồi :!!", "http://photo.depvd.com/14/124/13/ph_WMuMK5wY8w_zJFxJzJ3_wi.jpg", "test"], // forKeys: ["title", "absWidgetImage", "photos"]) // //var keys = "" //var values = "" //for (key: AnyObject, value : AnyObject) in d { // keys += " " + String(key as NSString) // values += " " + String(value as NSString) //} // //let iVar = class_getInstanceVariable(MTopic.self, "photos") as Ivar!
mit
90fa3e8f35866b7bcdb621a7b90c0a1a
28.846154
118
0.643041
2.713287
false
false
false
false
lordrio/speedvote
Sources/CommentData.swift
1
1261
// // CommentData.swift // PerfectTemplate // // Created by MD FADZLI BIN MD FADZIL on 6/7/17. // // import Foundation import PerfectLib class CommentData : BaseData { override var _tableName:String { get{ return "Comments" } } /*== Table structure for table Comments |------ |Column|Type|Null|Default |------ |//**id**//|bigint(20)|No| |event_id|bigint(20)|No| |user_id|bigint(20)|No| |comment|text|Yes|NULL |datetime|date|No| == Dumping data for table Comments*/ public var id:DataVar<UInt64> = DataVar<UInt64>("id", 0) public var event_id:DataVar<UInt64> = DataVar<UInt64>("event_id", 0) public var user_id:DataVar<UInt64> = DataVar<UInt64>("user_id", 0) public var user_name:DataVar<String> = DataVar<String>("user_name", "") public var comment:DataVar<String> = DataVar<String>("comment", "") public var datetime:DateDataVar<Date> = DateDataVar<Date>("datetime", Date()) public override func jsonEncodedString() throws -> String { do { return try ConvertToJsonDic([id, event_id, user_id, user_name, comment, datetime]).jsonEncodedString() } catch { fatalError("\(error)") } } }
apache-2.0
7ae8d7e8388dc472f5943eb565449180
27.659091
114
0.606661
3.493075
false
false
false
false
GuiminChu/JianshuExamples
CoreTextDemo/CoreTextDemo/CoreText/图文混排/CTDisplayView.swift
2
2984
// // CTDisplayView.swift // CoreTextDemo // // Created by Chu Guimin on 17/3/3. // Copyright © 2017年 cgm. All rights reserved. // import UIKit // 持有 CoreTextData 类的实例,负责将 CTFrame 绘制到界面上。 class CTDisplayView: UIView { typealias CoreTextImageTapAction = (_ displayView: CTDisplayView, _ imageData: CoreTextImageData) -> () var data: CoreTextData? var imageTapAction: CoreTextImageTapAction? override init(frame: CGRect) { super.init(frame: frame) setupEvents() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupEvents() } override func awakeFromNib() { super.awakeFromNib() setupEvents() } override func draw(_ rect: CGRect) { super.draw(rect) // 获取绘图上下文 let context = UIGraphicsGetCurrentContext()! // 翻转坐标系。对于底层的绘制引擎来说,屏幕的左下角是(0, 0)坐标。而对于上层的 UIKit 来说,左上角是(0, 0)坐标。 context.textMatrix = CGAffineTransform.identity context.translateBy(x: 0, y: self.bounds.size.height) context.scaleBy(x: 1.0, y: -1.0) if data != nil { CTFrameDraw(data!.ctFrame, context) for imageData in data!.imageArray { let image = UIImage(named: imageData.name) if let image = image { context.draw(image.cgImage!, in: imageData.imagePosition) } } } } private func setupEvents() { let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(userTapGestureDetected(recognizer:))) self.addGestureRecognizer(tapGestureRecognizer) self.isUserInteractionEnabled = true } func userTapGestureDetected(recognizer: UITapGestureRecognizer) { let point = recognizer.location(in: self) print("point\(point)") if let imageArray = data?.imageArray { for imageData in imageArray { // 翻转坐标系,因为 imageData 中的坐标是 CoreText 的坐标系 let imageRect = imageData.imagePosition var imagePosition = imageRect.origin imagePosition.y = self.bounds.size.height - imageRect.origin.y - imageRect.size.height let rect = CGRect(x: imagePosition.x, y: imagePosition.y, width: imageRect.size.width, height: imageRect.size.height) if rect.contains(point) { print("\(imageData.name)") imageTapAction?(self, imageData) break } } } } public func tapCoreTextImage(_ tapAction: CoreTextImageTapAction?) { imageTapAction = tapAction } }
mit
85c584eaed066298422bcc9ddfe89f7c
30.943182
133
0.578086
4.653974
false
false
false
false
themonki/onebusaway-iphone
OneBusAway/ui/MapTable/LabelSectionController.swift
1
3296
// // LabelSectionController.swift // OneBusAway // // Created by Aaron Brethorst on 6/28/18. // Copyright © 2018 OneBusAway. All rights reserved. // import UIKit import IGListKit final class LabelSectionController: ListSectionController { private var object: String? override func sizeForItem(at index: Int) -> CGSize { return CGSize(width: collectionContext!.containerSize.width, height: 55) } override func cellForItem(at index: Int) -> UICollectionViewCell { guard let cell = collectionContext?.dequeueReusableCell(of: BlahLabelCell.self, for: self, at: index) as? BlahLabelCell else { fatalError() } cell.text = object return cell } override func didUpdate(to object: Any) { self.object = String(describing: object) } } final class BlahLabelCell: UICollectionViewCell { fileprivate static let insets = UIEdgeInsets(top: 8, left: 15, bottom: 8, right: 15) fileprivate static let font = UIFont.systemFont(ofSize: 17) static var singleLineHeight: CGFloat { return font.lineHeight + insets.top + insets.bottom } static func textHeight(_ text: String, width: CGFloat) -> CGFloat { let constrainedSize = CGSize(width: width - insets.left - insets.right, height: CGFloat.greatestFiniteMagnitude) let attributes = [ NSAttributedString.Key.font: font ] let options: NSStringDrawingOptions = [.usesFontLeading, .usesLineFragmentOrigin] let bounds = (text as NSString).boundingRect(with: constrainedSize, options: options, attributes: attributes, context: nil) return ceil(bounds.height) + insets.top + insets.bottom } fileprivate let label: UILabel = { let label = UILabel() label.backgroundColor = .clear label.numberOfLines = 0 label.font = BlahLabelCell.font return label }() let separator: CALayer = { let layer = CALayer() layer.backgroundColor = UIColor(red: 200 / 255.0, green: 199 / 255.0, blue: 204 / 255.0, alpha: 1).cgColor return layer }() var text: String? { get { return label.text } set { label.text = newValue } } override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(label) contentView.layer.addSublayer(separator) contentView.backgroundColor = .white } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let bounds = contentView.bounds label.frame = bounds.inset(by: BlahLabelCell.insets) let height: CGFloat = 0.5 let left = BlahLabelCell.insets.left separator.frame = CGRect(x: left, y: bounds.height - height, width: bounds.width - left, height: height) } override var isHighlighted: Bool { didSet { contentView.backgroundColor = UIColor(white: isHighlighted ? 0.9 : 1, alpha: 1) } } } extension BlahLabelCell: ListBindable { func bindViewModel(_ viewModel: Any) { guard let viewModel = viewModel as? String else { return } label.text = viewModel } }
apache-2.0
64612f3d32399d5323116c8b4581405f
29.229358
134
0.646434
4.563712
false
false
false
false
xivol/Swift-CS333
playgrounds/uiKit/stopwatch/stopwatch/ViewController.swift
3
2645
// // ViewController.swift // stopwatch // // Created by Илья Лошкарёв on 21.02.17. // Copyright © 2017 Илья Лошкарёв. All rights reserved. // import UIKit class ViewController: UIViewController, StopwatchDelegate { weak var stopwatch: Stopwatch? override func viewDidLoad() { super.viewDidLoad() stopwatch = (UIApplication.shared.delegate as! AppDelegate).stopwatch stopwatch!.delegate = self let button = UIButton(type: .custom) button.frame = view.bounds button.titleLabel?.frame = button.bounds button.titleLabel?.font = button.titleLabel?.font.withSize( view.bounds.width / 6) button.titleLabel?.textAlignment = .justified button.setTitleColor(UIColor.white, for: .normal) button.addTarget(self, action: #selector(stopwatchTouch), for: .touchUpInside) view = button view.backgroundColor = UIColor.gray updateTime(0, 0, 0) } func stopwatchTouch() { if stopwatch!.isRunning { view.backgroundColor = UIColor.gray stopwatch!.stop() } else { view.backgroundColor = UIColor.orange stopwatch!.start() } } func stopwatchDidStart(stopwatch: Stopwatch) { print("stopwatch has started") } func stopwatchDidStop(stopwatch: Stopwatch) { print("stopwatch has stoped") updateTime(0, 0, 0) } func stopwatchDidPause(stopwatch: Stopwatch, at time: TimeInterval) { print("stopwatch has paused at \(time)") view.backgroundColor = UIColor.red } func stopwatchDidResume(stopwatch: Stopwatch, at time: TimeInterval) { print("stopwatch has resumed at \(time)") view.backgroundColor = UIColor.orange } func stopwatchTimeChanged(stopwatch: Stopwatch, elapsedTime: TimeInterval) { let minutes = UInt(elapsedTime / 60) let seconds = UInt(elapsedTime - TimeInterval(minutes * 60)) let milliseconds = UInt((elapsedTime - TimeInterval(minutes * 60 + seconds)) * 100) updateTime(minutes, seconds, milliseconds) if minutes >= 100 { stopwatch.stop() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() stopwatch?.stop() } func updateTime(_ minutes: UInt, _ seconds: UInt, _ milliseconds: UInt) { if let button = view as? UIButton { button.setTitle(String(format:"%02d:%02d:%02d", minutes, seconds, milliseconds), for: .normal) } } }
mit
357154efc7c49a67ad3c8f5f64ddce47
29.465116
106
0.622137
4.833948
false
false
false
false
kstaring/swift
benchmark/single-source/SortStrings.swift
1
38753
//===--- SortStrings.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Sort an array of strings using an explicit sort predicate. var stringBenchmarkWords: [String] = [ "woodshed", "lakism", "gastroperiodynia", "afetal", "ramsch", "Nickieben", "undutifulness", "birdglue", "ungentlemanize", "menacingly", "heterophile", "leoparde", "Casearia", "decorticate", "neognathic", "mentionable", "tetraphenol", "pseudonymal", "dislegitimate", "Discoidea", "intitule", "ionium", "Lotuko", "timbering", "nonliquidating", "oarialgia", "Saccobranchus", "reconnoiter", "criminative", "disintegratory", "executer", "Cylindrosporium", "complimentation", "Ixiama", "Araceae", "silaginoid", "derencephalus", "Lamiidae", "marrowlike", "ninepin", "dynastid", "lampfly", "feint", "trihemimer", "semibarbarous", "heresy", "tritanope", "indifferentist", "confound", "hyperbolaeon", "planirostral", "philosophunculist", "existence", "fretless", "Leptandra", "Amiranha", "handgravure", "gnash", "unbelievability", "orthotropic", "Susumu", "teleutospore", "sleazy", "shapeliness", "hepatotomy", "exclusivism", "stifler", "cunning", "isocyanuric", "pseudepigraphy", "carpetbagger", "respectiveness", "Jussi", "vasotomy", "proctotomy", "ovatotriangular", "aesthetic", "schizogamy", "disengagement", "foray", "haplocaulescent", "noncoherent", "astrocyte", "unreverberated", "presenile", "lanson", "enkraal", "contemplative", "Syun", "sartage", "unforgot", "wyde", "homeotransplant", "implicational", "forerunnership", "calcaneum", "stomatodeum", "pharmacopedia", "preconcessive", "trypanosomatic", "intracollegiate", "rampacious", "secundipara", "isomeric", "treehair", "pulmonal", "uvate", "dugway", "glucofrangulin", "unglory", "Amandus", "icterogenetic", "quadrireme", "Lagostomus", "brakeroot", "anthracemia", "fluted", "protoelastose", "thro", "pined", "Saxicolinae", "holidaymaking", "strigil", "uncurbed", "starling", "redeemeress", "Liliaceae", "imparsonee", "obtusish", "brushed", "mesally", "probosciformed", "Bourbonesque", "histological", "caroba", "digestion", "Vindemiatrix", "triactinal", "tattling", "arthrobacterium", "unended", "suspectfulness", "movelessness", "chartist", "Corynebacterium", "tercer", "oversaturation", "Congoleum", "antiskeptical", "sacral", "equiradiate", "whiskerage", "panidiomorphic", "unplanned", "anilopyrine", "Queres", "tartronyl", "Ing", "notehead", "finestiller", "weekender", "kittenhood", "competitrix", "premillenarian", "convergescence", "microcoleoptera", "slirt", "asteatosis", "Gruidae", "metastome", "ambuscader", "untugged", "uneducated", "redistill", "rushlight", "freakish", "dosology", "papyrine", "iconologist", "Bidpai", "prophethood", "pneumotropic", "chloroformize", "intemperance", "spongiform", "superindignant", "divider", "starlit", "merchantish", "indexless", "unidentifiably", "coumarone", "nomism", "diaphanous", "salve", "option", "anallantoic", "paint", "thiofurfuran", "baddeleyite", "Donne", "heterogenicity", "decess", "eschynite", "mamma", "unmonarchical", "Archiplata", "widdifow", "apathic", "overline", "chaetophoraceous", "creaky", "trichosporange", "uninterlined", "cometwise", "hermeneut", "unbedraggled", "tagged", "Sminthurus", "somniloquacious", "aphasiac", "Inoperculata", "photoactivity", "mobship", "unblightedly", "lievrite", "Khoja", "Falerian", "milfoil", "protectingly", "householder", "cathedra", "calmingly", "tordrillite", "rearhorse", "Leonard", "maracock", "youngish", "kammererite", "metanephric", "Sageretia", "diplococcoid", "accelerative", "choreal", "metalogical", "recombination", "unimprison", "invocation", "syndetic", "toadback", "vaned", "cupholder", "metropolitanship", "paramandelic", "dermolysis", "Sheriyat", "rhabdus", "seducee", "encrinoid", "unsuppliable", "cololite", "timesaver", "preambulate", "sampling", "roaster", "springald", "densher", "protraditional", "naturalesque", "Hydrodamalis", "cytogenic", "shortly", "cryptogrammatical", "squat", "genual", "backspier", "solubleness", "macroanalytical", "overcovetousness", "Natalie", "cuprobismutite", "phratriac", "Montanize", "hymnologist", "karyomiton", "podger", "unofficiousness", "antisplasher", "supraclavicular", "calidity", "disembellish", "antepredicament", "recurvirostral", "pulmonifer", "coccidial", "botonee", "protoglobulose", "isonym", "myeloid", "premiership", "unmonopolize", "unsesquipedalian", "unfelicitously", "theftbote", "undauntable", "lob", "praenomen", "underriver", "gorfly", "pluckage", "radiovision", "tyrantship", "fraught", "doppelkummel", "rowan", "allosyndetic", "kinesiology", "psychopath", "arrent", "amusively", "preincorporation", "Montargis", "pentacron", "neomedievalism", "sima", "lichenicolous", "Ecclesiastes", "woofed", "cardinalist", "sandaracin", "gymnasial", "lithoglyptics", "centimeter", "quadrupedous", "phraseology", "tumuli", "ankylotomy", "myrtol", "cohibitive", "lepospondylous", "silvendy", "inequipotential", "entangle", "raveling", "Zeugobranchiata", "devastating", "grainage", "amphisbaenian", "blady", "cirrose", "proclericalism", "governmentalist", "carcinomorphic", "nurtureship", "clancular", "unsteamed", "discernibly", "pleurogenic", "impalpability", "Azotobacterieae", "sarcoplasmic", "alternant", "fitly", "acrorrheuma", "shrapnel", "pastorize", "gulflike", "foreglow", "unrelated", "cirriped", "cerviconasal", "sexuale", "pussyfooter", "gadolinic", "duplicature", "codelinquency", "trypanolysis", "pathophobia", "incapsulation", "nonaerating", "feldspar", "diaphonic", "epiglottic", "depopulator", "wisecracker", "gravitational", "kuba", "lactesce", "Toxotes", "periomphalic", "singstress", "fannier", "counterformula", "Acemetae", "repugnatorial", "collimator", "Acinetina", "unpeace", "drum", "tetramorphic", "descendentalism", "cementer", "supraloral", "intercostal", "Nipponize", "negotiator", "vacationless", "synthol", "fissureless", "resoap", "pachycarpous", "reinspiration", "misappropriation", "disdiazo", "unheatable", "streng", "Detroiter", "infandous", "loganiaceous", "desugar", "Matronalia", "myxocystoma", "Gandhiism", "kiddier", "relodge", "counterreprisal", "recentralize", "foliously", "reprinter", "gender", "edaciousness", "chondriomite", "concordant", "stockrider", "pedary", "shikra", "blameworthiness", "vaccina", "Thamnophilinae", "wrongwise", "unsuperannuated", "convalescency", "intransmutable", "dropcloth", "Ceriomyces", "ponderal", "unstentorian", "mem", "deceleration", "ethionic", "untopped", "wetback", "bebar", "undecaying", "shoreside", "energize", "presacral", "undismay", "agricolite", "cowheart", "hemibathybian", "postexilian", "Phacidiaceae", "offing", "redesignation", "skeptically", "physicianless", "bronchopathy", "marabuto", "proprietory", "unobtruded", "funmaker", "plateresque", "preadventure", "beseeching", "cowpath", "pachycephalia", "arthresthesia", "supari", "lengthily", "Nepa", "liberation", "nigrify", "belfry", "entoolitic", "bazoo", "pentachromic", "distinguishable", "slideable", "galvanoscope", "remanage", "cetene", "bocardo", "consummation", "boycottism", "perplexity", "astay", "Gaetuli", "periplastic", "consolidator", "sluggarding", "coracoscapular", "anangioid", "oxygenizer", "Hunanese", "seminary", "periplast", "Corylus", "unoriginativeness", "persecutee", "tweaker", "silliness", "Dabitis", "facetiousness", "thymy", "nonimperial", "mesoblastema", "turbiniform", "churchway", "cooing", "frithbot", "concomitantly", "stalwartize", "clingfish", "hardmouthed", "parallelepipedonal", "coracoacromial", "factuality", "curtilage", "arachnoidean", "semiaridity", "phytobacteriology", "premastery", "hyperpurist", "mobed", "opportunistic", "acclimature", "outdistance", "sophister", "condonement", "oxygenerator", "acetonic", "emanatory", "periphlebitis", "nonsociety", "spectroradiometric", "superaverage", "cleanness", "posteroventral", "unadvised", "unmistakedly", "pimgenet", "auresca", "overimitate", "dipnoan", "chromoxylograph", "triakistetrahedron", "Suessiones", "uncopiable", "oligomenorrhea", "fribbling", "worriable", "flot", "ornithotrophy", "phytoteratology", "setup", "lanneret", "unbraceleted", "gudemother", "Spica", "unconsolatory", "recorruption", "premenstrual", "subretinal", "millennialist", "subjectibility", "rewardproof", "counterflight", "pilomotor", "carpetbaggery", "macrodiagonal", "slim", "indiscernible", "cuckoo", "moted", "controllingly", "gynecopathy", "porrectus", "wanworth", "lutfisk", "semiprivate", "philadelphy", "abdominothoracic", "coxcomb", "dambrod", "Metanemertini", "balminess", "homotypy", "waremaker", "absurdity", "gimcrack", "asquat", "suitable", "perimorphous", "kitchenwards", "pielum", "salloo", "paleontologic", "Olson", "Tellinidae", "ferryman", "peptonoid", "Bopyridae", "fallacy", "ictuate", "aguinaldo", "rhyodacite", "Ligydidae", "galvanometric", "acquisitor", "muscology", "hemikaryon", "ethnobotanic", "postganglionic", "rudimentarily", "replenish", "phyllorhine", "popgunnery", "summar", "quodlibetary", "xanthochromia", "autosymbolically", "preloreal", "extent", "strawberry", "immortalness", "colicwort", "frisca", "electiveness", "heartbroken", "affrightingly", "reconfiscation", "jacchus", "imponderably", "semantics", "beennut", "paleometeorological", "becost", "timberwright", "resuppose", "syncategorematical", "cytolymph", "steinbok", "explantation", "hyperelliptic", "antescript", "blowdown", "antinomical", "caravanserai", "unweariedly", "isonymic", "keratoplasty", "vipery", "parepigastric", "endolymphatic", "Londonese", "necrotomy", "angelship", "Schizogregarinida", "steeplebush", "sparaxis", "connectedness", "tolerance", "impingent", "agglutinin", "reviver", "hieroglyphical", "dialogize", "coestate", "declamatory", "ventilation", "tauromachy", "cotransubstantiate", "pome", "underseas", "triquadrantal", "preconfinemnt", "electroindustrial", "selachostomous", "nongolfer", "mesalike", "hamartiology", "ganglioblast", "unsuccessive", "yallow", "bacchanalianly", "platydactyl", "Bucephala", "ultraurgent", "penalist", "catamenial", "lynnhaven", "unrelevant", "lunkhead", "metropolitan", "hydro", "outsoar", "vernant", "interlanguage", "catarrhal", "Ionicize", "keelless", "myomantic", "booker", "Xanthomonas", "unimpeded", "overfeminize", "speronaro", "diaconia", "overholiness", "liquefacient", "Spartium", "haggly", "albumose", "nonnecessary", "sulcalization", "decapitate", "cellated", "unguirostral", "trichiurid", "loveproof", "amakebe", "screet", "arsenoferratin", "unfrizz", "undiscoverable", "procollectivistic", "tractile", "Winona", "dermostosis", "eliminant", "scomberoid", "tensile", "typesetting", "xylic", "dermatopathology", "cycloplegic", "revocable", "fissate", "afterplay", "screwship", "microerg", "bentonite", "stagecoaching", "beglerbeglic", "overcharitably", "Plotinism", "Veddoid", "disequalize", "cytoproct", "trophophore", "antidote", "allerion", "famous", "convey", "postotic", "rapillo", "cilectomy", "penkeeper", "patronym", "bravely", "ureteropyelitis", "Hildebrandine", "missileproof", "Conularia", "deadening", "Conrad", "pseudochylous", "typologically", "strummer", "luxuriousness", "resublimation", "glossiness", "hydrocauline", "anaglyph", "personifiable", "seniority", "formulator", "datiscaceous", "hydracrylate", "Tyranni", "Crawthumper", "overprove", "masher", "dissonance", "Serpentinian", "malachite", "interestless", "stchi", "ogum", "polyspermic", "archegoniate", "precogitation", "Alkaphrah", "craggily", "delightfulness", "bioplast", "diplocaulescent", "neverland", "interspheral", "chlorhydric", "forsakenly", "scandium", "detubation", "telega", "Valeriana", "centraxonial", "anabolite", "neger", "miscellanea", "whalebacker", "stylidiaceous", "unpropelled", "Kennedya", "Jacksonite", "ghoulish", "Dendrocalamus", "paynimhood", "rappist", "unluffed", "falling", "Lyctus", "uncrown", "warmly", "pneumatism", "Morisonian", "notate", "isoagglutinin", "Pelidnota", "previsit", "contradistinctly", "utter", "porometer", "gie", "germanization", "betwixt", "prenephritic", "underpier", "Eleutheria", "ruthenious", "convertor", "antisepsin", "winterage", "tetramethylammonium", "Rockaway", "Penaea", "prelatehood", "brisket", "unwishful", "Minahassa", "Briareus", "semiaxis", "disintegrant", "peastick", "iatromechanical", "fastus", "thymectomy", "ladyless", "unpreened", "overflutter", "sicker", "apsidally", "thiazine", "guideway", "pausation", "tellinoid", "abrogative", "foraminulate", "omphalos", "Monorhina", "polymyarian", "unhelpful", "newslessness", "oryctognosy", "octoradial", "doxology", "arrhythmy", "gugal", "mesityl", "hexaplaric", "Cabirian", "hordeiform", "eddyroot", "internarial", "deservingness", "jawbation", "orographically", "semiprecious", "seasick", "thermically", "grew", "tamability", "egotistically", "fip", "preabsorbent", "leptochroa", "ethnobotany", "podolite", "egoistic", "semitropical", "cero", "spinelessness", "onshore", "omlah", "tintinnabulist", "machila", "entomotomy", "nubile", "nonscholastic", "burnt", "Alea", "befume", "doctorless", "Napoleonic", "scenting", "apokreos", "cresylene", "paramide", "rattery", "disinterested", "idiopathetic", "negatory", "fervid", "quintato", "untricked", "Metrosideros", "mescaline", "midverse", "Musophagidae", "fictionary", "branchiostegous", "yoker", "residuum", "culmigenous", "fleam", "suffragism", "Anacreon", "sarcodous", "parodistic", "writmaking", "conversationism", "retroposed", "tornillo", "presuspect", "didymous", "Saumur", "spicing", "drawbridge", "cantor", "incumbrancer", "heterospory", "Turkeydom", "anteprandial", "neighborship", "thatchless", "drepanoid", "lusher", "paling", "ecthlipsis", "heredosyphilitic", "although", "garetta", "temporarily", "Monotropa", "proglottic", "calyptro", "persiflage", "degradable", "paraspecific", "undecorative", "Pholas", "myelon", "resteal", "quadrantly", "scrimped", "airer", "deviless", "caliciform", "Sefekhet", "shastaite", "togate", "macrostructure", "bipyramid", "wey", "didynamy", "knacker", "swage", "supermanism", "epitheton", "overpresumptuous" ] @inline(never) func benchSortStrings(_ words: [String]) { // Notice that we _copy_ the array of words before we sort it. // Pass an explicit '<' predicate to benchmark reabstraction thunks. var tempwords = words tempwords.sort(by: <) } public func run_SortStrings(_ N: Int) { for _ in 1...5*N { benchSortStrings(stringBenchmarkWords) } } var stringBenchmarkWordsUnicode: [String] = [ "❄️woodshed", "❄️lakism", "❄️gastroperiodynia", "❄️afetal", "❄️ramsch", "❄️Nickieben", "❄️undutifulness", "❄️birdglue", "❄️ungentlemanize", "❄️menacingly", "❄️heterophile", "❄️leoparde", "❄️Casearia", "❄️decorticate", "❄️neognathic", "❄️mentionable", "❄️tetraphenol", "❄️pseudonymal", "❄️dislegitimate", "❄️Discoidea", "❄️intitule", "❄️ionium", "❄️Lotuko", "❄️timbering", "❄️nonliquidating", "❄️oarialgia", "❄️Saccobranchus", "❄️reconnoiter", "❄️criminative", "❄️disintegratory", "❄️executer", "❄️Cylindrosporium", "❄️complimentation", "❄️Ixiama", "❄️Araceae", "❄️silaginoid", "❄️derencephalus", "❄️Lamiidae", "❄️marrowlike", "❄️ninepin", "❄️dynastid", "❄️lampfly", "❄️feint", "❄️trihemimer", "❄️semibarbarous", "❄️heresy", "❄️tritanope", "❄️indifferentist", "❄️confound", "❄️hyperbolaeon", "❄️planirostral", "❄️philosophunculist", "❄️existence", "❄️fretless", "❄️Leptandra", "❄️Amiranha", "❄️handgravure", "❄️gnash", "❄️unbelievability", "❄️orthotropic", "❄️Susumu", "❄️teleutospore", "❄️sleazy", "❄️shapeliness", "❄️hepatotomy", "❄️exclusivism", "❄️stifler", "❄️cunning", "❄️isocyanuric", "❄️pseudepigraphy", "❄️carpetbagger", "❄️respectiveness", "❄️Jussi", "❄️vasotomy", "❄️proctotomy", "❄️ovatotriangular", "❄️aesthetic", "❄️schizogamy", "❄️disengagement", "❄️foray", "❄️haplocaulescent", "❄️noncoherent", "❄️astrocyte", "❄️unreverberated", "❄️presenile", "❄️lanson", "❄️enkraal", "❄️contemplative", "❄️Syun", "❄️sartage", "❄️unforgot", "❄️wyde", "❄️homeotransplant", "❄️implicational", "❄️forerunnership", "❄️calcaneum", "❄️stomatodeum", "❄️pharmacopedia", "❄️preconcessive", "❄️trypanosomatic", "❄️intracollegiate", "❄️rampacious", "❄️secundipara", "❄️isomeric", "❄️treehair", "❄️pulmonal", "❄️uvate", "❄️dugway", "❄️glucofrangulin", "❄️unglory", "❄️Amandus", "❄️icterogenetic", "❄️quadrireme", "❄️Lagostomus", "❄️brakeroot", "❄️anthracemia", "❄️fluted", "❄️protoelastose", "❄️thro", "❄️pined", "❄️Saxicolinae", "❄️holidaymaking", "❄️strigil", "❄️uncurbed", "❄️starling", "❄️redeemeress", "❄️Liliaceae", "❄️imparsonee", "❄️obtusish", "❄️brushed", "❄️mesally", "❄️probosciformed", "❄️Bourbonesque", "❄️histological", "❄️caroba", "❄️digestion", "❄️Vindemiatrix", "❄️triactinal", "❄️tattling", "❄️arthrobacterium", "❄️unended", "❄️suspectfulness", "❄️movelessness", "❄️chartist", "❄️Corynebacterium", "❄️tercer", "❄️oversaturation", "❄️Congoleum", "❄️antiskeptical", "❄️sacral", "❄️equiradiate", "❄️whiskerage", "❄️panidiomorphic", "❄️unplanned", "❄️anilopyrine", "❄️Queres", "❄️tartronyl", "❄️Ing", "❄️notehead", "❄️finestiller", "❄️weekender", "❄️kittenhood", "❄️competitrix", "❄️premillenarian", "❄️convergescence", "❄️microcoleoptera", "❄️slirt", "❄️asteatosis", "❄️Gruidae", "❄️metastome", "❄️ambuscader", "❄️untugged", "❄️uneducated", "❄️redistill", "❄️rushlight", "❄️freakish", "❄️dosology", "❄️papyrine", "❄️iconologist", "❄️Bidpai", "❄️prophethood", "❄️pneumotropic", "❄️chloroformize", "❄️intemperance", "❄️spongiform", "❄️superindignant", "❄️divider", "❄️starlit", "❄️merchantish", "❄️indexless", "❄️unidentifiably", "❄️coumarone", "❄️nomism", "❄️diaphanous", "❄️salve", "❄️option", "❄️anallantoic", "❄️paint", "❄️thiofurfuran", "❄️baddeleyite", "❄️Donne", "❄️heterogenicity", "❄️decess", "❄️eschynite", "❄️mamma", "❄️unmonarchical", "❄️Archiplata", "❄️widdifow", "❄️apathic", "❄️overline", "❄️chaetophoraceous", "❄️creaky", "❄️trichosporange", "❄️uninterlined", "❄️cometwise", "❄️hermeneut", "❄️unbedraggled", "❄️tagged", "❄️Sminthurus", "❄️somniloquacious", "❄️aphasiac", "❄️Inoperculata", "❄️photoactivity", "❄️mobship", "❄️unblightedly", "❄️lievrite", "❄️Khoja", "❄️Falerian", "❄️milfoil", "❄️protectingly", "❄️householder", "❄️cathedra", "❄️calmingly", "❄️tordrillite", "❄️rearhorse", "❄️Leonard", "❄️maracock", "❄️youngish", "❄️kammererite", "❄️metanephric", "❄️Sageretia", "❄️diplococcoid", "❄️accelerative", "❄️choreal", "❄️metalogical", "❄️recombination", "❄️unimprison", "❄️invocation", "❄️syndetic", "❄️toadback", "❄️vaned", "❄️cupholder", "❄️metropolitanship", "❄️paramandelic", "❄️dermolysis", "❄️Sheriyat", "❄️rhabdus", "❄️seducee", "❄️encrinoid", "❄️unsuppliable", "❄️cololite", "❄️timesaver", "❄️preambulate", "❄️sampling", "❄️roaster", "❄️springald", "❄️densher", "❄️protraditional", "❄️naturalesque", "❄️Hydrodamalis", "❄️cytogenic", "❄️shortly", "❄️cryptogrammatical", "❄️squat", "❄️genual", "❄️backspier", "❄️solubleness", "❄️macroanalytical", "❄️overcovetousness", "❄️Natalie", "❄️cuprobismutite", "❄️phratriac", "❄️Montanize", "❄️hymnologist", "❄️karyomiton", "❄️podger", "❄️unofficiousness", "❄️antisplasher", "❄️supraclavicular", "❄️calidity", "❄️disembellish", "❄️antepredicament", "❄️recurvirostral", "❄️pulmonifer", "❄️coccidial", "❄️botonee", "❄️protoglobulose", "❄️isonym", "❄️myeloid", "❄️premiership", "❄️unmonopolize", "❄️unsesquipedalian", "❄️unfelicitously", "❄️theftbote", "❄️undauntable", "❄️lob", "❄️praenomen", "❄️underriver", "❄️gorfly", "❄️pluckage", "❄️radiovision", "❄️tyrantship", "❄️fraught", "❄️doppelkummel", "❄️rowan", "❄️allosyndetic", "❄️kinesiology", "❄️psychopath", "❄️arrent", "❄️amusively", "❄️preincorporation", "❄️Montargis", "❄️pentacron", "❄️neomedievalism", "❄️sima", "❄️lichenicolous", "❄️Ecclesiastes", "❄️woofed", "❄️cardinalist", "❄️sandaracin", "❄️gymnasial", "❄️lithoglyptics", "❄️centimeter", "❄️quadrupedous", "❄️phraseology", "❄️tumuli", "❄️ankylotomy", "❄️myrtol", "❄️cohibitive", "❄️lepospondylous", "❄️silvendy", "❄️inequipotential", "❄️entangle", "❄️raveling", "❄️Zeugobranchiata", "❄️devastating", "❄️grainage", "❄️amphisbaenian", "❄️blady", "❄️cirrose", "❄️proclericalism", "❄️governmentalist", "❄️carcinomorphic", "❄️nurtureship", "❄️clancular", "❄️unsteamed", "❄️discernibly", "❄️pleurogenic", "❄️impalpability", "❄️Azotobacterieae", "❄️sarcoplasmic", "❄️alternant", "❄️fitly", "❄️acrorrheuma", "❄️shrapnel", "❄️pastorize", "❄️gulflike", "❄️foreglow", "❄️unrelated", "❄️cirriped", "❄️cerviconasal", "❄️sexuale", "❄️pussyfooter", "❄️gadolinic", "❄️duplicature", "❄️codelinquency", "❄️trypanolysis", "❄️pathophobia", "❄️incapsulation", "❄️nonaerating", "❄️feldspar", "❄️diaphonic", "❄️epiglottic", "❄️depopulator", "❄️wisecracker", "❄️gravitational", "❄️kuba", "❄️lactesce", "❄️Toxotes", "❄️periomphalic", "❄️singstress", "❄️fannier", "❄️counterformula", "❄️Acemetae", "❄️repugnatorial", "❄️collimator", "❄️Acinetina", "❄️unpeace", "❄️drum", "❄️tetramorphic", "❄️descendentalism", "❄️cementer", "❄️supraloral", "❄️intercostal", "❄️Nipponize", "❄️negotiator", "❄️vacationless", "❄️synthol", "❄️fissureless", "❄️resoap", "❄️pachycarpous", "❄️reinspiration", "❄️misappropriation", "❄️disdiazo", "❄️unheatable", "❄️streng", "❄️Detroiter", "❄️infandous", "❄️loganiaceous", "❄️desugar", "❄️Matronalia", "❄️myxocystoma", "❄️Gandhiism", "❄️kiddier", "❄️relodge", "❄️counterreprisal", "❄️recentralize", "❄️foliously", "❄️reprinter", "❄️gender", "❄️edaciousness", "❄️chondriomite", "❄️concordant", "❄️stockrider", "❄️pedary", "❄️shikra", "❄️blameworthiness", "❄️vaccina", "❄️Thamnophilinae", "❄️wrongwise", "❄️unsuperannuated", "❄️convalescency", "❄️intransmutable", "❄️dropcloth", "❄️Ceriomyces", "❄️ponderal", "❄️unstentorian", "❄️mem", "❄️deceleration", "❄️ethionic", "❄️untopped", "❄️wetback", "❄️bebar", "❄️undecaying", "❄️shoreside", "❄️energize", "❄️presacral", "❄️undismay", "❄️agricolite", "❄️cowheart", "❄️hemibathybian", "❄️postexilian", "❄️Phacidiaceae", "❄️offing", "❄️redesignation", "❄️skeptically", "❄️physicianless", "❄️bronchopathy", "❄️marabuto", "❄️proprietory", "❄️unobtruded", "❄️funmaker", "❄️plateresque", "❄️preadventure", "❄️beseeching", "❄️cowpath", "❄️pachycephalia", "❄️arthresthesia", "❄️supari", "❄️lengthily", "❄️Nepa", "❄️liberation", "❄️nigrify", "❄️belfry", "❄️entoolitic", "❄️bazoo", "❄️pentachromic", "❄️distinguishable", "❄️slideable", "❄️galvanoscope", "❄️remanage", "❄️cetene", "❄️bocardo", "❄️consummation", "❄️boycottism", "❄️perplexity", "❄️astay", "❄️Gaetuli", "❄️periplastic", "❄️consolidator", "❄️sluggarding", "❄️coracoscapular", "❄️anangioid", "❄️oxygenizer", "❄️Hunanese", "❄️seminary", "❄️periplast", "❄️Corylus", "❄️unoriginativeness", "❄️persecutee", "❄️tweaker", "❄️silliness", "❄️Dabitis", "❄️facetiousness", "❄️thymy", "❄️nonimperial", "❄️mesoblastema", "❄️turbiniform", "❄️churchway", "❄️cooing", "❄️frithbot", "❄️concomitantly", "❄️stalwartize", "❄️clingfish", "❄️hardmouthed", "❄️parallelepipedonal", "❄️coracoacromial", "❄️factuality", "❄️curtilage", "❄️arachnoidean", "❄️semiaridity", "❄️phytobacteriology", "❄️premastery", "❄️hyperpurist", "❄️mobed", "❄️opportunistic", "❄️acclimature", "❄️outdistance", "❄️sophister", "❄️condonement", "❄️oxygenerator", "❄️acetonic", "❄️emanatory", "❄️periphlebitis", "❄️nonsociety", "❄️spectroradiometric", "❄️superaverage", "❄️cleanness", "❄️posteroventral", "❄️unadvised", "❄️unmistakedly", "❄️pimgenet", "❄️auresca", "❄️overimitate", "❄️dipnoan", "❄️chromoxylograph", "❄️triakistetrahedron", "❄️Suessiones", "❄️uncopiable", "❄️oligomenorrhea", "❄️fribbling", "❄️worriable", "❄️flot", "❄️ornithotrophy", "❄️phytoteratology", "❄️setup", "❄️lanneret", "❄️unbraceleted", "❄️gudemother", "❄️Spica", "❄️unconsolatory", "❄️recorruption", "❄️premenstrual", "❄️subretinal", "❄️millennialist", "❄️subjectibility", "❄️rewardproof", "❄️counterflight", "❄️pilomotor", "❄️carpetbaggery", "❄️macrodiagonal", "❄️slim", "❄️indiscernible", "❄️cuckoo", "❄️moted", "❄️controllingly", "❄️gynecopathy", "❄️porrectus", "❄️wanworth", "❄️lutfisk", "❄️semiprivate", "❄️philadelphy", "❄️abdominothoracic", "❄️coxcomb", "❄️dambrod", "❄️Metanemertini", "❄️balminess", "❄️homotypy", "❄️waremaker", "❄️absurdity", "❄️gimcrack", "❄️asquat", "❄️suitable", "❄️perimorphous", "❄️kitchenwards", "❄️pielum", "❄️salloo", "❄️paleontologic", "❄️Olson", "❄️Tellinidae", "❄️ferryman", "❄️peptonoid", "❄️Bopyridae", "❄️fallacy", "❄️ictuate", "❄️aguinaldo", "❄️rhyodacite", "❄️Ligydidae", "❄️galvanometric", "❄️acquisitor", "❄️muscology", "❄️hemikaryon", "❄️ethnobotanic", "❄️postganglionic", "❄️rudimentarily", "❄️replenish", "❄️phyllorhine", "❄️popgunnery", "❄️summar", "❄️quodlibetary", "❄️xanthochromia", "❄️autosymbolically", "❄️preloreal", "❄️extent", "❄️strawberry", "❄️immortalness", "❄️colicwort", "❄️frisca", "❄️electiveness", "❄️heartbroken", "❄️affrightingly", "❄️reconfiscation", "❄️jacchus", "❄️imponderably", "❄️semantics", "❄️beennut", "❄️paleometeorological", "❄️becost", "❄️timberwright", "❄️resuppose", "❄️syncategorematical", "❄️cytolymph", "❄️steinbok", "❄️explantation", "❄️hyperelliptic", "❄️antescript", "❄️blowdown", "❄️antinomical", "❄️caravanserai", "❄️unweariedly", "❄️isonymic", "❄️keratoplasty", "❄️vipery", "❄️parepigastric", "❄️endolymphatic", "❄️Londonese", "❄️necrotomy", "❄️angelship", "❄️Schizogregarinida", "❄️steeplebush", "❄️sparaxis", "❄️connectedness", "❄️tolerance", "❄️impingent", "❄️agglutinin", "❄️reviver", "❄️hieroglyphical", "❄️dialogize", "❄️coestate", "❄️declamatory", "❄️ventilation", "❄️tauromachy", "❄️cotransubstantiate", "❄️pome", "❄️underseas", "❄️triquadrantal", "❄️preconfinemnt", "❄️electroindustrial", "❄️selachostomous", "❄️nongolfer", "❄️mesalike", "❄️hamartiology", "❄️ganglioblast", "❄️unsuccessive", "❄️yallow", "❄️bacchanalianly", "❄️platydactyl", "❄️Bucephala", "❄️ultraurgent", "❄️penalist", "❄️catamenial", "❄️lynnhaven", "❄️unrelevant", "❄️lunkhead", "❄️metropolitan", "❄️hydro", "❄️outsoar", "❄️vernant", "❄️interlanguage", "❄️catarrhal", "❄️Ionicize", "❄️keelless", "❄️myomantic", "❄️booker", "❄️Xanthomonas", "❄️unimpeded", "❄️overfeminize", "❄️speronaro", "❄️diaconia", "❄️overholiness", "❄️liquefacient", "❄️Spartium", "❄️haggly", "❄️albumose", "❄️nonnecessary", "❄️sulcalization", "❄️decapitate", "❄️cellated", "❄️unguirostral", "❄️trichiurid", "❄️loveproof", "❄️amakebe", "❄️screet", "❄️arsenoferratin", "❄️unfrizz", "❄️undiscoverable", "❄️procollectivistic", "❄️tractile", "❄️Winona", "❄️dermostosis", "❄️eliminant", "❄️scomberoid", "❄️tensile", "❄️typesetting", "❄️xylic", "❄️dermatopathology", "❄️cycloplegic", "❄️revocable", "❄️fissate", "❄️afterplay", "❄️screwship", "❄️microerg", "❄️bentonite", "❄️stagecoaching", "❄️beglerbeglic", "❄️overcharitably", "❄️Plotinism", "❄️Veddoid", "❄️disequalize", "❄️cytoproct", "❄️trophophore", "❄️antidote", "❄️allerion", "❄️famous", "❄️convey", "❄️postotic", "❄️rapillo", "❄️cilectomy", "❄️penkeeper", "❄️patronym", "❄️bravely", "❄️ureteropyelitis", "❄️Hildebrandine", "❄️missileproof", "❄️Conularia", "❄️deadening", "❄️Conrad", "❄️pseudochylous", "❄️typologically", "❄️strummer", "❄️luxuriousness", "❄️resublimation", "❄️glossiness", "❄️hydrocauline", "❄️anaglyph", "❄️personifiable", "❄️seniority", "❄️formulator", "❄️datiscaceous", "❄️hydracrylate", "❄️Tyranni", "❄️Crawthumper", "❄️overprove", "❄️masher", "❄️dissonance", "❄️Serpentinian", "❄️malachite", "❄️interestless", "❄️stchi", "❄️ogum", "❄️polyspermic", "❄️archegoniate", "❄️precogitation", "❄️Alkaphrah", "❄️craggily", "❄️delightfulness", "❄️bioplast", "❄️diplocaulescent", "❄️neverland", "❄️interspheral", "❄️chlorhydric", "❄️forsakenly", "❄️scandium", "❄️detubation", "❄️telega", "❄️Valeriana", "❄️centraxonial", "❄️anabolite", "❄️neger", "❄️miscellanea", "❄️whalebacker", "❄️stylidiaceous", "❄️unpropelled", "❄️Kennedya", "❄️Jacksonite", "❄️ghoulish", "❄️Dendrocalamus", "❄️paynimhood", "❄️rappist", "❄️unluffed", "❄️falling", "❄️Lyctus", "❄️uncrown", "❄️warmly", "❄️pneumatism", "❄️Morisonian", "❄️notate", "❄️isoagglutinin", "❄️Pelidnota", "❄️previsit", "❄️contradistinctly", "❄️utter", "❄️porometer", "❄️gie", "❄️germanization", "❄️betwixt", "❄️prenephritic", "❄️underpier", "❄️Eleutheria", "❄️ruthenious", "❄️convertor", "❄️antisepsin", "❄️winterage", "❄️tetramethylammonium", "❄️Rockaway", "❄️Penaea", "❄️prelatehood", "❄️brisket", "❄️unwishful", "❄️Minahassa", "❄️Briareus", "❄️semiaxis", "❄️disintegrant", "❄️peastick", "❄️iatromechanical", "❄️fastus", "❄️thymectomy", "❄️ladyless", "❄️unpreened", "❄️overflutter", "❄️sicker", "❄️apsidally", "❄️thiazine", "❄️guideway", "❄️pausation", "❄️tellinoid", "❄️abrogative", "❄️foraminulate", "❄️omphalos", "❄️Monorhina", "❄️polymyarian", "❄️unhelpful", "❄️newslessness", "❄️oryctognosy", "❄️octoradial", "❄️doxology", "❄️arrhythmy", "❄️gugal", "❄️mesityl", "❄️hexaplaric", "❄️Cabirian", "❄️hordeiform", "❄️eddyroot", "❄️internarial", "❄️deservingness", "❄️jawbation", "❄️orographically", "❄️semiprecious", "❄️seasick", "❄️thermically", "❄️grew", "❄️tamability", "❄️egotistically", "❄️fip", "❄️preabsorbent", "❄️leptochroa", "❄️ethnobotany", "❄️podolite", "❄️egoistic", "❄️semitropical", "❄️cero", "❄️spinelessness", "❄️onshore", "❄️omlah", "❄️tintinnabulist", "❄️machila", "❄️entomotomy", "❄️nubile", "❄️nonscholastic", "❄️burnt", "❄️Alea", "❄️befume", "❄️doctorless", "❄️Napoleonic", "❄️scenting", "❄️apokreos", "❄️cresylene", "❄️paramide", "❄️rattery", "❄️disinterested", "❄️idiopathetic", "❄️negatory", "❄️fervid", "❄️quintato", "❄️untricked", "❄️Metrosideros", "❄️mescaline", "❄️midverse", "❄️Musophagidae", "❄️fictionary", "❄️branchiostegous", "❄️yoker", "❄️residuum", "❄️culmigenous", "❄️fleam", "❄️suffragism", "❄️Anacreon", "❄️sarcodous", "❄️parodistic", "❄️writmaking", "❄️conversationism", "❄️retroposed", "❄️tornillo", "❄️presuspect", "❄️didymous", "❄️Saumur", "❄️spicing", "❄️drawbridge", "❄️cantor", "❄️incumbrancer", "❄️heterospory", "❄️Turkeydom", "❄️anteprandial", "❄️neighborship", "❄️thatchless", "❄️drepanoid", "❄️lusher", "❄️paling", "❄️ecthlipsis", "❄️heredosyphilitic", "❄️although", "❄️garetta", "❄️temporarily", "❄️Monotropa", "❄️proglottic", "❄️calyptro", "❄️persiflage", "❄️degradable", "❄️paraspecific", "❄️undecorative", "❄️Pholas", "❄️myelon", "❄️resteal", "❄️quadrantly", "❄️scrimped", "❄️airer", "❄️deviless", "❄️caliciform", "❄️Sefekhet", "❄️shastaite", "❄️togate", "❄️macrostructure", "❄️bipyramid", "❄️wey", "❄️didynamy", "❄️knacker", "❄️swage", "❄️supermanism", "❄️epitheton", "❄️overpresumptuous" ] public func run_SortStringsUnicode(_ N: Int) { for _ in 1...5*N { benchSortStrings(stringBenchmarkWordsUnicode) } }
apache-2.0
cc58930e53e8e318cbac3987e86c5707
16.035784
80
0.584726
2.535605
false
false
false
false
artsy/Emergence
Emergence/Models/Electric Objects/Partner.swift
1
439
import Gloss struct Partner: Partnerable { let id: String let name: String let profileID: String? } extension Partner: Decodable { init?(json: JSON) { guard let idValue: String = "id" <~~ json, let nameValue: String = "name" <~~ json else { return nil } id = idValue name = nameValue profileID = "default_profile_id" <~~ json } }
mit
ea2471694af981b277136d4734bfab11
17.291667
51
0.526196
4.180952
false
false
false
false
swillsea/DailyDiary
DailyDiary/AddOrEditVC.swift
1
7217
// // AddOrEditVC.swift // Quotidian // // Created by Sam on 5/9/16. // Copyright © 2016 Sam Willsea, Pei Xiong, and Michael Merrill. All rights reserved. // import UIKit import CoreData class AddOrEditVC: UIViewController, UIActionSheetDelegate, UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate{ @IBOutlet weak var entryText: UITextView! @IBOutlet weak var entryImageView: UIImageView! var doneEditing = false var moc: NSManagedObjectContext! var entryBeingEdited: Entry! @IBOutlet weak var imageHeightConstraint: NSLayoutConstraint! @IBOutlet weak var textViewBottomConstraint: NSLayoutConstraint! //MARK: View Setup override func viewDidLoad() { super.viewDidLoad() self.styleNavBar() UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation:UIStatusBarAnimation.Fade) displayCorrectEntry() entryText.becomeFirstResponder() } func styleNavBar() { self.navigationController?.setNavigationBarHidden(true, animated: false) let newNavBar = UINavigationBar.init(frame:(CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 64.0))) let newItem = UINavigationItem() let addImageButtonImage = UIImage.init(named:"camera") let addImageBarButtonItem = UIBarButtonItem.init(image: addImageButtonImage, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.addImage)) let doneBarButtonItem = UIBarButtonItem.init(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: #selector(self.backTapped)) // the bar button item is actually set on the navigation item, not the navigation bar itself. newItem.rightBarButtonItem = addImageBarButtonItem newItem.leftBarButtonItem = doneBarButtonItem newNavBar.setItems([newItem], animated: false) self.view.addSubview(newNavBar) } func backTapped (){ if (self.entryText.text.characters.count > 0 || self.entryImageView.image != nil){ saveOrUpdate() } self.entryText.resignFirstResponder() self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } func displayCorrectEntry(){ if entryBeingEdited != nil { displayEntryDate(entryBeingEdited.date!) self.entryText.text = self.entryBeingEdited.text if entryBeingEdited.imageData != nil{ self.entryImageView.image = UIImage.init(data: self.entryBeingEdited.imageData!) textViewBottomConstraint.constant = 10 } else { textViewBottomConstraint.constant = -60 } } else { let today = NSDate() displayEntryDate(today) textViewBottomConstraint.constant = -60 } } func displayEntryDate(date: NSDate) { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MMM dd, yyyy" self.title = dateFormatter.stringFromDate(date) } //MARK: CoreData Interactions func saveOrUpdate() { if entryBeingEdited != nil { updateEntry() } else { saveNewEntry() } do { try self.moc.save() } catch let error as NSError { print("Error saving to CoreData \(error)") } } func updateEntry() { entryBeingEdited.text = self.entryText.text if (self.entryImageView.image != nil){ entryBeingEdited.imageData = UIImageJPEGRepresentation(self.entryImageView.image!, 1) } } func saveNewEntry() { let newEntry = NSEntityDescription.insertNewObjectForEntityForName("Entry", inManagedObjectContext: self.moc) as! Entry newEntry.text = self.entryText.text newEntry.date = NSDate() newEntry.location = "" if (self.entryImageView.image != nil){ newEntry.imageData = UIImageJPEGRepresentation(self.entryImageView.image!, 1) } else { newEntry.imageData = UIImageJPEGRepresentation(UIImage(), 0) } entryBeingEdited = newEntry } //MARK: Actions func addImage() { if self.entryImageView.image != nil { promptForReplaceImage() } else { promptForImageSource() } } @IBAction func onAddImageButtonPressed(sender: UIBarButtonItem) { } func promptForReplaceImage(){ let prompt = UIAlertController(title:nil, message:nil, preferredStyle: .ActionSheet) let continueToReplace = UIAlertAction(title: "Replace current image", style: .Default) { (alert:UIAlertAction!) -> Void in self.promptForImageSource() } let removeImage = UIAlertAction(title: "Remove image", style: .Destructive) { (alert:UIAlertAction!) -> Void in self.entryImageView.image = nil self.textViewBottomConstraint.constant = -60 if self.entryBeingEdited != nil { self.entryBeingEdited.imageData = UIImageJPEGRepresentation(UIImage(), 0) } } let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) prompt.addAction(continueToReplace) prompt.addAction(removeImage) prompt.addAction(cancel) presentViewController(prompt, animated: true, completion:nil) } func promptForImageSource(){ let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.allowsEditing = true let prompt = UIAlertController(title:nil, message:nil, preferredStyle: .ActionSheet) let cameraAction = UIAlertAction(title: "Use Camera", style: .Default) { (alert: UIAlertAction!) -> Void in if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){ imagePicker.sourceType = UIImagePickerControllerSourceType.Camera self.presentViewController(imagePicker, animated: true, completion: nil) } } let libraryAction = UIAlertAction(title: "Choose from Library", style: .Default) { (alert: UIAlertAction!) -> Void in imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary self.presentViewController(imagePicker, animated: true, completion: nil) } let cancel = UIAlertAction(title: "Cancel", style: .Cancel) { (alert: UIAlertAction) in } prompt.addAction(cameraAction) prompt.addAction(libraryAction) prompt.addAction(cancel) presentViewController(prompt, animated: true, completion:nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) self.entryImageView.image = image textViewBottomConstraint.constant = 10 self.dismissViewControllerAnimated(true, completion: nil) entryText.becomeFirstResponder() } }
mit
2c9c6e3e379031f2be89c2c3fd2d261f
38.431694
167
0.655488
5.298091
false
false
false
false
remirobert/Dotzu-Objective-c
Pods/Dotzu/Dotzu/LogCodeFilter.swift
2
1387
// // LogCodeFilter.swift // exampleWindow // // Created by Remi Robert on 27/01/2017. // Copyright © 2017 Remi Robert. All rights reserved. // import UIKit class LogCodeFilter { static let shared = LogCodeFilter() var enabled: [LogCode] { return [code200 ? .code200 : nil, code300 ? .code300 : nil, code400 ? .code400 : nil, code500 ? .code500 : nil].flatMap {$0} } var code200: Bool { didSet { setFilter(value: code200, key: "codeFilter200") } } var code300: Bool { didSet { setFilter(value: code300, key: "codeFilter300") } } var code400: Bool { didSet { setFilter(value: code400, key: "codeFilter400") } } var code500: Bool { didSet { setFilter(value: code500, key: "codeFilter500") } } private func setFilter(value: Bool, key: String) { UserDefaults.standard.set(value, forKey: key) LogNotificationApp.stopRequest.post(Void()) } init() { code200 = UserDefaults.standard.bool2(forKey: "codeFilter200") code300 = UserDefaults.standard.bool2(forKey: "codeFilter300") code400 = UserDefaults.standard.bool2(forKey: "codeFilter400") code500 = UserDefaults.standard.bool2(forKey: "codeFilter500") } }
mit
735a54736df5b524696080a07770ae07
24.666667
70
0.580087
3.85
false
false
false
false
atl009/WordPress-iOS
WordPress/Classes/ViewRelated/NUX/LoginLinkRequestViewController.swift
1
5179
import UIKit import CocoaLumberjack /// Step one in the auth link flow. This VC displays a form to request a "magic" /// authentication link be emailed to the user. Allows the user to signin via /// email instead of their password. /// class LoginLinkRequestViewController: LoginViewController { @IBOutlet var gravatarView: UIImageView? @IBOutlet var label: UILabel? @IBOutlet var sendLinkButton: NUXSubmitButton? @IBOutlet var usePasswordButton: UIButton? override var sourceTag: SupportSourceTag { get { return .loginMagicLink } } // MARK: - Lifecycle Methods override func viewDidLoad() { super.viewDidLoad() localizeControls() let email = loginFields.username if !email.isValidEmail() { assert(email.isValidEmail(), "The value of loginFields.username was not a valid email address.") } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let email = loginFields.username if email.isValidEmail() { gravatarView?.downloadGravatarWithEmail(email, rating: .x) } else { gravatarView?.isHidden = true } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) assert(SigninHelpers.controllerWasPresentedFromRootViewController(self), "Only present parts of the magic link signin flow from the application's root vc.") WPAppAnalytics.track(.loginMagicLinkRequestFormViewed) } // MARK: - Configuration /// Assigns localized strings to various UIControl defined in the storyboard. /// func localizeControls() { let format = NSLocalizedString("We'll email you a magic link that'll log you in instantly, no password needed. Hunt and peck no more!", comment: "Instructional text for the magic link login flow.") label?.text = NSString(format: format as NSString, loginFields.username) as String let sendLinkButtonTitle = NSLocalizedString("Send Link", comment: "Title of a button. The text should be uppercase. Clicking requests a hyperlink be emailed ot the user.") sendLinkButton?.setTitle(sendLinkButtonTitle, for: UIControlState()) sendLinkButton?.setTitle(sendLinkButtonTitle, for: .highlighted) let usePasswordTitle = NSLocalizedString("Enter your password instead.", comment: "Title of a button. ") usePasswordButton?.setTitle(usePasswordTitle, for: UIControlState()) usePasswordButton?.setTitle(usePasswordTitle, for: .highlighted) usePasswordButton?.titleLabel?.numberOfLines = 0 usePasswordButton?.accessibilityIdentifier = "Use Password" } func configureLoading(_ animating: Bool) { sendLinkButton?.showActivityIndicator(animating) sendLinkButton?.isEnabled = !animating } // MARK: - Instance Methods /// Makes the call to request a magic authentication link be emailed to the user. /// func requestAuthenticationLink() { let email = loginFields.username guard email.isValidEmail() else { // This is a bit of paranioa as in practice it should never happen. // However, let's make sure we give the user some useful feedback just in case. DDLogError("Attempted to request authentication link, but the email address did not appear valid.") WPError.showAlert(withTitle: NSLocalizedString("Can Not Request Link", comment: "Title of an alert letting the user know"), message: NSLocalizedString("A valid email address is needed to mail an authentication link. Please return to the previous screen and provide a valid email address.", comment: "An error message.")) return } configureLoading(true) let service = AccountService(managedObjectContext: ContextManager.sharedInstance().mainContext) service.requestAuthenticationLink(email, success: { [weak self] in self?.didRequestAuthenticationLink() self?.configureLoading(false) }, failure: { [weak self] (error: Error) in WPAppAnalytics.track(.loginMagicLinkFailed) WPAppAnalytics.track(.loginFailed, error: error) guard let strongSelf = self else { return } strongSelf.displayError(error as NSError, sourceTag: strongSelf.sourceTag) strongSelf.configureLoading(false) }) } // MARK: - Actions @IBAction func handleSendLinkTapped(_ sender: UIButton) { requestAuthenticationLink() } func didRequestAuthenticationLink() { WPAppAnalytics.track(.loginMagicLinkRequested) SigninHelpers.saveEmailAddressForTokenAuth(loginFields.username) performSegue(withIdentifier: .showLinkMailView, sender: self) } @IBAction func handleUsePasswordTapped(_ sender: UIButton) { WPAppAnalytics.track(.loginMagicLinkExited) } }
gpl-2.0
90de23554b65d9c18dbf4eaf0c4c925e
40.103175
226
0.663062
5.306352
false
false
false
false
youprofit/firefox-ios
Client/Frontend/Browser/URLBarView.swift
2
31700
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import Shared import SnapKit private struct URLBarViewUX { static let TextFieldBorderColor = UIColor(rgb: 0xBBBBBB) static let TextFieldActiveBorderColor = UIColor(rgb: 0x4A90E2) static let TextFieldContentInset = UIOffsetMake(9, 5) static let LocationLeftPadding = 5 static let LocationHeight = 28 static let LocationContentOffset: CGFloat = 8 static let TextFieldCornerRadius: CGFloat = 3 static let TextFieldBorderWidth: CGFloat = 1 // offset from edge of tabs button static let URLBarCurveOffset: CGFloat = 14 static let URLBarCurveOffsetLeft: CGFloat = -10 // buffer so we dont see edges when animation overshoots with spring static let URLBarCurveBounceBuffer: CGFloat = 8 static let TabsButtonRotationOffset: CGFloat = 1.5 static let TabsButtonHeight: CGFloat = 18.0 static let ToolbarButtonInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) static func backgroundColorWithAlpha(alpha: CGFloat) -> UIColor { return UIConstants.AppBackgroundColor.colorWithAlphaComponent(alpha) } } protocol URLBarDelegate: class { func urlBarDidPressTabs(urlBar: URLBarView) func urlBarDidPressReaderMode(urlBar: URLBarView) /// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied func urlBarDidLongPressReaderMode(urlBar: URLBarView) -> Bool func urlBarDidPressStop(urlBar: URLBarView) func urlBarDidPressReload(urlBar: URLBarView) func urlBarDidEnterOverlayMode(urlBar: URLBarView) func urlBarDidLeaveOverlayMode(urlBar: URLBarView) func urlBarDidLongPressLocation(urlBar: URLBarView) func urlBarLocationAccessibilityActions(urlBar: URLBarView) -> [UIAccessibilityCustomAction]? func urlBarDidPressScrollToTop(urlBar: URLBarView) func urlBar(urlBar: URLBarView, didEnterText text: String) func urlBar(urlBar: URLBarView, didSubmitText text: String) } class URLBarView: UIView { weak var delegate: URLBarDelegate? weak var browserToolbarDelegate: BrowserToolbarDelegate? var helper: BrowserToolbarHelper? var isTransitioning: Bool = false { didSet { if isTransitioning { // Cancel any pending/in-progress animations related to the progress bar self.progressBar.setProgress(1, animated: false) self.progressBar.alpha = 0.0 } } } var toolbarIsShowing = false /// Overlay mode is the state where the lock/reader icons are hidden, the home panels are shown, /// and the Cancel button is visible (allowing the user to leave overlay mode). Overlay mode /// is *not* tied to the location text field's editing state; for instance, when selecting /// a panel, the first responder will be resigned, yet the overlay mode UI is still active. var inOverlayMode = false lazy var locationView: BrowserLocationView = { let locationView = BrowserLocationView() locationView.translatesAutoresizingMaskIntoConstraints = false locationView.readerModeState = ReaderModeState.Unavailable locationView.delegate = self return locationView }() private lazy var locationTextField: ToolbarTextField = { let locationTextField = ToolbarTextField() locationTextField.translatesAutoresizingMaskIntoConstraints = false locationTextField.autocompleteDelegate = self locationTextField.keyboardType = UIKeyboardType.WebSearch locationTextField.autocorrectionType = UITextAutocorrectionType.No locationTextField.autocapitalizationType = UITextAutocapitalizationType.None locationTextField.returnKeyType = UIReturnKeyType.Go locationTextField.clearButtonMode = UITextFieldViewMode.WhileEditing locationTextField.backgroundColor = UIColor.whiteColor() locationTextField.font = UIConstants.DefaultMediumFont locationTextField.accessibilityIdentifier = "address" locationTextField.accessibilityLabel = NSLocalizedString("Address and Search", comment: "Accessibility label for address and search field, both words (Address, Search) are therefore nouns.") locationTextField.attributedPlaceholder = self.locationView.placeholder return locationTextField }() private lazy var locationContainer: UIView = { let locationContainer = UIView() locationContainer.translatesAutoresizingMaskIntoConstraints = false // Enable clipping to apply the rounded edges to subviews. locationContainer.clipsToBounds = true locationContainer.layer.borderColor = URLBarViewUX.TextFieldBorderColor.CGColor locationContainer.layer.cornerRadius = URLBarViewUX.TextFieldCornerRadius locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidth return locationContainer }() private lazy var tabsButton: UIButton = { let tabsButton = InsetButton() tabsButton.translatesAutoresizingMaskIntoConstraints = false tabsButton.setTitle("0", forState: UIControlState.Normal) tabsButton.setTitleColor(URLBarViewUX.backgroundColorWithAlpha(1), forState: UIControlState.Normal) tabsButton.titleLabel?.layer.backgroundColor = UIColor.whiteColor().CGColor tabsButton.titleLabel?.layer.cornerRadius = 2 tabsButton.titleLabel?.font = UIConstants.DefaultSmallFontBold tabsButton.titleLabel?.textAlignment = NSTextAlignment.Center tabsButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal) tabsButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal) tabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside) tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility Label for the tabs button in the browser toolbar") return tabsButton }() private lazy var progressBar: UIProgressView = { let progressBar = UIProgressView() progressBar.progressTintColor = UIColor(red:1, green:0.32, blue:0, alpha:1) progressBar.alpha = 0 progressBar.hidden = true return progressBar }() private lazy var cancelButton: UIButton = { let cancelButton = InsetButton() cancelButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) let cancelTitle = NSLocalizedString("Cancel", comment: "Button label to cancel entering a URL or search query") cancelButton.setTitle(cancelTitle, forState: UIControlState.Normal) cancelButton.titleLabel?.font = UIConstants.DefaultMediumFont cancelButton.addTarget(self, action: "SELdidClickCancel", forControlEvents: UIControlEvents.TouchUpInside) cancelButton.titleEdgeInsets = UIEdgeInsetsMake(10, 12, 10, 12) cancelButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal) cancelButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal) return cancelButton }() private lazy var curveShape: CurveView = { return CurveView() }() private lazy var scrollToTopButton: UIButton = { let button = UIButton() button.addTarget(self, action: "SELtappedScrollToTopArea", forControlEvents: UIControlEvents.TouchUpInside) return button }() lazy var shareButton: UIButton = { return UIButton() }() lazy var bookmarkButton: UIButton = { return UIButton() }() lazy var forwardButton: UIButton = { return UIButton() }() lazy var backButton: UIButton = { return UIButton() }() lazy var stopReloadButton: UIButton = { return UIButton() }() lazy var actionButtons: [UIButton] = { return [self.shareButton, self.bookmarkButton, self.forwardButton, self.backButton, self.stopReloadButton] }() // Used to temporarily store the cloned button so we can respond to layout changes during animation private weak var clonedTabsButton: InsetButton? private var rightBarConstraint: Constraint? private let defaultRightOffset: CGFloat = URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer var currentURL: NSURL? { get { return locationView.url } set(newURL) { locationView.url = newURL } } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { backgroundColor = URLBarViewUX.backgroundColorWithAlpha(0) addSubview(curveShape) addSubview(scrollToTopButton) addSubview(progressBar) addSubview(tabsButton) addSubview(cancelButton) addSubview(shareButton) addSubview(bookmarkButton) addSubview(forwardButton) addSubview(backButton) addSubview(stopReloadButton) locationContainer.addSubview(locationView) locationContainer.addSubview(locationTextField) addSubview(locationContainer) helper = BrowserToolbarHelper(toolbar: self) setupConstraints() // Make sure we hide any views that shouldn't be showing in non-overlay mode. updateViewsForOverlayModeAndToolbarChanges() self.locationTextField.hidden = !inOverlayMode } private func setupConstraints() { scrollToTopButton.snp_makeConstraints { make in make.top.equalTo(self) make.left.right.equalTo(self.locationContainer) } progressBar.snp_makeConstraints { make in make.top.equalTo(self.snp_bottom) make.width.equalTo(self) } locationView.snp_makeConstraints { make in make.edges.equalTo(self.locationContainer) } cancelButton.snp_makeConstraints { make in make.centerY.equalTo(self.locationContainer) make.trailing.equalTo(self) } tabsButton.titleLabel?.snp_makeConstraints { make in make.size.equalTo(URLBarViewUX.TabsButtonHeight) } tabsButton.snp_makeConstraints { make in make.centerY.equalTo(self.locationContainer) make.trailing.equalTo(self) make.width.height.equalTo(UIConstants.ToolbarHeight) } curveShape.snp_makeConstraints { make in make.top.left.bottom.equalTo(self) self.rightBarConstraint = make.right.equalTo(self).constraint self.rightBarConstraint?.updateOffset(defaultRightOffset) } locationTextField.snp_makeConstraints { make in make.edges.equalTo(self.locationView.urlTextField) } backButton.snp_makeConstraints { make in make.left.centerY.equalTo(self) make.size.equalTo(UIConstants.ToolbarHeight) } forwardButton.snp_makeConstraints { make in make.left.equalTo(self.backButton.snp_right) make.centerY.equalTo(self) make.size.equalTo(backButton) } stopReloadButton.snp_makeConstraints { make in make.left.equalTo(self.forwardButton.snp_right) make.centerY.equalTo(self) make.size.equalTo(backButton) } shareButton.snp_makeConstraints { make in make.right.equalTo(self.bookmarkButton.snp_left) make.centerY.equalTo(self) make.size.equalTo(backButton) } bookmarkButton.snp_makeConstraints { make in make.right.equalTo(self.tabsButton.snp_left).offset(URLBarViewUX.URLBarCurveOffsetLeft) make.centerY.equalTo(self) make.size.equalTo(backButton) } } override func updateConstraints() { super.updateConstraints() if inOverlayMode { // In overlay mode, we always show the location view full width self.locationContainer.snp_remakeConstraints { make in make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding) make.trailing.equalTo(self.cancelButton.snp_leading) make.height.equalTo(URLBarViewUX.LocationHeight) make.centerY.equalTo(self) } } else { self.locationContainer.snp_remakeConstraints { make in if self.toolbarIsShowing { // If we are showing a toolbar, show the text field next to the forward button make.leading.equalTo(self.stopReloadButton.snp_trailing) make.trailing.equalTo(self.shareButton.snp_leading) } else { // Otherwise, left align the location view make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding) make.trailing.equalTo(self.tabsButton.snp_leading).offset(-14) } make.height.equalTo(URLBarViewUX.LocationHeight) make.centerY.equalTo(self) } } } // Ideally we'd split this implementation in two, one URLBarView with a toolbar and one without // However, switching views dynamically at runtime is a difficult. For now, we just use one view // that can show in either mode. func setShowToolbar(shouldShow: Bool) { toolbarIsShowing = shouldShow setNeedsUpdateConstraints() // when we transition from portrait to landscape, calling this here causes // the constraints to be calculated too early and there are constraint errors if !toolbarIsShowing { updateConstraintsIfNeeded() } updateViewsForOverlayModeAndToolbarChanges() } func updateAlphaForSubviews(alpha: CGFloat) { self.tabsButton.alpha = alpha self.locationContainer.alpha = alpha self.backgroundColor = URLBarViewUX.backgroundColorWithAlpha(1 - alpha) self.actionButtons.forEach { $0.alpha = alpha } } func updateTabCount(count: Int) { updateTabCount(count, animated: true) } func updateTabCount(count: Int, animated: Bool) { if let _ = self.clonedTabsButton { self.clonedTabsButton?.layer.removeAllAnimations() self.clonedTabsButton?.removeFromSuperview() self.tabsButton.layer.removeAllAnimations() } // make a 'clone' of the tabs button let newTabsButton = InsetButton() self.clonedTabsButton = newTabsButton newTabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside) newTabsButton.setTitleColor(UIConstants.AppBackgroundColor, forState: UIControlState.Normal) newTabsButton.titleLabel?.layer.backgroundColor = UIColor.whiteColor().CGColor newTabsButton.titleLabel?.layer.cornerRadius = 2 newTabsButton.titleLabel?.font = UIConstants.DefaultSmallFontBold newTabsButton.titleLabel?.textAlignment = NSTextAlignment.Center newTabsButton.setTitle(count.description, forState: .Normal) addSubview(newTabsButton) newTabsButton.titleLabel?.snp_makeConstraints { make in make.size.equalTo(URLBarViewUX.TabsButtonHeight) } newTabsButton.snp_makeConstraints { make in make.centerY.equalTo(self.locationContainer) make.trailing.equalTo(self) make.size.equalTo(UIConstants.ToolbarHeight) } newTabsButton.frame = tabsButton.frame // Instead of changing the anchorPoint of the CALayer, lets alter the rotation matrix math to be // a rotation around a non-origin point if let labelFrame = newTabsButton.titleLabel?.frame { let halfTitleHeight = CGRectGetHeight(labelFrame) / 2 var newFlipTransform = CATransform3DIdentity newFlipTransform = CATransform3DTranslate(newFlipTransform, 0, halfTitleHeight, 0) newFlipTransform.m34 = -1.0 / 200.0 // add some perspective newFlipTransform = CATransform3DRotate(newFlipTransform, CGFloat(-M_PI_2), 1.0, 0.0, 0.0) newTabsButton.titleLabel?.layer.transform = newFlipTransform var oldFlipTransform = CATransform3DIdentity oldFlipTransform = CATransform3DTranslate(oldFlipTransform, 0, halfTitleHeight, 0) oldFlipTransform.m34 = -1.0 / 200.0 // add some perspective oldFlipTransform = CATransform3DRotate(oldFlipTransform, CGFloat(M_PI_2), 1.0, 0.0, 0.0) let animate = { newTabsButton.titleLabel?.layer.transform = CATransform3DIdentity self.tabsButton.titleLabel?.layer.transform = oldFlipTransform self.tabsButton.titleLabel?.layer.opacity = 0 } let completion: (Bool) -> Void = { finished in // remove the clone and setup the actual tab button newTabsButton.removeFromSuperview() self.tabsButton.titleLabel?.layer.opacity = 1 self.tabsButton.titleLabel?.layer.transform = CATransform3DIdentity self.tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility label for the tabs button in the (top) browser toolbar") if finished { self.tabsButton.setTitle(count.description, forState: UIControlState.Normal) self.tabsButton.accessibilityValue = count.description } } if animated { UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: animate, completion: completion) } else { completion(true) } } } func updateProgressBar(progress: Float) { if progress == 1.0 { self.progressBar.setProgress(progress, animated: !isTransitioning) UIView.animateWithDuration(1.5, animations: { self.progressBar.alpha = 0.0 }, completion: { finished in if finished { self.progressBar.setProgress(0.0, animated: false) } }) } else { if self.progressBar.alpha < 1.0 { self.progressBar.alpha = 1.0 } self.progressBar.setProgress(progress, animated: (progress > progressBar.progress) && !isTransitioning) } } func updateReaderModeState(state: ReaderModeState) { locationView.readerModeState = state } func setAutocompleteSuggestion(suggestion: String?) { locationTextField.setAutocompleteSuggestion(suggestion) } func enterOverlayMode(locationText: String?, pasted: Bool) { // Show the overlay mode UI, which includes hiding the locationView and replacing it // with the editable locationTextField. animateToOverlayState(overlayMode: true) delegate?.urlBarDidEnterOverlayMode(self) // Bug 1193755 Workaround - Calling becomeFirstResponder before the animation happens // won't take the initial frame of the label into consideration, which makes the label // look squished at the start of the animation and expand to be correct. As a workaround, // we becomeFirstResponder as the next event on UI thread, so the animation starts before we // set a first responder. if pasted { // Clear any existing text, focus the field, then set the actual pasted text. // This avoids highlighting all of the text. self.locationTextField.text = "" dispatch_async(dispatch_get_main_queue()) { self.locationTextField.becomeFirstResponder() self.locationTextField.text = locationText } } else { // Copy the current URL to the editable text field, then activate it. self.locationTextField.text = locationText dispatch_async(dispatch_get_main_queue()) { self.locationTextField.becomeFirstResponder() } } } func leaveOverlayMode(didCancel cancel: Bool = false) { locationTextField.resignFirstResponder() animateToOverlayState(overlayMode: false, didCancel: cancel) delegate?.urlBarDidLeaveOverlayMode(self) } func prepareOverlayAnimation() { // Make sure everything is showing during the transition (we'll hide it afterwards). self.bringSubviewToFront(self.locationContainer) self.cancelButton.hidden = false self.progressBar.hidden = false self.shareButton.hidden = !self.toolbarIsShowing self.bookmarkButton.hidden = !self.toolbarIsShowing self.forwardButton.hidden = !self.toolbarIsShowing self.backButton.hidden = !self.toolbarIsShowing self.stopReloadButton.hidden = !self.toolbarIsShowing } func transitionToOverlay(didCancel: Bool = false) { self.cancelButton.alpha = inOverlayMode ? 1 : 0 self.progressBar.alpha = inOverlayMode || didCancel ? 0 : 1 self.shareButton.alpha = inOverlayMode ? 0 : 1 self.bookmarkButton.alpha = inOverlayMode ? 0 : 1 self.forwardButton.alpha = inOverlayMode ? 0 : 1 self.backButton.alpha = inOverlayMode ? 0 : 1 self.stopReloadButton.alpha = inOverlayMode ? 0 : 1 let borderColor = inOverlayMode ? URLBarViewUX.TextFieldActiveBorderColor : URLBarViewUX.TextFieldBorderColor locationContainer.layer.borderColor = borderColor.CGColor if inOverlayMode { self.cancelButton.transform = CGAffineTransformIdentity let tabsButtonTransform = CGAffineTransformMakeTranslation(self.tabsButton.frame.width + URLBarViewUX.URLBarCurveOffset, 0) self.tabsButton.transform = tabsButtonTransform self.clonedTabsButton?.transform = tabsButtonTransform self.rightBarConstraint?.updateOffset(URLBarViewUX.URLBarCurveOffset + URLBarViewUX.URLBarCurveBounceBuffer + tabsButton.frame.width) // Make the editable text field span the entire URL bar, covering the lock and reader icons. self.locationTextField.snp_remakeConstraints { make in make.leading.equalTo(self.locationContainer).offset(URLBarViewUX.LocationContentOffset) make.top.bottom.trailing.equalTo(self.locationContainer) } } else { self.tabsButton.transform = CGAffineTransformIdentity self.clonedTabsButton?.transform = CGAffineTransformIdentity self.cancelButton.transform = CGAffineTransformMakeTranslation(self.cancelButton.frame.width, 0) self.rightBarConstraint?.updateOffset(defaultRightOffset) // Shrink the editable text field back to the size of the location view before hiding it. self.locationTextField.snp_remakeConstraints { make in make.edges.equalTo(self.locationView.urlTextField) } } } func updateViewsForOverlayModeAndToolbarChanges() { self.cancelButton.hidden = !inOverlayMode self.progressBar.hidden = inOverlayMode self.shareButton.hidden = !self.toolbarIsShowing || inOverlayMode self.bookmarkButton.hidden = !self.toolbarIsShowing || inOverlayMode self.forwardButton.hidden = !self.toolbarIsShowing || inOverlayMode self.backButton.hidden = !self.toolbarIsShowing || inOverlayMode self.stopReloadButton.hidden = !self.toolbarIsShowing || inOverlayMode } func animateToOverlayState(overlayMode overlay: Bool, didCancel cancel: Bool = false) { prepareOverlayAnimation() layoutIfNeeded() inOverlayMode = overlay locationView.urlTextField.hidden = inOverlayMode locationTextField.hidden = !inOverlayMode UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: [], animations: { _ in self.transitionToOverlay(cancel) self.setNeedsUpdateConstraints() self.layoutIfNeeded() }, completion: { _ in self.updateViewsForOverlayModeAndToolbarChanges() }) } func SELdidClickAddTab() { delegate?.urlBarDidPressTabs(self) } func SELdidClickCancel() { leaveOverlayMode(didCancel: true) } func SELtappedScrollToTopArea() { delegate?.urlBarDidPressScrollToTop(self) } } extension URLBarView: BrowserToolbarProtocol { func updateBackStatus(canGoBack: Bool) { backButton.enabled = canGoBack } func updateForwardStatus(canGoForward: Bool) { forwardButton.enabled = canGoForward } func updateBookmarkStatus(isBookmarked: Bool) { bookmarkButton.selected = isBookmarked } func updateReloadStatus(isLoading: Bool) { if isLoading { stopReloadButton.setImage(helper?.ImageStop, forState: .Normal) stopReloadButton.setImage(helper?.ImageStopPressed, forState: .Highlighted) } else { stopReloadButton.setImage(helper?.ImageReload, forState: .Normal) stopReloadButton.setImage(helper?.ImageReloadPressed, forState: .Highlighted) } } func updatePageStatus(isWebPage isWebPage: Bool) { bookmarkButton.enabled = isWebPage stopReloadButton.enabled = isWebPage shareButton.enabled = isWebPage } override var accessibilityElements: [AnyObject]? { get { if inOverlayMode { return [locationTextField, cancelButton] } else { if toolbarIsShowing { return [backButton, forwardButton, stopReloadButton, locationView, shareButton, bookmarkButton, tabsButton, progressBar] } else { return [locationView, tabsButton, progressBar] } } } set { super.accessibilityElements = newValue } } } extension URLBarView: BrowserLocationViewDelegate { func browserLocationViewDidLongPressReaderMode(browserLocationView: BrowserLocationView) -> Bool { return delegate?.urlBarDidLongPressReaderMode(self) ?? false } func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView) { enterOverlayMode(locationView.url?.absoluteString, pasted: false) } func browserLocationViewDidLongPressLocation(browserLocationView: BrowserLocationView) { delegate?.urlBarDidLongPressLocation(self) } func browserLocationViewDidTapReload(browserLocationView: BrowserLocationView) { delegate?.urlBarDidPressReload(self) } func browserLocationViewDidTapStop(browserLocationView: BrowserLocationView) { delegate?.urlBarDidPressStop(self) } func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView) { delegate?.urlBarDidPressReaderMode(self) } func browserLocationViewLocationAccessibilityActions(browserLocationView: BrowserLocationView) -> [UIAccessibilityCustomAction]? { return delegate?.urlBarLocationAccessibilityActions(self) } } extension URLBarView: AutocompleteTextFieldDelegate { func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool { guard let text = locationTextField.text else { return true } delegate?.urlBar(self, didSubmitText: text) return true } func autocompleteTextField(autocompleteTextField: AutocompleteTextField, didEnterText text: String) { delegate?.urlBar(self, didEnterText: text) } func autocompleteTextFieldDidBeginEditing(autocompleteTextField: AutocompleteTextField) { autocompleteTextField.highlightAll() } func autocompleteTextFieldShouldClear(autocompleteTextField: AutocompleteTextField) -> Bool { delegate?.urlBar(self, didEnterText: "") return true } } /* Code for drawing the urlbar curve */ // Curve's aspect ratio private let ASPECT_RATIO = 0.729 // Width multipliers private let W_M1 = 0.343 private let W_M2 = 0.514 private let W_M3 = 0.49 private let W_M4 = 0.545 private let W_M5 = 0.723 // Height multipliers private let H_M1 = 0.25 private let H_M2 = 0.5 private let H_M3 = 0.72 private let H_M4 = 0.961 /* Code for drawing the urlbar curve */ private class CurveView: UIView { private lazy var leftCurvePath: UIBezierPath = { var leftArc = UIBezierPath(arcCenter: CGPoint(x: 5, y: 5), radius: CGFloat(5), startAngle: CGFloat(-M_PI), endAngle: CGFloat(-M_PI_2), clockwise: true) leftArc.addLineToPoint(CGPoint(x: 0, y: 0)) leftArc.addLineToPoint(CGPoint(x: 0, y: 5)) leftArc.closePath() return leftArc }() override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { self.opaque = false self.contentMode = .Redraw } private func getWidthForHeight(height: Double) -> Double { return height * ASPECT_RATIO } private func drawFromTop(path: UIBezierPath) { let height: Double = Double(UIConstants.ToolbarHeight) let width = getWidthForHeight(height) let from = (Double(self.frame.width) - width * 2 - Double(URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer), Double(0)) path.moveToPoint(CGPoint(x: from.0, y: from.1)) path.addCurveToPoint(CGPoint(x: from.0 + width * W_M2, y: from.1 + height * H_M2), controlPoint1: CGPoint(x: from.0 + width * W_M1, y: from.1), controlPoint2: CGPoint(x: from.0 + width * W_M3, y: from.1 + height * H_M1)) path.addCurveToPoint(CGPoint(x: from.0 + width, y: from.1 + height), controlPoint1: CGPoint(x: from.0 + width * W_M4, y: from.1 + height * H_M3), controlPoint2: CGPoint(x: from.0 + width * W_M5, y: from.1 + height * H_M4)) } private func getPath() -> UIBezierPath { let path = UIBezierPath() self.drawFromTop(path) path.addLineToPoint(CGPoint(x: self.frame.width, y: UIConstants.ToolbarHeight)) path.addLineToPoint(CGPoint(x: self.frame.width, y: 0)) path.addLineToPoint(CGPoint(x: 0, y: 0)) path.closePath() return path } override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() CGContextSaveGState(context) CGContextClearRect(context, rect) CGContextSetFillColorWithColor(context, URLBarViewUX.backgroundColorWithAlpha(1).CGColor) getPath().fill() leftCurvePath.fill() CGContextDrawPath(context, CGPathDrawingMode.Fill) CGContextRestoreGState(context) } } private class ToolbarTextField: AutocompleteTextField { override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mpl-2.0
bd1ea4d241160f57cdd8b7f5ef5cfcc2
40.655716
207
0.682271
5.514002
false
false
false
false
dymx101/Gamers
Gamers/ViewModels/VideoRelateCell.swift
1
1513
// // VideoRelateCell.swift // Gamers // // Created by 虚空之翼 on 15/8/3. // Copyright (c) 2015年 Freedom. All rights reserved. // import UIKit class VideoRelateCell: UITableViewCell { @IBOutlet weak var videoImage: UIImageView! @IBOutlet weak var videoTitle: UILabel! @IBOutlet weak var videoViews: UILabel! override func awakeFromNib() { super.awakeFromNib() // 视频标题自动换行以及超出省略号 videoTitle.numberOfLines = 0 videoTitle.lineBreakMode = NSLineBreakMode.ByCharWrapping videoTitle.lineBreakMode = NSLineBreakMode.ByTruncatingTail } func setVideo(video: Video) { videoTitle.text = video.videoTitle //videoViews.text = String(video.views) + " 次" videoViews.text = BasicFunction.formatViewsTotal(video.views) + " • " + BasicFunction.formatDateString(video.publishedAt) let imageUrl = video.imageSource.stringByReplacingOccurrencesOfString(" ", withString: "%20", options: NSStringCompareOptions.LiteralSearch, range: nil) videoImage.hnk_setImageFromURL(NSURL(string: imageUrl)!) } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func prepareForReuse() { super.prepareForReuse() videoImage.hnk_cancelSetImage() videoImage.image = nil } }
apache-2.0
93da49457c8951dddc9f6bfba18c53c8
27.25
160
0.668482
4.678344
false
false
false
false
kaltura/playkit-ios
Classes/Providers/Mock/MockMediaProvider.swift
1
2793
// =================================================================================================== // Copyright (C) 2017 Kaltura Inc. // // Licensed under the AGPLv3 license, unless a different license for a // particular library is specified in the applicable library path. // // You may obtain a copy of the License at // https://www.gnu.org/licenses/agpl-3.0.html // =================================================================================================== import UIKit import SwiftyJSON @objc public class MockMediaEntryProvider: NSObject, MediaEntryProvider { public enum MockError: Error { case invalidParam(paramName:String) case fileIsEmptyOrNotFound case unableToParseJSON case mediaNotFound } @objc public var id: String? @objc public var url: URL? @objc public var content: Any? @discardableResult @nonobjc public func set(id: String?) -> Self { self.id = id return self } @discardableResult @nonobjc public func set(url: URL?) -> Self { self.url = url return self } @discardableResult @nonobjc public func set(content: Any?) -> Self { self.content = content return self } public override init() { } struct LoaderInfo { var id: String var content: JSON } @objc public func loadMedia(callback: @escaping (PKMediaEntry?, Error?) -> Void) { guard let id = self.id else { callback(nil, MockError.invalidParam(paramName: "id")) return } var json: JSON? = nil if let content = self.content { json = JSON(content) } else if self.url != nil { guard let stringPath = self.url?.absoluteString else { callback(nil, MockError.invalidParam(paramName: "url")) return } guard let data = NSData(contentsOfFile: stringPath) else { callback(nil, MockError.fileIsEmptyOrNotFound) return } json = try? JSON(data: data as Data) } guard let jsonContent = json else { callback(nil, MockError.unableToParseJSON) return } let loderInfo = LoaderInfo(id: id, content: jsonContent) guard loderInfo.content != .null else { callback(nil, MockError.unableToParseJSON) return } let jsonObject: JSON = loderInfo.content[loderInfo.id] guard jsonObject != .null else { callback(nil, MockError.mediaNotFound) return } let mediaEntry = PKMediaEntry(json: jsonObject.object) callback(mediaEntry, nil) } @objc public func cancel() { } }
agpl-3.0
39663c9e9c85eabac3be7af556d4c31b
26.653465
102
0.546366
4.807229
false
false
false
false
jimmy54/iRime
iRime/Keyboard/tasty-imitation-keyboard/Demo/iRNumberBoard/View/iRNumberBoardFatherView.swift
1
4213
// // iRNumberBoardFatherView.swift // iRime // // Created by 王宇 on 2017/2/28. // Copyright © 2017年 jimmy54. All rights reserved. // import UIKit protocol iRNumberBoardFatherViewProtocol:NSObjectProtocol { func presentTextFromNumberPad(_ text:String) -> Void func deleteBackwardOfiRNumberBoardFatherView() -> Void func getReturnKeyTitle() -> String } class iRNumberBoardFatherView: UIView,iRNumberBoardCentreKeysViewvProtocol,iRNumberBoardLeftKeysViewProtocol,iRNumberBoardRightKeysViewProtocol { var viewLeftKeys:iRNumberBoardLeftKeysView? var viewRightKeys:iRNumberBoardRightKeysView? var viewCentreKeys:iRNumberBoardCentreKeysView? var delegateAction:iRNumberBoardFatherViewProtocol? override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.red self.createSubViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func createSubViews() -> Void { //1.左侧的标点符号view viewLeftKeys = iRNumberBoardLeftKeysView.init(frame: CGRect.null) self.addSubview(viewLeftKeys!) //--属性设置 viewLeftKeys?.delegateToCallBack = self //--约束布局 viewLeftKeys?.mas_makeConstraints({ (maker:MASConstraintMaker!) in maker.left.equalTo()(self) maker.top.equalTo()(self) maker.bottom.equalTo()(self) maker.width.equalTo()(self.mas_width)?.multipliedBy()(1.0/6.0)?.offset()(-5) }) //2.右侧的标点符号view viewRightKeys = iRNumberBoardRightKeysView.init(frame: CGRect.null) self.addSubview(viewRightKeys!) //--属性设置 viewRightKeys?.delegateAction = self //--约束布局 viewRightKeys?.mas_makeConstraints({ (maker:MASConstraintMaker!) in maker.right.equalTo()(self) maker.top.equalTo()(self) maker.bottom.equalTo()(self) maker.width.equalTo()(self.mas_width)?.multipliedBy()(1.0/6.0)?.offset()(-5) }) //3.中间的view viewCentreKeys = iRNumberBoardCentreKeysView.init(frame: CGRect.null) self.addSubview(viewCentreKeys!) //--属性设置 viewCentreKeys?.delegateAction = self viewCentreKeys?.backgroundColor = UIColor.white //--约束布局 viewCentreKeys?.mas_makeConstraints({ (maker:MASConstraintMaker!) in maker.top.equalTo()(self) maker.left.equalTo()(self.viewLeftKeys!.mas_right) maker.right.equalTo()(self.viewRightKeys!.mas_left) maker.bottom.equalTo()(self) }) } func callBackOfCentreToPassText(_ text:String) -> Void { if self.delegateAction != nil { self.delegateAction?.presentTextFromNumberPad(text) } } func callBackOfCentreToHiddenNumberKeyBoard() -> Void { self.isHidden = true } func iRNumberBoardLeftKeysViewPassText(_ text:String) -> Void { if self.delegateAction != nil { self.delegateAction?.presentTextFromNumberPad(text) } } func passTextOfIRNumberBoardRightKeysView(_ text:String) -> Void { if self.delegateAction != nil { self.delegateAction?.presentTextFromNumberPad(text) } } func deleteOneOfIRNumberBoardRightKeysView() -> Void { if self.delegateAction != nil { self.delegateAction?.deleteBackwardOfiRNumberBoardFatherView() } } override var isHidden: Bool { get { return super.isHidden } set(v) { super.isHidden = v self.updateReturnKeyTitleWhenShow() } } func updateReturnKeyTitleWhenShow() -> Void { if self.delegateAction != nil { let stringTitle:String = (self.delegateAction?.getReturnKeyTitle())! if stringTitle != "返回" { viewRightKeys!.btnFour?.setTitle(stringTitle, for: UIControlState()) } } } }
gpl-3.0
6e361dec0202e24365632eccd8e7721f
23.670659
145
0.616019
4.225641
false
false
false
false
1457792186/JWSwift
SwiftWX/LGWeChatKit/LGChatKit/friend/LGFriendListCell.swift
1
2980
// // LGFriendListCecll.swift // LGChatViewController // // Created by jamy on 10/20/15. // Copyright © 2015 jamy. All rights reserved. // import UIKit class LGFriendListCell: LGConversionListBaseCell { let iconView: UIImageView! let userNameLabel: UILabel! let phoneLabel: UILabel! let messageListCellHeight = 44 let imageHeight = 40 override init(style: UITableViewCellStyle, reuseIdentifier: String?) { iconView = UIImageView(frame: CGRect(x: 5, y: CGFloat(messageListCellHeight - imageHeight) / 2, width: CGFloat(imageHeight), height: CGFloat(imageHeight))) iconView.layer.cornerRadius = 5.0 iconView.layer.masksToBounds = true userNameLabel = UILabel() userNameLabel.textAlignment = .left userNameLabel.font = UIFont.systemFont(ofSize: 14.0) phoneLabel = UILabel() phoneLabel.textAlignment = .left phoneLabel.font = UIFont.systemFont(ofSize: 13.0) phoneLabel.textColor = UIColor.lightGray super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(iconView) contentView.addSubview(userNameLabel) contentView.addSubview(phoneLabel) userNameLabel.translatesAutoresizingMaskIntoConstraints = false phoneLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addConstraint(NSLayoutConstraint(item: userNameLabel, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1, constant: CGFloat(messageListCellHeight + 8))) contentView.addConstraint(NSLayoutConstraint(item: userNameLabel, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 5)) contentView.addConstraint(NSLayoutConstraint(item: phoneLabel, attribute: .left, relatedBy: .equal, toItem: userNameLabel, attribute: .left, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: phoneLabel, attribute: .top, relatedBy: .equal, toItem: userNameLabel, attribute: .bottom, multiplier: 1, constant: 5)) contentView.addConstraint(NSLayoutConstraint(item: phoneLabel, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: -70)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var viewModel: contactCellModel? { didSet { viewModel?.iconName.observe { [unowned self] in self.iconView.image = UIImage(named: $0) } viewModel?.name.observe { [unowned self] in self.userNameLabel.text = $0 } viewModel?.phone.observe { [unowned self] in self.phoneLabel.text = $0 } } } }
apache-2.0
3a70ffc3c92db96943ba652e49bbce30
38.72
211
0.654246
5.101027
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureKYC/Sources/FeatureKYCUI/_New_KYC/EmailVerification/HelperViews/EditEmailView.swift
1
7981
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import ComposableArchitecture import FeatureKYCDomain import Localization import SwiftUI import UIComponentsKit private typealias L10n = LocalizationConstants.NewKYC struct EditEmailState: Equatable { var emailAddress: String var isEmailValid: Bool var savingEmailAddress: Bool = false var saveEmailFailureAlert: AlertState<EditEmailAction>? init(emailAddress: String) { self.emailAddress = emailAddress isEmailValid = emailAddress.isEmail } } enum EditEmailAction: Equatable { case didAppear case didChangeEmailAddress(String) case didReceiveSaveResponse(Result<Int, UpdateEmailAddressError>) case dismissSaveEmailFailureAlert case save } struct EditEmailEnvironment { let emailVerificationService: EmailVerificationServiceAPI let mainQueue: AnySchedulerOf<DispatchQueue> let validateEmail: (String) -> Bool = { $0.isEmail } } let editEmailReducer = Reducer<EditEmailState, EditEmailAction, EditEmailEnvironment> { state, action, environment in switch action { case .didAppear: state.isEmailValid = environment.validateEmail(state.emailAddress) return .none case .didChangeEmailAddress(let emailAddress): state.emailAddress = emailAddress state.isEmailValid = environment.validateEmail(emailAddress) return .none case .save: guard state.isEmailValid else { return .none } state.savingEmailAddress = true return environment.emailVerificationService.updateEmailAddress(to: state.emailAddress) .receive(on: environment.mainQueue) .catchToEffect() .map { result in switch result { case .success: return .didReceiveSaveResponse(.success(0)) case .failure(let error): return .didReceiveSaveResponse(.failure(error)) } } case .didReceiveSaveResponse(let response): state.savingEmailAddress = false switch response { case .success: return .none case .failure: state.saveEmailFailureAlert = AlertState( title: TextState(L10n.GenericError.title), message: TextState(L10n.EditEmail.couldNotUpdateEmailAlertMessage), primaryButton: .default( TextState(L10n.GenericError.retryButtonTitle), action: .send(.save) ), secondaryButton: .cancel( TextState(L10n.GenericError.cancelButtonTitle) ) ) return .none } case .dismissSaveEmailFailureAlert: state.saveEmailFailureAlert = nil return .none } } struct EditEmailView: View { let store: Store<EditEmailState, EditEmailAction> @State private var isEmailFieldFirstResponder: Bool = true var body: some View { WithViewStore(store) { viewStore in ActionableView( buttons: [ .init( title: L10n.EditEmail.saveButtonTitle, action: { viewStore.send(.save) }, loading: viewStore.savingEmailAddress, enabled: viewStore.isEmailValid ) ], content: { VStack { VStack(alignment: .leading, spacing: 0) { Text(L10n.EditEmail.title) .textStyle(.title) Text(L10n.EditEmail.message) .textStyle(.body) } .frame(maxWidth: .infinity, alignment: .leading) Spacer() VStack(spacing: LayoutConstants.VerticalSpacing.betweenContentGroups) { FormTextFieldGroup( text: viewStore.binding( get: { $0.emailAddress }, send: { .didChangeEmailAddress($0) } ), isFirstResponder: $isEmailFieldFirstResponder, isError: .constant(false), title: L10n.EditEmail.editEmailFieldLabel, configuration: { $0.textContentType = .emailAddress $0.returnKeyType = .done }, onPaddingTapped: { self.isEmailFieldFirstResponder = true }, onReturnTapped: { self.isEmailFieldFirstResponder = false } ) .accessibility(identifier: "KYC.EmailVerification.edit.email.group") if !viewStore.isEmailValid { BadgeView( title: L10n.EditEmail.invalidEmailInputMessage, style: .error ) .accessibility(identifier: "KYC.EmailVerification.edit.email.invalidEmail") } } Spacer() } } ) .alert( store.scope(state: \.saveEmailFailureAlert), dismiss: .dismissSaveEmailFailureAlert ) .onAppear { viewStore.send(.didAppear) } } .background(Color.viewPrimaryBackground) .accessibility(identifier: "KYC.EmailVerification.edit.container") } } #if DEBUG struct EditEmailView_Previews: PreviewProvider { static var previews: some View { // Invalid state: empty email EditEmailView( store: .init( initialState: .init(emailAddress: ""), reducer: editEmailReducer, environment: EditEmailEnvironment( emailVerificationService: NoOpEmailVerificationService(), mainQueue: .main ) ) ) // Invalid state: invalid email typed by user EditEmailView( store: .init( initialState: .init(emailAddress: "invalid.com"), reducer: editEmailReducer, environment: EditEmailEnvironment( emailVerificationService: NoOpEmailVerificationService(), mainQueue: .main ) ) ) // Valid state EditEmailView( store: .init( initialState: .init(emailAddress: "[email protected]"), reducer: editEmailReducer, environment: EditEmailEnvironment( emailVerificationService: NoOpEmailVerificationService(), mainQueue: .main ) ) ) // Loading state EditEmailView( store: .init( initialState: { var state = EditEmailState(emailAddress: "[email protected]") state.savingEmailAddress = true return state }(), reducer: editEmailReducer, environment: EditEmailEnvironment( emailVerificationService: NoOpEmailVerificationService(), mainQueue: .main ) ) ) } } #endif
lgpl-3.0
764fcdc047de83a2cc44b0cd7e76e26c
34
117
0.509148
6.022642
false
false
false
false
announce/MockURLSession
MockURLSessionTests/Example.swift
1
2264
// // Example.swift // MockURLSession // // Created by YAMAMOTOKenta on 8/25/16. // Copyright © 2016 ymkjp. All rights reserved. // import XCTest @testable import MockURLSession class Example: XCTestCase { class MyApp { static let apiUrl = URL(string: "https://example.com/foo/bar")! let session: URLSession var data: Data? var error: Error? init(session: URLSession = URLSession.shared) { self.session = session } func doSomething() { session.dataTask(with: MyApp.apiUrl) { (data, _, error) in self.data = data self.error = error }.resume() } } func testQuickGlance() { // Initialization let session = MockURLSession() // Or, use shared instance as `URLSession` provides // MockURLSession.sharedInstance // Setup a mock response let data = "Foo 123".data(using: .utf8)! session.registerMockResponse(MyApp.apiUrl, data: data) // Inject the session to the target app code and the response will be mocked like below let app = MyApp(session: session) app.doSomething() print(String(data:app.data!, encoding: .utf8)!) // Foo 123 print(app.error as Any) // nil // Make sure that the data task is resumed in the app code print(session.resumedResponse(MyApp.apiUrl) != nil) // true } func testUrlCustomization() { // Customize URL matching logic if you prefer class Normalizer: MockURLSessionNormalizer { func normalize(url: URL) -> URL { // Fuzzy matching example var components = URLComponents() components.host = url.host components.path = url.path return components.url! } } // Note that you should setup the normalizer before registering mocked response let data = NSKeyedArchiver.archivedData(withRootObject: ["username": "abc", "age": 20]) let session = MockURLSession() session.normalizer = Normalizer() session.registerMockResponse(MyApp.apiUrl, data: data) } }
mit
cc8fff43bdddaa36ad7c4c4cbec6b8e5
31.328571
95
0.583738
4.646817
false
true
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/NUX/Post Signup Interstitial/PostSignUpInterstitialCoordinator.swift
1
1818
import Foundation private struct Constants { static let userDefaultsKeyFormat = "PostSignUpInterstitial.hasSeenBefore.%@" } class PostSignUpInterstitialCoordinator { private let database: KeyValueDatabase private let userId: NSNumber? init(database: KeyValueDatabase = UserDefaults.standard, userId: NSNumber? = nil ) { self.database = database self.userId = userId ?? { let context = ContextManager.sharedInstance().mainContext let acctServ = AccountService(managedObjectContext: context) let account = acctServ.defaultWordPressComAccount() return account?.userID }() } /// Generates the user defaults key for the logged in user /// Returns nil if we can not get the default WP.com account private var userDefaultsKey: String? { get { guard let userId = self.userId else { return nil } return String(format: Constants.userDefaultsKeyFormat, userId) } } /// Determines whether or not the PSI should be displayed for the logged in user /// - Parameters: /// - numberOfBlogs: The number of blogs the account has @objc func shouldDisplay(numberOfBlogs: Int) -> Bool { if hasSeenBefore() { return false } return numberOfBlogs == 0 } /// Determines whether the PSI has been displayed to the logged in user func hasSeenBefore() -> Bool { guard let key = userDefaultsKey else { return false } return database.bool(forKey: key) } /// Marks the PSI as seen for the logged in user func markAsSeen() { guard let key = userDefaultsKey else { return } database.set(true, forKey: key) } }
gpl-2.0
9ddb0f29c08da5fcf5945c3500a9af6f
27.857143
88
0.624312
5.092437
false
false
false
false
sgrinich/BeatsByKenApp
BeatsByKen/BeatsByKen/RecordSessionCollectionView.swift
1
7940
// // TrialSettingsView.swift // BeatsByKen // /*Copyright (c) 2015 Aidan Carroll, Alex Calamaro, Max Willard, Liz Shank 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. */ // Code modified from original at: // http://www.raywenderlich.com/78550/beginning-ios-collection-views-swift-part-1 // http://www.raywenderlich.com/78550/beginning-ios-collection-views-swift-part-2 import Foundation import UIKit import CoreData class RecordSessionCollectionView : UICollectionViewController, RecordTrialVCDelegate, UIPopoverPresentationControllerDelegate { let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext let settingsFields = ["Pre-1", "Pre-2", "Pre-3", "Pre-4", "Post-1", "Post-2", "Post-3", "Post-4", "Exer-1", "Exer-2", "Exer-3", "Exer-4"] private let reuseIdentifier = "RecordTrialCell" private let sectionInsets = UIEdgeInsets(top: 50.0, left: 20.0, bottom: 50.0, right: 20.0) var participantID = 0 var sessionID = 0 var tableViewRow = 0 var settings = [NSManagedObject]() var strSaveText : NSString! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. for (index,field) in enumerate(settingsFields) { if (!SessionTable.checkInManagedObjectContext(managedObjectContext!, participantID: trialSettingsPID, sessionID: trialSettingsSID, tableViewRow: index)) { let newSettings = SessionTable.createInManagedObjectContext(managedObjectContext!, heartbeatCount: 0, trialDuration: 1, startTime: "", endTime: "", trialType: field, participantID: trialSettingsPID, sessionID: trialSettingsSID, tableViewRow: index) println(newSettings) } } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) loadTrialSettings() } // load current trial settings into the view /* TODO: fade out cells that already have SessionTable entries */ func loadTrialSettings() { if let temp = SessionTable.getCurrentSettings(managedObjectContext!, participantID: trialSettingsPID, sessionID: trialSettingsSID) { settings = temp } else { println("no settings...") } } // on select, popover RecordTrialView override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if let cell = collectionView.cellForItemAtIndexPath(indexPath) { let setting = settings[indexPath.row] var durationInt = setting.valueForKey("trialDuration") as? Int var trialType = setting.valueForKey("trialType") as? String var x = "\(indexPath.row)" let y = x.toInt() recordTrial(cell, trialType: trialType, trialDuration: durationInt, trialIndex: y!) } else { // Error indexPath is not on screen: this should never happen. } } // intialize RecordTrialView func recordTrial(sender: UIView!, trialType: String?, trialDuration : Int?, trialIndex: Int) { let recordTrialModal = storyboard?.instantiateViewControllerWithIdentifier("RecordTrialModal") as! RecordTrialView recordTrialModal.delegate = self; recordTrialModal.trialType = trialType!; recordTrialModal.trialDuration = trialDuration!; recordTrialModal.tableViewRow = tableViewRow; recordTrialModal.participantID = participantID; recordTrialModal.sessionID = sessionID; recordTrialModal.modalPresentationStyle = .Popover if let popoverController = recordTrialModal.popoverPresentationController { popoverController.sourceView = sender! popoverController.sourceRect = sender!.bounds popoverController.permittedArrowDirections = .Any popoverController.delegate = self } presentViewController(recordTrialModal, animated: true, completion: nil) } // handle reload view after RecordTrialView func saveText() { self.collectionView!.reloadData() loadTrialSettings() } // MARK: - UIPopoverPresentationControllerDelegate func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .FullScreen } func presentationController(controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? { return UINavigationController(rootViewController: controller.presentedViewController) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "toSessionSummary") { let destinationVC = segue.destinationViewController as! SessionSummaryView destinationVC.participantID = participantID destinationVC.sessionID = sessionID } } } extension RecordSessionCollectionView : UICollectionViewDataSource { //1 override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } //2 override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return settings.count } //3 override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { //1 let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! RecordTrialCell let setting = settings[indexPath.row] var str = "" if let v = setting.valueForKey("trialDuration") as? Int { str = "\(v)" } cell.trialTypeRLabel!.text = setting.valueForKey("trialType") as? String cell.trialDurationRLabel!.text = str return cell } } extension RecordSessionCollectionView : UICollectionViewDelegateFlowLayout { //1 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: 100, height: 200) } //3 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return sectionInsets } }
mit
0e02da483ec2c894958690b996a675e6
40.575916
264
0.693577
5.375762
false
false
false
false
DirtyPiece/dancestudio
Source/Mac/DanceStudio/DanceStudio/AppDelegate.swift
1
1632
// ======================================================================= // <copyright file="AppDelegate.swift" company="Bean &amp; Cheese Studios"> // Copyright 2015 Bean and Cheese Studios // </copyright> // <date>01-03-2015</date> // ======================================================================= import Cocoa /// <summary> /// Represents the main application delegate for Dance Studio. /// </summary> @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { /// <summary> /// Event that is raised when the user clicks the /// Help->DanceStudio Help menu item. /// </summary> @IBAction func danceStudioHelpClicked(sender: NSMenuItem) { let helpDocumentationUrl = "https://onedrive.live.com/redir?resid=DFA2592B559E3EE7!113&authkey=!AGur6S7aqPKWOVE&ithint=onenote%2c" if let checkURL = NSURL(string: helpDocumentationUrl) { NSWorkspace.sharedWorkspace().openURL(checkURL) } } /// <summary> /// Called when the application finished launching (used as a point to initialize the app). /// </summary> /// <param name="aNotification">The notification object.</param> func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application } /// <summary> /// Called when the application terminates (to perform cleanup). /// </summary> /// <param name="aNotification">The notification object.</param> func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
mit
e22c1fadfe060c1bcc3302ef25863a15
37.857143
138
0.620711
4.744186
false
false
false
false
shaps80/Peek
Pod/Classes/Coordinator/Coordinator.swift
1
4326
// // Coordinator.swift // Peek // // Created by Shaps Benkau on 24/02/2018. // import Foundation @objc public protocol Coordinator: class { @discardableResult func appendDynamic(keyPaths: [String], forModel model: Peekable, in group: Group) -> Coordinator @discardableResult func appendDynamic(keyPathToName mapping: [[String: String]], forModel model: Peekable, in group: Group) -> Coordinator @discardableResult func appendStatic(keyPath: String, title: String, detail: String?, value: Any?, in group: Group) -> Coordinator @discardableResult func appendPreview(image: UIImage, forModel model: Peekable) -> Coordinator @discardableResult func appendTransformed(keyPaths: [String], valueTransformer: AttributeValueTransformer?, forModel model: Peekable, in group: Group) -> Coordinator } internal protocol SwiftCoordinator: Coordinator { @discardableResult func appendEnum<T>(keyPath: String..., into: T.Type, forModel model: Peekable, group: Group) -> Self where T: RawRepresentable & PeekDescribing & Hashable, T.RawValue == Int } internal final class PeekCoordinator: SwiftCoordinator { internal unowned let model: Peekable internal private(set) var groupsMapping: [Group: PeekGroup] = [:] internal init(model: Peekable) { self.model = model } internal func appendPreview(image: UIImage, forModel model: Peekable) -> Coordinator { guard image.size.width > 0 && image.size.height > 0 else { return self } let peekGroup = groupsMapping[.preview] ?? Group.preview.peekGroup() groupsMapping[.preview] = peekGroup peekGroup.attributes.insert(PreviewAttribute(image: image), at: 0) return self } internal func appendDynamic(keyPaths: [String], forModel model: Peekable, in group: Group) -> Coordinator { return appendTransformed(keyPaths: keyPaths, valueTransformer: nil, forModel: model, in: group) } internal func appendDynamic(keyPathToName mapping: [[String : String]], forModel model: Peekable, in group: Group) -> Coordinator { let peekGroup = groupsMapping[group] ?? group.peekGroup() groupsMapping[group] = peekGroup peekGroup.attributes.insert(contentsOf: mapping.map { DynamicAttribute(title: $0.values.first!, keyPath: $0.keys.first!, model: model) }, at: peekGroup.attributes.count) return self } internal func appendStatic(keyPath: String, title: String, detail: String? = nil, value: Any?, in group: Group) -> Coordinator { let peekGroup = groupsMapping[group] ?? group.peekGroup() groupsMapping[group] = peekGroup let attribute = StaticAttribute(keyPath: keyPath, title: title, detail: detail, value: value) peekGroup.attributes.insert(attribute, at: peekGroup.attributes.count) return self } internal func appendTransformed(keyPaths: [String], valueTransformer: AttributeValueTransformer?, forModel model: Peekable, in group: Group) -> Coordinator { let peekGroup = groupsMapping[group] ?? group.peekGroup() groupsMapping[group] = peekGroup peekGroup.attributes.insert(contentsOf: keyPaths.map { DynamicAttribute(title: String.capitalized($0), detail: nil, keyPath: $0, model: model, valueTransformer: valueTransformer) }, at: peekGroup.attributes.count) return self } internal func appendEnum<T>(keyPath: String..., into: T.Type, forModel model: Peekable, group: Group) -> Self where T: RawRepresentable & PeekDescribing & Hashable, T.RawValue == Int { let peekGroup = groupsMapping[group] ?? group.peekGroup() groupsMapping[group] = peekGroup peekGroup.attributes.insert(contentsOf: keyPath.map { EnumAttribute<T>(title: String.capitalized($0), detail: nil, keyPath: $0, model: model, valueTransformer: nil) }, at: peekGroup.attributes.count) return self } } extension PeekCoordinator: CustomStringConvertible { internal var description: String { return """ \(type(of: self)) \(groupsMapping.values.map { "▹ \($0)" }.joined(separator: "\n")) """ } }
mit
5967d1d010383f8cde8d123240465b0b
40.180952
188
0.670444
4.425793
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Themes/ThemeBrowserViewController.swift
1
38734
import Foundation import CocoaLumberjack import WordPressShared.WPAnalytics import WordPressShared.WPStyleGuide /** * @brief Support for filtering themes by purchasability * @details Currently purchasing themes via native apps is unsupported */ public enum ThemeType { case all case free case premium static let mayPurchase = false static let types = [all, free, premium] var title: String { switch self { case .all: return NSLocalizedString("All", comment: "Browse all themes selection title") case .free: return NSLocalizedString("Free", comment: "Browse free themes selection title") case .premium: return NSLocalizedString("Premium", comment: "Browse premium themes selection title") } } var predicate: NSPredicate? { switch self { case .all: return nil case .free: return NSPredicate(format: "premium == 0") case .premium: return NSPredicate(format: "premium == 1") } } } /** * @brief Publicly exposed theme interaction support * @details Held as weak reference by owned subviews */ public protocol ThemePresenter: AnyObject { var filterType: ThemeType { get set } var screenshotWidth: Int { get } func currentTheme() -> Theme? func activateTheme(_ theme: Theme?) func presentCustomizeForTheme(_ theme: Theme?) func presentPreviewForTheme(_ theme: Theme?) func presentDetailsForTheme(_ theme: Theme?) func presentSupportForTheme(_ theme: Theme?) func presentViewForTheme(_ theme: Theme?) } /// Invalidates the layout whenever the collection view's bounds change @objc open class ThemeBrowserCollectionViewLayout: UICollectionViewFlowLayout { open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return shouldInvalidateForNewBounds(newBounds) } open override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewFlowLayoutInvalidationContext { let context = super.invalidationContext(forBoundsChange: newBounds) as! UICollectionViewFlowLayoutInvalidationContext context.invalidateFlowLayoutDelegateMetrics = shouldInvalidateForNewBounds(newBounds) return context } fileprivate func shouldInvalidateForNewBounds(_ newBounds: CGRect) -> Bool { guard let collectionView = collectionView else { return false } return (newBounds.width != collectionView.bounds.width || newBounds.height != collectionView.bounds.height) } } @objc open class ThemeBrowserViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, NSFetchedResultsControllerDelegate, UISearchControllerDelegate, UISearchResultsUpdating, ThemePresenter, WPContentSyncHelperDelegate { // MARK: - Constants @objc static let reuseIdentifierForThemesHeader = "ThemeBrowserSectionHeaderViewThemes" @objc static let reuseIdentifierForCustomThemesHeader = "ThemeBrowserSectionHeaderViewCustomThemes" static let themesLoaderFrame = CGRect(x: 0.0, y: 0.0, width: 40.0, height: 20.0) // MARK: - Properties: must be set by parent /** * @brief The blog this VC will work with. * @details Must be set by the creator of this VC. */ @objc open var blog: Blog! // MARK: - Properties @IBOutlet weak var collectionView: UICollectionView! fileprivate lazy var customizerNavigationDelegate: ThemeWebNavigationDelegate = { return ThemeWebNavigationDelegate() }() /** * @brief The FRCs this VC will use to display filtered content. */ fileprivate lazy var themesController: NSFetchedResultsController<NSFetchRequestResult> = { return self.createThemesFetchedResultsController() }() fileprivate lazy var customThemesController: NSFetchedResultsController<NSFetchRequestResult> = { return self.createThemesFetchedResultsController() }() fileprivate func createThemesFetchedResultsController() -> NSFetchedResultsController<NSFetchRequestResult> { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: Theme.entityName()) fetchRequest.fetchBatchSize = 20 let sort = NSSortDescriptor(key: "order", ascending: true) fetchRequest.sortDescriptors = [sort] let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.themeService.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) frc.delegate = self return frc } fileprivate var themeCount: NSInteger { return themesController.fetchedObjects?.count ?? 0 } fileprivate var customThemeCount: NSInteger { return blog.supports(BlogFeature.customThemes) ? (customThemesController.fetchedObjects?.count ?? 0) : 0 } // Absolute count of available themes for the site, as it comes from the ThemeService fileprivate var totalThemeCount: NSInteger = 0 { didSet { themesHeader?.themeCount = totalThemeCount } } fileprivate var totalCustomThemeCount: NSInteger = 0 { didSet { customThemesHeader?.themeCount = totalCustomThemeCount } } fileprivate var themesHeader: ThemeBrowserSectionHeaderView? { didSet { themesHeader?.descriptionLabel.text = NSLocalizedString("WordPress.com Themes", comment: "Title for the WordPress.com themes section, should be the same as in Calypso").localizedUppercase themesHeader?.themeCount = totalThemeCount > 0 ? totalThemeCount : themeCount } } fileprivate var customThemesHeader: ThemeBrowserSectionHeaderView? { didSet { customThemesHeader?.descriptionLabel.text = NSLocalizedString("Uploaded themes", comment: "Title for the user uploaded themes section, should be the same as in Calypso").localizedUppercase customThemesHeader?.themeCount = totalCustomThemeCount > 0 ? totalCustomThemeCount : customThemeCount } } fileprivate var hideSectionHeaders: Bool = false fileprivate var searchController: UISearchController! fileprivate var searchName = "" { didSet { if searchName != oldValue { fetchThemes() reloadThemes() } } } fileprivate var suspendedSearch = "" @objc func resumingSearch() -> Bool { return !suspendedSearch.trim().isEmpty } fileprivate var activityIndicator: UIActivityIndicatorView = { let indicatorView = UIActivityIndicatorView(style: .medium) indicatorView.frame = themesLoaderFrame //TODO update color with white headers indicatorView.color = .white indicatorView.startAnimating() return indicatorView }() open var filterType: ThemeType = ThemeType.mayPurchase ? .all : .free /** * @brief Collection view support */ fileprivate enum Section { case search case info case customThemes case themes } fileprivate var sections: [Section]! fileprivate func reloadThemes() { collectionView?.reloadData() updateResults() } fileprivate func themeAtIndexPath(_ indexPath: IndexPath) -> Theme? { if sections[indexPath.section] == .themes { return themesController.object(at: IndexPath(row: indexPath.row, section: 0)) as? Theme } else if sections[indexPath.section] == .customThemes { return customThemesController.object(at: IndexPath(row: indexPath.row, section: 0)) as? Theme } return nil } fileprivate func updateActivateButton(isLoading: Bool) { if isLoading { activateButton?.customView = activityIndicator activityIndicator.startAnimating() } else { activityIndicator.stopAnimating() activateButton?.customView = nil activateButton?.isEnabled = false activateButton?.title = ThemeAction.active.title } } fileprivate var presentingTheme: Theme? private var noResultsViewController: NoResultsViewController? private struct NoResultsTitles { static let noThemes = NSLocalizedString("No themes matching your search", comment: "Text displayed when theme name search has no matches") static let fetchingThemes = NSLocalizedString("Fetching Themes...", comment: "Text displayed while fetching themes") } private var noResultsShown: Bool { return noResultsViewController?.parent != nil } /** * @brief Load theme screenshots at maximum displayed width */ @objc open var screenshotWidth: Int = { let windowSize = UIApplication.shared.mainWindow!.bounds.size let vWidth = Styles.imageWidthForFrameWidth(windowSize.width) let hWidth = Styles.imageWidthForFrameWidth(windowSize.height) let maxWidth = Int(max(hWidth, vWidth)) return maxWidth }() /** * @brief The themes service we'll use in this VC and its helpers */ fileprivate let themeService = ThemeService(managedObjectContext: ContextManager.sharedInstance().mainContext) fileprivate var themesSyncHelper: WPContentSyncHelper! fileprivate var themesSyncingPage = 0 fileprivate var customThemesSyncHelper: WPContentSyncHelper! fileprivate let syncPadding = 5 fileprivate var activateButton: UIBarButtonItem? // MARK: - Private Aliases fileprivate typealias Styles = WPStyleGuide.Themes /** * @brief Convenience method for browser instantiation * * @param blog The blog to browse themes for * * @returns ThemeBrowserViewController instance */ @objc open class func browserWithBlog(_ blog: Blog) -> ThemeBrowserViewController { let storyboard = UIStoryboard(name: "ThemeBrowser", bundle: nil) let viewController = storyboard.instantiateInitialViewController() as! ThemeBrowserViewController viewController.blog = blog return viewController } // MARK: - UIViewController open override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Themes", comment: "Title of Themes browser page") WPStyleGuide.configureColors(view: view, collectionView: collectionView) fetchThemes() sections = (themeCount == 0 && customThemeCount == 0) ? [.search, .customThemes, .themes] : [.search, .info, .customThemes, .themes] configureSearchController() updateActiveTheme() setupThemesSyncHelper() if blog.supports(BlogFeature.customThemes) { setupCustomThemesSyncHelper() } syncContent() } fileprivate func configureSearchController() { extendedLayoutIncludesOpaqueBars = true definesPresentationContext = true searchController = UISearchController(searchResultsController: nil) searchController.obscuresBackgroundDuringPresentation = false searchController.delegate = self searchController.searchResultsUpdater = self collectionView.register(ThemeBrowserSearchHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: ThemeBrowserSearchHeaderView.reuseIdentifier) collectionView.register(UINib(nibName: "ThemeBrowserSectionHeaderView", bundle: Bundle(for: ThemeBrowserSectionHeaderView.self)), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: ThemeBrowserViewController.reuseIdentifierForThemesHeader) collectionView.register(UINib(nibName: "ThemeBrowserSectionHeaderView", bundle: Bundle(for: ThemeBrowserSectionHeaderView.self)), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: ThemeBrowserViewController.reuseIdentifierForCustomThemesHeader) WPStyleGuide.configureSearchBar(searchController.searchBar) } fileprivate var searchBarHeight: CGFloat { return searchController.searchBar.bounds.height + view.safeAreaInsets.top } open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) collectionView?.collectionViewLayout.invalidateLayout() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) registerForKeyboardNotifications() if resumingSearch() { beginSearchFor(suspendedSearch) suspendedSearch = "" } guard let theme = presentingTheme else { return } presentingTheme = nil if !theme.isCurrentTheme() { // presented page may have activated this theme updateActiveTheme() } } open override func viewWillDisappear(_ animated: Bool) { if searchController.isActive { searchController.isActive = false } super.viewWillDisappear(animated) unregisterForKeyboardNotifications() } fileprivate func registerForKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(ThemeBrowserViewController.keyboardDidShow(_:)), name: UIResponder.keyboardDidShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ThemeBrowserViewController.keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) } fileprivate func unregisterForKeyboardNotifications() { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } @objc open func keyboardDidShow(_ notification: Foundation.Notification) { let keyboardFrame = localKeyboardFrameFromNotification(notification) let keyboardHeight = collectionView.frame.maxY - keyboardFrame.origin.y collectionView.contentInset.bottom = keyboardHeight collectionView.verticalScrollIndicatorInsets.top = searchBarHeight collectionView.verticalScrollIndicatorInsets.bottom = keyboardHeight } @objc open func keyboardWillHide(_ notification: Foundation.Notification) { let tabBarHeight = tabBarController?.tabBar.bounds.height ?? 0 collectionView.contentInset.top = view.safeAreaInsets.top collectionView.contentInset.bottom = tabBarHeight collectionView.verticalScrollIndicatorInsets.top = searchBarHeight collectionView.verticalScrollIndicatorInsets.bottom = tabBarHeight } fileprivate func localKeyboardFrameFromNotification(_ notification: Foundation.Notification) -> CGRect { let key = UIResponder.keyboardFrameEndUserInfoKey guard let keyboardFrame = (notification.userInfo?[key] as? NSValue)?.cgRectValue else { return .zero } // Convert the frame from window coordinates return view.convert(keyboardFrame, from: nil) } // MARK: - Syncing the list of themes fileprivate func updateActiveTheme() { let lastActiveThemeId = blog.currentThemeId _ = themeService.getActiveTheme(for: blog, success: { [weak self] (theme: Theme?) in if lastActiveThemeId != theme?.themeId { self?.collectionView?.collectionViewLayout.invalidateLayout() } }, failure: { (error) in DDLogError("Error updating active theme: \(String(describing: error?.localizedDescription))") }) } fileprivate func setupThemesSyncHelper() { themesSyncHelper = WPContentSyncHelper() themesSyncHelper.delegate = self } fileprivate func setupCustomThemesSyncHelper() { customThemesSyncHelper = WPContentSyncHelper() customThemesSyncHelper.delegate = self } fileprivate func syncContent() { if themesSyncHelper.syncContent() && (!blog.supports(BlogFeature.customThemes) || customThemesSyncHelper.syncContent()) { updateResults() } } fileprivate func syncMoreThemesIfNeeded(_ indexPath: IndexPath) { let paddedCount = indexPath.row + syncPadding if paddedCount >= themeCount && themesSyncHelper.hasMoreContent && themesSyncHelper.syncMoreContent() { updateResults() } } fileprivate func syncThemePage(_ page: NSInteger, success: ((_ hasMore: Bool) -> Void)?, failure: ((_ error: NSError) -> Void)?) { assert(page > 0) themesSyncingPage = page _ = themeService.getThemesFor(blog, page: themesSyncingPage, sync: page == 1, success: {[weak self](themes: [Theme]?, hasMore: Bool, themeCount: NSInteger) in if let success = success { success(hasMore) } self?.totalThemeCount = themeCount }, failure: { (error) in DDLogError("Error syncing themes: \(String(describing: error?.localizedDescription))") if let failure = failure, let error = error { failure(error as NSError) } }) } fileprivate func syncCustomThemes(success: ((_ hasMore: Bool) -> Void)?, failure: ((_ error: NSError) -> Void)?) { _ = themeService.getCustomThemes(for: blog, sync: true, success: {[weak self](themes: [Theme]?, hasMore: Bool, themeCount: NSInteger) in if let success = success { success(hasMore) } self?.totalCustomThemeCount = themeCount }, failure: { (error) in DDLogError("Error syncing themes: \(String(describing: error?.localizedDescription))") if let failure = failure, let error = error { failure(error as NSError) } }) } @objc open func currentTheme() -> Theme? { guard let themeId = blog.currentThemeId, !themeId.isEmpty else { return nil } for theme in blog.themes as! Set<Theme> { if theme.themeId == themeId { return theme } } return nil } // MARK: - WPContentSyncHelperDelegate func syncHelper(_ syncHelper: WPContentSyncHelper, syncContentWithUserInteraction userInteraction: Bool, success: ((_ hasMore: Bool) -> Void)?, failure: ((_ error: NSError) -> Void)?) { if syncHelper == themesSyncHelper { syncThemePage(1, success: success, failure: failure) } else if syncHelper == customThemesSyncHelper { syncCustomThemes(success: success, failure: failure) } } func syncHelper(_ syncHelper: WPContentSyncHelper, syncMoreWithSuccess success: ((_ hasMore: Bool) -> Void)?, failure: ((_ error: NSError) -> Void)?) { if syncHelper == themesSyncHelper { let nextPage = themesSyncingPage + 1 syncThemePage(nextPage, success: success, failure: failure) } } func syncContentEnded(_ syncHelper: WPContentSyncHelper) { updateResults() let lastVisibleTheme = collectionView?.indexPathsForVisibleItems.last ?? IndexPath(item: 0, section: 0) if syncHelper == themesSyncHelper { syncMoreThemesIfNeeded(lastVisibleTheme) } } func hasNoMoreContent(_ syncHelper: WPContentSyncHelper) { if syncHelper == themesSyncHelper { themesSyncingPage = 0 } collectionView?.collectionViewLayout.invalidateLayout() } // MARK: - UICollectionViewDataSource open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch sections[section] { case .search, .info: return 0 case .customThemes: return customThemeCount case .themes: return themeCount } } open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ThemeBrowserCell.reuseIdentifier, for: indexPath) as! ThemeBrowserCell cell.presenter = self cell.theme = themeAtIndexPath(indexPath) if sections[indexPath.section] == .themes { syncMoreThemesIfNeeded(indexPath) } return cell } open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionView.elementKindSectionHeader: if sections[indexPath.section] == .search { let searchHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ThemeBrowserSearchHeaderView.reuseIdentifier, for: indexPath) as! ThemeBrowserSearchHeaderView searchHeader.searchBar = searchController.searchBar return searchHeader } else if sections[indexPath.section] == .info { let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ThemeBrowserHeaderView.reuseIdentifier, for: indexPath) as! ThemeBrowserHeaderView header.presenter = self return header } else { // We don't want the collectionView to reuse the section headers // since we need to keep a reference to them to update the counts if sections[indexPath.section] == .customThemes { customThemesHeader = (collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ThemeBrowserViewController.reuseIdentifierForCustomThemesHeader, for: indexPath) as! ThemeBrowserSectionHeaderView) customThemesHeader?.isHidden = customThemeCount == 0 return customThemesHeader! } else { themesHeader = (collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ThemeBrowserViewController.reuseIdentifierForCustomThemesHeader, for: indexPath) as! ThemeBrowserSectionHeaderView) themesHeader?.isHidden = themeCount == 0 return themesHeader! } } case UICollectionView.elementKindSectionFooter: let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "ThemeBrowserFooterView", for: indexPath) return footer default: fatalError("Unexpected theme browser element") } } open func numberOfSections(in collectionView: UICollectionView) -> Int { return sections.count } // MARK: - UICollectionViewDelegate open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let theme = themeAtIndexPath(indexPath) { if theme.isCurrentTheme() { presentCustomizeForTheme(theme) } else { theme.custom ? presentDetailsForTheme(theme) : presentViewForTheme(theme) } } } // MARK: - UICollectionViewDelegateFlowLayout open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: NSInteger) -> CGSize { switch sections[section] { case .themes, .customThemes: if !hideSectionHeaders && blog.supports(BlogFeature.customThemes) { return CGSize(width: 0, height: ThemeBrowserSectionHeaderView.height) } return .zero case .search: return CGSize(width: 0, height: searchController.searchBar.bounds.height) case .info: let horizontallyCompact = traitCollection.horizontalSizeClass == .compact let height = Styles.headerHeight(horizontallyCompact, includingSearchBar: ThemeType.mayPurchase) return CGSize(width: 0, height: height) } } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let parentViewWidth = collectionView.frame.size.width return Styles.cellSizeForFrameWidth(parentViewWidth) } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { guard sections[section] == .themes && themesSyncHelper.isLoadingMore else { return CGSize.zero } return CGSize(width: 0, height: Styles.footerHeight) } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { switch sections[section] { case .customThemes: if !blog.supports(BlogFeature.customThemes) { return .zero } return Styles.themeMargins case .themes: return Styles.themeMargins case .info, .search: return Styles.infoMargins } } // MARK: - Search support fileprivate func beginSearchFor(_ pattern: String) { searchController.isActive = true searchController.searchBar.text = pattern searchName = pattern } // MARK: - UISearchControllerDelegate open func willPresentSearchController(_ searchController: UISearchController) { hideSectionHeaders = true if sections[1] == .info { collectionView?.collectionViewLayout.invalidateLayout() setInfoSectionHidden(true) } } open func didPresentSearchController(_ searchController: UISearchController) { WPAppAnalytics.track(.themesAccessedSearch, with: blog) } open func willDismissSearchController(_ searchController: UISearchController) { hideSectionHeaders = false searchName = "" searchController.searchBar.text = "" } open func didDismissSearchController(_ searchController: UISearchController) { if sections[1] == .themes || sections[1] == .customThemes { setInfoSectionHidden(false) } collectionView.verticalScrollIndicatorInsets.top = view.safeAreaInsets.top } fileprivate func setInfoSectionHidden(_ hidden: Bool) { let hide = { self.collectionView?.deleteSections(IndexSet(integer: 1)) self.sections = [.search, .customThemes, .themes] } let show = { self.collectionView?.insertSections(IndexSet(integer: 1)) self.sections = [.search, .info, .customThemes, .themes] } collectionView.performBatchUpdates({ hidden ? hide() : show() }) } // MARK: - UISearchResultsUpdating open func updateSearchResults(for searchController: UISearchController) { searchName = searchController.searchBar.text ?? "" } // MARK: - NSFetchedResultsController helpers fileprivate func searchNamePredicate() -> NSPredicate? { guard !searchName.isEmpty else { return nil } return NSPredicate(format: "name contains[c] %@", searchName) } fileprivate func browsePredicate() -> NSPredicate? { return browsePredicateThemesWithCustomValue(false) } fileprivate func customThemesBrowsePredicate() -> NSPredicate? { return browsePredicateThemesWithCustomValue(true) } fileprivate func browsePredicateThemesWithCustomValue(_ custom: Bool) -> NSPredicate? { let blogPredicate = NSPredicate(format: "blog == %@ AND custom == %d", self.blog, custom ? 1 : 0) let subpredicates = [blogPredicate, searchNamePredicate(), filterType.predicate].compactMap { $0 } switch subpredicates.count { case 1: return subpredicates[0] default: return NSCompoundPredicate(andPredicateWithSubpredicates: subpredicates) } } fileprivate func fetchThemes() { do { themesController.fetchRequest.predicate = browsePredicate() try themesController.performFetch() if self.blog.supports(BlogFeature.customThemes) { customThemesController.fetchRequest.predicate = customThemesBrowsePredicate() try customThemesController.performFetch() } } catch { DDLogError("Error fetching themes: \(error)") } } // MARK: - NSFetchedResultsControllerDelegate open func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { reloadThemes() } // MARK: - ThemePresenter // optional closure that will be executed when the presented WebkitViewController closes @objc var onWebkitViewControllerClose: (() -> Void)? @objc open func activateTheme(_ theme: Theme?) { guard let theme = theme, !theme.isCurrentTheme() else { return } updateActivateButton(isLoading: true) _ = themeService.activate(theme, for: blog, success: { [weak self] (theme: Theme?) in WPAppAnalytics.track(.themesChangedTheme, withProperties: ["theme_id": theme?.themeId ?? ""], with: self?.blog) self?.collectionView?.reloadData() let successTitle = NSLocalizedString("Theme Activated", comment: "Title of alert when theme activation succeeds") let successFormat = NSLocalizedString("Thanks for choosing %@ by %@", comment: "Message of alert when theme activation succeeds") let successMessage = String(format: successFormat, theme?.name ?? "", theme?.author ?? "") let manageTitle = NSLocalizedString("Manage site", comment: "Return to blog screen action when theme activation succeeds") let okTitle = NSLocalizedString("OK", comment: "Alert dismissal title") self?.updateActivateButton(isLoading: false) let alertController = UIAlertController(title: successTitle, message: successMessage, preferredStyle: .alert) alertController.addActionWithTitle(manageTitle, style: .default, handler: { [weak self] (action: UIAlertAction) in _ = self?.navigationController?.popViewController(animated: true) }) alertController.addDefaultActionWithTitle(okTitle, handler: nil) alertController.presentFromRootViewController() }, failure: { [weak self] (error) in DDLogError("Error activating theme \(String(describing: theme.themeId)): \(String(describing: error?.localizedDescription))") let errorTitle = NSLocalizedString("Activation Error", comment: "Title of alert when theme activation fails") let okTitle = NSLocalizedString("OK", comment: "Alert dismissal title") self?.activityIndicator.stopAnimating() self?.activateButton?.customView = nil let alertController = UIAlertController(title: errorTitle, message: error?.localizedDescription, preferredStyle: .alert) alertController.addDefaultActionWithTitle(okTitle, handler: nil) alertController.presentFromRootViewController() }) } @objc open func installThemeAndPresentCustomizer(_ theme: Theme) { _ = themeService.installTheme(theme, for: blog, success: { [weak self] in self?.presentUrlForTheme(theme, url: theme.customizeUrl(), activeButton: !theme.isCurrentTheme()) }, failure: nil) } @objc open func presentCustomizeForTheme(_ theme: Theme?) { WPAppAnalytics.track(.themesCustomizeAccessed, with: self.blog) QuickStartTourGuide.shared.visited(.customize) presentUrlForTheme(theme, url: theme?.customizeUrl(), activeButton: false, modalStyle: .fullScreen) } @objc open func presentPreviewForTheme(_ theme: Theme?) { WPAppAnalytics.track(.themesPreviewedSite, with: self.blog) // In order to Try & Customize a theme we first need to install it (Jetpack sites) if let theme = theme, self.blog.supports(.customThemes) && !theme.custom { installThemeAndPresentCustomizer(theme) } else { presentUrlForTheme(theme, url: theme?.customizeUrl(), activeButton: !(theme?.isCurrentTheme() ?? true)) } } @objc open func presentDetailsForTheme(_ theme: Theme?) { WPAppAnalytics.track(.themesDetailsAccessed, with: self.blog) presentUrlForTheme(theme, url: theme?.detailsUrl()) } @objc open func presentSupportForTheme(_ theme: Theme?) { WPAppAnalytics.track(.themesSupportAccessed, with: self.blog) presentUrlForTheme(theme, url: theme?.supportUrl()) } @objc open func presentViewForTheme(_ theme: Theme?) { WPAppAnalytics.track(.themesDemoAccessed, with: self.blog) presentUrlForTheme(theme, url: theme?.viewUrl(), onClose: onWebkitViewControllerClose) } @objc open func presentUrlForTheme(_ theme: Theme?, url: String?, activeButton: Bool = true, modalStyle: UIModalPresentationStyle = .pageSheet, onClose: (() -> Void)? = nil) { guard let theme = theme, let url = url.flatMap(URL.init(string:)) else { return } suspendedSearch = searchName presentingTheme = theme let configuration = WebViewControllerConfiguration(url: url) configuration.authenticate(blog: theme.blog) configuration.secureInteraction = true configuration.customTitle = theme.name configuration.navigationDelegate = customizerNavigationDelegate configuration.onClose = onClose let title = activeButton ? ThemeAction.activate.title : ThemeAction.active.title activateButton = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(ThemeBrowserViewController.activatePresentingTheme)) activateButton?.isEnabled = !theme.isCurrentTheme() let webViewController = WebViewControllerFactory.controller(configuration: configuration) webViewController.navigationItem.rightBarButtonItem = activateButton let navigation = UINavigationController(rootViewController: webViewController) navigation.modalPresentationStyle = modalStyle if searchController != nil && searchController.isActive { searchController.dismiss(animated: true, completion: { self.present(navigation, animated: true) }) } else { present(navigation, animated: true) } } @objc open func activatePresentingTheme() { suspendedSearch = "" activateTheme(presentingTheme) presentingTheme = nil } } // MARK: - NoResults Handling private extension ThemeBrowserViewController { func updateResults() { if themeCount == 0 && customThemeCount == 0 { showNoResults() } else { hideNoResults() } } func showNoResults() { guard !noResultsShown else { return } if noResultsViewController == nil { noResultsViewController = NoResultsViewController.controller() } guard let noResultsViewController = noResultsViewController else { return } if searchController.isActive { noResultsViewController.configureForNoSearchResults(title: NoResultsTitles.noThemes) } else { noResultsViewController.configure(title: NoResultsTitles.fetchingThemes, accessoryView: NoResultsViewController.loadingAccessoryView()) } addChild(noResultsViewController) collectionView.addSubview(noResultsViewController.view) noResultsViewController.view.frame = collectionView.frame // There is a gap between the search bar and the collection view - https://github.com/wordpress-mobile/WordPress-iOS/issues/9730 // This makes the No Results View look vertically off-center. Until that is resolved, we'll adjust the NRV according to the search bar. if searchController.isActive { noResultsViewController.view.frame.origin.y = searchController.searchBar.bounds.height } else { noResultsViewController.view.frame.origin.y -= searchBarHeight } noResultsViewController.didMove(toParent: self) } func hideNoResults() { guard noResultsShown else { return } noResultsViewController?.removeFromView() if searchController.isActive { collectionView?.reloadData() } else { sections = [.search, .info, .customThemes, .themes] collectionView?.collectionViewLayout.invalidateLayout() } } }
gpl-2.0
dfb812702f4b6d33e2da2fcc63c764a3
38.4842
287
0.652063
6.01553
false
false
false
false
Anviking/Chromatism
Chromatism/CodeViewController.swift
1
3062
// // JLTextViewController.swift // Chromatism // // Created by Johannes Lund on 2014-07-18. // Copyright (c) 2014 anviking. All rights reserved. // import UIKit public class CodeViewController: UIViewController { public var textView: UITextView private let delegate: JLTextStorageDelegate public required init(text: String, language: Language, theme: ColorTheme) { let textView = UITextView() self.textView = textView textView.text = text delegate = JLTextStorageDelegate(managing: textView, language: language, theme: theme) super.init(nibName: nil, bundle: nil) registerForKeyboardNotifications() } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { unregisterForKeyboardNotifications() } override public func loadView() { view = textView } // MARK: Content Insets and Keyboard func registerForKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func unregisterForKeyboardNotifications() { NotificationCenter.default.removeObserver(self) } // Called when the UIKeyboardDidShowNotification is sent. func keyboardWasShown(_ notification: Notification) { // FIXME: ! could be wrong let info = (notification as NSNotification).userInfo! let scrollView = self.textView let kbSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue.size; var contentInsets = scrollView.contentInset; contentInsets.bottom = kbSize.height; scrollView.contentInset = contentInsets; scrollView.scrollIndicatorInsets = contentInsets; // FIXME: ! could be wrong var point = textView.caretRect(for: textView.selectedTextRange!.start).origin; point.y = min(point.y, self.textView.frame.size.height - kbSize.height); var aRect = self.view.frame; aRect.size.height -= kbSize.height; if (!aRect.contains(point) ) { var rect = CGRect(x: point.x, y: point.y, width: 1, height: 1) rect.size.height = kbSize.height rect.origin.y += kbSize.height textView.scrollRectToVisible(rect, animated: true) } } // Called when the UIKeyboardWillHideNotification is sent func keyboardWillBeHidden(_ notification: Notification) { var contentInsets = textView.contentInset; contentInsets.bottom = 0; textView.contentInset = contentInsets; textView.scrollIndicatorInsets = contentInsets; textView.contentInset = contentInsets; textView.scrollIndicatorInsets = contentInsets; } }
mit
1180f83594699b1c91136f908e56f3c5
35.023529
154
0.669824
5.207483
false
false
false
false
cwwise/CWWeChat
CWWeChat/MainClass/Mine/Expression/View/EmoticonListCell.swift
2
3454
// // EmoticonListCell.swift // CWWeChat // // Created by chenwei on 2017/8/23. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit class EmoticonListCell: UITableViewCell { var iconImageView: UIImageView! var titleLabel: UILabel! var subtitleLabel: UILabel! var downloadButton: UIButton! var progress: UIProgressView! var emoticonInfo: EmoticonPackage! { didSet { setupInfo() } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() addSnap() } func setupUI() { iconImageView = UIImageView() iconImageView.contentMode = .scaleAspectFill self.contentView.addSubview(iconImageView) titleLabel = UILabel() titleLabel.font = UIFont.systemFont(ofSize: 15) titleLabel.textColor = UIColor.black self.contentView.addSubview(titleLabel) subtitleLabel = UILabel() subtitleLabel.textColor = UIColor(hex: "#888") subtitleLabel.font = UIFont.systemFont(ofSize: 13) self.contentView.addSubview(subtitleLabel) let textColor = UIColor(hex: "#1AAD19") let normalImage = UIImage.size(width: 10, height: 10) .border(color: textColor) .border(width: 1) .corner(radius: 5).image.resizableImage() downloadButton = UIButton(type: .custom) downloadButton.setBackgroundImage(normalImage, for: .normal) downloadButton.titleLabel?.font = UIFont.systemFont(ofSize: 14) downloadButton.setTitle("下载", for: .normal) downloadButton.setTitleColor(textColor, for: .normal) downloadButton.addTarget(self, action: #selector(downloadAction), for: .touchUpInside) self.contentView.addSubview(downloadButton) } func addSnap() { iconImageView.snp.makeConstraints { (make) in make.left.top.equalTo(15) make.height.equalTo(iconImageView.snp.width) make.centerY.equalTo(self) } titleLabel.snp.makeConstraints { (make) in make.left.equalTo(iconImageView.snp.right).offset(15) make.top.equalTo(18) make.right.equalTo(-40) } subtitleLabel.snp.makeConstraints { (make) in make.left.equalTo(titleLabel.snp.left) make.top.equalTo(titleLabel.snp.bottom).offset(8) make.right.equalTo(-40) } downloadButton.snp.makeConstraints { (make) in make.centerY.equalTo(self) make.right.equalTo(-10) make.size.equalTo(CGSize(width: 60, height: 25)) } } func setupInfo() { iconImageView.kf.setImage(with: emoticonInfo) titleLabel.text = emoticonInfo.name subtitleLabel.text = emoticonInfo.subTitle } // MARK: Action @objc func downloadAction() { } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
f4a0787687c7c00970b87faa33cceb4c
26.576
94
0.601683
4.85493
false
false
false
false
plenprojectcompany/plen-Scenography_iOS
PLENConnect/Connect/Views/Button.swift
1
486
// // Button.swift // plencontrol // // Created by PLEN Project on 2017/03/14. // Copyright © 2017年 PLEN Project Company. All rights reserved. // import UIKit class Button: UIButton { override func awakeFromNib() { super.awakeFromNib() backgroundColor = Constants.Color.PlenGreenDark layer.borderColor = UIColor.white.cgColor layer.borderWidth = 1.0 layer.cornerRadius = 4.0 layer.masksToBounds = true } }
mit
2e310defb745b4b893318566864929f8
20
64
0.637681
4.09322
false
false
false
false
iOSDevCafe/YouTube-Example-Codes
Byte/Byte/Byte.swift
1
2088
// // Byte.swift // Byte // // Created by iOS Café on 23/09/2017. // Copyright © 2017 iOS Café. All rights reserved. // import Foundation protocol HasMaxBitCount{ static var maxBitCount: Int {get} } extension Sequence where Element == Bit, Self : HasMaxBitCount{ static func extractBits(outOf arrayOfBits: [Element]) -> [Element]{ //get maximum allowed number of bits, out of the bits parameter let maxBits: [Element] if arrayOfBits.count > maxBitCount{ maxBits = Array(arrayOfBits[0..<maxBitCount]) } else { maxBits = arrayOfBits } var allBits = Array(repeatElement(Element.zero, count: maxBitCount - maxBits.count)) allBits.insert(contentsOf: maxBits, at: 0) return allBits } } struct Byte: Sequence, HasMaxBitCount{ typealias Element = Bit typealias Iterator = IndexingIterator<[Element]> typealias SubSequence = AnySequence<Element> let bits: [Bit] static let maxBitCount = 8 init(bits: [Element]){ self.bits = Byte.extractBits(outOf: bits) } func makeIterator() -> IndexingIterator<[Element]> { return bits.makeIterator() } } struct Integer32: Sequence, HasMaxBitCount{ typealias Element = Bit typealias Iterator = IndexingIterator<[Element]> typealias SubSequence = AnySequence<Element> let bits: [Bit] static let maxBitCount = 32 init(bits: [Element]){ self.bits = Integer32.extractBits(outOf: bits) } func makeIterator() -> IndexingIterator<[Element]> { return bits.makeIterator() } } extension Bit{ var intValue: Int{ if self == .zero{ return 0 } else { return 1 } } } extension Sequence where Element == Bit{ var intValue: Int{ var result = 0 for bit in self.reversed(){ result = result << 1 result = result | bit.intValue } return result } }
mit
0841b7412c1f6b2f4afe179adb49fd49
21.180851
92
0.590887
4.445629
false
false
false
false
nakiostudio/EasyPeasy
EasyPeasy/Attribute.swift
1
11367
// The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif /** Typealias of a closure with no parameters and `Bool` as returning type. This type of closure is used to evaluate whether an `Attribute` should be applied or not. */ public typealias Condition = () -> Bool #if os(iOS) /** Typealias of a closure with a `Context` struct as parameter and `Bool` as returning type. This type of closure is used to evaluate whether an `Attribute` should be applied or not. */ public typealias ContextualCondition = (Context) -> Bool #endif /** This class is the abstraction of `NSLayoutConstraint` objects used by **EasyPeasy** to create and update `UIView` constraints */ open class Attribute { /// This property aggregates the `NSLayoutRelation`, /// the constant and the multiplier of a layout /// constraint open internal(set) var constant: Constant /// Priority level of the constraint open internal(set) var priority: Priority /// `Condition` to evaluate in order to apply /// (or not) the constraint. In iOS this /// property may hold a closure of type /// `ContextualCondition`. open internal(set) var condition: Any? /// Target `UIView` of the constraint open internal(set) weak var createItem: Item? /// `Attribute` applied to the view open var createAttribute: ReferenceAttribute { debugPrint("This point shouldn't have been reached") return .width } /// Reference `UIView` of the constraint open internal(set) weak var referenceItem: AnyObject? /// Referencce `Attribute` of the constraint open internal(set) var referenceAttribute: ReferenceAttribute? /// Whether the `NSLayoutConstraint` generated by the /// `Attribute` is owned by the the `createItem` open var ownedByItem: Bool { return false } /// Equivalent `NSLayoutConstraint`. It's `nil` unless the method /// `createConstraints(for item:_)` is called private(set) var layoutConstraint: NSLayoutConstraint? /// Element identifying the node this attribute will be /// stored in lazy var signature: String = { // Signature of the create `ReferenceAttribute` of // the passed `Attribute` var signature = self.createAttribute.signatureString // Signature of the `Relation` of the passed `Attribute` switch self.constant.relation { case .equal: signature += "eq_" case .greaterThanOrEqual: signature += "gt_" case .lessThanOrEqual: signature += "lt_" @unknown default: signature += "eq_" } // Signature of the `Priority` of the passed // `Attribute` signature += String(self.priority.layoutPriority()) return signature }() /** Initializer which creates an `Attribute` instance with `constant = 0.0`, `multiplier = 1.0` and `relatedBy = .Equal` - returns: the `Attribute` instance created */ public init() { self.constant = Constant(value: 0.0, relation: .equal, multiplier: 1.0) self.priority = .required } /** Initializer which creates an `Attribute` instance with `constant = value`, `multiplier = 1.0` and `relatedBy = .Equal` - parameter value: `constant` of the constraint - returns: the `Attribute` instance created */ public init(_ value: CGFloat) { self.constant = Constant(value: value, relation: .equal, multiplier: 1.0) self.priority = .required } /** Initializer which creates an `Attribute` instance with the `constant`, `multiplier` and `relatedBy` specified by the `Constant` struct - parameter constant: `Constant` struct aggregating `constant`, `multiplier` and `relatedBy` properties - returns: the `Attribute` instance created */ public init(_ constant: Constant) { self.constant = constant self.priority = .required } // MARK: Public methods /** Sets the `priority` of the constraint - parameter priority: `Priority` enum specifying the priority of the constraint - returns: the `Attribute` instance */ @discardableResult open func with(_ priority: Priority) -> Self { self.priority = priority return self } /** Sets the `when` closure of the `Attribute` - parameter closure: `Closure` to be called before installing a constraint - returns: the `Attribute` instance */ @discardableResult open func when(_ closure: Condition?) -> Self { self.condition = closure return self } #if os(iOS) /** Sets the `when` closure of the `Attribute` - parameter closure: `Closure` to be called before installing a constraint - returns: the `Attribute` instance */ @discardableResult open func when(_ closure: ContextualCondition?) -> Self { self.condition = closure return self } #endif // MARK: Internal methods (acting as protected) /** This method creates the `NSLayoutConstraints` equivalent to the current `Attribute`. The resulting constraint is held by the property `layoutConstraint` - parameter view: `UIView` in which the generated `NSLayoutConstraint` will be added - returns an `Array` of `NSLayoutConstraint` objects that will be installed on the `UIView` passed as parameter */ @discardableResult func createConstraints(for item: Item) -> [NSLayoutConstraint] { guard self.ownedByItem || item.owningView != nil else { debugPrint("EasyPeasy Attribute cannot be applied to item \(item) as its superview/owningView is nil") return [] } // Reference to the target view self.createItem = item // Build layout constraint let constantFactor: CGFloat = self.createAttribute.shouldInvertConstant ? -1 : 1 let layoutConstraint = NSLayoutConstraint( item: item, attribute: self.createAttribute.layoutAttribute, relatedBy: self.constant.relation, toItem: self.referenceItem, attribute: self.referenceAttributeHelper().layoutAttribute, multiplier: self.constant.multiplier, constant: (self.constant.value * constantFactor) ) // Set priority #if swift(>=4.0) #if os(iOS) || os(tvOS) layoutConstraint.priority = UILayoutPriority(rawValue: self.priority.layoutPriority()) #else layoutConstraint.priority = NSLayoutConstraint.Priority(rawValue: self.priority.layoutPriority()) #endif #else layoutConstraint.priority = self.priority.layoutPriority() #endif // Reference resulting constraint self.layoutConstraint = layoutConstraint // Return the constraint return [layoutConstraint] } /** Determines whether the `Attribute` must be installed or not depending on the `Condition` closure - return boolean determining if the `Attribute` has to be applied */ func shouldInstall() -> Bool { // If there is a ContextualCondition then create the context // struct and call the closure #if os(iOS) let item = self.createItem?.owningView ?? self.createItem if let contextualCondition = self.condition as? ContextualCondition, let view = item as? View { return contextualCondition(Context(with: view.traitCollection)) } #endif // Evaluate condition result if let condition = self.condition as? Condition { return condition() } // Otherwise default to true return true } /** Determines which `ReferenceAttribute` must be taken as reference attribute for the actual Attribute class. Usually is the opposite of the one that is going to be installed - returns `ReferenceAttribute` to install */ func referenceAttributeHelper() -> ReferenceAttribute { // If already set return if let attribute = self.referenceAttribute { return attribute } // If reference view is the superview then return same attribute // as `createAttribute` if let referenceItem = self.referenceItem, referenceItem === self.createItem?.owningView { return self.createAttribute } // Otherwise return the opposite of `createAttribute` return self.createAttribute.opposite } } /** Methods applicable to an `Array` of `Attributes`. The `Constants` will apply to each one of the `Attributes` within the `Array` overriding the values individually set. */ public extension Array where Element: Attribute { // MARK: Public methods /** Sets the `priority` of each constraint within the current `Array` of `Attributes`. If the priority was already set this method overrides it - parameter priority: `Priority` enum specifying the priority of the constraint - returns: the `Array` of `Attributes` */ @discardableResult func with(_ priority: Priority) -> [Attribute] { for attribute in self { attribute.with(priority) } return self } /** Sets the `when` closure of each one of `Attributes` within the current `Array`. If the condition was already set this method overrides it - parameter closure: `Closure` to be called before installing each constraint - returns: the `Array` of `Attributes` */ @discardableResult func when(_ closure: Condition?) -> [Attribute] { for attribute in self { attribute.when(closure) } return self } #if os(iOS) /** Sets the `when` closure of each one of `Attributes` within the current `Array`. If the condition was already set this method overrides it - parameter closure: `Closure` to be called before installing each constraint - returns: the `Array` of `Attributes` */ @discardableResult func when(_ closure: ContextualCondition?) -> [Attribute] { for attribute in self { attribute.when(closure) } return self } #endif }
mit
2ea9b0c06b762e13ff90283ea890e1d3
32.830357
114
0.623911
5.063252
false
false
false
false
rsmoz/swift-corelibs-foundation
Foundation/NSUUID.swift
1
2495
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif public class NSUUID : NSObject, NSCopying, NSSecureCoding, NSCoding { internal var buffer = UnsafeMutablePointer<UInt8>.alloc(16) public override init() { _cf_uuid_generate_random(buffer) } public convenience init?(UUIDString string: String) { let buffer = UnsafeMutablePointer<UInt8>.alloc(16) if _cf_uuid_parse(string, buffer) != 0 { return nil } self.init(UUIDBytes: buffer) } public init(UUIDBytes bytes: UnsafePointer<UInt8>) { if (bytes != nil) { memcpy(unsafeBitCast(buffer, UnsafeMutablePointer<Void>.self), UnsafePointer<Void>(bytes), 16) } else { memset(unsafeBitCast(buffer, UnsafeMutablePointer<Void>.self), 0, 16) } } public func getUUIDBytes(uuid: UnsafeMutablePointer<UInt8>) { _cf_uuid_copy(uuid, buffer) } public var UUIDString: String { get { let strPtr = UnsafeMutablePointer<Int8>.alloc(37) _cf_uuid_unparse_lower(buffer, strPtr) return String.fromCString(strPtr)! } } public override func copy() -> AnyObject { return copyWithZone(nil) } public func copyWithZone(zone: NSZone) -> AnyObject { return self } public static func supportsSecureCoding() -> Bool { return true } public required init?(coder: NSCoder) { NSUnimplemented() } public func encodeWithCoder(aCoder: NSCoder) { NSUnimplemented() } public override func isEqual(object: AnyObject?) -> Bool { if object === self { return true } else if let other = object as? NSUUID { return _cf_uuid_compare(buffer, other.buffer) == 0 } else { return false } } public override var hash: Int { return Int(bitPattern: CFHashBytes(buffer, 16)) } public override var description: String { return UUIDString } }
apache-2.0
4fac2e765cdbf078044c9db2d4bfa807
26.417582
106
0.610822
4.55292
false
false
false
false
codestergit/swift
test/Parse/switch.swift
4
9344
// RUN: %target-typecheck-verify-swift // TODO: Implement tuple equality in the library. // BLOCKED: <rdar://problem/13822406> func ~= (x: (Int,Int), y: (Int,Int)) -> Bool { return true } func parseError1(x: Int) { switch func {} // expected-error {{expected expression in 'switch' statement}} expected-error {{expected '{' after 'switch' subject expression}} expected-error {{expected identifier in function declaration}} expected-error {{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{15-15=do }} } func parseError2(x: Int) { switch x // expected-error {{expected '{' after 'switch' subject expression}} } func parseError3(x: Int) { switch x { case // expected-error {{expected pattern}} expected-error {{expected ':' after 'case'}} } } func parseError4(x: Int) { switch x { case var z where // expected-error {{expected expression for 'where' guard of 'case'}} expected-error {{expected ':' after 'case'}} } } func parseError5(x: Int) { switch x { case let z // expected-error {{expected ':' after 'case'}} expected-warning {{immutable value 'z' was never used}} {{12-13=_}} } } func parseError6(x: Int) { switch x { default // expected-error {{expected ':' after 'default'}} } } var x: Int switch x {} // expected-error {{'switch' statement body must have at least one 'case' or 'default' block}} switch x { case 0: x = 0 // Multiple patterns per case case 1, 2, 3: x = 0 // 'where' guard case _ where x % 2 == 0: x = 1 x = 2 x = 3 case _ where x % 2 == 0, _ where x % 3 == 0: x = 1 case 10, _ where x % 3 == 0: x = 1 case _ where x % 2 == 0, 20: x = 1 case var y where y % 2 == 0: x = y + 1 case _ where 0: // expected-error {{'Int' is not convertible to 'Bool'}} x = 0 default: x = 1 } // Multiple cases per case block switch x { case 0: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} case 1: x = 0 } switch x { case 0: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} default: x = 0 } switch x { case 0: x = 0 case 1: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } switch x { case 0: x = 0 default: // expected-error {{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} } switch x { case 0: ; // expected-error {{';' statements are not allowed}} {{3-5=}} case 1: x = 0 } switch x { x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} default: x = 0 case 0: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 case 1: x = 0 } switch x { default: x = 0 default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}} x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} } switch x { // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}} x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} x = 2 } switch x { default: // expected-error{{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} case 0: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { default: // expected-error{{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { default where x == 0: // expected-error{{'default' cannot be used with a 'where' guard expression}} x = 0 } switch x { case 0: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } switch x { case 0: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} case 1: x = 0 } switch x { case 0: x = 0 case 1: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } case 0: // expected-error{{'case' label can only appear inside a 'switch' statement}} var y = 0 default: // expected-error{{'default' label can only appear inside a 'switch' statement}} var z = 1 fallthrough // expected-error{{'fallthrough' is only allowed inside a switch}} switch x { case 0: fallthrough case 1: fallthrough default: fallthrough // expected-error{{'fallthrough' without a following 'case' or 'default' block}} } // Fallthrough can transfer control anywhere within a case and can appear // multiple times in the same case. switch x { case 0: if true { fallthrough } if false { fallthrough } x += 1 default: x += 1 } // Cases cannot contain 'var' bindings if there are multiple matching patterns // attached to a block. They may however contain other non-binding patterns. var t = (1, 2) switch t { case (var a, 2), (1, _): // expected-error {{'a' must be bound in every pattern}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} () case (_, 2), (var a, _): // expected-error {{'a' must be bound in every pattern}} () case (var a, 2), (1, var b): // expected-error {{'a' must be bound in every pattern}} expected-error {{'b' must be bound in every pattern}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} () case (var a, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} case (1, _): () case (_, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} case (1, var a): // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} () case (var a, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} case (1, var b): // expected-warning {{variable 'b' was never used; consider replacing with '_' or removing it}} () case (1, let b): // let bindings expected-warning {{immutable value 'b' was never used; consider replacing with '_' or removing it}} () case (_, 2), (let a, _): // expected-error {{'a' must be bound in every pattern}} () // OK case (_, 2), (1, _): () case (_, var a), (_, var a): // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} () case (var a, var b), (var b, var a): // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} expected-warning {{variable 'b' was never used; consider replacing with '_' or removing it}} () case (_, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} case (1, _): () } func patternVarUsedInAnotherPattern(x: Int) { switch x { case let a, // expected-error {{'a' must be bound in every pattern}} a: break } } // Fallthroughs can't transfer control into a case label with bindings. switch t { case (1, 2): fallthrough // expected-error {{'fallthrough' cannot transfer control to a case label that declares variables}} case (var a, var b): // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} t = (b, a) } func test_label(x : Int) { Gronk: switch x { case 42: return } } func enumElementSyntaxOnTuple() { switch (1, 1) { case .Bar: // expected-error {{pattern cannot match values of type '(Int, Int)'}} break default: break } } // sr-176 enum Whatever { case Thing } func f0(values: [Whatever]) { // expected-note {{did you mean 'values'?}} switch value { // expected-error {{use of unresolved identifier 'value'}} case .Thing: // Ok. Don't emit diagnostics about enum case not found in type <<error type>>. break } } // sr-720 enum Whichever { case Thing static let title = "title" static let alias: Whichever = .Thing } func f1(x: String, y: Whichever) { switch x { case Whichever.title: // Ok. Don't emit diagnostics for static member of enum. break case Whichever.buzz: // expected-error {{type 'Whichever' has no member 'buzz'}} break case Whichever.alias: // expected-error {{expression pattern of type 'Whichever' cannot match values of type 'String'}} break default: break } switch y { case Whichever.Thing: // Ok. break case Whichever.alias: // Ok. Don't emit diagnostics for static member of enum. break case Whichever.title: // expected-error {{expression pattern of type 'String' cannot match values of type 'Whichever'}} break } }
apache-2.0
6528a7b50aafb7a04cea2f1f10dfd6d7
29.337662
326
0.656678
3.540735
false
false
false
false
vsubrahmanian/iMotivate
iMotivate/ViewController.swift
1
1109
// // ViewController.swift // iMotivate // // Created by Vijay Subrahmanian on 15/05/15. // Copyright (c) 2015 Vijay Subrahmanian. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var quoteTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let filePath: String = NSBundle.mainBundle().pathForResource("Thoughts", ofType: "plist")! let thoughts: NSArray = NSArray(contentsOfFile: filePath)! let numberOfThoughts = UInt32(thoughts.count) // Generate a random number within the number of thoughts. let randomThoughtNumber = arc4random_uniform(numberOfThoughts) // Set the thought for today. let randomThought = thoughts.objectAtIndex(Int(randomThoughtNumber)) as! String self.quoteTextView.text = randomThought } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
cb0bb4fb2b0440178ea6aec0ffacbc46
30.685714
98
0.692516
4.60166
false
false
false
false