repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
nheagy/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Reader/ReaderCardDiscoverAttributionView.swift
gpl-2.0
1
import Foundation import WordPressShared @objc public class ReaderCardDiscoverAttributionView: UIView { @IBOutlet private weak var imageView: CircularImageView! @IBOutlet private(set) public weak var richTextView: RichTextView! private let gravatarImageName = "gravatar" private let blavatarImageName = "post-blavatar-placeholder" // MARK: - Lifecycle Methods public override func awakeFromNib() { super.awakeFromNib() richTextView.scrollsToTop = false } // MARK: - Accessors public override func intrinsicContentSize() -> CGSize { if richTextView.textStorage.length == 0 { return super.intrinsicContentSize() } return sizeThatFits(frame.size) } public override func sizeThatFits(size: CGSize) -> CGSize { let adjustedWidth = size.width - richTextView.frame.minX let adjustedSize = CGSize(width: adjustedWidth, height: CGFloat.max) var height = richTextView.sizeThatFits(adjustedSize).height height = max(height, imageView.frame.maxY) return CGSize(width: size.width, height: height) } // MARK: - Configuration public func configureView(contentProvider: ReaderPostContentProvider?) { if contentProvider?.sourceAttributionStyle() == SourceAttributionStyle.Post { configurePostAttribution(contentProvider!) } else if contentProvider?.sourceAttributionStyle() == SourceAttributionStyle.Site { configureSiteAttribution(contentProvider!, verboseAttribution: false) } else { reset() } invalidateIntrinsicContentSize() } public func configureViewWithVerboseSiteAttribution(contentProvider: ReaderPostContentProvider?) { if let contentProvider = contentProvider { configureSiteAttribution(contentProvider, verboseAttribution: true) } else { reset() } } private func reset() { imageView.image = nil richTextView.attributedText = nil } private func configurePostAttribution(contentProvider: ReaderPostContentProvider) { let url = contentProvider.sourceAvatarURLForDisplay() let placeholder = UIImage(named: gravatarImageName) imageView.setImageWithURL(url, placeholderImage: placeholder) imageView.shouldRoundCorners = true let str = stringForPostAttribution(contentProvider.sourceAuthorNameForDisplay(), blogName: contentProvider.sourceBlogNameForDisplay()) let attributes = WPStyleGuide.originalAttributionParagraphAttributes() richTextView.attributedText = NSAttributedString(string: str, attributes: attributes) } private func stringForPostAttribution(authorName: String?, blogName: String?) -> String { var str = "" if (authorName != nil) && (blogName != nil) { let pattern = NSLocalizedString("Originally posted by %@ on %@", comment: "Used to attribute a post back to its original author and blog. The '%@' characters are placholders for the author's name, and the author's blog repsectively.") str = String(format: pattern, authorName!, blogName!) } else if (authorName != nil) { let pattern = NSLocalizedString("Originally posted by %@", comment: "Used to attribute a post back to its original author. The '%@' characters are a placholder for the author's name.") str = String(format: pattern, authorName!) } else if (blogName != nil) { let pattern = NSLocalizedString("Originally posted on %@", comment: "Used to attribute a post back to its original blog. The '%@' characters are a placholder for the blog name.") str = String(format: pattern, blogName!) } return str } private func patternForSiteAttribution(verbose: Bool) -> String { var pattern: String if verbose { pattern = NSLocalizedString("Visit %@ for more", comment:"A call to action to visit the specified blog. The '%@' characters are a placholder for the blog name.") } else { pattern = NSLocalizedString("Visit %@", comment:"A call to action to visit the specified blog. The '%@' characters are a placholder for the blog name.") } return pattern } private func configureSiteAttribution(contentProvider: ReaderPostContentProvider, verboseAttribution verbose:Bool) { let url = contentProvider.sourceAvatarURLForDisplay() let placeholder = UIImage(named: blavatarImageName) imageView.setImageWithURL(url, placeholderImage: placeholder) imageView.shouldRoundCorners = false let blogName = contentProvider.sourceBlogNameForDisplay() let pattern = patternForSiteAttribution(verbose) let str = String(format: pattern, blogName) let range = (str as NSString).rangeOfString(blogName) let font = WPFontManager.systemItalicFontOfSize(WPStyleGuide.originalAttributionFontSize()) let attributes = WPStyleGuide.siteAttributionParagraphAttributes() let attributedString = NSMutableAttributedString(string: str, attributes: attributes) attributedString.addAttribute(NSFontAttributeName, value: font, range: range) attributedString.addAttribute(NSLinkAttributeName, value: "http://wordpress.com/", range: NSMakeRange(0, str.characters.count)) richTextView.attributedText = attributedString } }
7d7b28567860b0fff3706a7a85bde49b
41.128788
186
0.68369
false
true
false
false
KBvsMJ/IQKeyboardManager
refs/heads/master
Demo/Swift_Demo/ViewController/SettingsViewController.swift
mit
18
// // SettingsViewController.swift // Demo // // Created by Iftekhar on 26/08/15. // Copyright (c) 2015 Iftekhar. All rights reserved. // class SettingsViewController: UITableViewController, OptionsViewControllerDelegate { let sectionTitles = [ "UIKeyboard handling", "IQToolbar handling", "UITextView handling", "UIKeyboard appearance overriding", "Resign first responder handling", "UIScrollView handling", "UISound handling", "UIAnimation handling"] let keyboardManagerProperties = [ ["Enable", "Keyboard Distance From TextField", "Prevent Showing Bottom Blank Space"], ["Enable AutoToolbar","Toolbar Manage Behaviour","Should Toolbar Uses TextField TintColor","Should Show TextField Placeholder","Placeholder Font"], ["Can Adjust TextView","Should Fix TextView Clip"], ["Override Keyboard Appearance","UIKeyboard Appearance"], ["Should Resign On Touch Outside"], ["Should Restore ScrollView ContentOffset"], ["Should Play Input Clicks"], ["Should Adopt Default Keyboard Animation"]] let keyboardManagerPropertyDetails = [ ["Enable/Disable IQKeyboardManager","Set keyboard distance from textField","Prevent to show blank space between UIKeyboard and View"], ["Automatic add the IQToolbar on UIKeyboard","AutoToolbar previous/next button managing behaviour","Uses textField's tintColor property for IQToolbar","Add the textField's placeholder text on IQToolbar","UIFont for IQToolbar placeholder text"], ["Adjust textView's frame when it is too big in height","Adjust textView's contentInset to fix a bug"], ["Override the keyboardAppearance for all UITextField/UITextView","All the UITextField keyboardAppearance is set using this property"], ["Resigns Keyboard on touching outside of UITextField/View"], ["Restore scrollViewContentOffset when resigning from scrollView."], ["Plays inputClick sound on next/previous/done click"], ["Uses keyboard default animation curve style to move view"]] var selectedIndexPathForOptions : NSIndexPath? @IBAction func doneAction (sender: UIBarButtonItem) { self.dismissViewControllerAnimated(true, completion: nil) } /** UIKeyboard Handling */ func enableAction (sender: UISwitch) { IQKeyboardManager.sharedManager().enable = sender.on self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Fade) } func keyboardDistanceFromTextFieldAction (sender: UIStepper) { IQKeyboardManager.sharedManager().keyboardDistanceFromTextField = CGFloat(sender.value) self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 1, inSection: 0)], withRowAnimation: UITableViewRowAnimation.None) } func preventShowingBottomBlankSpaceAction (sender: UISwitch) { IQKeyboardManager.sharedManager().preventShowingBottomBlankSpace = sender.on self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Fade) } /** IQToolbar handling */ func enableAutoToolbarAction (sender: UISwitch) { IQKeyboardManager.sharedManager().enableAutoToolbar = sender.on self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.Fade) } func shouldToolbarUsesTextFieldTintColorAction (sender: UISwitch) { IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor = sender.on } func shouldShowTextFieldPlaceholder (sender: UISwitch) { IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder = sender.on self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.Fade) } /** UITextView handling */ func canAdjustTextViewAction (sender: UISwitch) { IQKeyboardManager.sharedManager().canAdjustTextView = sender.on self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Fade) } func shouldFixTextViewClipAction (sender: UISwitch) { IQKeyboardManager.sharedManager().shouldFixTextViewClip = sender.on self.tableView.reloadSections(NSIndexSet(index: 3), withRowAnimation: UITableViewRowAnimation.Fade) } /** "Keyboard appearance overriding */ func overrideKeyboardAppearanceAction (sender: UISwitch) { IQKeyboardManager.sharedManager().overrideKeyboardAppearance = sender.on self.tableView.reloadSections(NSIndexSet(index: 3), withRowAnimation: UITableViewRowAnimation.Fade) } /** Resign first responder handling */ func shouldResignOnTouchOutsideAction (sender: UISwitch) { IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = sender.on } /** UIScrollView handling */ func shouldRestoreScrollViewContentOffsetAction (sender: UISwitch) { IQKeyboardManager.sharedManager().shouldRestoreScrollViewContentOffset = sender.on } /** Sound handling */ func shouldPlayInputClicksAction (sender: UISwitch) { IQKeyboardManager.sharedManager().shouldPlayInputClicks = sender.on } /** Animation handling */ func shouldAdoptDefaultKeyboardAnimation (sender: UISwitch) { IQKeyboardManager.sharedManager().shouldAdoptDefaultKeyboardAnimation = sender.on } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sectionTitles.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch (section) { case 0: if IQKeyboardManager.sharedManager().enable == true { let properties = keyboardManagerProperties[section] return properties.count } else { return 1 } case 1: if IQKeyboardManager.sharedManager().enableAutoToolbar == false { return 1 } else if IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder == false { return 4 } else { let properties = keyboardManagerProperties[section] return properties.count } case 3: if IQKeyboardManager.sharedManager().overrideKeyboardAppearance == true { let properties = keyboardManagerProperties[section] return properties.count } else { return 1 } case 2,4,5,6,7: let properties = keyboardManagerProperties[section] return properties.count default: return 0 } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sectionTitles[section] } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch (indexPath.section) { case 0: switch (indexPath.row) { case 0: var cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell cell.switchEnable.enabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.on = IQKeyboardManager.sharedManager().enable cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) cell.switchEnable.addTarget(self, action: Selector("enableAction:"), forControlEvents: UIControlEvents.ValueChanged) return cell case 1: var cell = tableView.dequeueReusableCellWithIdentifier("StepperTableViewCell") as! StepperTableViewCell cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.stepper.value = Double(IQKeyboardManager.sharedManager().keyboardDistanceFromTextField) cell.labelStepperValue.text = NSString(format: "%.0f", IQKeyboardManager.sharedManager().keyboardDistanceFromTextField) as String cell.stepper.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) cell.stepper.addTarget(self, action: Selector("keyboardDistanceFromTextFieldAction:"), forControlEvents: UIControlEvents.ValueChanged) return cell case 2: var cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell cell.switchEnable.enabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.on = IQKeyboardManager.sharedManager().preventShowingBottomBlankSpace cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) cell.switchEnable.addTarget(self, action: Selector("preventShowingBottomBlankSpaceAction:"), forControlEvents: UIControlEvents.ValueChanged) return cell default: break } case 1: switch (indexPath.row) { case 0: var cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell cell.switchEnable.enabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.on = IQKeyboardManager.sharedManager().enableAutoToolbar cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) cell.switchEnable.addTarget(self, action: Selector("enableAutoToolbarAction:"), forControlEvents: UIControlEvents.ValueChanged) return cell case 1: var cell = tableView.dequeueReusableCellWithIdentifier("NavigationTableViewCell") as! NavigationTableViewCell cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] return cell case 2: var cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell cell.switchEnable.enabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) cell.switchEnable.addTarget(self, action: Selector("shouldToolbarUsesTextFieldTintColorAction:"), forControlEvents: UIControlEvents.ValueChanged) return cell case 3: var cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell cell.switchEnable.enabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) cell.switchEnable.addTarget(self, action: Selector("shouldShowTextFieldPlaceholder:"), forControlEvents: UIControlEvents.ValueChanged) return cell case 4: var cell = tableView.dequeueReusableCellWithIdentifier("NavigationTableViewCell") as! NavigationTableViewCell cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] return cell default: break } case 2: switch (indexPath.row) { case 0: var cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell cell.switchEnable.enabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.on = IQKeyboardManager.sharedManager().canAdjustTextView cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) cell.switchEnable.addTarget(self, action: Selector("canAdjustTextViewAction:"), forControlEvents: UIControlEvents.ValueChanged) return cell case 1: var cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell cell.switchEnable.enabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldFixTextViewClip cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) cell.switchEnable.addTarget(self, action: Selector("shouldFixTextViewClipwAction:"), forControlEvents: UIControlEvents.ValueChanged) return cell default: break } case 3: switch (indexPath.row) { case 0: var cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell cell.switchEnable.enabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.on = IQKeyboardManager.sharedManager().overrideKeyboardAppearance cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) cell.switchEnable.addTarget(self, action: Selector("overrideKeyboardAppearanceAction:"), forControlEvents: UIControlEvents.ValueChanged) return cell case 1: var cell = tableView.dequeueReusableCellWithIdentifier("NavigationTableViewCell") as! NavigationTableViewCell cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] return cell default: break } case 4: switch (indexPath.row) { case 0: var cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell cell.switchEnable.enabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldResignOnTouchOutside cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) cell.switchEnable.addTarget(self, action: Selector("shouldResignOnTouchOutsideAction:"), forControlEvents: UIControlEvents.ValueChanged) return cell default: break } case 5: switch (indexPath.row) { case 0: var cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell cell.switchEnable.enabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldRestoreScrollViewContentOffset cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) cell.switchEnable.addTarget(self, action: Selector("shouldRestoreScrollViewContentOffsetAction:"), forControlEvents: UIControlEvents.ValueChanged) return cell default: break } case 6: switch (indexPath.row) { case 0: var cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell cell.switchEnable.enabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldPlayInputClicks cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) cell.switchEnable.addTarget(self, action: Selector("shouldPlayInputClicksAction:"), forControlEvents: UIControlEvents.ValueChanged) return cell default: break } case 7: switch (indexPath.row) { case 0: var cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell cell.switchEnable.enabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldAdoptDefaultKeyboardAnimation cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) cell.switchEnable.addTarget(self, action: Selector("shouldAdoptDefaultKeyboardAnimation:"), forControlEvents: UIControlEvents.ValueChanged) return cell default: break } default: break } return UITableViewCell() } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { if identifier == "OptionsViewController" { let controller = segue.destinationViewController as! OptionsViewController controller.delegate = self let cell = sender as! UITableViewCell selectedIndexPathForOptions = self.tableView.indexPathForCell(cell) if let selectedIndexPath = selectedIndexPathForOptions { if selectedIndexPath.section == 1 && selectedIndexPath.row == 1 { controller.title = "Toolbar Manage Behaviour" controller.options = ["IQAutoToolbar By Subviews","IQAutoToolbar By Tag","IQAutoToolbar By Position"] controller.selectedIndex = IQKeyboardManager.sharedManager().toolbarManageBehaviour.hashValue } else if selectedIndexPath.section == 1 && selectedIndexPath.row == 4 { controller.title = "Fonts" controller.options = ["Bold System Font","Italic system font","Regular"] controller.selectedIndex = IQKeyboardManager.sharedManager().toolbarManageBehaviour.hashValue let fonts = [UIFont.boldSystemFontOfSize(12),UIFont.italicSystemFontOfSize(12),UIFont.systemFontOfSize(12)] if let placeholderFont = IQKeyboardManager.sharedManager().placeholderFont { if let index = find(fonts, placeholderFont) { controller.selectedIndex = index } } } else if selectedIndexPath.section == 3 && selectedIndexPath.row == 1 { controller.title = "Keyboard Appearance" controller.options = ["UIKeyboardAppearance Default","UIKeyboardAppearance Dark","UIKeyboardAppearance Light"] controller.selectedIndex = IQKeyboardManager.sharedManager().keyboardAppearance.hashValue } } } } } func optionsViewController(controller: OptionsViewController, index: NSInteger) { if let selectedIndexPath = selectedIndexPathForOptions { if selectedIndexPath.section == 1 && selectedIndexPath.row == 1 { IQKeyboardManager.sharedManager().toolbarManageBehaviour = IQAutoToolbarManageBehaviour(rawValue: index)! } else if selectedIndexPath.section == 1 && selectedIndexPath.row == 4 { let fonts = [UIFont.boldSystemFontOfSize(12),UIFont.italicSystemFontOfSize(12),UIFont.systemFontOfSize(12)] IQKeyboardManager.sharedManager().placeholderFont = fonts[index] } else if selectedIndexPath.section == 3 && selectedIndexPath.row == 1 { IQKeyboardManager.sharedManager().keyboardAppearance = UIKeyboardAppearance(rawValue: index)! } } } }
35b723f7437bce02cc97de32d514aecc
43.971631
252
0.602507
false
false
false
false
syd24/DouYuZB
refs/heads/master
DouYu/DouYu/classes/tools/NetworkTools.swift
mit
1
// // NetworkTools.swift // DouYu // // Created by ADMIN on 16/11/11. // Copyright © 2016年 ADMIN. All rights reserved. // import UIKit import Alamofire enum MethodType { case get case post } class NetworkTools: NSObject { class func requestData(type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback: @escaping (_ result : Any) -> ()) { let method = type == .get ? HTTPMethod.get : HTTPMethod.post; Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in guard let result = response.result.value else{ return; } finishedCallback(result) } } }
4b8004f651677011d568e50b6ba6e52a
20.945946
156
0.555419
false
false
false
false
Aneapiy/Swift-HAR
refs/heads/master
Swift-HAR/NeuralNet.swift
apache-2.0
1
// // NeuralNet.swift // Swift-AI // // Created by Collin Hundley on 4/3/17. // // import Foundation import Accelerate /// A 3-layer, feed-forward artificial neural network. public final class NeuralNet { // MARK: Errors /// Possible errors that may be thrown by `NeuralNet`. public enum Error: Swift.Error { case initialization(String) case weights(String) case inference(String) case train(String) } // MARK: Public properties /// The basic structure of the neural network (read-only). /// This includes the number of input, hidden and output nodes. public let structure: Structure /// The activation function to apply to hidden nodes during inference. public var hiddenActivation: ActivationFunction /// The activation function to apply to the output layer during inference. public var outputActivation: ActivationFunction /// The cost function to apply during backpropagation. public var costFunction: CostFunction /// The 'learning rate' parameter to apply during backpropagation. /// This property may be safely mutated at any time. public var learningRate: Float { // Must update mfLR whenever this property is changed didSet(newRate) { cache.mfLR = (1 - momentumFactor) * newRate } } /// The 'momentum factor' to apply during backpropagation. /// This property may be safely mutated at any time. public var momentumFactor: Float { // Must update mfLR whenever this property is changed didSet(newMomentum) { cache.mfLR = (1 - newMomentum) * learningRate } } // MARK: Private properties and caches /// A set of pre-computed values and caches used internally for performance optimization. fileprivate var cache: Cache // MARK: Initialization public init(structure: Structure, config: Configuration, weights: [Float]? = nil) throws { // Initialize basic properties self.structure = structure self.hiddenActivation = config.hiddenActivation self.outputActivation = config.outputActivation self.costFunction = config.cost self.learningRate = config.learningRate self.momentumFactor = config.momentumFactor // Initialize computed properties and caches self.cache = Cache(structure: structure, config: config) // Set initial weights, or randomize if none are provided if let weights = weights { try self.setWeights(weights) } else { randomizeWeights() } } } // MARK: Weights public extension NeuralNet { /// Resets the network with the given weights (i.e. from a pre-trained network). /// This change may safely be performed at any time. /// /// - Parameter weights: A serialized array of `Float`, to be used as hidden *and* output weights for the network. /// - IMPORTANT: The number of weights must equal `hidden * (inputs + 1) + outputs * (hidden + 1)`, or the weights will be rejected. public func setWeights(_ weights: [Float]) throws { // Ensure valid number of weights guard weights.count == structure.numHiddenWeights + structure.numOutputWeights else { throw Error.weights("Invalid number of weights provided: \(weights.count). Expected: \(structure.numHiddenWeights + structure.numOutputWeights).") } // Reset all weights in the network cache.hiddenWeights = Array(weights[0..<structure.numHiddenWeights]) cache.outputWeights = Array(weights[structure.numHiddenWeights..<weights.count]) } /// Returns a serialized array of the network's current weights. public func allWeights() -> [Float] { return cache.hiddenWeights + cache.outputWeights } /// Randomizes all of the network's weights. fileprivate func randomizeWeights() { // Randomize hidden weights. for i in 0..<structure.numHiddenWeights { cache.hiddenWeights[i] = randomHiddenWeight() } for i in 0..<structure.numOutputWeights { cache.outputWeights[i] = randomOutputWeight() } } // TODO: Generate random weights along a normal distribution, rather than a uniform distribution. // Also, these weights are optimized for sigmoid activation. // Alternatives should be considered for other activation functions. /// Generates a random weight for a hidden node, based on the parameters set for the network. fileprivate func randomHiddenWeight() -> Float { // Note: Hidden weight distribution depends on number of *input* nodes return randomWeight(layerInputs: structure.numInputNodes) } /// Generates a random weight for an output node, based on the parameters set for the network. fileprivate func randomOutputWeight() -> Float { // Note: Output weight distribution depends on number of *hidden* nodes return randomWeight(layerInputs: structure.numHiddenNodes) } /// Generates a single random weight. /// /// - Parameter layerInputs: The number of inputs to the layer in which this weight will be used. /// E.g., if this weight will be placed in the hidden layer, `layerInputs` should be the number of input nodes (including bias node). /// - Returns: A randomly-generated weight optimized for this layer. private func randomWeight(layerInputs: Int) -> Float { let range = 1 / sqrt(Float(layerInputs)) let rangeInt = UInt32(2_000_000 * range) let randomFloat = Float(arc4random_uniform(rangeInt)) - Float(rangeInt / 2) return randomFloat / 1_000_000 } } // MARK: Inference public extension NeuralNet { // Note: The inference method is somewhat complex, but testing has shown that // keeping the code in-line allows the Swift compiler to make better optimizations. // Thus, we achieve improved performance at the cost of slightly less readable code. /// Inference: propagates the given inputs through the neural network, returning the network's output. /// This is the typical method for 'using' a trained neural network. /// This is also used during the training process. /// /// - Parameter inputs: An array of `Float`, each element corresponding to one input node. /// - Returns: The network's output after applying the given inputs. /// - Throws: An error if an incorrect number of inputs is provided. /// - IMPORTANT: The number of inputs provided must exactly match the network's number of inputs (defined in its `Structure`). @discardableResult public func infer(_ inputs: [Float]) throws -> [Float] { // Ensure that the correct number of inputs is given guard inputs.count == structure.inputs else { throw Error.inference("Invalid number of inputs provided: \(inputs.count). Expected: \(structure.inputs).") } // Cache the inputs // Note: A bias node is inserted at index 0, followed by all of the given inputs cache.inputCache[0] = 1 // Note: This loop appears to be the fastest way to make this happen for i in 1..<structure.numInputNodes { cache.inputCache[i] = inputs[i - 1] } // Calculate the weighted sums for the hidden layer inputs vDSP_mmul(cache.hiddenWeights, 1, cache.inputCache, 1, &cache.hiddenOutputCache, 1, vDSP_Length(structure.hidden), 1, vDSP_Length(structure.numInputNodes)) // Apply the activation function to the hidden layer nodes for i in (1...structure.hidden).reversed() { // Note: Array elements are shifted one index to the right, in order to efficiently insert the bias node at index 0 cache.hiddenOutputCache[i] = hiddenActivation.activation(cache.hiddenOutputCache[i - 1]) } cache.hiddenOutputCache[0] = 1 // Calculate the weighted sum for the output layer vDSP_mmul(cache.outputWeights, 1, cache.hiddenOutputCache, 1, &cache.outputCache, 1, vDSP_Length(structure.outputs), 1, vDSP_Length(structure.numHiddenNodes)) // Apply the activation function to the output layer nodes for i in 0..<structure.outputs { cache.outputCache[i] = outputActivation.activation(cache.outputCache[i]) } // Return the final outputs return cache.outputCache } } // MARK: Training public extension NeuralNet { // Note: The backpropagation method is somewhat complex, but testing has shown that // keeping the code in-line allows the Swift compiler to make better optimizations. // Thus, we achieve improved performance at the cost of slightly less readable code. // Note: Refer to Chapter 3 in the following paper to view the equations applied // for this backpropagation algorithm (with modifications to allow for customizable activation/cost functions): // https://www.cheshireeng.com/Neuralyst/doc/NUG14x.pdf /// Applies modifications to the neural network by comparing its most recent output to the given `labels`, adjusting the network's weights as needed. /// This method should be used for training a neural network manually. /// /// - Parameter labels: The 'target' desired output for the most recent inference cycle, as an array `[Float]`. /// - Throws: An error if an incorrect number of outputs is provided. /// - IMPORTANT: The number of labels provided must exactly match the network's number of outputs (defined in its `Structure`). public func backpropagate(_ labels: [Float]) throws { // Ensure that the correct number of outputs was given guard labels.count == structure.outputs else { throw Error.train("Invalid number of labels provided: \(labels.count). Expected: \(structure.outputs).") } // ----------------------------------------------------- // // NOTE: // // In the following equations, it is assumed that the network has 3 layers. // The subscripts [i], [j], [k] will be used to refer to input, hidden and output layers respectively. // In networks with multiple hidden layers, [i] can be assumed to represent whichever layer preceeds the current layer (j), // and [k] can be assumed to represent the succeeding layer. // // ----------------------------------------------------- // MARK: Output error gradients -------------------------------------- // Note: Rather than calculating the cost gradient with respect to each output weight, // we calculate the gradient with respect to each output node's INPUT, cache the result, // and then calculate the gradient for each weight while simultaneously updating the weight. // This results in lower memory consumption and fewer calculations. // Calculate the error gradient with respect to each output node's INPUT. // e[k] = outputActivationDerivative(output) * costDerivative(output) for (index, output) in cache.outputCache.enumerated() { cache.outputErrorGradientsCache[index] = outputActivation.derivative(output) * costFunction.derivative(real: output, target: labels[index]) } // MARK: Hidden error gradients -------------------------------------- // Important: The cost function does not apply to hidden nodes. // Instead, the cost derivative component is replaced with the sum of the nodes' error gradients in the succeeding layer // (with respect to their inputs, as calculated above) multipled by the weight connecting this node to the following layer. // Below, w' represents the previous (and still current) weight connecting this node to the following layer. // e[j] = hiddenActivationDerivative(hiddenOutput) * Σ(e[k] * w'[j][k]) // Calculate the sums of the output error gradients multiplied by the output weights vDSP_mmul(cache.outputErrorGradientsCache, 1, cache.outputWeights, 1, &cache.outputErrorGradientSumsCache, 1, 1, vDSP_Length(structure.numHiddenNodes), vDSP_Length(structure.outputs)) // Calculate the error gradient for each hidden node, with respect to the node's INPUT for (index ,error) in cache.outputErrorGradientSumsCache.enumerated() { cache.hiddenErrorGradientsCache[index] = hiddenActivation.derivative(cache.hiddenOutputCache[index]) * error } // MARK: Output weights ---------------------------------------------- // Update output weights // Note: In this equation, w' represents the current (old) weight and w'' represents the PREVIOUS weight. // In addition, M represents the momentum factor and LR represents the learning rate. // X[j] represents the jth input to the node (or, the activated output from the jth hidden node) // // w[j][k] = w′[j][k] + (1 − M) ∗ LR ∗ e[k] ∗ X[j] + M ∗ (w′[j][k] − w′′[j][k]) for index in 0..<structure.numOutputWeights { // Pre-computed indices: translates the current weight index into the corresponding output error/hidden output indices let outputErrorIndex = cache.outputErrorIndices[index] let hiddenOutputIndex = cache.hiddenOutputIndices[index] // Note: mFLR is a pre-computed constant which equals (1 - M) * LR cache.newOutputWeights[index] = cache.outputWeights[index] - cache.mfLR * cache.outputErrorGradientsCache[outputErrorIndex] * cache.hiddenOutputCache[hiddenOutputIndex] + momentumFactor * (cache.outputWeights[index] - cache.previousOutputWeights[index]) } // Efficiently copy output weights from current to 'previous' array vDSP_mmov(cache.outputWeights, &cache.previousOutputWeights, 1, vDSP_Length(structure.numOutputWeights), 1, 1) // Copy output weights from 'new' to current array vDSP_mmov(cache.newOutputWeights, &cache.outputWeights, 1, vDSP_Length(structure.numOutputWeights), 1, 1) // MARK: Hidden weights ---------------------------------------------- // Note: This process is almost identical to the process for updating the output weights, // since the error gradients have already been calculated independently for each layer. // Update hidden weights // w[i][j] = w′[i][j] + (1 − M) ∗ LR ∗ e[j] ∗ X[i] + M ∗ (w′[i][j] − w′′[i][j]) for index in 0..<structure.numHiddenWeights { // Pre-computed indices: translates the current weight index into the corresponding hidden error/input indices let hiddenErrorIndex = cache.hiddenErrorIndices[index] let inputIndex = cache.inputIndices[index] // Note: mfLR is a pre-computed constant which equals (1 - M) * LR cache.newHiddenWeights[index] = cache.hiddenWeights[index] - // Note: +1 on hiddenErrorIndex to offset for bias 'error', which is ignored cache.mfLR * cache.hiddenErrorGradientsCache[hiddenErrorIndex + 1] * cache.inputCache[inputIndex] + momentumFactor * (cache.hiddenWeights[index] - cache.previousHiddenWeights[index]) } // Copy hidden weights from current to 'previous' array vDSP_mmov(cache.hiddenWeights, &cache.previousHiddenWeights, 1, vDSP_Length(structure.numHiddenWeights), 1, 1) // Copy hidden weights from 'new' to current array vDSP_mmov(cache.newHiddenWeights, &cache.hiddenWeights, 1, vDSP_Length(structure.numHiddenWeights), 1, 1) } /// Attempts to train the neural network using the given dataset. /// /// - Parameters: /// - data: A `Dataset` containing training and validation data, used to train the network. /// - errorThreshold: The minimum acceptable error, as calculated by the network's cost function. /// This error will be averaged across the validation set at the end of each training epoch. /// Once the error has dropped below `errorThreshold`, training will cease and return. /// This value must be determined by the user, as it varies based on the type of data and desired accuracy. /// - Returns: A serialized array containing the network's final weights, as calculated during the training process. /// - Throws: An error if invalid data is provided. Checks are performed in advance to avoid problems during the training cycle. /// - WARNING: `errorThreshold` should be considered carefully. A value too high will produce a poorly-performing network, while a value too low (i.e. too accurate) may be unachievable, resulting in an infinite training process. @discardableResult public func train(_ data: Dataset, errorThreshold: Float, maxEpochs: Int) throws -> [Float] { // Ensure valid error threshold guard errorThreshold > 0 else { throw Error.train("Training error threshold must be greater than zero.") } // ----------------------------- // TODO: Allow the trainer to exit early or regenerate new weights if it gets stuck in local minima // ----------------------------- // Train forever until the desired error threshold is met var epochCounter = 0 while true { // Complete one full training epoch for (index, input) in data.trainInputs.enumerated() { // Note: We don't care about outputs or error on the training set try infer(input) try backpropagate(data.trainLabels[index]) } // Calculate the total error of the validation set after each training epoch var error: Float = 0 for (index, inputs) in data.validationInputs.enumerated() { let outputs = try infer(inputs) error += costFunction.cost(real: outputs, target: data.validationLabels[index]) } // Divide error by number of sets to find average error across full validation set error /= Float(data.validationInputs.count) print(error) // Escape training loop if the network has met the error threshold if error < errorThreshold { break } if epochCounter >= maxEpochs { break } else { epochCounter += 1 } } // Return the weights of the newly-trained neural network return allWeights() } }
0cfb301c5d8af4029a914bceaf33998d
45.31829
232
0.626923
false
false
false
false
googlemaps/last-mile-fleet-solution-samples
refs/heads/main
ios_driverapp_samples/LMFSDriverSampleApp/ListTab/Details/TaskDetails.swift
apache-2.0
1
/* * Copyright 2022 Google LLC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import SwiftUI /// This view defines the details of a task, and buttons which let the driver to update the task /// status. struct TaskDetails: View { @ObservedObject var task: ModelData.Task @EnvironmentObject var modelData: ModelData var body: some View { let taskInfo = task.taskInfo VStack(alignment: HorizontalAlignment.leading) { if let contactName = taskInfo.contactName { Text(contactName) .fontWeight(.semibold) .padding(EdgeInsets(top: 0, leading: 0, bottom: 10, trailing: 0)) } switch task.taskInfo.taskType { case .PICKUP: Text("Pick up") .fontWeight(.semibold) case .SCHEDULED_STOP: Text("Scheduled stop") .fontWeight(.semibold) case .DELIVERY, .UNAVAIALBLE: EmptyView() } Text("ID: \(taskInfo.taskId)") TaskButtons(task: task) } } } struct TaskDetails_Previews: PreviewProvider { static var previews: some View { let _ = LMFSDriverSampleApp.googleMapsInited let modelData = ModelData(filename: "test_manifest") let stop = modelData.stops[0] let task = modelData.tasks(stop: stop)[0] TaskDetails(task: task) .environmentObject(modelData) .previewLayout(.sizeThatFits) } }
114f2a2a60a8185ca1da0a096fe1034c
30.4
96
0.683121
false
false
false
false
mactive/rw-courses-note
refs/heads/master
AdvancedSwift3/SwiftPlayground-101.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" let maximunNumberOfLoginAttemptes = 10 var currentLoginAttempt = 0 let ingredients:Set = ["cocoa beans", "suger", "cocoa butter", "salt"] if ingredients.contains("suger"){ print("No thanks, too sweet.") } var primes: Set = [2,3,5,7] print(primes.isSubset(of: 0..<10)) if primes.isEmpty { print("No primes") } else { print("we have \(primes.count) primes") } let cat = "🐱猫"; print(cat) let oneThird = 1.0 / 3.0 let oneThirdLongString = "One thrid is \(oneThird) as a decimal" print("Double.pi \(Double.pi), Float.pi \(Float.pi) ") //: Tuple let coordinates: (Int, Int) = (2,3) let an_coordinates = (2.1, 4.4) let x = an_coordinates.0 let coordinates3D = (x: 1, y: 8.9, z: 3) let (a, b, c) = coordinates3D print("coordinates \(a) \(b) \(c)") var yearInfo = (year: 2017, month: 06, day: 11) let (y,m,d) = yearInfo yearInfo = (2017, 06, 12) print("today is \(y),\(m),\(d)") let tuple = (day: 15, month: 8, year: 2015) let day = tuple.day let character1: Character = "🐶" let string2: String = "🐶"
a9aa00259b9d51cf1f7daab440b198bd
17.733333
70
0.637011
false
false
false
false
apple/swift-nio
refs/heads/main
Sources/NIOHTTP1/HTTPHeaders+Validation.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// extension String { /// Validates a given header field value against the definition in RFC 9110. /// /// The spec in [RFC 9110](https://httpwg.org/specs/rfc9110.html#fields.values) defines the valid /// characters as the following: /// /// ``` /// field-value = *field-content /// field-content = field-vchar /// [ 1*( SP / HTAB / field-vchar ) field-vchar ] /// field-vchar = VCHAR / obs-text /// obs-text = %x80-FF /// ``` /// /// Additionally, it makes the following note: /// /// "Field values containing CR, LF, or NUL characters are invalid and dangerous, due to the /// varying ways that implementations might parse and interpret those characters; a recipient /// of CR, LF, or NUL within a field value MUST either reject the message or replace each of /// those characters with SP before further processing or forwarding of that message. Field /// values containing other CTL characters are also invalid; however, recipients MAY retain /// such characters for the sake of robustness when they appear within a safe context (e.g., /// an application-specific quoted string that will not be processed by any downstream HTTP /// parser)." /// /// As we cannot guarantee the context is safe, this code will reject all ASCII control characters /// directly _except_ for HTAB, which is explicitly allowed. fileprivate var isValidHeaderFieldValue: Bool { let fastResult = self.utf8.withContiguousStorageIfAvailable { ptr in ptr.allSatisfy { $0.isValidHeaderFieldValueByte } } if let fastResult = fastResult { return fastResult } else { return self.utf8._isValidHeaderFieldValue_slowPath } } /// Validates a given header field name against the definition in RFC 9110. /// /// The spec in [RFC 9110](https://httpwg.org/specs/rfc9110.html#fields.values) defines the valid /// characters as the following: /// /// ``` /// field-name = token /// /// token = 1*tchar /// /// tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" /// / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" /// / DIGIT / ALPHA /// ; any VCHAR, except delimiters /// ``` /// /// We implement this check directly. fileprivate var isValidHeaderFieldName: Bool { let fastResult = self.utf8.withContiguousStorageIfAvailable { ptr in ptr.allSatisfy { $0.isValidHeaderFieldNameByte } } if let fastResult = fastResult { return fastResult } else { return self.utf8._isValidHeaderFieldName_slowPath } } } extension String.UTF8View { /// The equivalent of `String.isValidHeaderFieldName`, but a slow-path when a /// contiguous UTF8 storage is not available. /// /// This is deliberately `@inline(never)`, as slow paths should be forcibly outlined /// to encourage inlining the fast-path. @inline(never) fileprivate var _isValidHeaderFieldName_slowPath: Bool { self.allSatisfy { $0.isValidHeaderFieldNameByte } } /// The equivalent of `String.isValidHeaderFieldValue`, but a slow-path when a /// contiguous UTF8 storage is not available. /// /// This is deliberately `@inline(never)`, as slow paths should be forcibly outlined /// to encourage inlining the fast-path. @inline(never) fileprivate var _isValidHeaderFieldValue_slowPath: Bool { self.allSatisfy { $0.isValidHeaderFieldValueByte } } } extension UInt8 { /// Validates a byte of a given header field name against the definition in RFC 9110. /// /// The spec in [RFC 9110](https://httpwg.org/specs/rfc9110.html#fields.values) defines the valid /// characters as the following: /// /// ``` /// field-name = token /// /// token = 1*tchar /// /// tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" /// / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" /// / DIGIT / ALPHA /// ; any VCHAR, except delimiters /// ``` /// /// We implement this check directly. /// /// We use inline always here to force the check to be inlined, which it isn't always, leading to less optimal code. @inline(__always) fileprivate var isValidHeaderFieldNameByte: Bool { switch self { case UInt8(ascii: "0")...UInt8(ascii: "9"), // DIGIT UInt8(ascii: "a")...UInt8(ascii: "z"), UInt8(ascii: "A")...UInt8(ascii: "Z"), // ALPHA UInt8(ascii: "!"), UInt8(ascii: "#"), UInt8(ascii: "$"), UInt8(ascii: "%"), UInt8(ascii: "&"), UInt8(ascii: "'"), UInt8(ascii: "*"), UInt8(ascii: "+"), UInt8(ascii: "-"), UInt8(ascii: "."), UInt8(ascii: "^"), UInt8(ascii: "_"), UInt8(ascii: "`"), UInt8(ascii: "|"), UInt8(ascii: "~"): return true default: return false } } /// Validates a byte of a given header field value against the definition in RFC 9110. /// /// The spec in [RFC 9110](https://httpwg.org/specs/rfc9110.html#fields.values) defines the valid /// characters as the following: /// /// ``` /// field-value = *field-content /// field-content = field-vchar /// [ 1*( SP / HTAB / field-vchar ) field-vchar ] /// field-vchar = VCHAR / obs-text /// obs-text = %x80-FF /// ``` /// /// Additionally, it makes the following note: /// /// "Field values containing CR, LF, or NUL characters are invalid and dangerous, due to the /// varying ways that implementations might parse and interpret those characters; a recipient /// of CR, LF, or NUL within a field value MUST either reject the message or replace each of /// those characters with SP before further processing or forwarding of that message. Field /// values containing other CTL characters are also invalid; however, recipients MAY retain /// such characters for the sake of robustness when they appear within a safe context (e.g., /// an application-specific quoted string that will not be processed by any downstream HTTP /// parser)." /// /// As we cannot guarantee the context is safe, this code will reject all ASCII control characters /// directly _except_ for HTAB, which is explicitly allowed. /// /// We use inline always here to force the check to be inlined, which it isn't always, leading to less optimal code. @inline(__always) fileprivate var isValidHeaderFieldValueByte: Bool { switch self { case UInt8(ascii: "\t"): // HTAB, explicitly allowed. return true case 0...0x1f, 0x7F: // ASCII control character, forbidden. return false default: // Printable or non-ASCII, allowed. return true } } } extension HTTPHeaders { /// Whether these HTTPHeaders are valid to send on the wire. var areValidToSend: Bool { for (name, value) in self.headers { if !name.isValidHeaderFieldName { return false } if !value.isValidHeaderFieldValue { return false } } return true } }
36378e3225e068182f36fb969bd9ff92
38.160976
120
0.575984
false
false
false
false
proversity-org/edx-app-ios
refs/heads/master
Source/RegistrationFieldSelectView.swift
apache-2.0
1
// // RegistrationFieldSelectView.swift // edX // // Created by Akiva Leffert on 6/9/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit class RegistrationFieldSelectView: RegistrationFormFieldView, UIPickerViewDelegate, UIPickerViewDataSource { @objc var options : [OEXRegistrationOption] = [] @objc private(set) var selected : OEXRegistrationOption? @objc let picker = UIPickerView(frame: CGRect.zero) private let dropdownView = UIView(frame: CGRect(x: 0, y: 0, width: 27, height: 40)) private let dropdownTab = UIImageView() private let tapButton = UIButton() private var titleStyle : OEXTextStyle { return OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralDark()) } override var currentValue: String { return tapButton.attributedTitle(for: .normal)?.string ?? "" } override init(with formField: OEXRegistrationFormField) { super.init(with: formField) } override func loadView() { super.loadView() picker.dataSource = self picker.delegate = self picker.showsSelectionIndicator = true; picker.accessibilityIdentifier = "RegistrationFieldSelectView:picker-view" textInputField.isEnabled = false dropdownView.addSubview(dropdownTab) dropdownView.layoutIfNeeded() dropdownTab.image = Icon.Dropdown.imageWithFontSize(size: 12) dropdownTab.tintColor = OEXStyles.shared().neutralDark() dropdownTab.contentMode = .scaleAspectFit dropdownTab.sizeToFit() dropdownTab.center = dropdownView.center tapButton.localizedHorizontalContentAlignment = .Leading textInputField.rightViewMode = .always textInputField.rightView = dropdownView tapButton.oex_addAction({[weak self] _ in self?.makeFirstResponder() }, for: UIControl.Event.touchUpInside) self.addSubview(tapButton) tapButton.snp.makeConstraints { make in make.top.equalTo(textInputField) make.leading.equalTo(textInputField) make.trailing.equalTo(textInputField) make.bottom.equalTo(textInputField) } let insets = OEXStyles.shared().standardTextViewInsets tapButton.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: insets.left, bottom: 0, right: insets.right) refreshAccessibilty() } override func layoutSubviews() { super.layoutSubviews() } override func refreshAccessibilty() { guard let formField = formField else { return } let errorAccessibility = errorMessage ?? "" != "" ? ",\(Strings.Accessibility.errorText), \(errorMessage ?? "")" : "" tapButton.accessibilityLabel = String(format: "%@, %@", formField.label, Strings.accessibilityDropdownTrait) tapButton.accessibilityTraits = UIAccessibilityTraits.none let accessibilitHintText = isRequired ? String(format: "%@, %@, %@, %@", Strings.accessibilityRequiredInput,formField.instructions, errorAccessibility , Strings.accessibilityShowsDropdownHint) : String(format: "%@, %@, %@, %@", Strings.Accessibility.optionalInput,formField.instructions,errorAccessibility , Strings.accessibilityShowsDropdownHint) tapButton.accessibilityHint = accessibilitHintText textInputField.isAccessibilityElement = false textInputField.accessibilityIdentifier = "RegistrationFieldSelectView:text-input-field" } private func setButtonTitle(title: String) { tapButton.setAttributedTitle(titleStyle.attributedString(withText: title), for: .normal) tapButton.accessibilityLabel = String(format: "%@, %@, %@", formField?.label ?? "", title, Strings.accessibilityDropdownTrait) tapButton.accessibilityIdentifier = "RegistrationFieldSelectView:\(String(describing: formField?.name))-\(title)-dropdown" } override var canBecomeFirstResponder: Bool { return true } override var inputView : UIView { return picker } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return options.count } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return self.options[row].name } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { self.selected = self.options[row] if let selected = self.selected, !selected.value.isEmpty { setButtonTitle(title: selected.name) } else { setButtonTitle(title: "") } valueDidChange() } func makeFirstResponder() { self.becomeFirstResponder() UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: self.picker) } override func validate() -> String? { guard let field = formField else { return nil } if isRequired && currentValue == "" { return field.errorMessage.required == "" ? Strings.registrationFieldEmptySelectError(fieldName: field.label) : field.errorMessage.required } return nil } }
c53c9a6407026c8090b14b3e146827d5
39.262774
355
0.671501
false
false
false
false
PiXeL16/SendToMe
refs/heads/master
SendToMe/MainViewController.swift
mit
1
// // ViewController.swift // SendToMe // // Created by Chris Jimenez on 1/22/16. // Copyright © 2016 Chris Jimenez. All rights reserved. // import UIKit import IBAnimatable import SendToMeFramework import SwiftDelayer class MainViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var stackView: AnimatableStackView! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var logoImageView: UIImageView! @IBOutlet weak var saveEmailButton: AnimatableButton! lazy var emailDataStorage:EmailDataStorage = EmailDataStorage() override func viewDidLoad() { super.viewDidLoad() //Shows the email info if available showEmailInfo() saveInitialSettings(); // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func saveEmailClicked(sender: AnyObject) { if isValid(){ //Saves the email in the data storage saveEmail() }else { //Shakes the stackview to show an error stackView.shake() } } private func saveInitialSettings(){ log.debug("Saving initial settings") let keysData = KeysDataStorage(); log.debug("Save mailgun api key") keysData.saveMailgunApiKey(Keys.mailgunApiKey) log.debug("Save client domain path") keysData.saveClientDomainKey(Keys.clientDomain) } /** Check if the form is valid - returns: form is valid */ private func isValid() -> Bool{ var returnValue = false if emailTextField.text!.isValidEmail() { returnValue = true } return returnValue } //Saves the email in the local storage private func saveEmail() { //Shows an initial save animation //Sets an email for the delay saveEmailButton.setTitle("email_saved".localized, forState: UIControlState.Normal) saveEmailButton.zoomIn { () -> Void in //Sets the button back to normal Delayer.delayOnMainQueue(seconds:2.0){ self.saveEmailButton.squeezeFadeInRight() self.saveEmailButton.setTitle("save_email_title".localized, forState: UIControlState.Normal) } } if let emailText = emailTextField.text{ emailDataStorage.saveEmail(emailText) } //Shows the saved email info showEmailInfo() } //Shows the email info in the placeholder if is available private func showEmailInfo() { self.emailTextField.text = "" if emailDataStorage.hasEmailSaved { emailTextField.placeholder = String(format: "save_email_text".localized, arguments: [emailDataStorage.getEmail()]) } } //Hide the keyboard when done func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEditing(true) return false } }
a1b884cc8e243ea65c2b98760c1d4ea8
24.590909
126
0.592066
false
false
false
false
velthune/VFloatingButton
refs/heads/master
VFloatingButton/source/VAnimationQueue.swift
mit
1
// // VAnimationQueue.swift // VFloatingButton // // Created by Luca Davanzo on 01/07/16. // Copyright © 2017 Luca Davanzo. All rights reserved. // import Foundation internal class VAnimation: NSObject { /// An animation is represented by a closure typealias Animation = () -> Void // MARK: Public properties var action: (Animation)? var isAnimating = false } internal class VAnimationQueue: NSObject { // MARK: - Public properties - var maxAnimationInQueue = 2 // MARK: - Private properties - fileprivate var animations = [VAnimation]() // MARK: - Public methods - /// Add an animation to the queue. Animation will be processed immediately. /// /// - Parameter animation: animation to execute func addAnimation(_ animation: VAnimation) { if self.animations.count < self.maxAnimationInQueue { self.animations.append(animation) self.performAnimations() } } /// Call this method when animation have finished. /// /// - Parameter animation: animation func animationDidFinish(animation: VAnimation) { animation.isAnimating = false if let _ = self.animations.first { self.animations.removeFirst() } self.performAnimations() } // MARK: - Private method - /// Perfom the animation only if previous animation on the queue has finished. fileprivate func performAnimations() { if let a = self.animations.first { if !a.isAnimating { a.isAnimating = true a.action?() } else { print("animation not yet finished") } } } }
446863e5ab62d0bb0e2d4184197517e1
24.507246
82
0.594318
false
false
false
false
audrl1010/EasyMakePhotoPicker
refs/heads/master
Example/EasyMakePhotoPicker/DurationLabel.swift
mit
1
// // DurationLabel.swift // KaKaoChatInputView // // Created by myung gi son on 2017. 5. 30.. // Copyright © 2017년 grutech. All rights reserved. // import UIKit class DurationLabel: UILabel { struct Constant { static let padding = UIEdgeInsets(top: 5, left: 3, bottom: 5, right: 3) } struct Color { static let bgColor = UIColor( red: 0/255, green: 0/255, blue: 0/255, alpha: 0.35) static let durationLabelTextColor = UIColor.white } struct Font { static let durationLabelFont = UIFont.systemFont(ofSize: 14) } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { backgroundColor = Color.bgColor textColor = Color.durationLabelTextColor font = Font.durationLabelFont text = "00:00" } override func drawText(in rect: CGRect) { super.drawText(in: rect.inset(by: Constant.padding)) } override var intrinsicContentSize: CGSize { let size = super.intrinsicContentSize return CGSize( width: size.width + Constant.padding.left + Constant.padding.right, height: size.height + Constant.padding.top + Constant.padding.bottom) } }
c1ecb7fd316aaad98150cf3160d9131a
19.5
75
0.654726
false
false
false
false
calebd/swift
refs/heads/master
test/Reflection/typeref_lowering_objc.swift
apache-2.0
4
// RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/TypeLoweringObjectiveC.swift -parse-as-library -emit-module -emit-library -module-name TypeLowering -o %t/libTypesToReflect // RUN: %target-swift-reflection-dump -binary-filename %t/libTypesToReflect -binary-filename %platform-module-dir/libswiftCore.dylib -dump-type-lowering < %s | %FileCheck %s // REQUIRES: objc_interop // REQUIRES: CPU=x86_64 12TypeLowering14FunctionStructV // CHECK: (struct TypeLowering.FunctionStruct) // CHECK-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647 // CHECK-NEXT: (field name=blockFunction offset=0 // CHECK-NEXT: (reference kind=strong refcounting=unknown))) 12TypeLowering14HasObjCClassesC // CHECK: (class TypeLowering.HasObjCClasses) // CHECK-NEXT: (reference kind=strong refcounting=native) 12TypeLowering16NSObjectSubclassC // CHECK: (class TypeLowering.NSObjectSubclass) // CHECK-NEXT: (reference kind=strong refcounting=unknown)
4563e748bc288c0a69539a5f6bfa379b
45.761905
173
0.778004
false
false
false
false
AndrejJurkin/nova-osx
refs/heads/master
Nova/view/menubar/MenuBarViewModel.swift
apache-2.0
1
// // Copyright 2017 Andrej Jurkin. // // 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. // // // MenuBarViewModel.swift // Nova // // Created by Andrej Jurkin on 9/3/17. import Foundation import RxSwift class MenuBarViewModel { let repo: DataRepository let prefs: Prefs var menuBarText = Variable(R.String.appName) let disposeBag = DisposeBag() init(repo: DataRepository, prefs: Prefs) { self.repo = repo self.prefs = prefs } func subscribe() { // Watch when list with pinned tickers changes self.repo.getPinnedTickers() .retry(5) .flatMap({ tickers -> Observable<[String]> in // If we don't have any pinned tickers, show app name guard tickers.count > 0 else { self.repo.disposeTickerSubscription() self.menuBarText.value = R.String.appName return Observable.just([]) } var menuBarText = "" var tickerSymbols: [String] = [] let priceFormatter = PriceFormatter(displayCurrency: self.prefs.displayCurrency, decimalFormat: self.prefs.menuBarFormat) // Create menu bar string representation for ticker in tickers { menuBarText.append(priceFormatter.formatWithTickerSymbol(ticker: ticker)) tickerSymbols.append(ticker.symbol) } self.menuBarText.value = menuBarText.trim() return Observable.just(tickerSymbols) }) // Distinct if pinned tickers array has the same size // This is to avoid re-subscribing after values update .distinctUntilChanged({ (old, new) -> Bool in return old.count == new.count }) .filter { $0.count != 0 } .subscribe(onNext: { tickerSymbols in // Subscribe for updates for given ticker symbols self.repo.subscribeForTickerUpdates(baseSymbols: tickerSymbols) }) .addDisposableTo(disposeBag) self.repo.subscribeForGlobalUpdates() } func unsubscribe() { self.repo.disposeRefreshSubscriptions() } }
aac66d37b31e12fc1d26668de4e770b2
32.747126
137
0.577997
false
false
false
false
ashare80/ASTextInputAccessoryView
refs/heads/master
Example/ASTextInputAccessoryView/Extensions/UICollectionView.swift
mit
1
// // UICollectionView.swift // ASTextInputAccessoryView // // Created by Adam J Share on 4/18/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit extension UICollectionView { public var lastIndexPath: NSIndexPath? { guard let numberOfSections = dataSource?.numberOfSectionsInCollectionView?(self), let numberOfItems = dataSource?.collectionView(self, numberOfItemsInSection: numberOfSections - 1) where numberOfItems > 0 else { return nil } return NSIndexPath(forItem: numberOfItems - 1, inSection: numberOfSections - 1) } func scrollToLastCell(atScrollPosition: UICollectionViewScrollPosition = .None, animated: Bool = true) { guard let lastIndexPath = lastIndexPath else { return } scrollToItemAtIndexPath(lastIndexPath, atScrollPosition: atScrollPosition, animated: animated) } }
44d1e104e041b21a0bd42b2fcd61ea98
27.970588
110
0.652439
false
false
false
false
darrarski/BNRCoreDataStackConvenienceSaves
refs/heads/master
Example/Tests/NSManagedObjectContextFake.swift
mit
1
// // Created by Dariusz Rybicki on 18/04/16. // import CoreData class NSManagedObjectContextFake: NSManagedObjectContext { var fakeHasChanges = false var shouldThrowOnSave = false var shouldThrowOnSaveOnce = false var fakeInsertedObjectsCount = 0 var fakeUpdatedObjectsCount = 0 var fakeDeletedObjectsCount = 0 private(set) var saveCallsCount = 0 private(set) var savesCount = 0 private(set) var rollbacksCount = 0 override var hasChanges: Bool { guard fakeInsertedObjectsCount == 0 else { return true } guard fakeUpdatedObjectsCount == 0 else { return true } guard fakeDeletedObjectsCount == 0 else { return true } return fakeHasChanges } override var changedObjectsCount: Int { return fakeInsertedObjectsCount + fakeUpdatedObjectsCount + fakeDeletedObjectsCount } override func save() throws { saveCallsCount += 1 if shouldThrowOnSave || shouldThrowOnSaveOnce { shouldThrowOnSaveOnce = false throw NSError(domain: "FakeError", code: 0, userInfo: nil) } usleep(200_000) savesCount += 1 resetFakeModifiedObjectsCount() } override func rollback() { usleep(200_000) rollbacksCount += 1 resetFakeModifiedObjectsCount() } private func resetFakeModifiedObjectsCount() { fakeInsertedObjectsCount = 0 fakeUpdatedObjectsCount = 0 fakeDeletedObjectsCount = 0 } }
105fc7384445aa7c9dca580cee3b9d07
28.307692
91
0.660761
false
false
false
false
lllyyy/LY
refs/heads/master
ATBluetooth-master(swift4蓝牙连接)/ATBluetooth/ViewController.swift
mit
1
// // ViewController.swift // ATBluetooth // // Created by macpro on 2017/11/10. // Copyright © 2017年 macpro. All rights reserved. // import UIKit let atBlueTooth = ATBlueToothContext.default class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! // var atBlueTooth:ATBlueToothContext! var currentDevice:ATBleDevice? var dataArr:[ATBleDevice] = [] { didSet { tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // atBlueTooth = ATBlueTooth.default // // atBlueTooth.centerManangerDelegate = self // atBlueTooth.startScanForDevices() atBlueTooth.confing(.CenteMode) atBlueTooth.confing(.CenteMode) atBlueTooth.delegate = self atBlueTooth.startScanForDevices(advertisingWithServices: ["FFF0"]) if #available(iOS 11.0, *) { tableView.contentInsetAdjustmentBehavior = .never } //解决iOS 10.3.1上方留白问题 iOS 7.0问题 self.automaticallyAdjustsScrollViewInsets = false tableView.tableFooterView = UIView() // let device = atBlueTooth.atCentral.discoverPeripherals.filter({$0.peripheral.name == "Ozner Cup"}).last // let uuid1 = UUID(uuidString: "6E6B5C64-FAF7-40AE-9C21-D4933AF45B23")! // let uuid2 = UUID(uuidString: "477A2967-1FAB-4DC5-920A-DEE5DE685A3D")! // atBlueTooth.atCentral.configuration = ATConfiguration("FFF2", readServiceCharacteristicUUIDString: "FFF1") // atBlueTooth.atCentral.connect(device) // device?.delegate = self // device?.peripheral.writeValue(data1, for: (atBlueTooth.atCentral.configuration?.writeCharacteristic)!, type: CBCharacteristicWriteType.withResponse) // tableView.register(<#T##cellClass: AnyClass?##AnyClass?#>, forCellReuseIdentifier: <#T##String#>) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController:UITableViewDelegate,UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "deviceCellID") as! DeviceCell let device = dataArr[indexPath.row] cell.reloadUI(device) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //same device Don't need to disconnect if currentDevice?.uuid != dataArr[indexPath.row].uuid { atBlueTooth.disconnectDevice() } currentDevice = dataArr[indexPath.row] self.performSegue(withIdentifier: "devicePushId", sender: nil) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } } extension ViewController:ATCentralDelegte { func didFoundATBleDevice(_ device: ATBleDevice) { dataArr.append(device) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier! { case "devicePushId": let vc = segue.destination as! DeviceVc vc.device = currentDevice break default: break } } }
932e6aa8312b7b45c53b99220f1d9362
28.984375
158
0.631318
false
false
false
false
chengxianghe/MissGe
refs/heads/master
MissGe/MissGe/Class/Project/Request/Home/MLHomeCommentListRequest.swift
mit
1
// // MLHomeCommentListRequest.swift // MissLi // // Created by chengxianghe on 16/7/23. // Copyright © 2016年 cn. All rights reserved. // import UIKit //http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=article&a=comlist&aid=7992&pg=1&size=20 class MLHomeCommentListRequest: MLBaseRequest { var page = 1 var aid = "" override func requestParameters() -> [String : Any]? { let dict = ["c":"article","a":"comlist","aid":"\(aid)","pg":"\(page)","size":"20"] return dict } override func requestHandleResult() { print("requestHandleResult -- \(self.classForCoder)") } }
4b04437eece19b8a72c316076a3d7983
25.777778
174
0.647303
false
false
false
false
WXYC/wxyc-ios-64
refs/heads/master
iOS/RootPageViewController.swift
mit
1
import UIKit import Core final class RootPageViewController: UIPageViewController { let nowPlayingViewController = PlaylistViewController(style: .grouped) let infoDetailViewController = InfoDetailViewController() var pages: [UIViewController] { return [ nowPlayingViewController, infoDetailViewController ] } // MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() self.setUpBackground() self.setUpPages() } private func setUpBackground() { let backgroundImageView = UIImageView(image: #imageLiteral(resourceName: "background")) backgroundImageView.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(backgroundImageView, at: 0) view.leadingAnchor.constraint(equalTo: backgroundImageView.leadingAnchor).isActive = true view.trailingAnchor.constraint(equalTo: backgroundImageView.trailingAnchor).isActive = true view.topAnchor.constraint(equalTo: backgroundImageView.topAnchor).isActive = true view.bottomAnchor.constraint(equalTo: backgroundImageView.bottomAnchor).isActive = true } private func setUpPages() { self.dataSource = self self.setViewControllers( [nowPlayingViewController], direction: .forward, animated: false, completion: nil ) } // MARK - Customization override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() viewControllers?.forEach({ $0.viewWillLayoutSubviews() }) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() viewControllers?.forEach({ $0.viewDidLayoutSubviews() }) } } extension RootPageViewController: UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { switch viewController { case nowPlayingViewController: return nil case infoDetailViewController: return nowPlayingViewController default: fatalError() } } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { switch viewController { case nowPlayingViewController: return infoDetailViewController case infoDetailViewController: return nil default: fatalError() } } func presentationCount(for pageViewController: UIPageViewController) -> Int { return self.pages.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { return 0 } }
0a008863ccb44575551766a9f134c958
30.4375
149
0.665341
false
false
false
false
proxpero/Endgame
refs/heads/master
Tests/PositionTests.swift
mit
1
// // PositionTests.swift // Endgame // // Created by Todd Olsen on 9/21/16. // // import XCTest @testable import Endgame class PositionTests: XCTestCase { let sampleFens = [ "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", "1k1r4/pp1b1R2/3q2pp/4p3/2B5/4Q3/PPP2B2/2K5 b - - 0 1", "r1b1k3/p2p1Nr1/n2b3p/3pp1pP/2BB1p2/P3P2R/Q1P3P1/R3K1N1 b Qq - 0 1", "r1b1k2r/pp1n1ppp/2p1p3/q5B1/1b1P4/P1n1PN2/1P1Q1PPP/2R1KB1R b Kkq - 3 10", "5rk1/p5pp/2p3p1/1p1pR3/3P2P1/2N5/PP3n2/2KB4 w - - 1 26", "rnbq1rk1/ppp3pp/3bpn2/3p1p2/2PP4/2NBPN2/PP3PPP/R1BQK2R w KQ - 3 7", "8/5R2/8/r2KB3/6k1/8/8/8 w - - 19 79", "rnbqkbnr/pppppp2/7p/6pP/8/8/PPPPPPP1/RNBQKBNR w KQkq g6 0 3", "rnbqkbnr/pp1ppppp/8/8/2pP4/2P2N2/PP2PPPP/RNBQKB1R b KQkq d3 0 3", "rnbqkbnr/pp1ppppp/2p5/8/6P1/2P5/PP1PPP1P/RNBQKBNR b KQkq - 0 1", "rnb1kbnr/ppq1pppp/2pp4/8/6P1/2P5/PP1PPPBP/RNBQK1NR w KQkq - 0 1", "rn2kbnr/p1q1ppp1/1ppp3p/8/4B1b1/2P4P/PPQPPP2/RNB1K1NR w KQkq - 0 1", "rnkq1bnr/p3ppp1/1ppp3p/3B4/6b1/2PQ3P/PP1PPP2/RNB1K1NR w KQ - 0 1", "rn1q1bnr/3kppp1/2pp3p/pp6/1P2b3/2PQ1N1P/P2PPPB1/RNB1K2R w KQ - 0 1", "rnkq1bnr/4pp2/2pQ2pp/pp6/1P5N/2P4P/P2PPP2/RNB1KB1b w Q - 0 1", "rn3b1r/1kq1p3/2pQ1npp/Pp6/4b3/2PPP2P/P4P2/RNB1KB2 w Q - 0 1", "r4br1/8/k1p2npp/Ppn1p3/P7/2PPP1qP/4bPQ1/RNB1KB2 w Q - 0 1", "rnbqk1nr/p2p3p/1p5b/2pPppp1/8/P7/1PPQPPPP/RNB1KBNR w KQkq c6 0 1", "rnb1k2r/pp1p1p1p/1q1P4/2pnpPp1/6P1/2N5/PP1BP2P/R2QKBNR w KQkq e6 0 1", "1n4kr/2B4p/2nb2b1/ppp5/P1PpP3/3P4/5K2/1N1R4 b - c3 0 1", "r2n3r/1bNk2pp/6P1/pP3p2/3pPqnP/1P1P1p1R/2P3B1/Q1B1bKN1 b - e3 0 1" ] func testInitialization() { for fen in sampleFens { let p = try? Position(fen: fen) XCTAssertNotNil(p) } } func testEquality() { XCTAssertEqual(Position(), Position()) } func testFen() { for fen in sampleFens { let p = try? Position(fen: fen) XCTAssertEqual(p!.fen, fen) } } func testMoveForSanMove() { /* +-----------------+ 8 | . . b k . . . r | 7 | N . . . N P P . | 6 | . . . . . . . . | 5 | . . . . . p P . | 4 | . . . . p . . . | 3 | P . . P . . . . | 2 | . P P . . . . . | 1 | R . . . K . . R | +-----------------+ a b c d e f g h */ let fen = "2bk3r/N3NPP1/8/5pP1/4p3/P2P4/1PP5/R3K2R w KQkq f6 0 1" let position = try? Position(fen: fen) XCTAssertNotNil(position) let moves: [(String, Move, Piece?)] = [ // ("Ra2", Move(.a1, .a2), nil), // regular ("gxf6", Move(.g5, .f6), nil), // en passant ("Kd2", Move(.e1, .d2), nil), // regular ("a4", Move(.a3, .a4), nil), // pawn push ("b4", Move(.b2, .b4), nil), // double pawn push ("dxe4", Move(.d3, .e4), nil), // pawn capture ("O-O-O", Move(.e1, .c1), nil), // Castle queenside ("O-O", Move(.e1, .g1), nil), // Castle kingside ("Nec6", Move(.e7, .c6), nil), // disambiguated move ("Nexc8", Move(.e7, .c8), nil), // disambiguated capture ("f8=Q+", Move(.f7, .f8), Piece(queen: .white)), // pawn promotion ("gxh8=N", Move(.g7, .h8), Piece(knight: .white)) // pawn capture + promotion ] for (san, move, promotion) in moves { let result = try? position!.move(for: san) XCTAssertNotNil(result, "San: \(san) returned nil.") XCTAssertEqual(move, result!.0) XCTAssertEqual(promotion, result!.1) } let nils: [(String, Move)] = [ ("Rg2", Move(.h1, .g2)) ] for (san, _) in nils { let result = try? position!.move(for: san) XCTAssertNil(result, "san: \(san) should have returned nil. returned: \(result!)") } } } class MoveLegality: XCTestCase { func testPawnPushes() { /* +-----------------+ 8 | r n b q k b n r | 7 | p p p p p p p p | 6 | . . . . . . . . | 5 | . . . . . . . . | 4 | . . . . . . . . | 3 | . . . . . . . . | 2 | P P P P P P P P | 1 | R N B Q K B N R | +-----------------+ a b c d e f g h */ let p = Position() XCTAssertEqual(p.legalTargetSquares(from: .d2), [.d3, .d4]) } func testPawnCaptures() { /* +-----------------+ 8 | k . . . . . . . | 7 | . . . . . . . . | 6 | . . . . p . . . | 5 | . . . P . . . . | 4 | . . . . . . . . | 3 | . . . . . . . . | 2 | . . . . . . . . | 1 | . . . . . . . K | +-----------------+ a b c d e f g h */ let p = try? Position(fen: "k7/8/4p3/3P4/8/8/8/7K w - - 0 1") XCTAssertEqual(p!.legalTargetSquares(from: .d5), [.d6, .e6]) } func testEnPassant() { /* +-----------------+ 8 | k . . . . . . . | 7 | . . . . . . . . | 6 | . . . . . . . . | 5 | . . p P . . . . | 4 | . . . . . . . . | 3 | . . . . . . . . | 2 | . . . . . . . . | 1 | . . . . . . . K | +-----------------+ a b c d e f g h */ let p = try! Position(fen: "k7/8/8/2pP4/8/8/8/7K w - c6 0 1") XCTAssertEqual(p.legalTargetSquares(from: .d5), [.c6, .d6]) } func testKnightMoves() { /* +-----------------+ 8 | k . . . . . . . | 7 | . . . . . . . . | 6 | . . . . . . . . | 5 | . . . . . . . . | 4 | . . . q . . . . | 3 | . N . . . . . . | 2 | . . . . . . . . | 1 | . . K . . . . . | +-----------------+ a b c d e f g h */ let p = try! Position(fen: "k7/8/8/8/3q5/1N6/8/2K5 w - - 0 1") XCTAssertEqual(p.legalTargetSquares(from: .b3), [.a1, .d2, .d4, .a5, .c5]) } func testBishopMoves() { /* +-----------------+ 8 | k . . . . . . . | 7 | . . . . . . . . | 6 | . . . r . . . . | 5 | . . B . . . . . | 4 | . . . . . . . . | 3 | . . . . P . . . | 2 | . . . . . . . . | 1 | . . . . . . . K | +-----------------+ a b c d e f g h */ let p = try! Position(fen: "k7/8/3r4/2B5/8/4P3/8/7K w - - 0 1") XCTAssertEqual(p.legalTargetSquares(from: .c5), [.a3, .b4, .d4, .b6, .d6, .a7]) } // func testRookMoves() { // /* // // */ // let p = Position(fen: "")! // XCTAssertEqual(p._legalTargetSquares(from: <#T##Square#>), []) // } // func testQueenMoves() { // /* // // */ // let p = Position(fen: "")! // XCTAssertEqual(p._legalTargetSquares(from: <#T##Square#>), []) // } func testKingMoves() { /* +-----------------+ 8 | k . . . . r . . | 7 | . . . . . . . . | 6 | . . . . . . . . | 5 | . . . . . . . . | 4 | . . . . . . . . | 3 | . . . . n . . . | 2 | . . . . . . p . | 1 | . . . . . . K . | +-----------------+ a b c d e f g h */ let p = try! Position(fen: "k4r2/8/8/8/8/4n3/6p1/6K1 w - - 0 1") XCTAssertEqual(p.legalTargetSquares(from: .g1), [.h2]) XCTAssertFalse(p.isKingInCheck) } func testKingInCheck() { /* +-----------------+ 8 | k . . . . r . . | 7 | . . . . . . . . | 6 | . . . . . . . . | 5 | . . . . . . . . | 4 | . . . . . . . . | 3 | . . . . n . . . | 2 | R . . . . . . p | 1 | . . . . . . K . | +-----------------+ a b c d e f g h */ let p = try! Position(fen: "k4r2/8/8/8/8/4n3/R6p/6K1 w - - 0 1") XCTAssertEqual(p.legalTargetSquares(from: .g1), [.h1, .h2]) XCTAssertEqual(p.legalTargetSquares(from: .a2), [.h2]) XCTAssertTrue(p.isKingInCheck) XCTAssertFalse(p.isKingInMultipleCheck) } func testKingInMultipleCheck() { /* +-----------------+ 8 | k . . . . r . . | 7 | . . . . . . . . | 6 | . . . . . . . . | 5 | . . . . . . . . | 4 | . . . . . . . . | 3 | . . . . . n . . | 2 | R . . . . . . p | 1 | . . . . . . K . | +-----------------+ a b c d e f g h */ let p = try! Position(fen: "k4r2/8/8/8/8/5n2/R6p/6K1 w - - 0 1") XCTAssertEqual(p.legalTargetSquares(from: .g1), [.f1, .h1, .f2, .g2]) XCTAssertEqual(p.legalTargetSquares(from: .a2), []) XCTAssertTrue(p.isKingInCheck) XCTAssertTrue(p.isKingInMultipleCheck) } func testDiscoveredSelfCheck() { /* +-----------------+ 8 | k . . . . . r . | 7 | . . . . . . . . | 6 | . . . . . . . . | 5 | . . . . . . . . | 4 | . . . . . . N . | 3 | . . . . . . . . | 2 | . . . . . . . . | 1 | . . . . . . K . | +-----------------+ a b c d e f g h */ let p = try! Position(fen: "k5r1/8/8/8/6N1/8/8/6K1 w - - 0 1") XCTAssertEqual(p.legalTargetSquares(from: .g4), []) } func testBlockingCheck() { /* +-----------------+ 8 | k . . . . . r . | 7 | . . . . . . . . | 6 | . . . . . . . . | 5 | . . . . . . . . | 4 | . . . . . . . . | 3 | . . . . . . . . | 2 | . . . . . . . . | 1 | . . . B . . K . | +-----------------+ a b c d e f g h */ let p = try! Position(fen: "k5r1/8/8/8/8/8/8/3B2K1 w - - 0 1") XCTAssertEqual(p.legalTargetSquares(from: .d1), [.g4]) } func testRegularCastle() { /* +-----------------+ 8 | . . . . k . . . | 7 | . . . . . . . . | 6 | . . . . . . . . | 5 | . . . . . . . . | 4 | . . . . . . . . | 3 | . . . . . . . . | 2 | P P P P P P P P | 1 | R . . . K . . R | +-----------------+ a b c d e f g h */ let p = try! Position(fen: "4k3/8/8/8/8/8/PPPPPPPP/R3K2R w KQ - 0 1") XCTAssertEqual(p.legalTargetSquares(from: .e1), [.c1, .d1, .f1, .g1]) } func testCastlingAcrossObastacles() { /* +-----------------+ 8 | . . . . k . . . | 7 | . . . . . . . . | 6 | . . . . . . . . | 5 | . . . . . . . . | 4 | . . . . . . . . | 3 | . . . . . . . . | 2 | P P P P P P P P | 1 | R . . Q K . . R | +-----------------+ a b c d e f g h */ let p = try! Position(fen: "4k3/8/8/8/8/8/PPPPPPPP/R2QK2R w KQ - 0 1") XCTAssertEqual(p.legalTargetSquares(from: .e1), [.f1, .g1]) } func testCastleRights() { /* +-----------------+ 8 | . . . . k . . . | 7 | . . . . . . . . | 6 | . . . . . . . . | 5 | . . . . . . . . | 4 | . . . . . . . . | 3 | . . . . . . . . | 2 | P P P P P P P P | 1 | R . . . K . . R | +-----------------+ a b c d e f g h */ let p1 = try! Position(fen: "4k3/8/8/8/8/8/PPPPPPPP/R3K2R w K - 0 1") XCTAssertEqual(p1.legalTargetSquares(from: .e1), [.d1, .f1, .g1]) let p2 = try! Position(fen: "4k3/8/8/8/8/8/PPPPPPPP/R3K2R w Q - 0 1") XCTAssertEqual(p2.legalTargetSquares(from: .e1), [.c1, .d1, .f1]) } func testCastlingInCheck() { /* +-----------------+ 8 | . . . . k . . . | 7 | . . . . q . . . | 6 | . . . . . . . . | 5 | . . . . . . . . | 4 | . . . . . . . . | 3 | . . . . . . . . | 2 | P P P P . P P P | 1 | R . . . K . . R | +-----------------+ a b c d e f g h */ let p = try! Position(fen: "4k3/4q3/8/8/8/8/PPPP1PPP/R3K2R w KQ - 0 1") XCTAssertEqual(p.legalTargetSquares(from: .e1), [.d1, .f1]) } func testCastlingAcrossAttackedSquares() { /* +-----------------+ 8 | . . . . k . . . | 7 | . . . q . . . . | 6 | . . . . . . . . | 5 | . . . . . . . . | 4 | . . . . . . . . | 3 | . . . . . . . . | 2 | P P P . P P P P | 1 | R . . . K . . R | +-----------------+ a b c d e f g h */ let p = try! Position(fen: "4k3/3q4/8/8/8/8/PPP1PPPP/R3K2R w KQ - 0 1") XCTAssertEqual(p.legalTargetSquares(from: .e1), [.f1, .g1]) } } // let test1: Test = { // // /* // +-----------------+ // 8 | r n b q k b n r | // 7 | p p p p p p p p | // 6 | . . . . . . . . | // 5 | . . . . . . . . | // 4 | . . . . . . . . | // 3 | . . . . . . . . | // 2 | P P P P P P P P | // 1 | R N B Q K B N R | // +-----------------+ // a b c d e f g h // */ // // let p1 = Position() // // let sample1 = Test.Sample( // origin: .d2, // targets: [.d3, .d4] // ) // // let sample2 = Test.Sample( // origin: .b1, // targets: [.a3, .c3] // ) // // return Test(position: p1, samples: [sample1, sample2]) // }() // // let test2: Test = { // // /* // // +-----------------+ // 8 | k . . . . . . . | // 7 | . . . . . . b b | // 6 | . . . . . . . . | // 5 | . . . . . . . . | // 4 | . . . . . . . . | // 3 | . . . . . . . . | // 2 | P P . . . . . . | // 1 | K . . . . . . . | // +-----------------+ // a b c d e f g h // // */ // // let position = Position(fen: "k7/6bb/8/8/8/8/PP6/K7 w - - 0 1") // XCTAssertNotNil(position) // // let sample1 = Test.Sample( // origin: .a2, // targets: [.a3, .a4] // ) // // let sample2 = Test.Sample( // origin: .b2, // targets: [] // ) // // let sample3 = Test.Sample( // origin: .a1, // targets: [] // ) // // return Test(position: position!, samples: [sample1, sample2, sample3]) // // }() // // let test3: Test = { // // /* // // +-----------------+ // 8 | k . . . . . . . | // 7 | . . . . . . b b | // 6 | . . . . . . . . | // 5 | . . . . . . . . | // 4 | . . . . . . . . | // 3 | . . . . . N . . | // 2 | P . . . . . . . | // 1 | K . . . . . . . | // +-----------------+ // a b c d e f g h // // */ // // let position = Position(fen: "k7/6bb/8/8/8/5N3/P7/K7 w - - 0 1") // XCTAssertNotNil(position) // // let sample1 = Test.Sample( // origin: .a1, // targets: [] // ) // // let sample2 = Test.Sample( // origin: .a2, // targets: [] // ) // // let sample3 = Test.Sample( // origin: .f3, // targets: [.d4, .e5] // ) // // return Test(position: position!, samples: [sample1, sample2, sample3]) // // }() // // let test4: Test = { // // /* // // +-----------------+ // 8 | . . . . k . . . | // 7 | . . . . . . . . | // 6 | . . . . . . . . | // 5 | . . . . . . . . | // 4 | . . . . . . . . | // 3 | . . . . . . . . | // 2 | P P P P P P P P | // 1 | R . . . K . . R | // +-----------------+ // a b c d e f g h // // */ // // let position = Position(fen: "4k3/8/8/8/8/8/PPPPPPPP/R3K2R w KQkq - 0 1") // XCTAssertNotNil(position) // // // let sample1 = Test.Sample( // origin: .e1, // targets: [.c1, .d1, .f1, .g1] // ) // // return Test(position: position!, samples: [sample1]) // // }() // // let test5: Test = { // // /* // // +-----------------+ // 8 | . . . . k . . . | // 7 | . . . . . . . . | // 6 | . . . . . . . . | // 5 | . . . . . . . . | // 4 | . . . . . . . . | // 3 | . . . . . . . . | // 2 | P P P P P P P P | // 1 | R . . . K . . R | // +-----------------+ // a b c d e f g h // // */ // // let position = Position(fen: "4k3/8/8/8/8/8/PPPPPPPP/R3K2R w Qkq - 0 1") // XCTAssertNotNil(position) // // let sample1 = Test.Sample( // origin: .e1, // targets: [.c1, .d1, .f1] // ) // // return Test(position: position!, samples: [sample1]) // }() // // // // // let test90: Test = { // // /* // // +-----------------+ // 8 | . . . k . . . . | // 7 | . . . . . . . . | // 6 | . . . . . . . . | // 5 | . . . . . . . . | // 4 | . . . P p P p . | // 3 | . . . . . . . . | // 2 | P P P . P . P P | // 1 | . . . K . . . . | // +-----------------+ // a b c d e f g h // // */ // // let position = Position(fen: "3k4/8/8/8/3PpPp1/8/PPP1P1PP/3K4 b KQkq f3 0 1") // XCTAssertNotNil(position) // // let sample1 = Test.Sample( // origin: .g4, // targets: [.f3, .g3] // ) // // let sample2 = Test.Sample( // origin: .e4, // targets: [.e3, .f3] // ) // // return Test(position: position!, samples: [sample1, sample2]) // // }() // // test1.perform() // test2.perform() // test3.perform() // test4.perform() // test5.perform() // test6.perform() // // } // // struct ExecutionTest { // typealias Example = (move: Move, promotion: Piece?, expectedFen: String) // let position: Position // let trueExamples: [Example] // let falseExamples: [Example] // func perform() { // for example in trueExamples { // let item = position._execute(uncheckedMove: example.move, promotion: example.promotion) // XCTAssertNotNil(item) // XCTAssertEqual(example.expectedFen, item!.position.fen) // } // for example in falseExamples { // let item = position._execute(uncheckedMove: example.move, promotion: example.promotion) // XCTAssertNil(item) // } // } // } // // struct ItemConstructionTest { // let position: Position // let trueExecutions: [(move: Move, promotion: Piece?, expectedItem: HistoryItem)] // let falseExecutions: [(move: Move, promotion: Piece?)] // func perform() { // for execution in trueExecutions { // let result = position._execute(uncheckedMove: execution.move, promotion: execution.promotion) // XCTAssertNotNil(result) // XCTAssertEqual(result!, execution.expectedItem) // } // for execution in falseExecutions { // let result = position._execute(uncheckedMove: execution.move, promotion: execution.promotion) // XCTAssertNil(result) // } // } // } // // func testExecutability() { // // struct Test { // let position: Position // let trueMoves: [Move] // let falseMoves: [Move] // func perform() { // for move in trueMoves { // XCTAssertTrue(position._canExecute(move: move)) // } // // for move in falseMoves { // XCTAssertFalse(position._canExecute(move: move)) // } // } // } // // let test1: Test = { // // /* // +-----------------+ // 8 | r n b q k b n r | // 7 | p p p p p p p p | // 6 | . . . . . . . . | // 5 | . . . . . . . . | // 4 | . . . . . . . . | // 3 | . . . . . . . . | // 2 | P P P P P P P P | // 1 | R N B Q K B N R | // +-----------------+ // a b c d e f g h // */ // // let position = Position() // // let trueMoves = [ // Move(.d2, .d3), // Move(.d2, .d4), // Move(.g1, .f3) // ] // // let falseMoves = [ // Move(.d2, .d5), // Move(.d3, .d4) // ] // // return Test(position: position, trueMoves: trueMoves, falseMoves: falseMoves) // // }() // // let test2: Test = { // // /* // // +-----------------+ // 8 | k . . . . . . . | // 7 | . . . . . . b b | // 6 | . . . . . . . . | // 5 | . . . . . . . . | // 4 | . . . . . . . . | // 3 | . . . . . . . . | // 2 | P P . . . . . . | // 1 | K . . . . . . . | // +-----------------+ // a b c d e f g h // // */ // // let position = Position(fen: "k7/6bb/8/8/8/8/PP6/K7 w - - 0 1") // XCTAssertNotNil(position) // // let trueMoves = [ // Move(.a2, .a3), // Move(.a2, .a3) // ] // let falseMoves = [ // Move(.b2, .b3), // Move(.b2, .b4), // Move(.a1, .b1) // ] // // return Test( // position: position!, // trueMoves: trueMoves, // falseMoves: falseMoves // ) // }() // // let test3: Test = { // // /* // // +-----------------+ // 8 | . . . . k . . . | // 7 | . . . . . . . . | // 6 | . . . . . . . . | // 5 | . . . . . . . . | // 4 | . . . . . . . . | // 3 | . . . . . . . . | // 2 | P P P P P P P P | // 1 | R . . . K . . R | // +-----------------+ // a b c d e f g h // // */ // // let position = Position(fen: "4k3/8/8/8/8/8/PPPPPPPP/R3K2R w KQkq - 0 1") // XCTAssertNotNil(position) // // let trueMoves = [ // Move(.e1, .g1), // Move(.e1, .c1) // ] // // return Test(position: position!, trueMoves: trueMoves, falseMoves: []) // // }() // // let test4: Test = { // // /* // // +-----------------+ // 8 | . . . k . . . . | // 7 | . . . . . . . . | // 6 | . . . . . . . . | // 5 | . . . . . . . . | // 4 | . . . P p P p . | // 3 | . . . . . . . . | // 2 | P P P . P . P P | // 1 | . . . K . . . . | // +-----------------+ // a b c d e f g h // // */ // // let position = Position(fen: "3k4/8/8/8/3PpPp1/8/PPP1P1PP/3K4 b KQkq f3 0 1") // XCTAssertNotNil(position) // // let trueMoves = [ // Move(.e4, .f3), // Move(.g4, .f3) // ] // // let falseMoves = [ // Move(.e4, .d3), // Move(.e4, .e2) // ] // // return Test(position: position!, trueMoves: trueMoves, falseMoves: falseMoves) // // }() // // test1.perform() // test2.perform() // test3.perform() // test4.perform() // // } // // func testExecution() { // // struct Test { // // struct Sample { // let move: Move // let promotion: Piece? // let expectedFen: String? // } // // let position: Position // let trueSamples: [Sample] // let falseSamples: [Sample] // // func perform() { // // for sample in trueSamples { // let item = position._execute(uncheckedMove: sample.move, promotion: sample.promotion) // XCTAssertNotNil(item) // XCTAssertEqual(sample.expectedFen!, item!.position.fen) // } // // for sample in falseSamples { // let item = position._execute(uncheckedMove: sample.move, promotion: sample.promotion) // XCTAssertNil(item) // } // } // } // // let test1: Test = { // // /* // +-----------------+ // 8 | r n b q k b n r | // 7 | p p p p p p p p | // 6 | . . . . . . . . | // 5 | . . . . . . . . | // 4 | . . . . . . . . | // 3 | . . . . . . . . | // 2 | P P P P P P P P | // 1 | R N B Q K B N R | // +-----------------+ // a b c d e f g h // */ // // let position = Position() // // // MARK: A double pawn push produce an en passant square. // let true1 = Test.Sample( // move: Move(.e2, .e4), // promotion: nil, // expectedFen: "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1" // ) // // return Test( // position: position, // trueSamples: [true1], // falseSamples: [] // ) // // }() // // test1.perform() // // let test2: Test = { // // /* // // +-----------------+ // 8 | r . . . k . . r | // 7 | p p p p p p p p | // 6 | . . . . . . . . | // 5 | . . . . . . . . | // 4 | . . . . . . . . | // 3 | . . . . . . . . | // 2 | P P P P P P P P | // 1 | R . . . K . . R | // +-----------------+ // a b c d e f g h // // */ // // // let position = Position(fen: "r3k2r/pppppppp/8/8/8/8/PPPPPPPP/R3K2R w KQkq - 0 1") // XCTAssertNotNil(position) // // // MARK: A white queenside castle should also move the queenside rook. // let sample1 = Test.Sample( // move: Move(.e1, .c1), // promotion: nil, // expectedFen: "r3k2r/pppppppp/8/8/8/8/PPPPPPPP/2KR3R b kq - 1 1" // ) // // // MARK: A white kingside castle should also move the kingside rook. // let sample2 = Test.Sample( // move: Move(.e1, .g1), // promotion: nil, // expectedFen: "r3k2r/pppppppp/8/8/8/8/PPPPPPPP/R4RK1 b kq - 1 1" // ) // // return Test(position: position!, trueSamples: [sample1, sample2], falseSamples: []) // // }() // // let test3: Test = { // // /* // // +-----------------+ // 8 | r . . . k . . r | // 7 | p p p . p p p p | // 6 | . . . . . . . . | // 5 | . . . . . . . . | // 4 | . . . . . . . . | // 3 | . . . . . . . . | // 2 | P P P P P P P P | // 1 | R . . . K . . R | // +-----------------+ // a b c d e f g h // // */ // // // let position = Position(fen: "r3k2r/pppppppp/8/8/8/8/PPPPPPPP/R3K2R b KQkq - 0 1") // XCTAssertNotNil(position) // // // MARK: A black queenside castle should also move the queenside rook. // let true1 = Test.Sample( // move: Move(.e8, .c8), // promotion: nil, // expectedFen: "2kr3r/pppppppp/8/8/8/8/PPPPPPPP/R3K2R w KQ - 1 2" // ) // // // MARK: A black kingside castle should also move the kingside rook. // let true2 = Test.Sample( // move: Move(.e8, .g8), // promotion: nil, // expectedFen: "r4rk1/pppppppp/8/8/8/8/PPPPPPPP/R3K2R w KQ - 1 2" // ) // // return Test(position: position!, trueSamples: [true1, true2], falseSamples: []) // // }() // // let test4: Test = { // // /* // // +-----------------+ // 8 | r . . . k . . r | // 7 | p p p . p p p p | // 6 | . . . . . . . . | // 5 | . . . . . . . . | // 4 | B . . . . . . . | // 3 | . . . . . . . . | // 2 | P P P P P P P P | // 1 | R . . . K . . R | // +-----------------+ // a b c d e f g h // // */ // // // let position = Position(fen: "r3k2r/pppppppp/8/8/B7/8/PPPPPPPP/R3K2R b KQkq - 0 1") // XCTAssertNotNil(position) // // // MARK: King may not castle while in check // let false1 = Test.Sample( // move: Move(.e8, .c8), // promotion: nil, // expectedFen: nil // ) // // let false2 = Test.Sample( // move: Move(.e8, .g8), // promotion: nil, // expectedFen: nil // ) // // return Test(position: position!, trueSamples: [], falseSamples: [false1, false2]) // // }() // // let test5: Test = { // // /* // // +-----------------+ // 8 | r . . . k . . r | // 7 | p p p . p p p p | // 6 | . . . . . . . . | // 5 | . . . . . . . . | // 4 | . . . . . . . . | // 3 | . . . Q . . . . | // 2 | P P P P P P P P | // 1 | R . . . K . . R | // +-----------------+ // a b c d e f g h // // */ // // // let position = Position(fen: "r3k2r/ppp1pppp/8/8/8/3Q4/PPPPPPPP/R3K2R b KQq - 0 1") // XCTAssertNotNil(position) // // // MARK: King cannot castle across an attacked square. // let false1 = Test.Sample( // move: Move(.e8, .c8), // promotion: nil, // expectedFen: nil // ) // // // MARK: King may not castle without the having right to do so. // let false2 = Test.Sample( // move: Move(.e8, .g8), // promotion: nil, // expectedFen: nil // ) // // return Test(position: position!, trueSamples: [], falseSamples: [false1, false2]) // // }() // //// test1.perform() //// test2.perform() //// test3.perform() // test4.perform() //// test5.perform() // // } // // func testPerformanceExample() { // // This is an example of a performance test case. // self.measure { // // Put the code you want to measure the time of here. // } // } // //}
713622c934867f44f2bede5d3ff905da
29.480642
111
0.326931
false
true
false
false
jianghongbing/APIReferenceDemo
refs/heads/master
WebKit/WKUIDelegate/WKUIDelegate/WebViewController.swift
mit
1
// // WebViewController.swift // WKUIDelegate // // Created by pantosoft on 2018/12/14. // Copyright © 2018 jianghongbing. All rights reserved. // import UIKit import WebKit class WebViewController: UIViewController { private var previewElementInfo: WKPreviewElementInfo? @IBOutlet weak var webView: WKWebView! var loadHTMLFromLocal = false override func viewDidLoad() { super.viewDidLoad() setupWebView() navigationItem.rightBarButtonItem = UIBarButtonItem(title: "remove", style: .plain, target: self, action: #selector(removeWebView(barButtonItem:))) } @objc private func removeWebView(barButtonItem: UIBarButtonItem) { if(webView.superview != nil) { webView.removeFromSuperview() } } private func setupWebView() { webView.uiDelegate = self webView.allowsLinkPreview = true if loadHTMLFromLocal { let path = Bundle.main.path(forResource: "index", ofType: "html") let url = URL(fileURLWithPath: path!) webView.loadFileURL(url, allowingReadAccessTo: url) }else { let url = URL(string: "https://www.baidu.com") let request = URLRequest(url: url!) webView.load(request) } } } extension WebViewController: WKUIDelegate { //当在js中执行window.open方法时,该方法会被触发 func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { print(#function, #line, navigationAction, windowFeatures) webView.load(navigationAction.request) return nil // let webView = WKWebView(frame: self.view.bounds, configuration: configuration) // return webView } //当js中执行window.close方法时,也就是关闭当前窗口的时候,该方法会被触发 func webViewDidClose(_ webView: WKWebView) { print(#function, #line); navigationController?.popViewController(animated: true) } //webView通过js执行alert时,该方法会被回调. webView通过js执行alert时,默认是不会显示在webView上的,通过通过拦截该方法加一个原生的alert func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { print(#function, #line, message, frame) webViewAlert(with: nil, message: message, completionHandler: completionHandler) } //webView通过js执行comfirm方法时,该方法会被回调 func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { print(#function, #line, message, frame) webViewConfirm(with: nil, message: message, completionHandler: completionHandler) } //webView通过js执行prompt时,该方法会被回调 func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { print(#function, #line, prompt, defaultText ?? "", frame) webViewInput(with: nil, message: prompt, defaultText: defaultText, completionHandler: completionHandler) } //是否允许预览链接的内容 func webView(_ webView: WKWebView, shouldPreviewElement elementInfo: WKPreviewElementInfo) -> Bool { print(#function, #line, elementInfo) self.previewElementInfo = elementInfo return true } //提供一个controller来预览内容 func webView(_ webView: WKWebView, previewingViewControllerForElement elementInfo: WKPreviewElementInfo, defaultActions previewActions: [WKPreviewActionItem]) -> UIViewController? { print(#function, #line, elementInfo, previewActions) var viewController: UIViewController? = nil if let url = elementInfo.linkURL { viewController = PreviewViewController(url: url) } return viewController } //提交预览的时候,会被回调 func webView(_ webView: WKWebView, commitPreviewingViewController previewingViewController: UIViewController) { print(#function, #line, previewingViewController) self.navigationController?.pushViewController(previewingViewController, animated: true) } } extension UIViewController { func webViewAlert(with title:String?, message: String?, completionHandler: @escaping () -> Void ) { let alertViewController = UIAlertController(title: title, message: message, preferredStyle: .alert) let action = UIAlertAction(title: "确定", style: .default) { _ in completionHandler() } alertViewController.addAction(action) present(alertViewController, animated: true, completion: nil) } func webViewConfirm(with title: String?, message: String?, completionHandler: @escaping (Bool) -> Void) { let alertViewController = UIAlertController(title: title, message: message, preferredStyle: .alert) let cancelAction = UIAlertAction(title: "取消", style: .default) { _ in completionHandler(false) } let confirmAction = UIAlertAction(title: "确定", style: .default) { _ in completionHandler(true) } alertViewController.addAction(cancelAction) alertViewController.addAction(confirmAction) present(alertViewController, animated: true, completion: nil) } func webViewInput(with title: String?, message: String?, defaultText: String?, completionHandler: @escaping (String?) -> Void) { let alertViewController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertViewController.addTextField(configurationHandler: nil) let textField = alertViewController.textFields?.first textField?.text = defaultText let cancelAction = UIAlertAction(title: "取消", style: .default) { _ in completionHandler(nil) } let confirmAction = UIAlertAction(title: "确定", style: .default) { _ in print(textField?.text ?? "姓名输入为空") completionHandler(textField?.text) } alertViewController.addAction(cancelAction) alertViewController.addAction(confirmAction) present(alertViewController, animated: true, completion: nil) } }
f2a560a531702f076dffcb364a439b2b
42.475862
201
0.690197
false
false
false
false
0bin/Project-collection
refs/heads/master
项目swift/项目swift/BBBTabBarController.swift
mit
1
// // BBBTabBarController.swift // 项目swift // // Created by LinBin on 16/6/24. // Copyright © 2016年 LinBin. All rights reserved. // import UIKit class BBBTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() loadVCName() self.tabBar.tintColor = UIColor.orangeColor() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) addComposeButton() } /** 获取子控制器VC的名字string */ func loadVCName() { addChildVC("BBBOneViewController", title: "One", imageName: "tabbar_home", highlightedImageName: "tabbar_home_highlighted") addChildVC("BBBTwoViewController", title: "One", imageName: "tabbar_home", highlightedImageName: "tabbar_home_highlighted") addChildVC("BBBFiveViewController", title: "One", imageName: "tabbar_home", highlightedImageName: "tabbar_home_highlighted") addChildVC("BBBThreeController", title: "One", imageName: "tabbar_home", highlightedImageName: "tabbar_home_highlighted") addChildVC("BBBFourController", title: "One", imageName: "tabbar_home", highlightedImageName: "tabbar_home_highlighted") } /** 添加tabBar中间button */ private func addComposeButton() { let ComposeButton = UIButton() ComposeButton.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal) ComposeButton.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted) ComposeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal) ComposeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted) ComposeButton.addTarget(self, action: #selector(composeButtonClick), forControlEvents: UIControlEvents.TouchUpInside) let buttonW = UIScreen.mainScreen().bounds.size.width / CGFloat(viewControllers!.count) let buttonH = tabBar.bounds.size.height let buttonX = tabBar.bounds.size.width * 0.5 let buttonY = tabBar.bounds.size.height * 0.5 ComposeButton.frame = CGRectMake(0, 0, buttonW, buttonH) ComposeButton.center = CGPointMake(buttonX, buttonY) tabBar.addSubview(ComposeButton) } /** 中间button的点击方法 */ func composeButtonClick() { let fiveVC = BBBFiveViewController() self.presentViewController(fiveVC, animated: true, completion: nil) print(#function) } /** 传进字符串创建tabbar子控制器方法 - parameter childVC: 控制器 - parameter title: tabbarItem和navigation文字 - parameter imageName: tabbarItem图片名 - parameter highlightedImageName: tabbarItem高亮图片名 */ private func addChildVC(childVCName:String, title:String, imageName:String, highlightedImageName:String){ //将string 转成 UIViewController类 let bundleName = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String let className: AnyClass? = NSClassFromString(bundleName + "." + childVCName) print(className) let VCClass = className as! UIViewController.Type //通过类创建控制器 let childVC = VCClass.init() print(childVC) //设置页面 childVC.title = title childVC.tabBarItem.image = UIImage(named: imageName) childVC.tabBarItem.selectedImage = UIImage(named: highlightedImageName) //添加导航栏 let navVC = UINavigationController() navVC.addChildViewController(childVC) //添加到TabBarController self.addChildViewController(navVC) } }
8134bbcf8f857f213821310df03c9a4d
34.601852
132
0.656957
false
false
false
false
tskulbru/NBMaterialDialogIOS
refs/heads/master
Pod/Classes/NBMaterialAlertDialog.swift
mit
1
// // NBMaterialAlertDialog.swift // NBMaterialDialogIOS // // Created by Torstein Skulbru on 02/05/15. // Copyright (c) 2015 Torstein Skulbru. All rights reserved. // // The MIT License (MIT) // // Copyright (c) 2015 Torstein Skulbru // // 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. @objc open class NBMaterialAlertDialog : NBMaterialDialog { /** Displays an alert dialog with a simple text and buttons - parameter windowView: The window which the dialog is to be attached - parameter text: The main alert message - parameter okButtonTitle: The positive button if multiple buttons, or a dismiss action button if one button. Usually either OK or CANCEL (of only one button) - parameter action: The block you want to run when the user clicks any of the buttons. If no block is given, the standard dismiss action will be used - parameter cancelButtonTitle: The negative button when multiple buttons. */ @discardableResult open class func showAlertWithText(_ windowView: UIView, text: String, okButtonTitle: String?, action: ((_ isOtherButton: Bool) -> Void)?, cancelButtonTitle: String?) -> NBMaterialAlertDialog { return NBMaterialAlertDialog.showAlertWithTextAndTitle(windowView, text: text, title: nil, dialogHeight: nil, okButtonTitle: okButtonTitle, action: action, cancelButtonTitle: cancelButtonTitle) } /** Displays an alert dialog with a simple text, title and buttons. Remember to read Material guidelines on when to include a dialog title. - parameter windowView: The window which the dialog is to be attached - parameter text: The main alert message - parameter title: The title of the alert - parameter okButtonTitle: The positive button if multiple buttons, or a dismiss action button if one button. Usually either OK or CANCEL (of only one button) - parameter action: The block you want to run when the user clicks any of the buttons. If no block is given, the standard dismiss action will be used - parameter cancelButtonTitle: The negative button when multiple buttons. */ @discardableResult open class func showAlertWithTextAndTitle(_ windowView: UIView, text: String, title: String?, dialogHeight: CGFloat?, okButtonTitle: String?, action: ((_ isOtherButton: Bool) -> Void)?, cancelButtonTitle: String?) -> NBMaterialAlertDialog { let alertLabel = UILabel() alertLabel.numberOfLines = 0 alertLabel.font = UIFont.robotoRegularOfSize(14) alertLabel.textColor = NBConfig.PrimaryTextDark alertLabel.text = text alertLabel.sizeToFit() let dialog = NBMaterialAlertDialog() return dialog.showDialog(windowView, title: title, content: alertLabel, dialogHeight: dialogHeight ?? dialog.kMinimumHeight, okButtonTitle: okButtonTitle, action: action, cancelButtonTitle: cancelButtonTitle) } }
a99c778b721a5e67a72a447f2209200c
55.507246
244
0.748397
false
false
false
false
njdehoog/swift-hoedown
refs/heads/master
source/Hoedown.swift
mit
1
// // Markdown.swift // MarkPub // // Created by Niels de Hoog on 17/04/15. // Copyright (c) 2015 Invisible Pixel. All rights reserved. // import Foundation import Hoedown public final class Hoedown { public class func renderHTMLForMarkdown(_ string: String, flags: HoedownHTMLFlags = .None, extensions: HoedownExtensions = .None) -> String? { let renderer = HoedownHTMLRenderer(flags: flags) let document = HoedownDocument(renderer: renderer, extensions: extensions) return document.renderMarkdown(string) } } public protocol HoedownRenderer { var internalRenderer: UnsafeMutablePointer<hoedown_renderer> { get } } open class HoedownHTMLRenderer: HoedownRenderer { open let internalRenderer: UnsafeMutablePointer<hoedown_renderer> public init(flags: HoedownHTMLFlags = .None, nestingLevel: Int = 0) { self.internalRenderer = hoedown_html_renderer_new(hoedown_html_flags(flags.rawValue), CInt(nestingLevel)) } deinit { hoedown_html_renderer_free(self.internalRenderer) } } open class HoedownDocument { let internalDocument: OpaquePointer public init(renderer: HoedownRenderer, extensions: HoedownExtensions = .None, maxNesting: UInt = 16) { self.internalDocument = hoedown_document_new(renderer.internalRenderer, hoedown_extensions(extensions.rawValue), Int(maxNesting)) } open func renderMarkdown(_ string: String, bufferSize: UInt = 16) -> String? { let buffer = hoedown_buffer_new(Int(bufferSize)) hoedown_document_render(self.internalDocument, buffer, string, string.utf8.count); guard let htmlOutput = hoedown_buffer_cstr(buffer) else { return nil } let output = String(cString: htmlOutput) hoedown_buffer_free(buffer) return output } deinit { hoedown_document_free(self.internalDocument) } } public struct HoedownExtensions : OptionSet { public let rawValue: UInt32 public init(rawValue: UInt32) { self.rawValue = rawValue } init(_ value: hoedown_extensions) { self.rawValue = value.rawValue } public static let None = HoedownExtensions(rawValue: 0) // Block-level extensions public static let Tables = HoedownExtensions(HOEDOWN_EXT_TABLES) public static let FencedCodeBlocks = HoedownExtensions(HOEDOWN_EXT_FENCED_CODE) public static let FootNotes = HoedownExtensions(HOEDOWN_EXT_FOOTNOTES) // Span-level extensions public static let AutoLinkURLs = HoedownExtensions(HOEDOWN_EXT_AUTOLINK) public static let StrikeThrough = HoedownExtensions(HOEDOWN_EXT_STRIKETHROUGH) public static let Underline = HoedownExtensions(HOEDOWN_EXT_UNDERLINE) public static let Highlight = HoedownExtensions(HOEDOWN_EXT_HIGHLIGHT) public static let Quote = HoedownExtensions(HOEDOWN_EXT_QUOTE) public static let Superscript = HoedownExtensions(HOEDOWN_EXT_SUPERSCRIPT) public static let Math = HoedownExtensions(HOEDOWN_EXT_MATH) // Other flags public static let NoIntraEmphasis = HoedownExtensions(HOEDOWN_EXT_NO_INTRA_EMPHASIS) public static let SpaceHeaders = HoedownExtensions(HOEDOWN_EXT_SPACE_HEADERS) public static let MathExplicit = HoedownExtensions(HOEDOWN_EXT_MATH_EXPLICIT) // Negative flags public static let DisableIndentedCode = HoedownExtensions(HOEDOWN_EXT_DISABLE_INDENTED_CODE) } public struct HoedownHTMLFlags : OptionSet { public let rawValue: UInt32 public init(rawValue: UInt32) { self.rawValue = rawValue } init(_ value: hoedown_html_flags) { self.rawValue = value.rawValue } public static let None = HoedownHTMLFlags(rawValue: 0) public static let SkipHTML = HoedownHTMLFlags(HOEDOWN_HTML_SKIP_HTML) public static let Escape = HoedownHTMLFlags(HOEDOWN_HTML_ESCAPE) public static let HardWrap = HoedownHTMLFlags(HOEDOWN_HTML_HARD_WRAP) public static let UseXHTML = HoedownHTMLFlags(HOEDOWN_HTML_USE_XHTML) }
554a20769fec9a33d5867de56cdfc3ce
38.96
146
0.728228
false
false
false
false
phxlle/CircularCollectionView
refs/heads/master
Example/Pods/CircularCollectionView/CircularCollectionView/CircularCollectionViewLayout.swift
mit
1
// // CircularCollectionViewLayout.swift // // Created by Philippe Asselbergh on 13/09/2017. // Copyright © 2017 Philippe Asselbergh. All rights reserved. // import UIKit public class CircularCollectionViewLayout: UICollectionViewLayout { public var itemSize : CGSize { if let collectionView = collectionView{ let numOfItems = CGFloat(collectionView.numberOfItems(inSection: 0)) let w = numOfItems * 150 < collectionView.bounds.width ? ((collectionView.bounds.width+15)/numOfItems) : 150 return CGSize(width: w, height: 150) } return CGSize(width: 150, height: 150) } public var angleAtExtreme: CGFloat { return collectionView!.numberOfItems(inSection: 0) > 0 ? -CGFloat(collectionView!.numberOfItems(inSection: 0)-1)*anglePerItem : 0 } public var angle: CGFloat { let collAngle = angleAtExtreme*collectionView!.contentOffset.x/(collectionViewContentSize.width - ((collectionView?.bounds.width)!)) //print(collAngle) return collAngle } public var radius: CGFloat = 500 { didSet { invalidateLayout() } } public var anglePerItem: CGFloat { return atan(itemSize.width/(radius)) } public var attributesList = [CircularCollectionViewLayoutAttributes]() override public var collectionViewContentSize: CGSize{ return CGSize(width: CGFloat(collectionView!.numberOfItems(inSection: 0))*itemSize.width, height: collectionView!.bounds.height) } override public class var layoutAttributesClass: AnyClass { return CircularCollectionViewLayoutAttributes.self } override public func prepare() { super.prepare() let centerX = collectionView!.contentOffset.x + (collectionView!.bounds.width/2.0) let anchorPointY = ((itemSize.height/2.0) + radius)/itemSize.height //1 let theta = atan2(collectionViewContentSize.width/2.0, radius + (itemSize.height/2.0) - (collectionView!.bounds.height/2.0)) //1//collectionView!.bounds.width //2 var startIndex = 0 var endIndex = collectionView!.numberOfItems(inSection: 0) - 1 //3 if (angle < -theta) { startIndex = Int(floor((-theta - angle)/anglePerItem)) } //4 endIndex = min(endIndex, Int(ceil((theta - angle)/anglePerItem))) //5 if (endIndex < startIndex) { endIndex = 0 startIndex = 0 } attributesList = (startIndex...endIndex).map { (i) -> CircularCollectionViewLayoutAttributes in let attributes = CircularCollectionViewLayoutAttributes(forCellWith: NSIndexPath(item: i, section: 0) as IndexPath) attributes.size = self.itemSize attributes.center = CGPoint(x: centerX, y: self.collectionView!.bounds.midY) attributes.angle = self.angle + (self.anglePerItem*CGFloat(i)) attributes.anchorPoint = CGPoint(x: 0.5, y: anchorPointY) return attributes } } override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return attributesList } override public func layoutAttributesForItem(at indexPath: IndexPath) -> (UICollectionViewLayoutAttributes!) { return attributesList[indexPath.row] } override public func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override public func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { var finalContentOffset = proposedContentOffset let factor = -angleAtExtreme/((collectionView?.contentSize.width)! - (collectionView?.bounds.width)!) //(collectionView?.bounds.width)!) let proposedAngle = proposedContentOffset.x*factor let ratio = proposedAngle/anglePerItem var multiplier: CGFloat if (velocity.x > 0) { multiplier = ceil(ratio) } else if (velocity.x < 0) { multiplier = floor(ratio) } else { multiplier = round(ratio) } finalContentOffset.x = multiplier*anglePerItem/factor return finalContentOffset } }
6e81be189ea8089e564556f63bc13ee6
37.80531
166
0.650627
false
false
false
false
andersio/MantleData
refs/heads/master
MantleData/ManagedObjectContext+Extension.swift
mit
1
// // ManagedContext+Extension.swift // MantleData // // Created by Anders on 11/10/2015. // Copyright © 2015 Anders. All rights reserved. // import Foundation import CoreData import ReactiveSwift import ReactiveCocoa @nonobjc let batchRequestResultIDArrayKey = Notification.Name(rawValue: "MDResultIDs") extension Notification.Name { @nonobjc public static let objectContextWillMergeChanges = Notification.Name(rawValue: "MDContextWillMergeChangesNotification") @nonobjc static let didBatchUpdate = Notification.Name(rawValue: "MDDidBatchUpdate") @nonobjc static let willBatchDelete = Notification.Name(rawValue: "MDWillBatchDelete") @nonobjc static let didBatchDelete = Notification.Name(rawValue: "MDDidBatchDelete") } extension NSManagedObjectContext { /// Enqueue a block to the context. public func async(_ block: @escaping () -> Void) { perform(block) } /// Execute a block on the context, and propagate the returned result. /// - Important: The call is pre-emptive and jumps the context's internal queue. public func sync<Result>(_ block: () -> Result) -> Result { var returnResult: Result! performBlockAndWaitNoEscape { returnResult = block() } return returnResult } } extension Reactive where Base: NSManagedObjectContext { public func objects<E: NSManagedObject>(_ type: E.Type) -> ObjectQuery<E> { return ObjectQuery(in: base) } public func fetch<E: NSManagedObject>(_ id: ManagedObjectID<E>, in context: NSManagedObjectContext) throws -> E { return try context.existingObject(with: id.id) as! E } @discardableResult public func observeSavedChanges(from other: NSManagedObjectContext) -> Disposable? { return NotificationCenter.default.reactive .notifications(forName: .NSManagedObjectContextDidSave, object: other) .take(until: lifetime.ended.zip(with: other.reactive.lifetime.ended).map { _ in }) .observeValues(handleExternalChanges(_:)) } @discardableResult public func observeBatchChanges(from other: NSManagedObjectContext) -> Disposable { let disposable = CompositeDisposable() let defaultCenter = NotificationCenter.default disposable += defaultCenter.reactive .notifications(forName: .didBatchUpdate, object: other) .take(until: lifetime.ended.zip(with: other.reactive.lifetime.ended).map { _ in }) .observeValues(handleExternalBatchUpdate(_:)) disposable += defaultCenter.reactive .notifications(forName: .willBatchDelete, object: other) .take(until: lifetime.ended.zip(with: other.reactive.lifetime.ended).map { _ in }) .observeValues(preprocessBatchDelete(_:)) return disposable } /// Batch update objects, and update other contexts asynchronously. public func batchUpdate(_ request: NSBatchUpdateRequest) throws { request.resultType = .updatedObjectIDsResultType guard let requestResult = try base.execute(request) as? NSBatchUpdateResult else { fatalError("StoreCoordinator.performBatchRequest: Cannot obtain the result object from the object context.") } guard let objectIDs = requestResult.result as? [NSManagedObjectID] else { fatalError("StoreCoordinator.performBatchRequest: Cannot obtain the result ID array for a batch update request.") } updateObjectsWith(objectIDs) NotificationCenter.default .post(name: .didBatchUpdate, object: base, userInfo: [batchRequestResultIDArrayKey: objectIDs]) } /// Batch delete objects, and update other contexts asynchronously. @available(iOS 9.0, macOS 10.11, *) public func batchDelete(_ request: NSBatchDeleteRequest) throws { let IDRequest = request.fetchRequest.copy() as! NSFetchRequest<NSManagedObjectID> IDRequest.resultType = .managedObjectIDResultType IDRequest.includesPropertyValues = false IDRequest.includesPendingChanges = false guard let affectingObjectIDs = try? base.fetch(IDRequest) else { fatalError("StoreCoordinator.performBatchRequest: Cannot obtain the affecting ID array for a batch delete request.") } deleteObjects(with: affectingObjectIDs) NotificationCenter.default .post(name: .willBatchDelete, object: base, userInfo: [batchRequestResultIDArrayKey: affectingObjectIDs]) request.resultType = .resultTypeCount guard let requestResult = try base.execute(request) as? NSBatchDeleteResult else { fatalError("StoreCoordinator.performBatchRequest: Cannot obtain the result object from the object context.") } guard let count = requestResult.result as? NSNumber else { fatalError("StoreCoordinator.performBatchRequest: Cannot obtain the result count for a batch delete request.") } precondition(count.intValue == affectingObjectIDs.count) NotificationCenter.default .post(name: .didBatchDelete, object: base, userInfo: [batchRequestResultIDArrayKey: affectingObjectIDs]) } private func deleteObjects(with resultIDs: [NSManagedObjectID]) { for ID in resultIDs { base.delete(base.object(with: ID)) } base.processPendingChanges() } private func updateObjectsWith(_ resultIDs: [NSManagedObjectID]) { // Force the context to discard the cached data. // breaks infinite staleness guarantee?? let objects = resultIDs.flatMap { base.registeredObject(for: $0) } NotificationCenter.default .post(name: .objectContextWillMergeChanges, object: base, userInfo: nil) let previousInterval = base.stalenessInterval base.stalenessInterval = 0 objects.forEach { base.refresh($0, mergeChanges: true) } base.stalenessInterval = previousInterval } private func isSourcedFromIdenticalPersistentStoreCoordinator(as other: NSManagedObjectContext, localCoordinator: inout NSPersistentStoreCoordinator?) -> Bool { guard other !== base else { return true } var _baseCoordinator = base.persistentStoreCoordinator var iterator = Optional(base as NSManagedObjectContext) while _baseCoordinator == nil && iterator?.parent != nil { iterator = iterator!.parent _baseCoordinator = iterator?.persistentStoreCoordinator } guard let baseCoordinator = _baseCoordinator else { preconditionFailure("The tree of contexts have no persistent store coordinator presented at the root.") } var _remoteCoordinator = base.persistentStoreCoordinator iterator = Optional(other) while _remoteCoordinator == nil && iterator?.parent != nil { iterator = iterator!.parent _remoteCoordinator = iterator?.persistentStoreCoordinator } guard let remoteCoordinator = _remoteCoordinator else { preconditionFailure("The tree of contexts have no persistent store coordinator presented at the root.") } localCoordinator = baseCoordinator return remoteCoordinator === baseCoordinator } private func isSiblingOf(_ other: NSManagedObjectContext) -> Bool { if other !== base { // Fast Paths if let persistentStoreCoordinator = base.persistentStoreCoordinator, persistentStoreCoordinator == other.persistentStoreCoordinator { return true } if let parentContext = base.parent, parentContext == other.parent { return true } // Slow Path var myPSC = base.persistentStoreCoordinator var otherPSC = other.persistentStoreCoordinator var myContext: NSManagedObjectContext = base var otherContext: NSManagedObjectContext = other while let parent = myContext.parent { myContext = parent myPSC = myContext.persistentStoreCoordinator } while let parent = otherContext.parent { otherContext = parent otherPSC = otherContext.persistentStoreCoordinator } if myPSC == otherPSC { return true } } return false } public func handleExternalChanges(_ notification: Notification) { guard let userInfo = (notification as NSNotification).userInfo else { return } let context = notification.object as! NSManagedObjectContext var localCoordinator: NSPersistentStoreCoordinator? let hasIdenticalSource = isSourcedFromIdenticalPersistentStoreCoordinator(as: context, localCoordinator: &localCoordinator) base.sync { NotificationCenter.default .post(name: .objectContextWillMergeChanges, object: base, userInfo: nil) if #available(iOS 9.0, macOS 10.11, *), !hasIdenticalSource { NSManagedObjectContext.mergeChanges(fromRemoteContextSave: userInfo, into: [base]) } else { base.mergeChanges(fromContextDidSave: notification) } } } private func preprocessBatchDelete(_ notification: Notification) { base.sync { guard let resultIDs = (notification as NSNotification).userInfo?[batchRequestResultIDArrayKey] as? [NSManagedObjectID] else { return } deleteObjects(with: resultIDs) } } private func handleExternalBatchUpdate(_ notification: Notification) { base.sync { guard let resultIDs = (notification as NSNotification).userInfo?[batchRequestResultIDArrayKey] as? [NSManagedObjectID] else { return } updateObjectsWith(resultIDs) } } }
a8f3c2aa3d74ba39754695139fb4c649
32.199262
161
0.745693
false
false
false
false
dduan/swift
refs/heads/master
test/SILGen/dynamic_lookup.swift
apache-2.0
2
// RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | FileCheck %s // REQUIRES: objc_interop class X { @objc func f() { } @objc class func staticF() { } @objc var value: Int { return 17 } @objc subscript (i: Int) -> Int { get { return i } set {} } } @objc protocol P { func g() } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup15direct_to_class func direct_to_class(obj: AnyObject) { // CHECK: [[OBJ_SELF:%[0-9]+]] = open_existential_ref [[EX:%[0-9]+]] : $AnyObject to $@opened({{.*}}) AnyObject // CHECK: [[METHOD:%[0-9]+]] = dynamic_method [volatile] [[OBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign : (X) -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> () // CHECK: apply [[METHOD]]([[OBJ_SELF]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> () obj.f!() } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup18direct_to_protocol func direct_to_protocol(obj: AnyObject) { // CHECK: [[OBJ_SELF:%[0-9]+]] = open_existential_ref [[EX:%[0-9]+]] : $AnyObject to $@opened({{.*}}) AnyObject // CHECK: [[METHOD:%[0-9]+]] = dynamic_method [volatile] [[OBJ_SELF]] : $@opened({{.*}}) AnyObject, #P.g!1.foreign : <Self where Self : P> Self -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> () // CHECK: apply [[METHOD]]([[OBJ_SELF]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> () obj.g!() } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup23direct_to_static_method func direct_to_static_method(obj: AnyObject) { var obj = obj // CHECK: [[START:[A-Za-z0-9_]+]]([[OBJ:%[0-9]+]] : $AnyObject): // CHECK: [[OBJBOX:%[0-9]+]] = alloc_box $AnyObject // CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]] // CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[OBJCOPY:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject // CHECK-NEXT: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened([[UUID:".*"]]) AnyObject).Type // CHECK-NEXT: [[METHOD:%[0-9]+]] = dynamic_method [volatile] [[OPENMETA]] : $@thick (@opened([[UUID]]) AnyObject).Type, #X.staticF!1.foreign : (X.Type) -> () -> (), $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> () // CHECK: apply [[METHOD]]([[OPENMETA]]) : $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> () obj.dynamicType.staticF!() } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup12opt_to_class func opt_to_class(obj: AnyObject) { var obj = obj // CHECK: [[ENTRY:[A-Za-z0-9]+]]([[PARAM:%[0-9]+]] : $AnyObject) // CHECK: [[EXISTBOX:%[0-9]+]] = alloc_box $AnyObject // CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[EXISTBOX]] // CHECK: store [[PARAM]] to [[PBOBJ]] // CHECK-NEXT: [[OPTBOX:%[0-9]+]] = alloc_box $ImplicitlyUnwrappedOptional<() -> ()> // CHECK-NEXT: [[PBOPT:%.*]] = project_box [[OPTBOX]] // CHECK-NEXT: [[EXISTVAL:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject // CHECK-NEXT: strong_retain [[EXISTVAL]] : $AnyObject // CHECK-NEXT: [[OBJ_SELF:%[0-9]*]] = open_existential_ref [[EXIST:%[0-9]+]] // CHECK-NEXT: [[OPTTEMP:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<() -> ()> // CHECK-NEXT: dynamic_method_br [[OBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign, [[HASBB:[a-zA-z0-9]+]], [[NOBB:[a-zA-z0-9]+]] // Has method BB: // CHECK: [[HASBB]]([[UNCURRIED:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()): // CHECK-NEXT: strong_retain [[OBJ_SELF]] // CHECK-NEXT: [[PARTIAL:%[0-9]+]] = partial_apply [[UNCURRIED]]([[OBJ_SELF]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> () // CHECK-NEXT: [[THUNK_PAYLOAD:%.*]] = init_enum_data_addr [[OPTIONAL:%[0-9]+]] // CHECK: [[THUNKFN:%.*]] = function_ref @{{.*}} : $@convention(thin) (@in (), @owned @callee_owned () -> ()) -> @out () // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [[THUNKFN]]([[PARTIAL]]) // CHECK-NEXT: store [[THUNK]] to [[THUNK_PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[OPTIONAL]]{{.*}}some // CHECK-NEXT: br [[CONTBB:[a-zA-Z0-9]+]] // No method BB: // CHECK: [[NOBB]]: // CHECK-NEXT: inject_enum_addr [[OPTIONAL]]{{.*}}none // CHECK-NEXT: br [[CONTBB]] // Continuation block // CHECK: [[CONTBB]]: // CHECK-NEXT: [[OPT:%.*]] = load [[OPTTEMP]] // CHECK-NEXT: store [[OPT]] to [[PBOPT]] : $*ImplicitlyUnwrappedOptional<() -> ()> // CHECK-NEXT: dealloc_stack [[OPTTEMP]] var of = obj.f // Exit // CHECK-NEXT: strong_release [[OBJ_SELF]] : $@opened({{".*"}}) AnyObject // CHECK-NEXT: strong_release [[OPTBOX]] : $@box ImplicitlyUnwrappedOptional<() -> ()> // CHECK-NEXT: strong_release [[EXISTBOX]] : $@box AnyObject // CHECK-NEXT: strong_release %0 // CHECK-NEXT: [[RESULT:%[0-9]+]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup20forced_without_outer func forced_without_outer(obj: AnyObject) { // CHECK: dynamic_method_br var f = obj.f! } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup20opt_to_static_method func opt_to_static_method(obj: AnyObject) { var obj = obj // CHECK: [[ENTRY:[A-Za-z0-9]+]]([[OBJ:%[0-9]+]] : $AnyObject): // CHECK: [[OBJBOX:%[0-9]+]] = alloc_box $AnyObject // CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]] // CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[OPTBOX:%[0-9]+]] = alloc_box $ImplicitlyUnwrappedOptional<() -> ()> // CHECK-NEXT: [[PBO:%.*]] = project_box [[OPTBOX]] // CHECK-NEXT: [[OBJCOPY:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject // CHECK-NEXT: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened // CHECK-NEXT: [[OBJCMETA:%[0-9]+]] = thick_to_objc_metatype [[OPENMETA]] // CHECK-NEXT: [[OPTTEMP:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<() -> ()> // CHECK-NEXT: dynamic_method_br [[OBJCMETA]] : $@objc_metatype (@opened({{".*"}}) AnyObject).Type, #X.staticF!1.foreign, [[HASMETHOD:[A-Za-z0-9_]+]], [[NOMETHOD:[A-Za-z0-9_]+]] var optF = obj.dynamicType.staticF } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup15opt_to_property func opt_to_property(obj: AnyObject) { var obj = obj // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject): // CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box $AnyObject // CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]] // CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[INT_BOX:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: project_box [[INT_BOX]] // CHECK-NEXT: [[UNKNOWN_USE:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<Int> // CHECK-NEXT: [[OBJ:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject // CHECK-NEXT: strong_retain [[OBJ]] : $AnyObject // CHECK-NEXT: [[RAWOBJ_SELF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject // CHECK-NEXT: [[OPTTEMP:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<Int> // CHECK-NEXT: dynamic_method_br [[RAWOBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.value!getter.1.foreign, bb1, bb2 // CHECK: bb1([[METHOD:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int): // CHECK-NEXT: strong_retain [[RAWOBJ_SELF]] // CHECK-NEXT: [[BOUND_METHOD:%[0-9]+]] = partial_apply [[METHOD]]([[RAWOBJ_SELF]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int // CHECK-NEXT: [[VALUE:%[0-9]+]] = apply [[BOUND_METHOD]]() : $@callee_owned () -> Int // CHECK-NEXT: [[VALUETEMP:%.*]] = init_enum_data_addr [[OPTTEMP]] // CHECK-NEXT: store [[VALUE]] to [[VALUETEMP]] // CHECK-NEXT: inject_enum_addr [[OPTTEMP]]{{.*}}some // CHECK-NEXT: br bb3 var i: Int = obj.value! } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup19direct_to_subscript func direct_to_subscript(obj: AnyObject, i: Int) { var obj = obj var i = i // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject, [[I:%[0-9]+]] : $Int): // CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box $AnyObject // CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]] // CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[I_BOX:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: [[PBI:%.*]] = project_box [[I_BOX]] // CHECK-NEXT: store [[I]] to [[PBI]] : $*Int // CHECK-NEXT: alloc_box $Int // CHECK-NEXT: project_box // CHECK-NEXT: [[UNKNOWN_USE:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<Int> // CHECK-NEXT: [[OBJ:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject // CHECK-NEXT: strong_retain [[OBJ]] : $AnyObject // CHECK-NEXT: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject // CHECK-NEXT: [[I:%[0-9]+]] = load [[PBI]] : $*Int // CHECK-NEXT: [[OPTTEMP:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<Int> // CHECK-NEXT: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2 // CHECK: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int): // CHECK-NEXT: strong_retain [[OBJ_REF]] // CHECK-NEXT: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [[GETTER]]([[OBJ_REF]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[GETTER_WITH_SELF]]([[I]]) : $@callee_owned (Int) -> Int // CHECK-NEXT: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]] // CHECK-NEXT: store [[RESULT]] to [[RESULTTEMP]] // CHECK-NEXT: inject_enum_addr [[OPTTEMP]]{{.*}}some // CHECK-NEXT: br bb3 var x: Int = obj[i]! } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup16opt_to_subscript func opt_to_subscript(obj: AnyObject, i: Int) { var obj = obj var i = i // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject, [[I:%[0-9]+]] : $Int): // CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box $AnyObject // CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]] // CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[I_BOX:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: [[PBI:%.*]] = project_box [[I_BOX]] // CHECK-NEXT: store [[I]] to [[PBI]] : $*Int // CHECK-NEXT: [[OBJ:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject // CHECK-NEXT: strong_retain [[OBJ]] : $AnyObject // CHECK-NEXT: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject // CHECK-NEXT: [[I:%[0-9]+]] = load [[PBI]] : $*Int // CHECK-NEXT: [[OPTTEMP:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<Int> // CHECK-NEXT: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2 // CHECK: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int): // CHECK-NEXT: strong_retain [[OBJ_REF]] // CHECK-NEXT: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [[GETTER]]([[OBJ_REF]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[GETTER_WITH_SELF]]([[I]]) : $@callee_owned (Int) -> Int // CHECK-NEXT: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]] // CHECK-NEXT: store [[RESULT]] to [[RESULTTEMP]] // CHECK-NEXT: inject_enum_addr [[OPTTEMP]] // CHECK-NEXT: br bb3 obj[i] } // CHECK-LABEL: sil hidden @_TF14dynamic_lookup8downcast func downcast(obj: AnyObject) -> X { var obj = obj // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject): // CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box $AnyObject // CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]] // CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[OBJ:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject // CHECK-NEXT: strong_retain [[OBJ]] : $AnyObject // CHECK-NEXT: [[X:%[0-9]+]] = unconditional_checked_cast [[OBJ]] : $AnyObject to $X // CHECK-NEXT: strong_release [[OBJ_BOX]] : $@box AnyObject // CHECK-NEXT: strong_release %0 // CHECK-NEXT: return [[X]] : $X return obj as! X }
11099c338364deaf75448b4f5654f89f
51.682819
243
0.586253
false
false
false
false
cache0928/CCWeibo
refs/heads/master
CCWeibo/CCWeibo/Classes/Home/HomeRefreshControl.swift
mit
1
// // HomeRefreshControl.swift // CCWeibo // // Created by 徐才超 on 16/2/13. // Copyright © 2016年 徐才超. All rights reserved. // import UIKit class HomeRefreshControl: UIRefreshControl { @IBOutlet weak var circleView: UIView! @IBOutlet weak var infoLabel: UILabel! private lazy var circleLayer: CAShapeLayer = { let layer = CAShapeLayer() layer.lineCap = kCALineCapRound layer.lineCap = kCALineCapRound layer.strokeColor = UIColor.orangeColor().CGColor layer.fillColor = UIColor.clearColor().CGColor layer.strokeStart = 0.0 layer.strokeEnd = 0.0 layer.lineWidth = 5 return layer }() private var progress: CGFloat = 0.0 { didSet { circleLayer.strokeEnd = progress if progress == 1 { if !refreshing { infoLabel.text = "释放刷新..." } } else { infoLabel.text = "下拉刷新..." } } } private var animating: Bool = false override init(frame: CGRect) { super.init(frame: frame) setupXib() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupXib() } // 核心设置代码 private func setupXib() { let bundle = NSBundle(forClass: self.dynamicType) let nib = UINib(nibName: "HomeRefreshControl", bundle: bundle) let view: UIView = nib.instantiateWithOwner(self, options: nil).first as! UIView view.frame = bounds circleView.layer.addSublayer(circleLayer) circleLayer.path = UIBezierPath(ovalInRect: CGRectInset(circleView.bounds, 18, 18)).CGPath addSubview(view) addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil) } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if refreshing && !animating { startAnimate() return } if keyPath == "frame" && frame.origin.y < 0 && !refreshing { progress = min(1, -frame.origin.y / frame.height) } } // 刷新状态动画 private func startAnimate() { //旋转 let startPointStroken = CABasicAnimation(keyPath: "strokeStart") startPointStroken.fromValue = -1 startPointStroken.toValue = 1 let endPointStroken = CABasicAnimation(keyPath: "strokeEnd") endPointStroken.fromValue = 0 endPointStroken.toValue = 1 let strokeAnimateGroup = CAAnimationGroup() strokeAnimateGroup.duration = 1.2 strokeAnimateGroup.repeatCount = HUGE strokeAnimateGroup.animations = [startPointStroken, endPointStroken] circleLayer.addAnimation(strokeAnimateGroup, forKey: nil) infoLabel.text = "正在刷新..." animating = true } private func endAnimate() { animating = false circleLayer.removeAllAnimations() } override func beginRefreshing() { super.beginRefreshing() startAnimate() } override func endRefreshing() { super.endRefreshing() endAnimate() } deinit { removeObserver(self, forKeyPath: "frame") } }
c2d02920224f6b2e8e780fc8c3c1a6d8
31.156863
157
0.616159
false
false
false
false
alexfeng/BubbleTransition
refs/heads/master
Source/BubbleTransition.swift
mit
2
// // BubbleTransition.swift // BubbleTransition // // Created by Andrea Mazzini on 04/04/15. // Copyright (c) 2015 Fancy Pixel. All rights reserved. // import UIKit /** A custom modal transition that presents and dismiss a controller with an expanding bubble effect. */ public class BubbleTransition: NSObject, UIViewControllerAnimatedTransitioning { /** The point that originates the bubble. */ public var startingPoint = CGPointZero { didSet { if let bubble = bubble { bubble.center = startingPoint } } } /** The transition duration. */ public var duration = 0.5 /** The transition direction. Either `.Present` or `.Dismiss.` */ public var transitionMode: BubbleTransitionMode = .Present /** The color of the bubble. Make sure that it matches the destination controller's background color. */ public var bubbleColor: UIColor = .whiteColor() private var bubble: UIView? // MARK: - UIViewControllerAnimatedTransitioning /** Required by UIViewControllerAnimatedTransitioning */ public func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return duration } /** Required by UIViewControllerAnimatedTransitioning */ public func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView() if transitionMode == .Present { let presentedControllerView = transitionContext.viewForKey(UITransitionContextToViewKey)! let originalCenter = presentedControllerView.center let originalSize = presentedControllerView.frame.size bubble = UIView(frame: frameForBubble(originalCenter, size: originalSize, start: startingPoint)) bubble?.layer.cornerRadius = bubble!.frame.size.height / 2 bubble?.center = startingPoint bubble?.transform = CGAffineTransformMakeScale(0.001, 0.001) bubble?.backgroundColor = bubbleColor containerView.addSubview(bubble!) presentedControllerView.center = startingPoint presentedControllerView.transform = CGAffineTransformMakeScale(0.001, 0.001) presentedControllerView.alpha = 0 containerView.addSubview(presentedControllerView) UIView.animateWithDuration(duration, animations: { self.bubble?.transform = CGAffineTransformIdentity presentedControllerView.transform = CGAffineTransformIdentity presentedControllerView.alpha = 1 presentedControllerView.center = originalCenter }) { (_) in transitionContext.completeTransition(true) } } else { let key = (transitionMode == .Pop) ? UITransitionContextToViewKey : UITransitionContextFromViewKey let returningControllerView = transitionContext.viewForKey(key)! let originalCenter = returningControllerView.center let originalSize = returningControllerView.frame.size if let bubble = bubble { bubble.frame = frameForBubble(originalCenter, size: originalSize, start: startingPoint) bubble.layer.cornerRadius = bubble.frame.size.height / 2 bubble.center = startingPoint } UIView.animateWithDuration(duration, animations: { self.bubble?.transform = CGAffineTransformMakeScale(0.001, 0.001) returningControllerView.transform = CGAffineTransformMakeScale(0.001, 0.001) returningControllerView.center = self.startingPoint returningControllerView.alpha = 0 if self.transitionMode == .Pop { containerView.insertSubview(returningControllerView, belowSubview: returningControllerView) containerView.insertSubview(self.bubble!, belowSubview: returningControllerView) } }) { (_) in returningControllerView.removeFromSuperview() self.bubble?.removeFromSuperview() transitionContext.completeTransition(true) } } } /** The possible directions of the transition */ @objc public enum BubbleTransitionMode: Int { case Present, Dismiss, Pop } } private extension BubbleTransition { private func frameForBubble(originalCenter: CGPoint, size originalSize: CGSize, start: CGPoint) -> CGRect { let lengthX = fmax(start.x, originalSize.width - start.x); let lengthY = fmax(start.y, originalSize.height - start.y) let offset = sqrt(lengthX * lengthX + lengthY * lengthY) * 2; let size = CGSize(width: offset, height: offset) return CGRect(origin: CGPointZero, size: size) } }
9b697defa0101d98d267a82daf8a6af2
37.564885
111
0.645091
false
false
false
false
LeafPlayer/Leaf
refs/heads/master
Leaf/UIComponents/ISO639_2Helper.swift
gpl-3.0
1
// // ISO639_2Helper.swift // iina // // Created by lhc on 14/3/2017. // Copyright © 2017 lhc. All rights reserved. // import Foundation class ISO639_2Helper { struct Language { var code: String var name: [String] var description: String { return "\(name[0]) (\(code))" } } static let languages: [Language] = { var result: [Language] = [] for (k, v) in dictionary { let names = v.split(separator: ";").map { String($0) } result.append(Language(code: k, name: names)) } return result }() static let dictionary: [String: String] = { let filePath = Bundle.main.path(forResource: "ISO639_2", ofType: "strings")! return NSDictionary(contentsOfFile: filePath) as! [String : String] }() }
f04992a0622fa4d7b34a64709d937adf
19.648649
80
0.608639
false
false
false
false
infobip/mobile-messaging-sdk-ios
refs/heads/master
Classes/Core/Utils/BaseUrlManager.swift
apache-2.0
1
// // BaseUrlManager.swift // MobileMessaging // // Created by Andrey Kadochnikov on 28.01.2021. // import Foundation class BaseUrlManager: MobileMessagingService { private let defaultTimeout: Double = 60 * 60 * 24 // a day private var lastCheckDate : Date? { set { UserDefaults.standard.set(newValue, forKey: Consts.BaseUrlRecovery.lastCheckDateKey) UserDefaults.standard.synchronize() } get { return UserDefaults.standard.object(forKey: Consts.BaseUrlRecovery.lastCheckDateKey) as? Date } } init(mmContext: MobileMessaging) { super.init(mmContext: mmContext, uniqueIdentifier: "BaseUrlManager") } override func appWillEnterForeground(_ completion: @escaping () -> Void) { checkBaseUrl({ completion() }) } func checkBaseUrl(_ completion: @escaping (() -> Void)) { guard itsTimeToCheckBaseUrl() else { completion() return } logDebug("Checking actual base URL...") mmContext.remoteApiProvider.getBaseUrl(applicationCode: mmContext.applicationCode, queue: mmContext.queue) { self.handleResult(result: $0) completion() } } func resetLastCheckDate(_ date: Date? = nil) { self.lastCheckDate = date } private func itsTimeToCheckBaseUrl() -> Bool { let ret = lastCheckDate == nil || (lastCheckDate?.addingTimeInterval(defaultTimeout).compare(MobileMessaging.date.now) != ComparisonResult.orderedDescending) if ret { logDebug("It's time to check the base url") } else { logDebug("It's not time to check the base url now. lastCheckDate \(String(describing: lastCheckDate)), now \(MobileMessaging.date.now), timeout \(defaultTimeout)") } return ret } private func handleResult(result: BaseUrlResult) { if let response = result.value { if let baseUrl = response.baseUrl, let newBaseUrl = URL(string: baseUrl) { mmContext.httpSessionManager.setNewBaseUrl(newBaseUrl: newBaseUrl) self.lastCheckDate = MobileMessaging.date.now } else { logDebug("No base url available") } } else { logError("An error occurred while trying to get base url from server: \(result.error.orNil)") } } }
186ba6d8f2ea4be4250329da0d86de86
34.676471
175
0.622836
false
false
false
false
zon/that-bus
refs/heads/master
ios/That Bus/RegisterLayout.swift
gpl-3.0
1
import Foundation import UIKit class RegisterLayout : UIView { let content: UIView let email: TextField required init() { let frame = Unit.screen let m2 = Unit.m2 let font = Font.medium email = TextField(frame: CGRect(x: 0, y: 0, width: frame.width, height: font.lineHeight + m2 * 2)) email.backgroundColor = Palette.white email.addBorder(width: Unit.one, color: Palette.border, visible: BorderVisible(top: true, bottom: true)) email.placeholder = "Email" email.padding = UIEdgeInsets(top: 0, left: m2, bottom: 0, right: m2) email.keyboardType = .emailAddress email.autocapitalizationType = .none email.autocorrectionType = .no email.returnKeyType = .next email.spellCheckingType = .no let details = UILabel(frame: CGRect(x: m2, y: email.frame.maxY + m2, width: frame.width - m2 * 2, height: 10)) details.font = Font.small details.textColor = UIColor.gray details.text = "Save your tickets online." details.resizeHeight() content = UIView(frame: CGRect(x: 0, y: m2, width: frame.width, height: details.frame.maxY + m2)) content.addSubview(email) content.addSubview(details) super.init(frame: frame) backgroundColor = Palette.background addSubview(content) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setInsets(top: CGFloat?, bottom: CGFloat?) { content.frame.origin.y = (top ?? 0) + Unit.m2 } }
eaea284c20835d6926100d7297a67693
33.583333
118
0.610843
false
false
false
false
amosavian/swift-corelibs-foundation
refs/heads/master
Foundation/JSONEncoder.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import CoreFoundation //===----------------------------------------------------------------------===// // JSON Encoder //===----------------------------------------------------------------------===// /// `JSONEncoder` facilitates the encoding of `Encodable` values into JSON. open class JSONEncoder { // MARK: Options /// The formatting of the output JSON data. public struct OutputFormatting : OptionSet { /// The format's default value. public let rawValue: UInt /// Creates an OutputFormatting value with the given raw value. public init(rawValue: UInt) { self.rawValue = rawValue } /// Produce human-readable JSON with indented output. public static let prettyPrinted = OutputFormatting(rawValue: 1 << 0) /// Produce JSON with dictionary keys sorted in lexicographic order. @available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) public static let sortedKeys = OutputFormatting(rawValue: 1 << 1) } /// The strategy to use for encoding `Date` values. public enum DateEncodingStrategy { /// Defer to `Date` for choosing an encoding. This is the default strategy. case deferredToDate /// Encode the `Date` as a UNIX timestamp (as a JSON number). case secondsSince1970 /// Encode the `Date` as UNIX millisecond timestamp (as a JSON number). case millisecondsSince1970 /// Encode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). @available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Encode the `Date` as a string formatted by the given formatter. case formatted(DateFormatter) /// Encode the `Date` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Date, Encoder) throws -> Void) } /// The strategy to use for encoding `Data` values. public enum DataEncodingStrategy { /// Defer to `Data` for choosing an encoding. case deferredToData /// Encoded the `Data` as a Base64-encoded string. This is the default strategy. case base64 /// Encode the `Data` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Data, Encoder) throws -> Void) } /// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloatEncodingStrategy { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Encode the values using the given representation strings. case convertToString(positiveInfinity: String, negativeInfinity: String, nan: String) } /// The output format to produce. Defaults to `[]`. open var outputFormatting: OutputFormatting = [] /// The strategy to use in encoding dates. Defaults to `.deferredToDate`. open var dateEncodingStrategy: DateEncodingStrategy = .deferredToDate /// The strategy to use in encoding binary data. Defaults to `.base64`. open var dataEncodingStrategy: DataEncodingStrategy = .base64 /// The strategy to use in encoding non-conforming numbers. Defaults to `.throw`. open var nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy = .throw /// Contextual user-provided information for use during encoding. open var userInfo: [CodingUserInfoKey : Any] = [:] /// Options set on the top-level encoder to pass down the encoding hierarchy. internal struct _Options { let dateEncodingStrategy: DateEncodingStrategy let dataEncodingStrategy: DataEncodingStrategy let nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy let userInfo: [CodingUserInfoKey : Any] } /// The options set on the top-level encoder. fileprivate var options: _Options { return _Options(dateEncodingStrategy: dateEncodingStrategy, dataEncodingStrategy: dataEncodingStrategy, nonConformingFloatEncodingStrategy: nonConformingFloatEncodingStrategy, userInfo: userInfo) } // MARK: - Constructing a JSON Encoder /// Initializes `self` with default strategies. public init() {} // MARK: - Encoding Values /// Encodes the given top-level value and returns its JSON representation. /// /// - parameter value: The value to encode. /// - returns: A new `Data` value containing the encoded JSON data. /// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`. /// - throws: An error if any value throws an error during encoding. open func encode<T : Encodable>(_ value: T) throws -> Data { let encoder = _JSONEncoder(options: self.options) try value.encode(to: encoder) guard encoder.storage.count > 0 else { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) did not encode any values.")) } let topLevel = encoder.storage.popContainer() if topLevel is NSNull { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as null JSON fragment.")) } else if topLevel is NSNumber { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as number JSON fragment.")) } else if topLevel is NSString { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as string JSON fragment.")) } let writingOptions = JSONSerialization.WritingOptions(rawValue: self.outputFormatting.rawValue) return try JSONSerialization.data(withJSONObject: topLevel, options: writingOptions) } } // MARK: - _JSONEncoder internal class _JSONEncoder : Encoder { // MARK: Properties /// The encoder's storage. fileprivate var storage: _JSONEncodingStorage /// Options set on the top-level encoder. internal let options: JSONEncoder._Options /// The path to the current point in encoding. public var codingPath: [CodingKey] /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level encoder options. fileprivate init(options: JSONEncoder._Options, codingPath: [CodingKey] = []) { self.options = options self.storage = _JSONEncodingStorage() self.codingPath = codingPath } // MARK: - Coding Path Operations /// Performs the given closure with the given key pushed onto the end of the current coding path. /// /// - parameter key: The key to push. May be nil for unkeyed containers. /// - parameter work: The work to perform with the key in the path. fileprivate func with<T>(pushedKey key: CodingKey, _ work: () throws -> T) rethrows -> T { self.codingPath.append(key) let ret: T = try work() self.codingPath.removeLast() return ret } /// Returns whether a new element can be encoded at this coding path. /// /// `true` if an element has not yet been encoded at this coding path; `false` otherwise. fileprivate var canEncodeNewValue: Bool { // Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container). // At the same time, every time a container is requested, a new value gets pushed onto the storage stack. // If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition. // // This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path. // Things which will not request containers do not need to have the coding path extended for them (but it doesn't matter if it is, because they will not reach here). return self.storage.count == self.codingPath.count } // MARK: - Encoder Methods public func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> { // If an existing keyed container was already requested, return that one. let topContainer: NSMutableDictionary if self.canEncodeNewValue { // We haven't yet pushed a container at this level; do so here. topContainer = self.storage.pushKeyedContainer() } else { guard let container = self.storage.containers.last as? NSMutableDictionary else { preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.") } topContainer = container } let container = _JSONKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer) return KeyedEncodingContainer(container) } public func unkeyedContainer() -> UnkeyedEncodingContainer { // If an existing unkeyed container was already requested, return that one. let topContainer: NSMutableArray if self.canEncodeNewValue { // We haven't yet pushed a container at this level; do so here. topContainer = self.storage.pushUnkeyedContainer() } else { guard let container = self.storage.containers.last as? NSMutableArray else { preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.") } topContainer = container } return _JSONUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer) } public func singleValueContainer() -> SingleValueEncodingContainer { return self } } // MARK: - Encoding Storage and Containers fileprivate struct _JSONEncodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the JSON types (NSNull, NSNumber, NSString, NSArray, NSDictionary). private(set) fileprivate var containers: [NSObject] = [] // MARK: - Initialization /// Initializes `self` with no containers. fileprivate init() {} // MARK: - Modifying the Stack fileprivate var count: Int { return self.containers.count } fileprivate mutating func pushKeyedContainer() -> NSMutableDictionary { let dictionary = NSMutableDictionary() self.containers.append(dictionary) return dictionary } fileprivate mutating func pushUnkeyedContainer() -> NSMutableArray { let array = NSMutableArray() self.containers.append(array) return array } fileprivate mutating func push(container: NSObject) { self.containers.append(container) } fileprivate mutating func popContainer() -> NSObject { precondition(self.containers.count > 0, "Empty container stack.") return self.containers.popLast()! } } // MARK: - Encoding Containers fileprivate struct _JSONKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the encoder we're writing to. private let encoder: _JSONEncoder /// A reference to the container we're writing to. private let container: NSMutableDictionary /// The path of coding keys taken to get to this point in encoding. private(set) public var codingPath: [CodingKey] // MARK: - Initialization /// Initializes `self` with the given references. fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - Coding Path Operations /// Performs the given closure with the given key pushed onto the end of the current coding path. /// /// - parameter key: The key to push. May be nil for unkeyed containers. /// - parameter work: The work to perform with the key in the path. fileprivate mutating func with<T>(pushedKey key: CodingKey, _ work: () throws -> T) rethrows -> T { self.codingPath.append(key) let ret: T = try work() self.codingPath.removeLast() return ret } // MARK: - KeyedEncodingContainerProtocol Methods public mutating func encodeNil(forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = NSNull() } public mutating func encode(_ value: Bool, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Int, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Int8, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Int16, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Int32, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Int64, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: UInt, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: UInt8, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: UInt16, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: UInt32, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: UInt64, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: String, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Float, forKey key: Key) throws { // Since the float may be invalid and throw, the coding path needs to contain this key. try self.encoder.with(pushedKey: key) { self.container[key.stringValue._bridgeToObjectiveC()] = try self.encoder.box(value) } } public mutating func encode(_ value: Double, forKey key: Key) throws { // Since the double may be invalid and throw, the coding path needs to contain this key. try self.encoder.with(pushedKey: key) { self.container[key.stringValue._bridgeToObjectiveC()] = try self.encoder.box(value) } } public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws { try self.encoder.with(pushedKey: key) { self.container[key.stringValue._bridgeToObjectiveC()] = try self.encoder.box(value) } } public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { let dictionary = NSMutableDictionary() self.container[key.stringValue._bridgeToObjectiveC()] = dictionary return self.with(pushedKey: key) { let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } } public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { let array = NSMutableArray() self.container[key.stringValue._bridgeToObjectiveC()] = array return self.with(pushedKey: key) { return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array) } } public mutating func superEncoder() -> Encoder { return _JSONReferencingEncoder(referencing: self.encoder, at: _JSONKey.super, wrapping: self.container) } public mutating func superEncoder(forKey key: Key) -> Encoder { return _JSONReferencingEncoder(referencing: self.encoder, at: key, wrapping: self.container) } } fileprivate struct _JSONUnkeyedEncodingContainer : UnkeyedEncodingContainer { // MARK: Properties /// A reference to the encoder we're writing to. private let encoder: _JSONEncoder /// A reference to the container we're writing to. private let container: NSMutableArray /// The path of coding keys taken to get to this point in encoding. private(set) public var codingPath: [CodingKey] /// The number of elements encoded into the container. public var count: Int { return self.container.count } // MARK: - Initialization /// Initializes `self` with the given references. fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - Coding Path Operations /// Performs the given closure with the given key pushed onto the end of the current coding path. /// /// - parameter key: The key to push. May be nil for unkeyed containers. /// - parameter work: The work to perform with the key in the path. fileprivate mutating func with<T>(pushedKey key: CodingKey, _ work: () throws -> T) rethrows -> T { self.codingPath.append(key) let ret: T = try work() self.codingPath.removeLast() return ret } // MARK: - UnkeyedEncodingContainer Methods public mutating func encodeNil() throws { self.container.add(NSNull()) } public mutating func encode(_ value: Bool) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int8) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int16) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int32) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int64) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt8) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt16) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt32) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt64) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: String) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Float) throws { // Since the float may be invalid and throw, the coding path needs to contain this key. try self.encoder.with(pushedKey: _JSONKey(index: self.count)) { self.container.add(try self.encoder.box(value)) } } public mutating func encode(_ value: Double) throws { // Since the double may be invalid and throw, the coding path needs to contain this key. try self.encoder.with(pushedKey: _JSONKey(index: self.count)) { self.container.add(try self.encoder.box(value)) } } public mutating func encode<T : Encodable>(_ value: T) throws { try self.encoder.with(pushedKey: _JSONKey(index: self.count)) { self.container.add(try self.encoder.box(value)) } } public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> { let dictionary = NSMutableDictionary() self.container.add(dictionary) // self.count - 1 to accommodate the fact that we just pushed a container. return self.with(pushedKey: _JSONKey(index: self.count - 1)) { let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } } public mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { let array = NSMutableArray() self.container.add(array) // self.count - 1 to accommodate the fact that we just pushed a container. return self.with(pushedKey: _JSONKey(index: self.count - 1)) { return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array) } } public mutating func superEncoder() -> Encoder { return _JSONReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container) } } extension _JSONEncoder : SingleValueEncodingContainer { // MARK: - SingleValueEncodingContainer Methods fileprivate func assertCanEncodeNewValue() { precondition(self.canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.") } public func encodeNil() throws { assertCanEncodeNewValue() self.storage.push(container: NSNull()) } public func encode(_ value: Bool) throws { assertCanEncodeNewValue() self.storage.push(container: box(value)) } public func encode(_ value: Int) throws { assertCanEncodeNewValue() self.storage.push(container: box(value)) } public func encode(_ value: Int8) throws { assertCanEncodeNewValue() self.storage.push(container: box(value)) } public func encode(_ value: Int16) throws { assertCanEncodeNewValue() self.storage.push(container: box(value)) } public func encode(_ value: Int32) throws { assertCanEncodeNewValue() self.storage.push(container: box(value)) } public func encode(_ value: Int64) throws { assertCanEncodeNewValue() self.storage.push(container: box(value)) } public func encode(_ value: UInt) throws { assertCanEncodeNewValue() self.storage.push(container: box(value)) } public func encode(_ value: UInt8) throws { assertCanEncodeNewValue() self.storage.push(container: box(value)) } public func encode(_ value: UInt16) throws { assertCanEncodeNewValue() self.storage.push(container: box(value)) } public func encode(_ value: UInt32) throws { assertCanEncodeNewValue() self.storage.push(container: box(value)) } public func encode(_ value: UInt64) throws { assertCanEncodeNewValue() self.storage.push(container: box(value)) } public func encode(_ value: String) throws { assertCanEncodeNewValue() self.storage.push(container: box(value)) } public func encode(_ value: Float) throws { assertCanEncodeNewValue() try self.storage.push(container: box(value)) } public func encode(_ value: Double) throws { assertCanEncodeNewValue() try self.storage.push(container: box(value)) } public func encode<T : Encodable>(_ value: T) throws { assertCanEncodeNewValue() try self.storage.push(container: box(value)) } } // MARK: - Concrete Value Representations extension _JSONEncoder { /// Returns the given value boxed in a container appropriate for pushing onto the container stack. fileprivate func box(_ value: Bool) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: String) -> NSObject { return NSString(string: value) } fileprivate func box(_ float: Float) throws -> NSObject { guard !float.isInfinite && !float.isNaN else { guard case let .convertToString(positiveInfinity: posInfString, negativeInfinity: negInfString, nan: nanString) = self.options.nonConformingFloatEncodingStrategy else { throw EncodingError._invalidFloatingPointValue(float, at: codingPath) } if float == Float.infinity { return NSString(string: posInfString) } else if float == -Float.infinity { return NSString(string: negInfString) } else { return NSString(string: nanString) } } return NSNumber(value: float) } fileprivate func box(_ double: Double) throws -> NSObject { guard !double.isInfinite && !double.isNaN else { guard case let .convertToString(positiveInfinity: posInfString, negativeInfinity: negInfString, nan: nanString) = self.options.nonConformingFloatEncodingStrategy else { throw EncodingError._invalidFloatingPointValue(double, at: codingPath) } if double == Double.infinity { return NSString(string: posInfString) } else if double == -Double.infinity { return NSString(string: negInfString) } else { return NSString(string: nanString) } } return NSNumber(value: double) } fileprivate func box(_ date: Date) throws -> NSObject { switch self.options.dateEncodingStrategy { case .deferredToDate: // Must be called with a surrounding with(pushedKey:) call. try date.encode(to: self) return self.storage.popContainer() case .secondsSince1970: return NSNumber(value: date.timeIntervalSince1970) case .millisecondsSince1970: return NSNumber(value: 1000.0 * date.timeIntervalSince1970) case .iso8601: if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { return NSString(string: _iso8601Formatter.string(from: date)) } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): return NSString(string: formatter.string(from: date)) case .custom(let closure): let depth = self.storage.count try closure(date, self) guard self.storage.count > depth else { // The closure didn't encode anything. Return the default keyed container. return NSDictionary() } // We can pop because the closure encoded something. return self.storage.popContainer() } } fileprivate func box(_ data: Data) throws -> NSObject { switch self.options.dataEncodingStrategy { case .deferredToData: // Must be called with a surrounding with(pushedKey:) call. try data.encode(to: self) return self.storage.popContainer() case .base64: return NSString(string: data.base64EncodedString()) case .custom(let closure): let depth = self.storage.count try closure(data, self) guard self.storage.count > depth else { // The closure didn't encode anything. Return the default keyed container. return NSDictionary() } // We can pop because the closure encoded something. return self.storage.popContainer() } } fileprivate func box<T : Encodable>(_ value: T) throws -> NSObject { if T.self == Date.self { // Respect Date encoding strategy return try self.box((value as! Date)) } else if T.self == Data.self { // Respect Data encoding strategy return try self.box((value as! Data)) } else if T.self == URL.self { // Encode URLs as single strings. return self.box((value as! URL).absoluteString) } else if T.self == Decimal.self { // On Darwin we get ((value as! Decimal) as NSDecimalNumber) since JSONSerialization can consume NSDecimalNumber values. // FIXME: Attempt to create a Decimal value if JSONSerialization on Linux consume one. let doubleValue = (value as! Decimal).doubleValue return try self.box(doubleValue) } // The value should request a container from the _JSONEncoder. let topContainer = self.storage.containers.last try value.encode(to: self) // The top container should be a new container. guard self.storage.containers.last! !== topContainer else { // If the value didn't request a container at all, encode the default container instead. return NSDictionary() } return self.storage.popContainer() } } // MARK: - _JSONReferencingEncoder /// _JSONReferencingEncoder is a special subclass of _JSONEncoder which has its own storage, but references the contents of a different encoder. /// It's used in superEncoder(), which returns a new encoder for encoding a superclass -- the lifetime of the encoder should not escape the scope it's created in, but it doesn't necessarily know when it's done being used (to write to the original container). fileprivate class _JSONReferencingEncoder : _JSONEncoder { // MARK: Reference types. /// The type of container we're referencing. private enum Reference { /// Referencing a specific index in an array container. case array(NSMutableArray, Int) /// Referencing a specific key in a dictionary container. case dictionary(NSMutableDictionary, String) } // MARK: - Properties /// The encoder we're referencing. fileprivate let encoder: _JSONEncoder /// The container reference itself. private let reference: Reference // MARK: - Initialization /// Initializes `self` by referencing the given array container in the given encoder. fileprivate init(referencing encoder: _JSONEncoder, at index: Int, wrapping array: NSMutableArray) { self.encoder = encoder self.reference = .array(array, index) super.init(options: encoder.options, codingPath: encoder.codingPath) self.codingPath.append(_JSONKey(index: index)) } /// Initializes `self` by referencing the given dictionary container in the given encoder. fileprivate init(referencing encoder: _JSONEncoder, at key: CodingKey, wrapping dictionary: NSMutableDictionary) { self.encoder = encoder self.reference = .dictionary(dictionary, key.stringValue) super.init(options: encoder.options, codingPath: encoder.codingPath) self.codingPath.append(key) } // MARK: - Coding Path Operations fileprivate override var canEncodeNewValue: Bool { // With a regular encoder, the storage and coding path grow together. // A referencing encoder, however, inherits its parents coding path, as well as the key it was created for. // We have to take this into account. return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1 } // MARK: - Deinitialization // Finalizes `self` by writing the contents of our storage to the referenced encoder's storage. deinit { let value: Any switch self.storage.count { case 0: value = NSDictionary() case 1: value = self.storage.popContainer() default: fatalError("Referencing encoder deallocated with multiple containers on stack.") } switch self.reference { case .array(let array, let index): array.insert(value, at: index) case .dictionary(let dictionary, let key): dictionary[NSString(string: key)] = value } } } //===----------------------------------------------------------------------===// // JSON Decoder //===----------------------------------------------------------------------===// /// `JSONDecoder` facilitates the decoding of JSON into semantic `Decodable` types. open class JSONDecoder { // MARK: Options /// The strategy to use for decoding `Date` values. public enum DateDecodingStrategy { /// Defer to `Date` for decoding. This is the default strategy. case deferredToDate /// Decode the `Date` as a UNIX timestamp from a JSON number. case secondsSince1970 /// Decode the `Date` as UNIX millisecond timestamp from a JSON number. case millisecondsSince1970 /// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). @available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Decode the `Date` as a string parsed by the given formatter. case formatted(DateFormatter) /// Decode the `Date` as a custom value decoded by the given closure. case custom((_ decoder: Decoder) throws -> Date) } /// The strategy to use for decoding `Data` values. public enum DataDecodingStrategy { /// Defer to `Data` for decoding. case deferredToData /// Decode the `Data` from a Base64-encoded string. This is the default strategy. case base64 /// Decode the `Data` as a custom value decoded by the given closure. case custom((_ decoder: Decoder) throws -> Data) } /// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloatDecodingStrategy { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Decode the values from the given representation strings. case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String) } /// The strategy to use in decoding dates. Defaults to `.deferredToDate`. open var dateDecodingStrategy: DateDecodingStrategy = .deferredToDate /// The strategy to use in decoding binary data. Defaults to `.base64`. open var dataDecodingStrategy: DataDecodingStrategy = .base64 /// The strategy to use in decoding non-conforming numbers. Defaults to `.throw`. open var nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy = .throw /// Contextual user-provided information for use during decoding. open var userInfo: [CodingUserInfoKey : Any] = [:] /// Options set on the top-level encoder to pass down the decoding hierarchy. internal struct _Options { let dateDecodingStrategy: DateDecodingStrategy let dataDecodingStrategy: DataDecodingStrategy let nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy let userInfo: [CodingUserInfoKey : Any] } /// The options set on the top-level decoder. fileprivate var options: _Options { return _Options(dateDecodingStrategy: dateDecodingStrategy, dataDecodingStrategy: dataDecodingStrategy, nonConformingFloatDecodingStrategy: nonConformingFloatDecodingStrategy, userInfo: userInfo) } // MARK: - Constructing a JSON Decoder /// Initializes `self` with default strategies. public init() {} // MARK: - Decoding Values /// Decodes a top-level value of the given type from the given JSON representation. /// /// - parameter type: The type of the value to decode. /// - parameter data: The data to decode from. /// - returns: A value of the requested type. /// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not valid JSON. /// - throws: An error if any value throws an error during decoding. open func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T { let topLevel = try JSONSerialization.jsonObject(with: data, options: [.useReferenceNumericTypes]) let decoder = _JSONDecoder(referencing: topLevel, options: self.options) return try T(from: decoder) } } // MARK: - _JSONDecoder internal class _JSONDecoder : Decoder { // MARK: Properties /// The decoder's storage. fileprivate var storage: _JSONDecodingStorage /// Options set on the top-level decoder. internal let options: JSONDecoder._Options /// The path to the current point in encoding. private(set) public var codingPath: [CodingKey] /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level container and options. fileprivate init(referencing container: Any, at codingPath: [CodingKey] = [], options: JSONDecoder._Options) { self.storage = _JSONDecodingStorage() self.storage.push(container: container) self.codingPath = codingPath self.options = options } // MARK: - Coding Path Operations /// Performs the given closure with the given key pushed onto the end of the current coding path. /// /// - parameter key: The key to push. May be nil for unkeyed containers. /// - parameter work: The work to perform with the key in the path. fileprivate func with<T>(pushedKey key: CodingKey, _ work: () throws -> T) rethrows -> T { self.codingPath.append(key) let ret: T = try work() self.codingPath.removeLast() return ret } // MARK: - Decoder Methods public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let topContainer = self.storage.topContainer as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: self.storage.topContainer) } let container = _JSONKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer) return KeyedDecodingContainer(container) } public func unkeyedContainer() throws -> UnkeyedDecodingContainer { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get unkeyed decoding container -- found null value instead.")) } guard let topContainer = self.storage.topContainer as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: self.storage.topContainer) } return _JSONUnkeyedDecodingContainer(referencing: self, wrapping: topContainer) } public func singleValueContainer() throws -> SingleValueDecodingContainer { return self } } // MARK: - Decoding Storage fileprivate struct _JSONDecodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the JSON types (NSNull, NSNumber, String, Array, [String : Any]). private(set) fileprivate var containers: [Any] = [] // MARK: - Initialization /// Initializes `self` with no containers. fileprivate init() {} // MARK: - Modifying the Stack fileprivate var count: Int { return self.containers.count } fileprivate var topContainer: Any { precondition(self.containers.count > 0, "Empty container stack.") return self.containers.last! } fileprivate mutating func push(container: Any) { self.containers.append(container) } fileprivate mutating func popContainer() { precondition(self.containers.count > 0, "Empty container stack.") self.containers.removeLast() } } // MARK: Decoding Containers fileprivate struct _JSONKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the decoder we're reading from. private let decoder: _JSONDecoder /// A reference to the container we're reading from. private let container: [String : Any] /// The path of coding keys taken to get to this point in decoding. private(set) public var codingPath: [CodingKey] // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [String : Any]) { self.decoder = decoder self.container = container self.codingPath = decoder.codingPath } // MARK: - KeyedDecodingContainerProtocol Methods public var allKeys: [Key] { return self.container.keys.flatMap { Key(stringValue: $0) } } public func contains(_ key: Key) -> Bool { return self.container[key.stringValue] != nil } public func decodeNil(forKey key: Key) throws -> Bool { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return entry is NSNull } public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return try self.decoder.with(pushedKey: key) { guard let value = try self.decoder.unbox(entry, as: Bool.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } } public func decode(_ type: Int.Type, forKey key: Key) throws -> Int { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return try self.decoder.with(pushedKey: key) { guard let value = try self.decoder.unbox(entry, as: Int.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } } public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return try self.decoder.with(pushedKey: key) { guard let value = try self.decoder.unbox(entry, as: Int8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } } public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return try self.decoder.with(pushedKey: key) { guard let value = try self.decoder.unbox(entry, as: Int16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } } public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return try self.decoder.with(pushedKey: key) { guard let value = try self.decoder.unbox(entry, as: Int32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } } public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return try self.decoder.with(pushedKey: key) { guard let value = try self.decoder.unbox(entry, as: Int64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } } public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return try self.decoder.with(pushedKey: key) { guard let value = try self.decoder.unbox(entry, as: UInt.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } } public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return try self.decoder.with(pushedKey: key) { guard let value = try self.decoder.unbox(entry, as: UInt8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } } public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return try self.decoder.with(pushedKey: key) { guard let value = try self.decoder.unbox(entry, as: UInt16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } } public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return try self.decoder.with(pushedKey: key) { guard let value = try self.decoder.unbox(entry, as: UInt32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } } public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return try self.decoder.with(pushedKey: key) { guard let value = try self.decoder.unbox(entry, as: UInt64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } } public func decode(_ type: Float.Type, forKey key: Key) throws -> Float { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return try self.decoder.with(pushedKey: key) { guard let value = try self.decoder.unbox(entry, as: Float.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } } public func decode(_ type: Double.Type, forKey key: Key) throws -> Double { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return try self.decoder.with(pushedKey: key) { guard let value = try self.decoder.unbox(entry, as: Double.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } } public func decode(_ type: String.Type, forKey key: Key) throws -> String { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return try self.decoder.with(pushedKey: key) { guard let value = try self.decoder.unbox(entry, as: String.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } } public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\").")) } return try self.decoder.with(pushedKey: key) { guard let value = try self.decoder.unbox(entry, as: T.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } } public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> { return try self.decoder.with(pushedKey: key) { guard let value = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get \(KeyedDecodingContainer<NestedKey>.self) -- no value found for key \"\(key.stringValue)\"")) } guard let dictionary = value as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value) } let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } } public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { return try self.decoder.with(pushedKey: key) { guard let value = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get UnkeyedDecodingContainer -- no value found for key \"\(key.stringValue)\"")) } guard let array = value as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value) } return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } } private func _superDecoder(forKey key: CodingKey) throws -> Decoder { return self.decoder.with(pushedKey: key) { let value: Any = self.container[key.stringValue] ?? NSNull() return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options) } } public func superDecoder() throws -> Decoder { return try _superDecoder(forKey: _JSONKey.super) } public func superDecoder(forKey key: Key) throws -> Decoder { return try _superDecoder(forKey: key) } } fileprivate struct _JSONUnkeyedDecodingContainer : UnkeyedDecodingContainer { // MARK: Properties /// A reference to the decoder we're reading from. private let decoder: _JSONDecoder /// A reference to the container we're reading from. private let container: [Any] /// The path of coding keys taken to get to this point in decoding. private(set) public var codingPath: [CodingKey] /// The index of the element we're about to decode. private(set) public var currentIndex: Int // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [Any]) { self.decoder = decoder self.container = container self.codingPath = decoder.codingPath self.currentIndex = 0 } // MARK: - UnkeyedDecodingContainer Methods public var count: Int? { return self.container.count } public var isAtEnd: Bool { return self.currentIndex >= self.count! } public mutating func decodeNil() throws -> Bool { guard !self.isAtEnd else { throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } if self.container[self.currentIndex] is NSNull { self.currentIndex += 1 return true } else { return false } } public mutating func decode(_ type: Bool.Type) throws -> Bool { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Bool.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } } public mutating func decode(_ type: Int.Type) throws -> Int { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } } public mutating func decode(_ type: Int8.Type) throws -> Int8 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } } public mutating func decode(_ type: Int16.Type) throws -> Int16 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } } public mutating func decode(_ type: Int32.Type) throws -> Int32 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } } public mutating func decode(_ type: Int64.Type) throws -> Int64 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } } public mutating func decode(_ type: UInt.Type) throws -> UInt { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } } public mutating func decode(_ type: UInt8.Type) throws -> UInt8 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } } public mutating func decode(_ type: UInt16.Type) throws -> UInt16 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } } public mutating func decode(_ type: UInt32.Type) throws -> UInt32 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } } public mutating func decode(_ type: UInt64.Type) throws -> UInt64 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } } public mutating func decode(_ type: Float.Type) throws -> Float { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Float.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } } public mutating func decode(_ type: Double.Type) throws -> Double { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Double.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } } public mutating func decode(_ type: String.Type) throws -> String { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: String.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } } public mutating func decode<T : Decodable>(_ type: T.Type) throws -> T { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: T.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } } public mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> { return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard !self.isAtEnd else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let dictionary = value as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value) } self.currentIndex += 1 let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } } public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard !self.isAtEnd else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let array = value as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value) } self.currentIndex += 1 return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } } public mutating func superDecoder() throws -> Decoder { return try self.decoder.with(pushedKey: _JSONKey(index: self.currentIndex)) { guard !self.isAtEnd else { throw DecodingError.valueNotFound(Decoder.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get superDecoder() -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] self.currentIndex += 1 return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options) } } } extension _JSONDecoder : SingleValueDecodingContainer { // MARK: SingleValueDecodingContainer Methods private func expectNonNull<T>(_ type: T.Type) throws { guard !self.decodeNil() else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected \(type) but found null value instead.")) } } public func decodeNil() -> Bool { return self.storage.topContainer is NSNull } public func decode(_ type: Bool.Type) throws -> Bool { try expectNonNull(Bool.self) return try self.unbox(self.storage.topContainer, as: Bool.self)! } public func decode(_ type: Int.Type) throws -> Int { try expectNonNull(Int.self) return try self.unbox(self.storage.topContainer, as: Int.self)! } public func decode(_ type: Int8.Type) throws -> Int8 { try expectNonNull(Int8.self) return try self.unbox(self.storage.topContainer, as: Int8.self)! } public func decode(_ type: Int16.Type) throws -> Int16 { try expectNonNull(Int16.self) return try self.unbox(self.storage.topContainer, as: Int16.self)! } public func decode(_ type: Int32.Type) throws -> Int32 { try expectNonNull(Int32.self) return try self.unbox(self.storage.topContainer, as: Int32.self)! } public func decode(_ type: Int64.Type) throws -> Int64 { try expectNonNull(Int64.self) return try self.unbox(self.storage.topContainer, as: Int64.self)! } public func decode(_ type: UInt.Type) throws -> UInt { try expectNonNull(UInt.self) return try self.unbox(self.storage.topContainer, as: UInt.self)! } public func decode(_ type: UInt8.Type) throws -> UInt8 { try expectNonNull(UInt8.self) return try self.unbox(self.storage.topContainer, as: UInt8.self)! } public func decode(_ type: UInt16.Type) throws -> UInt16 { try expectNonNull(UInt16.self) return try self.unbox(self.storage.topContainer, as: UInt16.self)! } public func decode(_ type: UInt32.Type) throws -> UInt32 { try expectNonNull(UInt32.self) return try self.unbox(self.storage.topContainer, as: UInt32.self)! } public func decode(_ type: UInt64.Type) throws -> UInt64 { try expectNonNull(UInt64.self) return try self.unbox(self.storage.topContainer, as: UInt64.self)! } public func decode(_ type: Float.Type) throws -> Float { try expectNonNull(Float.self) return try self.unbox(self.storage.topContainer, as: Float.self)! } public func decode(_ type: Double.Type) throws -> Double { try expectNonNull(Double.self) return try self.unbox(self.storage.topContainer, as: Double.self)! } public func decode(_ type: String.Type) throws -> String { try expectNonNull(String.self) return try self.unbox(self.storage.topContainer, as: String.self)! } public func decode<T : Decodable>(_ type: T.Type) throws -> T { try expectNonNull(T.self) return try self.unbox(self.storage.topContainer, as: T.self)! } } // MARK: - Concrete Value Representations extension _JSONDecoder { /// Returns the given value unboxed from a container. fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } // TODO: Add a flag to coerce non-boolean numbers into Bools? guard number._cfTypeID == CFBooleanGetTypeID() else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } return number.boolValue } fileprivate func unbox(_ value: Any, as type: Int.Type) throws -> Int? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int = number.intValue guard NSNumber(value: int) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int } fileprivate func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int8 = number.int8Value guard NSNumber(value: int8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int8 } fileprivate func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int16 = number.int16Value guard NSNumber(value: int16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int16 } fileprivate func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int32 = number.int32Value guard NSNumber(value: int32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int32 } fileprivate func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int64 = number.int64Value guard NSNumber(value: int64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int64 } fileprivate func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint = number.uintValue guard NSNumber(value: uint) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint } fileprivate func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint8 = number.uint8Value guard NSNumber(value: uint8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint8 } fileprivate func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint16 = number.uint16Value guard NSNumber(value: uint16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint16 } fileprivate func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint32 = number.uint32Value guard NSNumber(value: uint32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint32 } fileprivate func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint64 = number.uint64Value guard NSNumber(value: uint64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint64 } fileprivate func unbox(_ value: Any, as type: Float.Type) throws -> Float? { guard !(value is NSNull) else { return nil } if let number = value as? NSNumber { // We are willing to return a Float by losing precision: // * If the original value was integral, // * and the integral value was > Float.greatestFiniteMagnitude, we will fail // * and the integral value was <= Float.greatestFiniteMagnitude, we are willing to lose precision past 2^24 // * If it was a Float, you will get back the precise value // * If it was a Double or Decimal, you will get back the nearest approximation if it will fit let double = number.doubleValue guard abs(double) <= Double(Float.greatestFiniteMagnitude) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number \(number) does not fit in \(type).")) } return Float(double) /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let double = value as? Double { if abs(double) <= Double(Float.max) { return Float(double) } overflow = true } else if let int = value as? Int { if let float = Float(exactly: int) { return float } overflow = true */ } else if let string = value as? String, case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy { if string == posInfString { return Float.infinity } else if string == negInfString { return -Float.infinity } else if string == nanString { return Float.nan } } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func unbox(_ value: Any, as type: Double.Type) throws -> Double? { guard !(value is NSNull) else { return nil } if let number = value as? NSNumber { // We are always willing to return the number as a Double: // * If the original value was integral, it is guaranteed to fit in a Double; we are willing to lose precision past 2^53 if you encoded a UInt64 but requested a Double // * If it was a Float or Double, you will get back the precise value // * If it was Decimal, you will get back the nearest approximation return number.doubleValue /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let double = value as? Double { return double } else if let int = value as? Int { if let double = Double(exactly: int) { return double } overflow = true */ } else if let string = value as? String, case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy { if string == posInfString { return Double.infinity } else if string == negInfString { return -Double.infinity } else if string == nanString { return Double.nan } } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func unbox(_ value: Any, as type: String.Type) throws -> String? { guard !(value is NSNull) else { return nil } guard let string = value as? String else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } return string } fileprivate func unbox(_ value: Any, as type: Date.Type) throws -> Date? { guard !(value is NSNull) else { return nil } switch self.options.dateDecodingStrategy { case .deferredToDate: self.storage.push(container: value) let date = try Date(from: self) self.storage.popContainer() return date case .secondsSince1970: let double = try self.unbox(value, as: Double.self)! return Date(timeIntervalSince1970: double) case .millisecondsSince1970: let double = try self.unbox(value, as: Double.self)! return Date(timeIntervalSince1970: double / 1000.0) case .iso8601: if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { let string = try self.unbox(value, as: String.self)! guard let date = _iso8601Formatter.date(from: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected date string to be ISO8601-formatted.")) } return date } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): let string = try self.unbox(value, as: String.self)! guard let date = formatter.date(from: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Date string does not match format expected by formatter.")) } return date case .custom(let closure): self.storage.push(container: value) let date = try closure(self) self.storage.popContainer() return date } } fileprivate func unbox(_ value: Any, as type: Data.Type) throws -> Data? { guard !(value is NSNull) else { return nil } switch self.options.dataDecodingStrategy { case .deferredToData: self.storage.push(container: value) let data = try Data(from: self) self.storage.popContainer() return data case .base64: guard let string = value as? String else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } guard let data = Data(base64Encoded: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Encountered Data is not valid Base64.")) } return data case .custom(let closure): self.storage.push(container: value) let data = try closure(self) self.storage.popContainer() return data } } fileprivate func unbox(_ value: Any, as type: Decimal.Type) throws -> Decimal? { guard !(value is NSNull) else { return nil } // On Darwin we get (value as? Decimal) since JSONSerialization can produce NSDecimalNumber values. // FIXME: Attempt to grab a Decimal value if JSONSerialization on Linux produces one. let doubleValue = try self.unbox(value, as: Double.self)! return Decimal(doubleValue) } fileprivate func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? { let decoded: T if T.self == Date.self { guard let date = try self.unbox(value, as: Date.self) else { return nil } decoded = date as! T } else if T.self == Data.self { guard let data = try self.unbox(value, as: Data.self) else { return nil } decoded = data as! T } else if T.self == URL.self { guard let urlString = try self.unbox(value, as: String.self) else { return nil } guard let url = URL(string: urlString) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Invalid URL string.")) } decoded = (url as! T) } else if T.self == Decimal.self { guard let decimal = try self.unbox(value, as: Decimal.self) else { return nil } decoded = decimal as! T } else { self.storage.push(container: value) decoded = try T(from: self) self.storage.popContainer() } return decoded } } //===----------------------------------------------------------------------===// // Shared Key Types //===----------------------------------------------------------------------===// fileprivate struct _JSONKey : CodingKey { public var stringValue: String public var intValue: Int? public init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } public init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } fileprivate init(index: Int) { self.stringValue = "Index \(index)" self.intValue = index } fileprivate static let `super` = _JSONKey(stringValue: "super")! } //===----------------------------------------------------------------------===// // Shared ISO8601 Date Formatter //===----------------------------------------------------------------------===// // NOTE: This value is implicitly lazy and _must_ be lazy. We're compiled against the latest SDK (w/ ISO8601DateFormatter), but linked against whichever Foundation the user has. ISO8601DateFormatter might not exist, so we better not hit this code path on an older OS. @available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) fileprivate var _iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter }() //===----------------------------------------------------------------------===// // Error Utilities //===----------------------------------------------------------------------===// fileprivate extension EncodingError { /// Returns a `.invalidValue` error describing the given invalid floating-point value. /// /// /// - parameter value: The value that was invalid to encode. /// - parameter path: The path of `CodingKey`s taken to encode this value. /// - returns: An `EncodingError` with the appropriate path and debug description. fileprivate static func _invalidFloatingPointValue<T : FloatingPoint>(_ value: T, at codingPath: [CodingKey]) -> EncodingError { let valueDescription: String if value == T.infinity { valueDescription = "\(T.self).infinity" } else if value == -T.infinity { valueDescription = "-\(T.self).infinity" } else { valueDescription = "\(T.self).nan" } let debugDescription = "Unable to encode \(valueDescription) directly in JSON. Use JSONEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded." return .invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: debugDescription)) } }
308e72c0f0c482af7cec0971f24d3a3c
43.288462
267
0.64264
false
false
false
false
DataArt/SmartSlides
refs/heads/master
PresentatorS/Framer/FrameCutter.swift
mit
1
// // FrameCutter.swift // PresentatorS // // Created by Igor Litvinenko on 12/19/14. // Copyright (c) 2014 Igor Litvinenko. All rights reserved. // import Foundation import UIKit protocol FrameCutterInternal{ static func createWebView() -> UIWebView func loadWebView(webView: UIWebView) func freeWebView(webView: UIWebView) func frameWebContent(webView: UIWebView, callback:(([String]) -> ())) } class FrameCutter: NSObject, FrameCutterInternal { typealias FramingResult = ([String]) -> Void private var presentationFileUrl: NSURL private var resultClosure: FramingResult? private var viewForWebView: UIView? private var internalWebView: UIWebView private let progressView = ProgressView.loadFromNib() as! ProgressView var fileUrl: NSURL { get { return presentationFileUrl } } var presenterView: UIView { get { if let viewForWebView = viewForWebView{ return viewForWebView } else if let viewForWebView = UIApplication.sharedApplication().keyWindow{ return viewForWebView; } return UIView() } } init(fileUrl: NSURL){ presentationFileUrl = fileUrl internalWebView = FrameCutter.createWebView() } func startFramingProcess(parentView: UIView?, callback: FramingResult){ let famedPresentationDirectoryPath = getPathToFolderForFamedPresentation() if NSFileManager.defaultManager().fileExistsAtPath(famedPresentationDirectoryPath){ let content = (try? NSFileManager.defaultManager().contentsOfDirectoryAtPath(famedPresentationDirectoryPath)) if (content?.count > 0) { callback(content!.map({ (famedPresentationDirectoryPath as NSString).stringByAppendingPathComponent($0) })) } else { do { try NSFileManager.defaultManager().createDirectoryAtPath(famedPresentationDirectoryPath, withIntermediateDirectories: true, attributes: nil) } catch _ { } viewForWebView = parentView resultClosure = callback loadWebView(internalWebView) } } else { do { try NSFileManager.defaultManager().createDirectoryAtPath(famedPresentationDirectoryPath, withIntermediateDirectories: true, attributes: nil) } catch _ { } viewForWebView = parentView resultClosure = callback loadWebView(internalWebView) } } private func getPathToFolderForFamedPresentation() -> String { return NSURL.CM_pathForFramedPresentationDir(presentationFileUrl) } //MARK: Internal internal class func createWebView() -> UIWebView { let scaleCoefficient = CGFloat(1.32129037); let screenHeight = CGRectGetHeight(UIScreen.mainScreen().bounds) let result = UIWebView(frame: CGRectMake(0, 0, screenHeight * scaleCoefficient, screenHeight)) result.scalesPageToFit = true result.autoresizingMask = .None return result } internal func freeWebView(webView: UIWebView) { webView.delegate = nil webView.removeFromSuperview() viewForWebView = nil } internal func loadWebView(webView: UIWebView) { let parent = self.presenterView var frame = internalWebView.frame frame.origin.x = (CGRectGetWidth(parent.bounds) - CGRectGetWidth(frame)) / 2 internalWebView.frame = frame parent.addSubview(internalWebView) internalWebView.loadRequest(NSURLRequest(URL: presentationFileUrl)) internalWebView.delegate = self self.progressView.frame = parent.bounds self.progressView.progressView.hidden = false self.progressView.progressView.progress = 0 parent.addSubview(self.progressView) } internal func frameWebContent(webView: UIWebView, callback: (([String]) -> ())) { var currentOffset = CGFloat(0.0) let frameSize = internalWebView.bounds.size let presentationHeight = internalWebView.scrollView.contentSize.height var page = 0 var totalPages = 0 if presentationFileUrl.pathExtension == "key" { totalPages = Int(ceil(presentationHeight/frameSize.height)) } else { if let slidesCount = webView.stringByEvaluatingJavaScriptFromString("document.getElementsByClassName('slide').length") { totalPages = Int(slidesCount)! } } print("FRAME CUTTER: total pages = \(totalPages)") var result = [String]() // let group = dispatch_group_create() // let queue = dispatch_queue_create("Saving images queue", nil) // while page < totalPages { let image = takeScreenShot() // dispatch_group_async(group, queue, { page++ result.append(self.saveImageToTmpDirectory(image, page: page)) NSOperationQueue.mainQueue().addOperationWithBlock({ [unowned self] in let value = CGFloat(page)/CGFloat(totalPages) self.progressView.progressView.progress = Float(value) }) // }) // currentOffset = ceil(currentOffset + frameSize.height) - CGFloat(page) * 0.08 currentOffset = ceil(currentOffset + frameSize.height) webView.scrollView.scrollRectToVisible(CGRectMake(0, currentOffset, frameSize.width, frameSize.height), animated: false) } webView.scrollView.scrollRectToVisible(CGRectMake(0, 0, 0, 0), animated: false) self.freeWebView(webView) if let callback = self.resultClosure{ callback(result) } NSOperationQueue.mainQueue().addOperationWithBlock({ [unowned self] in self.progressView.removeFromSuperview() }) } internal func takeScreenShot() -> UIImage{ UIGraphicsBeginImageContext(internalWebView.bounds.size) internalWebView.layer.renderInContext(UIGraphicsGetCurrentContext()!) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } internal func saveImageToTmpDirectory(image: UIImage, page: Int) -> String{ let resultPath = String(format: "%@/page_%03d.jpg", getPathToFolderForFamedPresentation(), page) //println("resultPath \(resultPath)") // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { UIImageJPEGRepresentation(image, 0.9)!.writeToFile(resultPath, atomically: true) // }) return resultPath as String } } //MARK: WebView Delegate extension FrameCutter: UIWebViewDelegate{ func webViewDidFinishLoad(webView: UIWebView) { frameWebContent(webView, callback: { if let callback = self.resultClosure{ callback($0) } }) } func webView(webView: UIWebView, didFailLoadWithError error: NSError?) { print("FRAMECUTTER: didFailLoadWithError \(error)") if let callback = self.resultClosure{ callback([]) } } }
f5c5d10e8f2e82f0363bca7e3be16640
37.125
160
0.642077
false
false
false
false
1aurabrown/eidolon
refs/heads/master
Kiosk/App/Models/SaleArtwork.swift
mit
1
import UIKit enum ReserveStatus { case NoReserve case ReserveNotMet(Int) case ReserveMet } struct SaleNumberFormatter { static let dollarFormatter = createDollarFormatter() } class SaleArtwork: JSONAble { let id: String let artwork: Artwork var auctionID: String? // The bidder is given from JSON if user is registered let bidder: Bidder? var saleHighestBid: Bid? dynamic var bidCount: NSNumber? var userBidderPosition: BidderPosition? var positions: [String]? dynamic var openingBidCents: NSNumber? dynamic var minimumNextBidCents: NSNumber? dynamic var highestBidCents: NSNumber? var lowEstimateCents: Int? var highEstimateCents: Int? init(id: String, artwork: Artwork) { self.id = id self.artwork = artwork } override class func fromJSON(json: [String: AnyObject]) -> JSONAble { let json = JSON(json) let id = json["id"].stringValue let artworkDict = json["artwork"].object as [String: AnyObject] let artwork = Artwork.fromJSON(artworkDict) as Artwork let saleArtwork = SaleArtwork(id: id, artwork: artwork) as SaleArtwork if let highestBidDict = json["highest_bid"].object as? [String: AnyObject] { saleArtwork.saleHighestBid = Bid.fromJSON(highestBidDict) as? Bid } saleArtwork.auctionID = json["sale_id"].string saleArtwork.openingBidCents = json["opening_bid_cents"].int saleArtwork.minimumNextBidCents = json["minimum_next_bid_cents"].int saleArtwork.highestBidCents = json["highest_bid_amount_cents"].int saleArtwork.lowEstimateCents = json["low_estimate_cents"].int saleArtwork.highEstimateCents = json["high_estimate_cents"].int saleArtwork.bidCount = json["bidder_positions_count"].int // let reserveStatus = json["reserve_status"].integer return saleArtwork; } func updateWithValues(newSaleArtwork: SaleArtwork) { saleHighestBid = newSaleArtwork.saleHighestBid auctionID = newSaleArtwork.auctionID openingBidCents = newSaleArtwork.openingBidCents minimumNextBidCents = newSaleArtwork.minimumNextBidCents highestBidCents = newSaleArtwork.highestBidCents lowEstimateCents = newSaleArtwork.lowEstimateCents highEstimateCents = newSaleArtwork.highEstimateCents bidCount = newSaleArtwork.bidCount } var estimateString: String { switch (lowEstimateCents, highEstimateCents) { case let (.Some(lowCents), .Some(highCents)): let lowDollars = NSNumberFormatter.currencyStringForCents(lowCents) let highDollars = NSNumberFormatter.currencyStringForCents(highCents) return "Estimate: \(lowDollars)–\(highDollars)" case let (.Some(lowCents), nil): let lowDollars = NSNumberFormatter.currencyStringForCents(lowCents) return "Estimate: \(lowDollars)" case let (nil, .Some(highCents)): let highDollars = NSNumberFormatter.currencyStringForCents(highCents) return "Estimate: \(highDollars)" default: return "No Estimate" } } override class func keyPathsForValuesAffectingValueForKey(key: String) -> NSSet { if key == "estimateString" { return NSSet(array: ["lowEstimateCents", "highEstimateCents"]) } else { return super.keyPathsForValuesAffectingValueForKey(key) } } } func createDollarFormatter() -> NSNumberFormatter { let formatter = NSNumberFormatter() formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle // This is always dollars, so let's make sure that's how it shows up // regardless of locale. formatter.currencyGroupingSeparator = "," formatter.currencySymbol = "$" formatter.maximumFractionDigits = 0 return formatter }
76a943cdac0e1ec38fff206056960f52
33.491228
85
0.68176
false
false
false
false
syoung-smallwisdom/ResearchUXFactory-iOS
refs/heads/master
ResearchUXFactory/SBAPasswordOptions.swift
bsd-3-clause
1
// // SBAPasswordOptions.swift // ResearchUXFactory // // Copyright © 2017 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation /** Object with the options for the password form item `ORKAnswerFormat`. Default implementation is to create this with a dictionary with the following keys: "identifier": "password" "shouldConfirm": Bool "maximumLength": Int "validationRegex": String "invalidMessage": String @note If the "validationRegex" is defined, then the "invalidMessage" should also be defined. */ public struct SBAPasswordOptions { /** By default, the minimum password length is 2 */ public static let defaultMinLength: Int = 2 /** By default, the maximum password length is 24 */ public static let defaultMaxLength: Int = 24 /** The maximum password length. Default = `2`. Dictionary key = "maximumLength" */ public let minimumLength: Int /** The maximum password length. Default = `24`. Dictionary key = "maximumLength" */ public let maximumLength: Int /** The validation RegEx for the password (optional). Dictionary key = "validationRegex" Default = "[[:ascii:]]{`self.minimumLength`,`self.maximumLength`}" @note If the "validationRegex" is defined using a dictionary key/value pair, then the `invalidMessage` should also be defined */ public let validationRegex: String /** The message to display if the password is invalid (optional). Dictionary key = "invalidMessage" */ public let invalidMessage: String /** Should the password be confirmed. Default = `YES`. Dictionary key = "shouldConfirm" */ public let shouldConfirm: Bool public init(options: [String : AnyObject]? = nil) { self.init(validationRegex: options?["validationRegex"] as? String, invalidMessage: options?["invalidMessage"] as? String, maximumLength: options?["maximumLength"] as? Int, minimumLength: options?["minimumLength"] as? Int, shouldConfirm: options?["shouldConfirm"] as? Bool) } public init(validationRegex: String?, invalidMessage: String?, maximumLength: Int?, minimumLength: Int?, shouldConfirm: Bool?) { self.maximumLength = maximumLength ?? SBAPasswordOptions.defaultMaxLength self.minimumLength = minimumLength ?? SBAPasswordOptions.defaultMinLength self.shouldConfirm = shouldConfirm ?? true // Validation must be defined for both the RegEx and the message // or else use the default if (validationRegex != nil) && (invalidMessage != nil) { self.validationRegex = validationRegex! self.invalidMessage = invalidMessage! } else { // If this is a registration, go ahead and set the default password verification self.validationRegex = "[[:ascii:]]{\(self.minimumLength),\(self.maximumLength)}" self.invalidMessage = Localization.localizedStringWithFormatKey("SBA_REGISTRATION_INVALID_PASSWORD_LENGTH_%@_TO_%@", NSNumber(value: self.minimumLength), NSNumber(value: self.maximumLength)) } } }
245bf6a17d691ffac20b7c6c0e95d6ab
40.853448
202
0.700515
false
false
false
false
i-schuetz/rest_client_ios
refs/heads/master
clojushop_client_ios/ProductListViewController.swift
apache-2.0
1
// // ProductListViewController.swift // clojushop_client_ios // // Created by ischuetz on 07/06/2014. // Copyright (c) 2014 ivanschuetz. All rights reserved. // import Foundation class ProductListViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate { var products:[Product] = [] @IBOutlet var tableView:UITableView! var detailsViewController:ProductDetailViewController! override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.title = "Clojushop client" } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad(); let productCellNib:UINib = UINib(nibName: "CSProductCell", bundle: nil) tableView.registerNib(productCellNib, forCellReuseIdentifier: "CSProductCell") self.requestProducts() } func requestProducts() { self.setProgressHidden(false) DataStore.sharedDataStore().getProducts(0, size: 4, successHandler: {(products:[Product]!) -> Void in self.setProgressHidden(true) self.onRetrievedProducts(products) }, failureHandler: {(Int) -> Bool in return false}) } func onRetrievedProducts(products:[Product]) { self.products = products tableView.reloadData() } func tableView(tableView:UITableView, numberOfRowsInSection section:NSInteger) -> Int { return products.count } func tableView(tableView:UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) { let product = products[indexPath.row] if self.splitViewController == nil { let detailsViewController:ProductDetailViewController = ProductDetailViewController(nibName: "CSProductDetailsViewController", bundle: nil) detailsViewController.product = product detailsViewController.listViewController(product) navigationController?.pushViewController(detailsViewController, animated: true) } else { detailsViewController.listViewController(product) } } func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier:String = "CSProductCell" let cell:ProductCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as ProductCell let product:Product = products[indexPath.row] cell.productName.text = product.name cell.productDescr.text = product.descr cell.productBrand.text = product.seller cell.productPrice.text = CurrencyManager.sharedCurrencyManager().getFormattedPrice(product.price, currencyId: product.currency) cell.productImg.setImageWithURL(NSURL(string: product.imgList)) return cell } func tableView(tableView:UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> Double { return 133 } func transferBarButtonToViewController(vc:UIViewController) { if let splitViewController = self.splitViewController { let nvc:UINavigationController = splitViewController.viewControllers[0] as UINavigationController let currentVC:UIViewController = nvc.viewControllers[0] as UIViewController if vc == currentVC {return} let currentVCItem:UINavigationItem = currentVC.navigationItem vc.navigationItem.setLeftBarButtonItem(currentVCItem.leftBarButtonItem, animated: true) currentVCItem.setLeftBarButtonItem(nil, animated: false) } } }
aaf3585b294e5fab4f7d210f9dc05f47
32.666667
151
0.664382
false
false
false
false
IvanVorobei/RequestPermission
refs/heads/master
Example/SPPermission/SPPermission/Frameworks/SparrowKit/UI/Tables/Cells/Form/SPFormTextInputTableViewCell.swift
mit
1
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class SPFormTextInputTableViewCell: SPTableViewCell { let textInputView: UITextView = UITextView() var textInputViewHeight: CGFloat = 150 { didSet { self.textInputViewHeightConstraint.constant = self.textInputViewHeight } } private var textInputViewHeightConstraint: NSLayoutConstraint! override var contentViews: [UIView] { return [self.textInputView] } override var accessoryType: UITableViewCell.AccessoryType { didSet { if self.accessoryType == .disclosureIndicator { self.selectionStyle = .default } else { self.selectionStyle = .none } } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } private func commonInit() { self.backgroundColor = UIColor.white self.textInputView.textAlignment = .left self.textInputView.text = "" self.textInputView.font = UIFont.system(weight: .regular, size: 17) self.textInputView.translatesAutoresizingMaskIntoConstraints = false self.textInputView.showsVerticalScrollIndicator = false self.contentView.addSubview(self.textInputView) let marginGuide = contentView.layoutMarginsGuide self.textInputView.topAnchor.constraint(equalTo: marginGuide.topAnchor).isActive = true self.textInputView.leadingAnchor.constraint(equalTo: marginGuide.leadingAnchor).isActive = true self.textInputView.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor).isActive = true self.textInputView.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor).isActive = true self.textInputViewHeightConstraint = self.textInputView.heightAnchor.constraint(equalToConstant: self.textInputViewHeight) self.textInputViewHeightConstraint.isActive = true self.stopLoading(animated: false) self.separatorInsetStyle = .auto self.accessoryType = .none } override func prepareForReuse() { super.prepareForReuse() self.accessoryType = .none self.textInputView.text = "" } override func layoutSubviews() { super.layoutSubviews() let xPosition: CGFloat = (self.imageView?.frame.bottomX ?? 0) + self.layoutMargins.left self.textInputView.frame = CGRect.init( x: xPosition, y: 0, width: self.frame.width - self.layoutMargins.left - self.layoutMargins.right, height: self.contentView.frame.height ) switch self.separatorInsetStyle { case .all: self.separatorInset.left = 0 case .beforeImage: if let imageView = self.imageView { self.separatorInset.left = imageView.frame.bottomY + self.layoutMargins.left } else { self.separatorInset.left = 0 } case .none: self.separatorInset.left = self.frame.width case .auto: self.separatorInset.left = self.layoutMargins.left } } }
d9f937aa934145be3814bd9ec1a941fd
37.940171
130
0.673178
false
false
false
false
iCrany/iOSExample
refs/heads/master
iOSExample/Module/MediaExample/MediaExampleTableViewController.swift
mit
1
// // MediaExampleTableViewController.swift // iOSExample // // Created by iCrany on 2018/3/30. // Copyright © 2018 iCrany. All rights reserved. // import Foundation class MediaExampleTableViewController: UIViewController { struct Constant { static let kReplayKitExample = "ReplayKit Example" } private lazy var tableView: UITableView = { let tableView = UITableView.init(frame: .zero, style: .plain) tableView.tableFooterView = UIView.init() tableView.delegate = self tableView.dataSource = self return tableView }() fileprivate var dataSource: [String] = [] init() { super.init(nibName: nil, bundle: nil) self.prepareDataSource() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.title = "ReplayKit Example" self.setupUI() } private func setupUI() { self.view.addSubview(self.tableView) self.tableView.snp.makeConstraints { maker in maker.edges.equalTo(self.view) } self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: Constant.kReplayKitExample) } private func prepareDataSource() { self.dataSource.append(Constant.kReplayKitExample) } } extension MediaExampleTableViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let dataSourceStr: String = self.dataSource[indexPath.row] let tableViewCell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: dataSourceStr) if let cell = tableViewCell { cell.textLabel?.text = dataSourceStr cell.textLabel?.textColor = UIColor.black return cell } else { return UITableViewCell.init(style: .default, reuseIdentifier: "error") } } } extension MediaExampleTableViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedDataSourceStr = self.dataSource[indexPath.row] switch selectedDataSourceStr { case Constant.kReplayKitExample: let vc = ReplayKitExampleVC() self.navigationController?.pushViewController(vc, animated: true) default: break } } }
671dbb4baba381fc6a1b0b37abfc4276
28.287234
106
0.668362
false
false
false
false
Faryn/CycleMaps
refs/heads/master
CycleMaps/MapViewController.swift
mit
1
// // ViewController.swift // CycleMaps // // Created by Paul Pfeiffer on 05/02/17. // Copyright © 2017 Paul Pfeiffer. All rights reserved. // import UIKit import MapKit protocol HandleMapSearch: class { func dropPinZoomIn(_ placemark: MKPlacemark) } class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UISearchBarDelegate, UIPopoverPresentationControllerDelegate, SettingsViewControllerDelegate, FilesViewControllerDelegate, UIGestureRecognizerDelegate, SettingDetailViewControllerDelegate { let locationManager = CLLocationManager() var resultSearchController: UISearchController? var selectedPin: MKPlacemark? let settings = SettingsStore() var filesViewController: FilesViewController? var quickZoomStart: CGFloat? var quickZoomStartLevel: Double? var tapGestureRecognizer: UITapGestureRecognizer? var quickZoomGestureRecognizer: UILongPressGestureRecognizer? override func viewDidLoad() { super.viewDidLoad() navigationItem.largeTitleDisplayMode = .never locationManager.delegate = self locationManager.requestWhenInUseAuthorization() map.tileSource = settings.tileSource setupSearchBar() addTrackButton() tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.toggleBarsOnTap(_:))) tapGestureRecognizer!.delegate = self self.view.addGestureRecognizer(tapGestureRecognizer!) quickZoomGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.handleQuickZoom(_:))) quickZoomGestureRecognizer!.numberOfTapsRequired = 1 quickZoomGestureRecognizer!.minimumPressDuration = 0.1 self.view.addGestureRecognizer(quickZoomGestureRecognizer!) } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer == self.tapGestureRecognizer && otherGestureRecognizer == quickZoomGestureRecognizer { return true } return false } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if settings.idleTimerDisabled { UIApplication.shared.isIdleTimerDisabled = true } } func importFile() { self.performSegue(withIdentifier: Constants.Storyboard.filesSegueIdentifier, sender: self) if filesViewController != nil { filesViewController?.initiateImport() } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if UIApplication.shared.isIdleTimerDisabled { UIApplication.shared.isIdleTimerDisabled = false } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(false, animated: true) self.navigationController?.setToolbarHidden(false, animated: true) } func clearCache() { map.tileSourceOverlay?.clearCache() } func changedSetting(setting: String?) { switch setting! { case Constants.Settings.cacheDisabled: if let overlay = map.overlays.last as? OverlayTile { overlay.enableCache = !settings.cacheDisabled } case Constants.Settings.tileSource: map.tileSource = settings.tileSource default: return } } private func addTrackButton() { let trackButton = MKUserTrackingBarButtonItem(mapView: map) self.toolbarItems?.insert(trackButton, at: 0) } private func setupSearchBar() { if let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "LocationSearchTable") as? LocationSearchTable { resultSearchController = UISearchController(searchResultsController: locationSearchTable) resultSearchController?.searchResultsUpdater = locationSearchTable let searchBar = resultSearchController!.searchBar searchBar.delegate = self searchBar.placeholder = NSLocalizedString("SearchForPlaces", comment: "Displayed as Search String") searchBar.sizeToFit() searchBar.searchBarStyle = .minimal navigationItem.titleView = resultSearchController?.searchBar resultSearchController?.hidesNavigationBarDuringPresentation = false resultSearchController?.obscuresBackgroundDuringPresentation = true definesPresentationContext = true locationSearchTable.mapView = map locationSearchTable.handleMapSearchDelegate = self locationSearchTable.searchBar = searchBar } } internal func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { resultSearchController?.searchResultsUpdater?.updateSearchResults(for: resultSearchController!) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.showsCancelButton = false if selectedPin != nil { map.removeAnnotation(selectedPin!) selectedPin = nil } } func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if overlay is OverlayTile { return MKTileOverlayRenderer(tileOverlay: (overlay as? MKTileOverlay)!) } if overlay is MKPolyline { let renderer = MKPolylineRenderer(overlay: overlay) renderer.strokeColor = Constants.Visual.polylineColor renderer.lineWidth = 6 return renderer } else { return MKOverlayRenderer(overlay: overlay) } } // Will be called shortly after locationmanager is instantiated // Map is initialized in following mode so we only need to disable if permission is missing func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .denied || status == .restricted { map.userTrackingMode = .none } if status == .notDetermined { locationManager.requestWhenInUseAuthorization() } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Failed to find user's location: \(error.localizedDescription)") } @IBOutlet weak var map: MapView! { didSet { map.delegate = self map.setUserTrackingMode(.follow, animated: true) } } @objc func toggleBarsOnTap(_ sender: UITapGestureRecognizer) { let hidden = !(self.navigationController?.isNavigationBarHidden)! self.navigationController?.setNavigationBarHidden(hidden, animated: true) self.navigationController?.setToolbarHidden(hidden, animated: true) } @objc func handleQuickZoom(_ sender: UILongPressGestureRecognizer) { switch sender.state { case .began: self.quickZoomStart = sender.location(in: sender.view).y self.quickZoomStartLevel = map.zoomLevel case .changed: if self.quickZoomStart != nil { var newZoomLevel = quickZoomStartLevel! var distance = self.quickZoomStart! - sender.location(in: sender.view).y if distance > 1 { distance = pow(1.02, distance) } else if distance < -1 { distance = pow(0.98, distance*(-1)) } else { distance = 1 } print(distance) newZoomLevel = self.quickZoomStartLevel! * Double(distance) map.zoomLevel = newZoomLevel } default: break } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let identifier = segue.identifier { switch identifier { case Constants.Storyboard.settingsSegueIdentifier: if let nvc = segue.destination as? UINavigationController { if let svc = nvc.topViewController as? SettingsViewController { svc.delegate = self } } case Constants.Storyboard.filesSegueIdentifier: self.filesViewController = segue.destination as? FilesViewController filesViewController?.delegate = self case Constants.Storyboard.mapStyleSegueIdentifier: if let nvc = segue.destination as? UINavigationController { if let svc = nvc.topViewController as? SettingDetailViewController { svc.navigationItem.title = Constants.Settings.mapStyleTitle svc.delegate = self svc.generator.prepare() } } default: break } } } // MARK: - FilesViewDelegate func selectedFile(name: String, url: URL) { GPX.parse(url as URL) { if let gpx = $0 { self.map.displayGpx(name: name, gpx: gpx) self.filesViewController?.tableView.reloadData() } } } func deselectedFile(name: String) { map.removeOverlay(name: name) filesViewController?.tableView.reloadData() } func isSelected(name: String) -> Bool { return map.namedOverlays[name] != nil } func changedMapStyle() { changedSetting(setting: Constants.Settings.tileSource) } } extension MapViewController: HandleMapSearch { func dropPinZoomIn(_ placemark: MKPlacemark) { // cache the pin selectedPin = placemark // clear existing pins map.removeAnnotations(map.annotations) let annotation = MKPointAnnotation() annotation.coordinate = placemark.coordinate annotation.title = placemark.name if let userLocation = locationManager.location { let distance = userLocation.distance(from: CLLocation( latitude: annotation.coordinate.latitude, longitude: annotation.coordinate.longitude)) if Constants.Settings.useKilometers { annotation.subtitle = String(format: "%.2f km", distance*0.001) } else { annotation.subtitle = String(format: "%.2f mi", distance*0.000621371) } } map.addAnnotation(annotation) let span = MKCoordinateSpan.init(latitudeDelta: 0.05, longitudeDelta: 0.05) let region = MKCoordinateRegion.init(center: placemark.coordinate, span: span) map.setRegion(region, animated: true) } } extension GPX.Waypoint: MKAnnotation { // MARK: - MKAnnotation var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } var title: String? { return name } var subtitle: String? { return info } } private extension MKPolyline { convenience init(coordinates coords: [CLLocationCoordinate2D]) { let unsafeCoordinates = UnsafeMutablePointer<CLLocationCoordinate2D>.allocate(capacity: coords.count) unsafeCoordinates.initialize(from: coords, count: coords.count) self.init(coordinates: unsafeCoordinates, count: coords.count) unsafeCoordinates.deallocate() } }
dcfb7b5d3dab4f26a0ae5499901bf5bd
38.608247
115
0.653306
false
false
false
false
firebase/appquality-codelab-ios
refs/heads/master
ios/swift/AppQualitySwift/AQViewController.swift
apache-2.0
1
// // Copyright (c) 2015 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import Firebase @objc(AQViewController) class AQViewController: UIViewController { @IBOutlet var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let documentsDirectory = paths[0] //make a file name to write the data to using the documents directory let fileName = "\(documentsDirectory)/perfsamplelog.txt" // Start tracing let trace = Performance.startTrace(name: "request_trace") let contents: String do { contents = try String(contentsOfFile: fileName, encoding: .utf8) } catch { print("Log file doesn't exist yet") contents = "" } let fileLength = contents.lengthOfBytes(using: .utf8) trace?.setValue(Int64(fileLength), forMetric: "log_file_size") let fileLengthString = fileLength > (1024 * 1024) ? ">1MB": "<1MB" trace?.setValue(fileLengthString, forAttribute: "file_size") let target = "https://www.gstatic.com/mobilesdk/160503_mobilesdk/logo/2x/firebase_96dp.png" guard let targetUrl = URL(string: target) else { return } var request = URLRequest(url:targetUrl) request.httpMethod = "GET" let task = URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { print("error=\(error)") return } DispatchQueue.main.async { self.imageView.image = UIImage(data: data!) } trace?.stop() let contentToWrite = contents + (response?.url?.absoluteString ?? "") do { try contentToWrite.write(toFile: fileName, atomically: false, encoding: .utf8) } catch { print("Can't write to log file") } } task.resume() trace?.incrementMetric("request_sent", by: 1) } @IBAction func didPressCrash(_ sender: AnyObject) { print("Crash button pressed!") fatalError() } }
2f036b4bba3f850b930168feda2964c4
28.505747
95
0.674718
false
false
false
false
tombuildsstuff/swiftcity
refs/heads/master
SwiftCity/Connection/Extensions/UsersClient.swift
mit
1
import Foundation extension TeamCityClient { public func allUsers(successful: (Users) -> (), failure: (NSError) -> ()) { self.connection.get("/app/rest/users", acceptHeader: "application/json", done: { (data) -> () in let json = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject] let users = Users(dictionary: json)! successful(users) }) { (error: NSError) -> () in failure(error) } } public func userById(id: Int, successful: (User?) -> (), failure: (NSError) -> ()) { self.connection.get("/app/rest/users/id:\(id)", acceptHeader: "application/json", done: { (data) -> () in let json = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject] let user = User(dictionary: json)! successful(user) }) { (error: NSError) -> () in failure(error) } } public func userByName(username: String, successful: (User?) -> (), failure: (NSError) -> ()) { self.connection.get("/app/rest/users/username:\(username)", acceptHeader: "application/json", done: { (data) -> () in let json = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject] let user = User(dictionary: json)! successful(user) }) { (error: NSError) -> () in failure(error) } } }
3e7f380f7eba4b7672ae1a366dc4f5cd
45.558824
142
0.595073
false
false
false
false
mmick66/kinieta
refs/heads/master
Kinieta/ColorSpaces.swift
apache-2.0
1
/* * ColorSpaces.swift * Created by Tim Wood on 10/9/15. * * 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. */ /* Original source: https://github.com/timrwood/ColorSpaces */ import UIKit // MARK: - Constants private let RAD_TO_DEG = 180 / CGFloat.pi private let LAB_E: CGFloat = 0.008856 private let LAB_16_116: CGFloat = 0.1379310 private let LAB_K_116: CGFloat = 7.787036 private let LAB_X: CGFloat = 0.95047 private let LAB_Y: CGFloat = 1 private let LAB_Z: CGFloat = 1.088_83 // MARK: - RGB struct RGBColor { let r: CGFloat // 0..1 let g: CGFloat // 0..1 let b: CGFloat // 0..1 let alpha: CGFloat // 0..1 init (r: CGFloat, g: CGFloat, b: CGFloat, alpha: CGFloat) { self.r = r self.g = g self.b = b self.alpha = alpha } fileprivate func sRGBCompand(_ v: CGFloat) -> CGFloat { let absV = abs(v) let out = absV > 0.040_45 ? pow((absV + 0.055) / 1.055, 2.4) : absV / 12.92 return v > 0 ? out : -out } func toXYZ() -> XYZColor { let R = sRGBCompand(r) let G = sRGBCompand(g) let B = sRGBCompand(b) let x: CGFloat = (R * 0.412_456_4) + (G * 0.357_576_1) + (B * 0.180_437_5) let y: CGFloat = (R * 0.212_672_9) + (G * 0.715_152_2) + (B * 0.072_175_0) let z: CGFloat = (R * 0.019_333_9) + (G * 0.119_192_0) + (B * 0.950_304_1) return XYZColor(x: x, y: y, z: z, alpha: alpha) } func toLAB() -> LABColor { return toXYZ().toLAB() } func toLCH() -> LCHColor { return toXYZ().toLCH() } func color() -> UIColor { return UIColor(red: r, green: g, blue: b, alpha: alpha) } func lerp(_ other: RGBColor, t: CGFloat) -> RGBColor { return RGBColor( r: r + (other.r - r) * t, g: g + (other.g - g) * t, b: b + (other.b - b) * t, alpha: alpha + (other.alpha - alpha) * t ) } } extension UIColor { func rgbColor() -> RGBColor { return RGBColor(r: rgba.red, g: rgba.green, b: rgba.blue, alpha: rgba.alpha) } } // MARK: - XYZ struct XYZColor { let x: CGFloat // 0..0.95047 let y: CGFloat // 0..1 let z: CGFloat // 0..1.08883 let alpha: CGFloat // 0..1 init (x: CGFloat, y: CGFloat, z: CGFloat, alpha: CGFloat) { self.x = x self.y = y self.z = z self.alpha = alpha } fileprivate func sRGBCompand(_ v: CGFloat) -> CGFloat { let absV = abs(v) let out = absV > 0.003_130_8 ? 1.055 * pow(absV, 1 / 2.4) - 0.055 : absV * 12.92 return v > 0 ? out : -out } func toRGB() -> RGBColor { let r = (x * 3.240_454_2) + (y * -1.537_138_5) + (z * -0.498_531_4) let g = (x * -0.969_266_0) + (y * 1.876_010_8) + (z * 0.041_556_0) let b = (x * 0.055_643_4) + (y * -0.204_025_9) + (z * 1.057_225_2) let R = sRGBCompand(r) let G = sRGBCompand(g) let B = sRGBCompand(b) return RGBColor(r: R, g: G, b: B, alpha: alpha) } fileprivate func labCompand(_ v: CGFloat) -> CGFloat { return v > LAB_E ? pow(v, 1.0 / 3.0) : (LAB_K_116 * v) + LAB_16_116 } func toLAB() -> LABColor { let fx = labCompand(x / LAB_X) let fy = labCompand(y / LAB_Y) let fz = labCompand(z / LAB_Z) return LABColor( l: 116 * fy - 16, a: 500 * (fx - fy), b: 200 * (fy - fz), alpha: alpha ) } func toLCH() -> LCHColor { return toLAB().toLCH() } func lerp(_ other: XYZColor, t: CGFloat) -> XYZColor { return XYZColor( x: x + (other.x - x) * t, y: y + (other.y - y) * t, z: z + (other.z - z) * t, alpha: alpha + (other.alpha - alpha) * t ) } } // MARK: - LAB struct LABColor { let l: CGFloat // 0..100 let a: CGFloat // -128..128 let b: CGFloat // -128..128 let alpha: CGFloat // 0..1 init (l: CGFloat, a: CGFloat, b: CGFloat, alpha: CGFloat) { self.l = l self.a = a self.b = b self.alpha = alpha } fileprivate func xyzCompand(_ v: CGFloat) -> CGFloat { let v3 = v * v * v return v3 > LAB_E ? v3 : (v - LAB_16_116) / LAB_K_116 } func toXYZ() -> XYZColor { let y = (l + 16) / 116 let x = y + (a / 500) let z = y - (b / 200) return XYZColor( x: xyzCompand(x) * LAB_X, y: xyzCompand(y) * LAB_Y, z: xyzCompand(z) * LAB_Z, alpha: alpha ) } func toLCH() -> LCHColor { let c = sqrt(a * a + b * b) let angle = atan2(b, a) * RAD_TO_DEG let h = angle < 0 ? angle + 360 : angle return LCHColor(l: l, c: c, h: h, alpha: alpha) } func toRGB() -> RGBColor { return toXYZ().toRGB() } func lerp(_ other: LABColor, t: CGFloat) -> LABColor { return LABColor( l: l + (other.l - l) * t, a: a + (other.a - a) * t, b: b + (other.b - b) * t, alpha: alpha + (other.alpha - alpha) * t ) } } // MARK: - LCH struct LCHColor { static let MaxL: CGFloat = 100.0 static let MaxC: CGFloat = 128.0 static let MaxH: CGFloat = 360.0 let l: CGFloat // 0..100 let c: CGFloat // 0..128 let h: CGFloat // 0..360 let alpha: CGFloat // 0..1 init (l: CGFloat, c: CGFloat, h: CGFloat, alpha: CGFloat) { self.l = l self.c = c self.h = h self.alpha = alpha } func toLAB() -> LABColor { let rad = h / RAD_TO_DEG let a = cos(rad) * c let b = sin(rad) * c return LABColor(l: l, a: a, b: b, alpha: alpha) } func toXYZ() -> XYZColor { return toLAB().toXYZ() } func toRGB() -> RGBColor { return toXYZ().toRGB() } func lerp(_ other: LCHColor, t: CGFloat) -> LCHColor { let angle = (((((other.h - h).truncatingRemainder(dividingBy: 360)) + 540).truncatingRemainder(dividingBy: 360)) - 180) * t return LCHColor( l: l + (other.l - l) * t, c: c + (other.c - c) * t, h: (h + angle + 360).truncatingRemainder(dividingBy: 360), alpha: alpha + (other.alpha - alpha) * t ) } }
bd67278c6718d4a27ff5f051ce1cde10
28.232283
131
0.527273
false
false
false
false
garygriswold/Bible.js
refs/heads/master
SafeBible2/SafeBible_ios/SafeBible/ToolBars/ColorPicker.swift
mit
1
// // ColorPicker.swift // Settings // // Created by Gary Griswold on 11/20/18. // Copyright © 2018 ShortSands. All rights reserved. // import WebKit class ColorPicker : UIView { private static let yellow = UIColor(displayP3Red: 0.91015, green: 0.89843, blue: 0.39062, alpha: 1.0) // E9 E6 64 private static let red = UIColor(displayP3Red: 0.66015, green: 0.31640, blue: 0.57031, alpha: 1.0) // A9 51 92 private static let orange = UIColor(displayP3Red: 0.77343, green: 0.48046, blue: 0.26171, alpha: 1.0) // C6 7B 43 private static let green = UIColor(displayP3Red: 0.51562, green: 0.69921, blue: 0.36718, alpha: 1.0) // 84 B3 5E private static let blue = UIColor(displayP3Red: 0.48046, green: 0.67968, blue: 0.77734, alpha: 1.0) // 7B AE C7 //private static let purple = UIColor(displayP3Red: 0.57031, green: 0.32421, blue: 0.58593, alpha: 1.0) // 92 53 96 private static let salmon = UIColor(displayP3Red: 0.76953, green: 0.37890, blue: 0.42578, alpha: 1.0) // C5 61 6D private static let clear = UIColor(displayP3Red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) /** This method is called each time a color is picked. */ static func toHEX(color: UIColor) -> String { var r:CGFloat = 0, g:CGFloat = 0, b:CGFloat = 0, a:CGFloat = 0 color.getRed(&r, green: &g, blue: &b, alpha: &a) let red = Int(255.0 * r) let gre = Int(255.0 * g) let blu = Int(255.0 * b) let alf = Int(64.0 * a) return String(format: "#%02x%02x%02x%02x", red, gre, blu, alf) } private static var colorMap = [String: UIColor]() static func toUIColor(hexColor: String) -> UIColor { let color = colorMap[hexColor] if (color != nil) { return color! } var parts = [CGFloat]() for index in 0..<4 { let start = index * 2 + 1 // 1, 3, 5, 7 let end = start + 2 // 3, 5, 7, 9 let part = hexColor[hexColor.index(hexColor.startIndex, offsetBy: start)..<hexColor.index(hexColor.startIndex, offsetBy: end)] let byte = UInt8(part, radix: 16)! // unsafe if index < 3 { parts.append(CGFloat(byte) / 255.0) } else { parts.append(CGFloat(byte) / 128.0) } } let color2 = UIColor(red: parts[0], green: parts[1], blue: parts[2], alpha: parts[3]) colorMap[hexColor] = color2 return color2 } private let webView: WKWebView init(webView: WKWebView) { self.webView = webView super.init(frame: .zero) self.frame = computeFrame() self.layer.cornerRadius = 10 self.layer.masksToBounds = true self.backgroundColor = AppFont.textColor self.alpha = 0.8 let colors = [ColorPicker.yellow, ColorPicker.red, ColorPicker.orange, ColorPicker.green, ColorPicker.blue, ColorPicker.salmon, ColorPicker.clear] let dotDiameter: CGFloat = 30.0 let yPos = (frame.height - dotDiameter) / 2.0 let spacer = (frame.width - (dotDiameter * CGFloat(colors.count))) / CGFloat(colors.count + 1) var xPos = spacer for color in colors { let frame = CGRect(x: xPos, y: yPos, width: dotDiameter, height: dotDiameter) let coloredDot = drawDot(frame: frame, color: color) self.addSubview(coloredDot) xPos += spacer + dotDiameter } } private func computeFrame() -> CGRect { let menu = UIMenuController.shared.menuFrame var yAdd: CGFloat = -menu.height switch UIMenuController.shared.arrowDirection { case .default: yAdd = -menu.height case .up: yAdd = menu.height case .down: yAdd = -menu.height case .left: yAdd = 0.0 // not tested case .right: yAdd = 0.0 // not tested } let result = CGRect(x: menu.minX, y: (menu.minY + yAdd), width: menu.width, height: menu.height) return result } private func drawDot(frame: CGRect, color: UIColor) -> UILabel { let label = UILabel(frame: frame) label.backgroundColor = color label.layer.cornerRadius = frame.width / 2.0 label.layer.masksToBounds = true let tapGesture = UITapGestureRecognizer(target: self.webView, action: #selector(self.webView.colorTouchHandler)) tapGesture.numberOfTapsRequired = 1 label.addGestureRecognizer(tapGesture) label.isUserInteractionEnabled = true return label } required init(coder: NSCoder) { self.webView = WKWebView() //self.selection = Selection(selection: "startNode:1:2/endNode:1:2") super.init(coder: coder)! } }
7e944339be1a60db0f4a7fe5b4637cce
39.991525
138
0.593756
false
false
false
false
ReSwift/ReSwift
refs/heads/master
Pods/ReSwift/ReSwift/CoreTypes/Subscription.swift
mit
3
// // SubscriberWrapper.swift // ReSwift // // Created by Virgilio Favero Neto on 4/02/2016. // Copyright © 2016 ReSwift Community. All rights reserved. // /// A box around subscriptions and subscribers. /// /// Acts as a type-erasing wrapper around a subscription and its transformed subscription. /// The transformed subscription has a type argument that matches the selected substate of the /// subscriber; however that type cannot be exposed to the store. /// /// The box subscribes either to the original subscription, or if available to the transformed /// subscription and passes any values that come through this subscriptions to the subscriber. class SubscriptionBox<State>: Hashable { private let originalSubscription: Subscription<State> weak var subscriber: AnyStoreSubscriber? private let objectIdentifier: ObjectIdentifier #if swift(>=5.0) func hash(into hasher: inout Hasher) { hasher.combine(self.objectIdentifier) } #elseif swift(>=4.2) #if compiler(>=5.0) func hash(into hasher: inout Hasher) { hasher.combine(self.objectIdentifier) } #else var hashValue: Int { return self.objectIdentifier.hashValue } #endif #else var hashValue: Int { return self.objectIdentifier.hashValue } #endif init<T>( originalSubscription: Subscription<State>, transformedSubscription: Subscription<T>?, subscriber: AnyStoreSubscriber ) { self.originalSubscription = originalSubscription self.subscriber = subscriber self.objectIdentifier = ObjectIdentifier(subscriber) // If we received a transformed subscription, we subscribe to that subscription // and forward all new values to the subscriber. if let transformedSubscription = transformedSubscription { transformedSubscription.observer = { [unowned self] _, newState in self.subscriber?._newState(state: newState as Any) } // If we haven't received a transformed subscription, we forward all values // from the original subscription. } else { originalSubscription.observer = { [unowned self] _, newState in self.subscriber?._newState(state: newState as Any) } } } func newValues(oldState: State, newState: State) { // We pass all new values through the original subscription, which accepts // values of type `<State>`. If present, transformed subscriptions will // receive this update and transform it before passing it on to the subscriber. self.originalSubscription.newValues(oldState: oldState, newState: newState) } static func == (left: SubscriptionBox<State>, right: SubscriptionBox<State>) -> Bool { return left.objectIdentifier == right.objectIdentifier } } /// Represents a subscription of a subscriber to the store. The subscription determines which new /// values from the store are forwarded to the subscriber, and how they are transformed. /// The subscription acts as a very-light weight signal/observable that you might know from /// reactive programming libraries. public class Subscription<State> { private func _select<Substate>( _ selector: @escaping (State) -> Substate ) -> Subscription<Substate> { return Subscription<Substate> { sink in self.observer = { oldState, newState in sink(oldState.map(selector) ?? nil, selector(newState)) } } } // MARK: Public Interface /// Initializes a subscription with a sink closure. The closure provides a way to send /// new values over this subscription. public init(sink: @escaping (@escaping (State?, State) -> Void) -> Void) { // Provide the caller with a closure that will forward all values // to observers of this subscription. sink { old, new in self.newValues(oldState: old, newState: new) } } /// Provides a subscription that selects a substate of the state of the original subscription. /// - parameter selector: A closure that maps a state to a selected substate public func select<Substate>( _ selector: @escaping (State) -> Substate ) -> Subscription<Substate> { return self._select(selector) } /// Provides a subscription that selects a substate of the state of the original subscription. /// - parameter keyPath: A key path from a state to a substate public func select<Substate>( _ keyPath: KeyPath<State, Substate> ) -> Subscription<Substate> { return self._select { $0[keyPath: keyPath] } } /// Provides a subscription that skips certain state updates of the original subscription. /// - parameter isRepeat: A closure that determines whether a given state update is a repeat and /// thus should be skipped and not forwarded to subscribers. /// - parameter oldState: The store's old state, before the action is reduced. /// - parameter newState: The store's new state, after the action has been reduced. public func skipRepeats(_ isRepeat: @escaping (_ oldState: State, _ newState: State) -> Bool) -> Subscription<State> { return Subscription<State> { sink in self.observer = { oldState, newState in switch (oldState, newState) { case let (old?, new): if !isRepeat(old, new) { sink(oldState, newState) } else { return } default: sink(oldState, newState) } } } } /// The closure called with changes from the store. /// This closure can be written to for use in extensions to Subscription similar to `skipRepeats` public var observer: ((State?, State) -> Void)? // MARK: Internals init() {} /// Sends new values over this subscription. Observers will be notified of these new values. func newValues(oldState: State?, newState: State) { self.observer?(oldState, newState) } } extension Subscription where State: Equatable { public func skipRepeats() -> Subscription<State>{ return self.skipRepeats(==) } } /// Subscription skipping convenience methods extension Subscription { /// Provides a subscription that skips certain state updates of the original subscription. /// /// This is identical to `skipRepeats` and is provided simply for convenience. /// - parameter when: A closure that determines whether a given state update is a repeat and /// thus should be skipped and not forwarded to subscribers. /// - parameter oldState: The store's old state, before the action is reduced. /// - parameter newState: The store's new state, after the action has been reduced. public func skip(when: @escaping (_ oldState: State, _ newState: State) -> Bool) -> Subscription<State> { return self.skipRepeats(when) } /// Provides a subscription that only updates for certain state changes. /// /// This is effectively the inverse of `skip(when:)` / `skipRepeats(:)` /// - parameter when: A closure that determines whether a given state update should notify /// - parameter oldState: The store's old state, before the action is reduced. /// - parameter newState: The store's new state, after the action has been reduced. /// the subscriber. public func only(when: @escaping (_ oldState: State, _ newState: State) -> Bool) -> Subscription<State> { return self.skipRepeats { oldState, newState in return !when(oldState, newState) } } }
5e1bc87d3048cf6225f69a1d5efac078
39.4
109
0.649784
false
false
false
false
iAladdin/SwiftyFORM
refs/heads/master
Source/Cells/DatePickerCell.swift
mit
1
// // DatePickerCell.swift // SwiftyFORM // // Created by Simon Strandgaard on 08/11/14. // Copyright (c) 2014 Simon Strandgaard. All rights reserved. // import UIKit public struct DatePickerCellModel { var title: String = "" var toolbarMode: ToolbarMode = .Simple var datePickerMode: UIDatePickerMode = .DateAndTime var locale: NSLocale? = nil // default is [NSLocale currentLocale]. setting nil returns to default var minimumDate: NSDate? = nil // specify min/max date range. default is nil. When min > max, the values are ignored. Ignored in countdown timer mode var maximumDate: NSDate? = nil // default is nil var valueDidChange: NSDate -> Void = { (date: NSDate) in DLog("date \(date)") } } public class DatePickerCell: UITableViewCell, SelectRowDelegate { public let model: DatePickerCellModel public init(model: DatePickerCellModel) { /* Known problem: UIDatePickerModeCountDownTimer is buggy and therefore not supported UIDatePicker has a bug in it when used in UIDatePickerModeCountDownTimer mode. The picker does not fire the target-action associated with the UIControlEventValueChanged event the first time the user changes the value by scrolling the wheels. It works fine for subsequent changes. http://stackoverflow.com/questions/20181980/uidatepicker-bug-uicontroleventvaluechanged-after-hitting-minimum-internal http://stackoverflow.com/questions/19251803/objective-c-uidatepicker-uicontroleventvaluechanged-only-fired-on-second-select Possible work around: Continuously poll for changes. */ assert(model.datePickerMode != .CountDownTimer, "CountDownTimer is not supported") self.model = model super.init(style: .Value1, reuseIdentifier: nil) selectionStyle = .Default textLabel?.text = model.title updateValue() assignDefaultColors() } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func assignDefaultColors() { textLabel?.textColor = UIColor.blackColor() detailTextLabel?.textColor = UIColor.grayColor() } public func assignTintColors() { let color = self.tintColor DLog("assigning tint color: \(color)") textLabel?.textColor = color detailTextLabel?.textColor = color } public func resolveLocale() -> NSLocale { return model.locale ?? NSLocale.currentLocale() } public lazy var datePicker: UIDatePicker = { let instance = UIDatePicker() instance.datePickerMode = self.model.datePickerMode instance.minimumDate = self.model.minimumDate instance.maximumDate = self.model.maximumDate instance.addTarget(self, action: "valueChanged", forControlEvents: .ValueChanged) instance.locale = self.resolveLocale() return instance }() public lazy var toolbar: SimpleToolbar = { let instance = SimpleToolbar() weak var weakSelf = self instance.jumpToPrevious = { if let cell = weakSelf { cell.gotoPrevious() } } instance.jumpToNext = { if let cell = weakSelf { cell.gotoNext() } } instance.dismissKeyboard = { if let cell = weakSelf { cell.dismissKeyboard() } } return instance }() public func updateToolbarButtons() { if model.toolbarMode == .Simple { toolbar.updateButtonConfiguration(self) } } public func gotoPrevious() { DLog("make previous cell first responder") form_makePreviousCellFirstResponder() } public func gotoNext() { DLog("make next cell first responder") form_makeNextCellFirstResponder() } public func dismissKeyboard() { DLog("dismiss keyboard") resignFirstResponder() } public override var inputView: UIView? { return datePicker } public override var inputAccessoryView: UIView? { if model.toolbarMode == .Simple { return toolbar } return nil } public func valueChanged() { let date = datePicker.date model.valueDidChange(date) updateValue() } public func obtainDateStyle(datePickerMode: UIDatePickerMode) -> NSDateFormatterStyle { switch datePickerMode { case .Time: return .NoStyle case .Date: return .LongStyle case .DateAndTime: return .ShortStyle case .CountDownTimer: return .NoStyle } } public func obtainTimeStyle(datePickerMode: UIDatePickerMode) -> NSDateFormatterStyle { switch datePickerMode { case .Time: return .ShortStyle case .Date: return .NoStyle case .DateAndTime: return .ShortStyle case .CountDownTimer: return .ShortStyle } } public func humanReadableValue() -> String { if model.datePickerMode == .CountDownTimer { let t = datePicker.countDownDuration let date = NSDate(timeIntervalSinceReferenceDate: t) let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)! calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0) let components = calendar.components([NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: date) let hour = components.hour let minute = components.minute return String(format: "%02d:%02d", hour, minute) } if true { let date = datePicker.date //DLog("date: \(date)") let dateFormatter = NSDateFormatter() dateFormatter.locale = self.resolveLocale() dateFormatter.dateStyle = obtainDateStyle(model.datePickerMode) dateFormatter.timeStyle = obtainTimeStyle(model.datePickerMode) return dateFormatter.stringFromDate(date) } } public func updateValue() { detailTextLabel?.text = humanReadableValue() } public func setDateWithoutSync(date: NSDate?, animated: Bool) { DLog("set date \(date), animated \(animated)") datePicker.setDate(date ?? NSDate(), animated: animated) updateValue() } public func form_didSelectRow(indexPath: NSIndexPath, tableView: UITableView) { // Hide the datepicker wheel, if it's already visible // Otherwise show the datepicker let alreadyFirstResponder = (self.form_firstResponder() != nil) if alreadyFirstResponder { tableView.form_firstResponder()?.resignFirstResponder() tableView.deselectRowAtIndexPath(indexPath, animated: true) return } //DLog("will invoke") // hide keyboard when the user taps this kind of row tableView.form_firstResponder()?.resignFirstResponder() self.becomeFirstResponder() tableView.deselectRowAtIndexPath(indexPath, animated: true) //DLog("did invoke") } // MARK: UIResponder public override func canBecomeFirstResponder() -> Bool { return true } public override func becomeFirstResponder() -> Bool { let result = super.becomeFirstResponder() updateToolbarButtons() assignTintColors() return result } public override func resignFirstResponder() -> Bool { super.resignFirstResponder() assignDefaultColors() return true } }
d63db6416847b0850929a014a25ad489
27.07173
150
0.737261
false
false
false
false
zyuanming/EffectDesignerX
refs/heads/master
EffectDesignerX/Model/EmitterCellModel.swift
mit
1
// // EmitterCellModel.swift // EffectDesignerX // // Created by Zhang Yuanming on 10/13/16. // Copyright © 2016 Zhang Yuanming. All rights reserved. // import Foundation class EmitterCellModel: NSObject { dynamic var birthRate: CGFloat = 0 dynamic var lifetime: CGFloat = 0 dynamic var lifetimeRange: CGFloat = 0 dynamic var velocity: CGFloat = 0 dynamic var velocityRange: CGFloat = 0 dynamic var emissionLatitude: CGFloat = 0 dynamic var emissionLongitude: CGFloat = 0 dynamic var emissionRange: CGFloat = 0 dynamic var xAcceleration: CGFloat = 0 dynamic var yAcceleration: CGFloat = 0 dynamic var zAcceleration: CGFloat = 0 dynamic var contents: String = "" dynamic var contentsRect: String = "" dynamic var name: String = "" dynamic var color: NSColor = NSColor.white dynamic var redRange: CGFloat = 0 dynamic var redSpeed: CGFloat = 0 dynamic var greenRange: CGFloat = 0 dynamic var greenSpeed: CGFloat = 0 dynamic var blueRange: CGFloat = 0 dynamic var blueSpeed: CGFloat = 0 dynamic var alpha: CGFloat = 0 dynamic var alphaRange: CGFloat = 0 dynamic var alphaSpeed: CGFloat = 0 dynamic var scale: CGFloat = 0 dynamic var scaleRange: CGFloat = 0 dynamic var scaleSpeed: CGFloat = 0 dynamic var spin: CGFloat = 0 dynamic var spinRange: CGFloat = 0 dynamic var contentsImage: NSImage? func toDictionary() -> [String: Any] { var dic: [String: Any] = [:] dic["birthRate"] = self.birthRate dic["lifetime"] = self.lifetime dic["lifetimeRange"] = self.lifetimeRange dic["velocity"] = self.velocity dic["velocityRange"] = self.velocityRange dic["emissionLatitude"] = self.emissionLatitude dic["emissionLongitude"] = self.emissionLongitude dic["emissionRange"] = self.emissionRange dic["xAcceleration"] = self.xAcceleration dic["yAcceleration"] = self.yAcceleration dic["zAcceleration"] = self.zAcceleration dic["contents"] = self.contents dic["contentsRect"] = self.contentsRect dic["name"] = self.name dic["color"] = self.color.getHexString(withAlpha: alpha) dic["redRange"] = self.redRange dic["redSpeed"] = self.redSpeed dic["greenRange"] = self.greenRange dic["greenSpeed"] = self.greenSpeed dic["blueRange"] = self.blueRange dic["blueSpeed"] = self.blueSpeed dic["alphaRange"] = self.alphaRange dic["alphaSpeed"] = self.alphaSpeed dic["scale"] = self.scale dic["scaleRange"] = self.scaleRange dic["scaleSpeed"] = self.scaleSpeed dic["spin"] = self.spin dic["spinRange"] = self.spinRange return dic } func allPropertyNames() -> [String] { return Mirror(reflecting: self).children.flatMap({ $0.label }) } func update(from effectModel: EmitterCellModel) { self.birthRate = effectModel.birthRate self.lifetime = effectModel.lifetime self.lifetimeRange = effectModel.lifetimeRange self.velocity = effectModel.velocity self.velocityRange = effectModel.velocityRange self.emissionRange = effectModel.emissionRange self.emissionLongitude = effectModel.emissionLongitude self.emissionLatitude = effectModel.emissionLatitude self.xAcceleration = effectModel.xAcceleration self.yAcceleration = effectModel.yAcceleration self.zAcceleration = effectModel.zAcceleration self.contents = effectModel.contents self.contentsRect = effectModel.contentsRect self.name = effectModel.name self.color = effectModel.color self.redRange = effectModel.redRange self.redSpeed = effectModel.redSpeed self.greenRange = effectModel.greenRange self.greenSpeed = effectModel.greenSpeed self.blueRange = effectModel.blueRange self.blueSpeed = effectModel.blueSpeed self.alpha = effectModel.alpha self.alphaRange = effectModel.alphaRange self.alphaSpeed = effectModel.alphaSpeed self.scale = effectModel.scale self.scaleRange = effectModel.scaleRange self.scaleSpeed = effectModel.scaleSpeed self.spin = effectModel.spin self.spinRange = effectModel.spinRange self.contentsImage = effectModel.contentsImage } func update2(from effectModel: BindingModel) { self.birthRate = effectModel.birthRate self.lifetime = effectModel.lifetime self.lifetimeRange = effectModel.lifetimeRange self.velocity = effectModel.velocity self.velocityRange = effectModel.velocityRange self.emissionRange = effectModel.emissionRange self.emissionLongitude = effectModel.emissionLongitude self.emissionLatitude = effectModel.emissionLatitude self.xAcceleration = effectModel.xAcceleration self.yAcceleration = effectModel.yAcceleration self.zAcceleration = effectModel.zAcceleration self.contents = effectModel.contents self.contentsRect = effectModel.contentsRect self.name = effectModel.name self.color = effectModel.color self.redRange = effectModel.redRange self.redSpeed = effectModel.redSpeed self.greenRange = effectModel.greenRange self.greenSpeed = effectModel.greenSpeed self.blueRange = effectModel.blueRange self.blueSpeed = effectModel.blueSpeed self.alpha = effectModel.alpha self.alphaRange = effectModel.alphaRange self.alphaSpeed = effectModel.alphaSpeed self.scale = effectModel.scale self.scaleRange = effectModel.scaleRange self.scaleSpeed = effectModel.scaleSpeed self.spin = effectModel.spin self.spinRange = effectModel.spinRange self.contentsImage = effectModel.contentsImage } }
836a28f20b5253c4bc7c53aa3718242b
38.430464
70
0.680215
false
false
false
false
apple/swift-protobuf
refs/heads/main
Tests/SwiftProtobufTests/Test_MapFields_Access_Proto2.swift
apache-2.0
3
// Test/Sources/TestSuite/Test_MapFields_Access_Proto2.swift // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Exercises the apis map fields. /// // ----------------------------------------------------------------------------- import XCTest import Foundation // NOTE: The generator changes what is generated based on the number/types // of fields (using a nested storage class or not), to be completel, all // these tests should be done once with a message that gets that storage // class and a second time with messages that avoid that. class Test_MapFields_Access_Proto2: XCTestCase { func testMapInt32Int32() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapInt32Int32, [:]) msg.mapInt32Int32 = [70: 1070] XCTAssertEqual(msg.mapInt32Int32, [70: 1070]) msg.mapInt32Int32[170] = 1170 XCTAssertEqual(msg.mapInt32Int32, [70: 1070, 170: 1170]) } func testMapInt64Int64() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapInt64Int64, [:]) msg.mapInt64Int64 = [71: 1071] XCTAssertEqual(msg.mapInt64Int64, [71: 1071]) msg.mapInt64Int64[171] = 1171 XCTAssertEqual(msg.mapInt64Int64, [71: 1071, 171: 1171]) } func testMapUint32Uint32() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapUint32Uint32, [:]) msg.mapUint32Uint32 = [72: 1072] XCTAssertEqual(msg.mapUint32Uint32, [72: 1072]) msg.mapUint32Uint32[172] = 1172 XCTAssertEqual(msg.mapUint32Uint32, [72: 1072, 172: 1172]) } func testMapUint64Uint64() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapUint64Uint64, [:]) msg.mapUint64Uint64 = [73: 1073] XCTAssertEqual(msg.mapUint64Uint64, [73: 1073]) msg.mapUint64Uint64[173] = 1173 XCTAssertEqual(msg.mapUint64Uint64, [73: 1073, 173: 1173]) } func testMapSint32Sint32() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapSint32Sint32, [:]) msg.mapSint32Sint32 = [74: 1074] XCTAssertEqual(msg.mapSint32Sint32, [74: 1074]) msg.mapSint32Sint32[174] = 1174 XCTAssertEqual(msg.mapSint32Sint32, [74: 1074, 174: 1174]) } func testMapSint64Sint64() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapSint64Sint64, [:]) msg.mapSint64Sint64 = [75: 1075] XCTAssertEqual(msg.mapSint64Sint64, [75: 1075]) msg.mapSint64Sint64[175] = 1175 XCTAssertEqual(msg.mapSint64Sint64, [75: 1075, 175: 1175]) } func testMapFixed32Fixed32() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapFixed32Fixed32, [:]) msg.mapFixed32Fixed32 = [76: 1076] XCTAssertEqual(msg.mapFixed32Fixed32, [76: 1076]) msg.mapFixed32Fixed32[176] = 1176 XCTAssertEqual(msg.mapFixed32Fixed32, [76: 1076, 176: 1176]) } func testMapFixed64Fixed64() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapFixed64Fixed64, [:]) msg.mapFixed64Fixed64 = [77: 1077] XCTAssertEqual(msg.mapFixed64Fixed64, [77: 1077]) msg.mapFixed64Fixed64[177] = 1177 XCTAssertEqual(msg.mapFixed64Fixed64, [77: 1077, 177: 1177]) } func testMapSfixed32Sfixed32() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapSfixed32Sfixed32, [:]) msg.mapSfixed32Sfixed32 = [78: 1078] XCTAssertEqual(msg.mapSfixed32Sfixed32, [78: 1078]) msg.mapSfixed32Sfixed32[178] = 1178 XCTAssertEqual(msg.mapSfixed32Sfixed32, [78: 1078, 178: 1178]) } func testMapSfixed64Sfixed64() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapSfixed64Sfixed64, [:]) msg.mapSfixed64Sfixed64 = [79: 1079] XCTAssertEqual(msg.mapSfixed64Sfixed64, [79: 1079]) msg.mapSfixed64Sfixed64[179] = 1179 XCTAssertEqual(msg.mapSfixed64Sfixed64, [79: 1079, 179: 1179]) } func testMapInt32Float() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapInt32Float, [:]) msg.mapInt32Float = [80: 1080.0] XCTAssertEqual(msg.mapInt32Float, [80: 1080.0]) msg.mapInt32Float[180] = 1180.0 XCTAssertEqual(msg.mapInt32Float, [80: 1080.0, 180: 1180.0]) } func testMapInt32Double() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapInt32Double, [:]) msg.mapInt32Double = [81: 1081.0] XCTAssertEqual(msg.mapInt32Double, [81: 1081.0]) msg.mapInt32Double[181] = 1181.0 XCTAssertEqual(msg.mapInt32Double, [81: 1081, 181: 1181.0]) } func testMapBoolBool() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapBoolBool, [:]) msg.mapBoolBool = [true: false] XCTAssertEqual(msg.mapBoolBool, [true: false]) msg.mapBoolBool[false] = true XCTAssertEqual(msg.mapBoolBool, [true: false, false: true]) } func testMapStringString() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapStringString, [:]) msg.mapStringString = ["83": "1083"] XCTAssertEqual(msg.mapStringString, ["83": "1083"]) msg.mapStringString["183"] = "1183" XCTAssertEqual(msg.mapStringString, ["83": "1083", "183": "1183"]) } func testMapStringBytes() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapStringBytes, [:]) msg.mapStringBytes = ["84": Data([84])] XCTAssertEqual(msg.mapStringBytes, ["84": Data([84])]) msg.mapStringBytes["184"] = Data([184]) XCTAssertEqual(msg.mapStringBytes, ["84": Data([84]), "184": Data([184])]) } func testMapStringMessage() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapStringMessage, [:]) var valueMsg1 = ProtobufUnittest_Message2() valueMsg1.optionalInt32 = 1085 msg.mapStringMessage = ["85": valueMsg1] XCTAssertEqual(msg.mapStringMessage.count, 1) if let v = msg.mapStringMessage["85"] { XCTAssertEqual(v.optionalInt32, 1085) } else { XCTFail("Lookup failed") } XCTAssertEqual(msg.mapStringMessage, ["85": valueMsg1]) var valueMsg2 = ProtobufUnittest_Message2() valueMsg2.optionalInt32 = 1185 msg.mapStringMessage["185"] = valueMsg2 XCTAssertEqual(msg.mapStringMessage.count, 2) if let v = msg.mapStringMessage["85"] { XCTAssertEqual(v.optionalInt32, 1085) } else { XCTFail("Lookup failed") } if let v = msg.mapStringMessage["185"] { XCTAssertEqual(v.optionalInt32, 1185) } else { XCTFail("Lookup failed") } XCTAssertEqual(msg.mapStringMessage, ["85": valueMsg1, "185": valueMsg2]) } func testMapInt32Bytes() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapInt32Bytes, [:]) msg.mapInt32Bytes = [86: Data([86])] XCTAssertEqual(msg.mapInt32Bytes, [86: Data([86])]) msg.mapInt32Bytes[186] = Data([186]) XCTAssertEqual(msg.mapInt32Bytes, [86: Data([86]), 186: Data([186])]) } func testMapInt32Enum() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapInt32Enum, [:]) msg.mapInt32Enum = [87: .bar] XCTAssertEqual(msg.mapInt32Enum, [87: .bar]) msg.mapInt32Enum[187] = .baz XCTAssertEqual(msg.mapInt32Enum, [87: .bar, 187: .baz]) } func testMapInt32Message() { var msg = ProtobufUnittest_Message2() XCTAssertEqual(msg.mapInt32Message, [:]) var valueMsg1 = ProtobufUnittest_Message2() valueMsg1.optionalInt32 = 1088 msg.mapInt32Message = [88: valueMsg1] XCTAssertEqual(msg.mapInt32Message.count, 1) if let v = msg.mapInt32Message[88] { XCTAssertEqual(v.optionalInt32, 1088) } else { XCTFail("Lookup failed") } XCTAssertEqual(msg.mapInt32Message, [88: valueMsg1]) var valueMsg2 = ProtobufUnittest_Message2() valueMsg2.optionalInt32 = 1188 msg.mapInt32Message[188] = valueMsg2 XCTAssertEqual(msg.mapInt32Message.count, 2) if let v = msg.mapInt32Message[88] { XCTAssertEqual(v.optionalInt32, 1088) } else { XCTFail("Lookup failed") } if let v = msg.mapInt32Message[188] { XCTAssertEqual(v.optionalInt32, 1188) } else { XCTFail("Lookup failed") } XCTAssertEqual(msg.mapInt32Message, [88: valueMsg1, 188: valueMsg2]) } }
edb3120371d3de07e6900ee55975c66e
33.890756
80
0.677384
false
true
false
false
geekaurora/ReactiveListViewKit
refs/heads/master
Example/ReactiveListViewKitDemo/UI Layer/FeedList/FeedListViewModel.swift
mit
1
// // FeedListViewModel.swift // ReactiveListViewKitDemo // // Created by Cheng Zhang on 7/14/17. // Copyright © 2017 Cheng Zhang. All rights reserved. // import UIKit import CZUtils import ReactiveListViewKit typealias FeedListState = FeedListViewModel /** State/ViewModel of `FeedListViewController`, composed of elements needed for UI populating */ class FeedListViewModel: NSObject, CopyableState { /// List of feeds private(set) lazy var feeds: [Feed] = { return CZMocker.shared.feeds }() /// List of users with Story private(set) var storyUsers: [User] = { return CZMocker.shared.hotUsers }() /// List of suggested users private(set) var suggestedUsers: [User] = { return CZMocker.shared.hotUsers }() /// Current page number private(set) var page: Int = 0 /// Indicates whether is loading feeds private(set) var isLoadingFeeds: Bool = false /// Last minimum FeedId, used as baseId for feeds request private(set) var lastMinFeedId: String = "-1" /// `Store` of FLUX, composed of `Dispatcher` and `Store` var store: Store<FeedListState>? /// SectionModelsTransformer closure - mapping feeds to sectionModels var sectionModelsTransformer: CZFeedListFacadeView.SectionModelsTransformer! override init() { super.init() /// SectionModelsTransformer closure - mapping feeds to sectionModels sectionModelsTransformer = { (feeds: [Any]) -> [CZSectionModel] in guard let feeds = feeds as? [Feed] else { fatalError() } var sectionModels = [CZSectionModel]() // HotUsers section let HotUsersFeedModels = self.storyUsers.compactMap { CZFeedModel(viewClass: HotUserCellView.self, viewModel: HotUserCellViewModel($0)) } let hotUsersSectionModel = CZSectionModel(isHorizontal: true, heightForHorizontal: HotUserSection.heightForHorizontal, feedModels: HotUsersFeedModels, headerModel: CZFeedListSupplementaryTextFeedModel(title: "Stories", inset: UIEdgeInsets(top: 8, left: 10, bottom: 1, right: 10)), footerModel: CZFeedListSupplementaryLineFeedModel(), sectionInset: UIEdgeInsets(top: 0, left: 3, bottom: 0, right: 5)) sectionModels.append(hotUsersSectionModel) // Feeds section var feedModels = feeds.compactMap { CZFeedModel(viewClass: FeedCellView.self, viewModel: FeedCellViewModel($0)) } // SuggestedUsers - CellViewController if feedModels.count > 0 { let suggestedUsers = self.suggestedUsers let suggestedUsersFeedModel = CZFeedModel(viewClass: HotUsersCellViewController.self, viewModel: HotUsersCellViewModel(suggestedUsers)) feedModels.insert(suggestedUsersFeedModel, at: 3) } let feedsSectionModel = CZSectionModel(feedModels: feedModels) sectionModels.append(feedsSectionModel) return sectionModels } } func copy(with zone: NSZone? = nil) -> Any { return self } } extension FeedListViewModel: State { /// Reacts to action func reduce(action: Action) { feeds.forEach { $0.reduce(action: action) } switch action { case let CZFeedListViewAction.selectedCell(feedModel): break default: break } } }
aefdbbe6aa5a7d099c7bf1ae417d67b0
43.201923
136
0.494018
false
false
false
false
madeatsampa/MacMagazine-iOS
refs/heads/release/4.2
MacMagazine/APIXMLParser.swift
mit
1
// // XMLParser.swift // MacMagazine // // Created by Cassio Rossi on 15/04/2019. // Copyright © 2019 MacMagazine. All rights reserved. // import UIKit struct XMLPost: Hashable { var title: String = "" var link: String = "" var pubDate: String = "" var categories: [String] = [] var excerpt: String = "" var artworkURL: String = "" var podcastURL: String = "" var podcast: String = "" var duration: String = "" var podcastFrame: String = "" var favorite: Bool = false var postId: String = "" var shortURL: String = "" fileprivate func decodeHTMLString(string: String) -> String { guard let encodedData = string.data(using: String.Encoding.utf8) else { return "" } do { return try NSAttributedString(data: encodedData, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil).string } catch { return error.localizedDescription } } func getCategorias() -> String { return self.categories.joined(separator: ",") } } class APIXMLParser: NSObject, XMLParserDelegate { // MARK: - Properties - var onCompletion: ((XMLPost?) -> Void)? var currentPost = XMLPost() var processItem = false var value = "" var attributes: [String: String]? var numberOfPosts = -1 var parsedPosts = 0 // MARK: - Init - init(onCompletion: ((XMLPost?) -> Void)?, numberOfPosts: Int) { self.onCompletion = onCompletion self.numberOfPosts = numberOfPosts } // MARK: - Parse Delegate - func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String] = [:]) { value = "" if elementName == "item" { processItem = true currentPost = XMLPost() } if elementName == "media:content" { attributes = attributeDict } if elementName == "enclosure" { attributes = attributeDict } } func parser(_ parser: XMLParser, foundCharacters string: String) { if processItem { value += string } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if processItem { value = value.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) switch elementName { case "post-id": currentPost.postId = value case "title": currentPost.title = value case "link": currentPost.link = value case "pubDate": currentPost.pubDate = value case "category": if currentPost.categories.isEmpty { currentPost.categories = [] } currentPost.categories.append(value) case "description": currentPost.excerpt = value case "media:content": guard let url = attributes?["url"] else { return } currentPost.artworkURL = url case "enclosure": guard let url = attributes?["url"] else { return } currentPost.podcastURL = url case "itunes:subtitle": currentPost.podcast = value case "itunes:duration": currentPost.duration = value case "rawvoice:embed": currentPost.podcastFrame = value case "item": onCompletion?(currentPost) parsedPosts += 1 processItem = false if numberOfPosts > 0 && parsedPosts >= numberOfPosts { parser.abortParsing() } case "guid": currentPost.shortURL = value default: return } } } func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) { onCompletion?(nil) } func parserDidEndDocument(_ parser: XMLParser) { onCompletion?(nil) } }
396b7c8be17ab1b7210ee4539b024c09
23.840278
198
0.671792
false
false
false
false
tellowkrinkle/Sword
refs/heads/master
Sources/Sword/Types/VoiceState.swift
mit
1
// // VoiceState.swift // Sword // // Created by Alejandro Alonso // Copyright © 2017 Alejandro Alonso. All rights reserved. // /// Structure with user's voice state info public struct VoiceState { // MARK: Properties /// The ID of the voice channel public let channelId: ChannelID /// Whether or not the user is server deafend public let isDeafend: Bool /// Whether or not the user is server muted public let isMuted: Bool /// Whether or not the user self deafend themselves public let isSelfDeafend: Bool /// Whether or not the user self muted themselves public let isSelfMuted: Bool /// Whether or not the bot suppressed the user public let isSuppressed: Bool /// The Session ID of the user and voice connection public let sessionId: String // MARK: Initializer /** Cretaes VoiceState structure - parameter json: The json data */ init(_ json: [String: Any]) { self.channelId = ChannelID(json["channel_id"] as! String)! self.isDeafend = json["deaf"] as! Bool self.isMuted = json["mute"] as! Bool self.isSelfDeafend = json["self_deaf"] as! Bool self.isSelfMuted = json["self_mute"] as! Bool self.isSuppressed = json["suppress"] as! Bool self.sessionId = json["session_id"] as! String } }
9e9d44b54300a5b47022cefbf7082e63
23.615385
62
0.685938
false
false
false
false
michael-lehew/swift-corelibs-foundation
refs/heads/master
Foundation/NSPersonNameComponents.swift
apache-2.0
1
// 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 // open class NSPersonNameComponents : NSObject, NSCopying, NSSecureCoding { public convenience required init?(coder aDecoder: NSCoder) { self.init() guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } func bridgeOptionalString(_ value: NSString?) -> String? { if let obj = value { return String._unconditionallyBridgeFromObjectiveC(obj) } else { return nil } } self.namePrefix = bridgeOptionalString(aDecoder.decodeObject(of: NSString.self, forKey: "NS.namePrefix") as NSString?) self.givenName = bridgeOptionalString(aDecoder.decodeObject(of: NSString.self, forKey: "NS.givenName") as NSString?) self.middleName = bridgeOptionalString(aDecoder.decodeObject(of: NSString.self, forKey: "NS.middleName") as NSString?) self.familyName = bridgeOptionalString(aDecoder.decodeObject(of: NSString.self, forKey: "NS.familyName") as NSString?) self.nameSuffix = bridgeOptionalString(aDecoder.decodeObject(of: NSString.self, forKey: "NS.nameSuffix") as NSString?) self.nickname = bridgeOptionalString(aDecoder.decodeObject(of: NSString.self, forKey: "NS.nickname") as NSString?) } static public var supportsSecureCoding: Bool { return true } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(self.namePrefix?._bridgeToObjectiveC(), forKey: "NS.namePrefix") aCoder.encode(self.givenName?._bridgeToObjectiveC(), forKey: "NS.givenName") aCoder.encode(self.middleName?._bridgeToObjectiveC(), forKey: "NS.middleName") aCoder.encode(self.familyName?._bridgeToObjectiveC(), forKey: "NS.familyName") aCoder.encode(self.nameSuffix?._bridgeToObjectiveC(), forKey: "NS.nameSuffix") aCoder.encode(self.nickname?._bridgeToObjectiveC(), forKey: "NS.nickname") } open func copy(with zone: NSZone? = nil) -> Any { NSUnimplemented() } /* The below examples all assume the full name Dr. Johnathan Maple Appleseed Esq., nickname "Johnny" */ /* Pre-nominal letters denoting title, salutation, or honorific, e.g. Dr., Mr. */ open var namePrefix: String? /* Name bestowed upon an individual by one's parents, e.g. Johnathan */ open var givenName: String? /* Secondary given name chosen to differentiate those with the same first name, e.g. Maple */ open var middleName: String? /* Name passed from one generation to another to indicate lineage, e.g. Appleseed */ open var familyName: String? /* Post-nominal letters denoting degree, accreditation, or other honor, e.g. Esq., Jr., Ph.D. */ open var nameSuffix: String? /* Name substituted for the purposes of familiarity, e.g. "Johnny"*/ open var nickname: String? /* Each element of the phoneticRepresentation should correspond to an element of the original PersonNameComponents instance. The phoneticRepresentation of the phoneticRepresentation object itself will be ignored. nil by default, must be instantiated. */ /*@NSCopying*/ open var phoneticRepresentation: PersonNameComponents? } extension NSPersonNameComponents : _StructTypeBridgeable { public typealias _StructType = PersonNameComponents public func _bridgeToSwift() -> _StructType { return PersonNameComponents._unconditionallyBridgeFromObjectiveC(self) } }
a86703261f5b7af659f5048fc5f3b6f2
47.864198
132
0.697322
false
false
false
false
IBAnimatable/IBAnimatable
refs/heads/master
Sources/Animators/TransitionAnimator/NatGeoAnimator.swift
mit
2
// // Created by Tom Baranes on 24/04/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public class NatGeoAnimator: NSObject, AnimatedTransitioning { // MARK: - AnimatorProtocol public var transitionAnimationType: TransitionAnimationType public var transitionDuration: Duration = defaultTransitionDuration public var reverseAnimationType: TransitionAnimationType? public var interactiveGestureType: InteractiveGestureType? // MARK: - private fileprivate var fromDirection: TransitionAnimationType.Direction fileprivate let firstPartRatio: Double = 0.8 // MARK: - Life cycle public init(from direction: TransitionAnimationType.Direction, duration: Duration) { transitionDuration = duration fromDirection = direction transitionAnimationType = .natGeo(to: direction) reverseAnimationType = .natGeo(to: direction.opposite) super.init() } } extension NatGeoAnimator: UIViewControllerAnimatedTransitioning { public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return retrieveTransitionDuration(transitionContext: transitionContext) } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let (tempfromView, tempToView, tempContainerView) = retrieveViews(transitionContext: transitionContext) guard let fromView = tempfromView, let toView = tempToView, let containerView = tempContainerView else { transitionContext.completeTransition(true) return } let (_, tempToViewController, _) = retrieveViewControllers(transitionContext: transitionContext) if let toViewController = tempToViewController { toView.frame = transitionContext.finalFrame(for: toViewController) } containerView.addSubview(toView) containerView.addSubview(fromView) if fromDirection == .left { executeLeftAnimation(context: transitionContext, containerView: containerView, fromView: fromView, toView: toView) } else { executeRightAnimations(context: transitionContext, containerView: containerView, fromView: fromView, toView: toView) } } } // MARK: - Left private extension NatGeoAnimator { func executeLeftAnimation(context transitionContext: UIViewControllerContextTransitioning, containerView: UIView, fromView: UIView, toView: UIView) { fromView.isUserInteractionEnabled = false var fromLayer = fromView.layer var toLayer = toView.layer let oldFrame = fromLayer.frame let oldCenter = fromView.center let oldAnchorPoint = fromLayer.anchorPoint fromLayer.anchorPoint = CGPoint(x: 0.0, y: 0.5) fromLayer.frame = oldFrame sourceFirstTransform(&fromLayer) destinationFirstTransform(&toLayer) UIView.animateKeyframes(withDuration: transitionDuration, delay: 0.0, options: .calculationModeCubic, animations: { UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 1.0) { self.destinationLastTransform(&toLayer) } UIView.addKeyframe(withRelativeStartTime: 1.0 - self.firstPartRatio, relativeDuration: self.firstPartRatio) { self.sourceLastTransform(&fromLayer) } }) { _ in if transitionContext.transitionWasCancelled { containerView.bringSubviewToFront(fromView) fromView.isUserInteractionEnabled = true } self.animationDidFinish(transitionContext, containerView: containerView, fromView: fromView, toView: toView) fromLayer.anchorPoint = oldAnchorPoint fromView.center = oldCenter } } } // MARK: - Right private extension NatGeoAnimator { func executeRightAnimations(context transitionContext: UIViewControllerContextTransitioning, containerView: UIView, fromView: UIView, toView: UIView) { toView.isUserInteractionEnabled = true var fromLayer = toView.layer var toLayer = fromView.layer let oldFrame = fromLayer.frame let oldCenter = toView.center let oldAnchorPoint = fromLayer.anchorPoint fromLayer.anchorPoint = CGPoint(x: 0.0, y: 0.5) fromLayer.frame = oldFrame sourceLastTransform(&fromLayer) destinationLastTransform(&toLayer) UIView.animateKeyframes(withDuration: transitionDuration, delay: 0.0, options: .calculationModeCubic, animations: { UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: self.firstPartRatio) { self.sourceFirstTransform(&fromLayer) } UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 1.0) { self.destinationFirstTransform(&toLayer) } }) { _ in if transitionContext.transitionWasCancelled { containerView.bringSubviewToFront(fromView) toView.isUserInteractionEnabled = false } self.animationDidFinish(transitionContext, containerView: containerView, fromView: fromView, toView: toView) fromLayer.anchorPoint = oldAnchorPoint toView.center = oldCenter } } } // MARK: - Helpers private extension NatGeoAnimator { func sourceFirstTransform(_ layer: inout CALayer) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -500 transform = CATransform3DTranslate(transform, 0.0, 0.0, 0.0) layer.transform = transform } func sourceLastTransform(_ layer: inout CALayer) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -500.0 transform = CATransform3DRotate(transform, radianFromDegree(80), 0.0, 1.0, 0.0) transform = CATransform3DTranslate(transform, 0.0, 0.0, -30.0) transform = CATransform3DTranslate(transform, 170.0, 0.0, 0.0) layer.transform = transform } func destinationFirstTransform(_ layer: inout CALayer) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -500.0 transform = CATransform3DRotate(transform, radianFromDegree(5.0), 0.0, 0.0, 1.0) transform = CATransform3DTranslate(transform, 320.0, -40.0, 150.0) transform = CATransform3DRotate(transform, radianFromDegree(-45), 0.0, 1.0, 0.0) transform = CATransform3DRotate(transform, radianFromDegree(10), 1.0, 0.0, 0.0) layer.transform = transform } func destinationLastTransform(_ layer: inout CALayer) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -500 transform = CATransform3DRotate(transform, radianFromDegree(0), 0.0, 0.0, 1.0) transform = CATransform3DTranslate(transform, 0.0, 0.0, 0.0) transform = CATransform3DRotate(transform, radianFromDegree(0), 0.0, 1.0, 0.0) transform = CATransform3DRotate(transform, radianFromDegree(0), 1.0, 0.0, 0.0) layer.transform = transform } func radianFromDegree(_ degrees: Double) -> CGFloat { return CGFloat((degrees / 180) * .pi) } func animationDidFinish(_ transitionContext: UIViewControllerContextTransitioning, containerView: UIView, fromView: UIView, toView: UIView) { fromView.layer.transform = CATransform3DIdentity toView.layer.transform = CATransform3DIdentity containerView.layer.transform = CATransform3DIdentity transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } }
b72107c78397b57c150ae9d18771ef3a
35.89899
143
0.725568
false
false
false
false
panadaW/MyNews
refs/heads/master
MyWb完善首页数据/MyWb/Class/Model/Status.swift
mit
1
// // Status.swift // MyWb // // Created by 王明申 on 15/10/13. // Copyright © 2015年 晨曦的Mac. All rights reserved. // import SDWebImage import UIKit //微博数据模型 class Status: NSObject { // 微博创建时间 var created_at: String? // 微博ID var id: Int = 0 // 微博信息内容 var text: String? // 微博来源 var source: String? { didSet { source = source?.hrefLink().text } } // 配图数组 var pic_urls: [[String: AnyObject]]? { didSet { if pic_urls?.count == 0 { return } // 实例化数组 storepictureURLs = [NSURL]() storedLargePictureURLs = [NSURL]() // 遍历配图数组 for dict in pic_urls! { if let urlstring = dict["thumbnail_pic"] as? String { storepictureURLs?.append(NSURL(string: urlstring)!) let largeurlstring = urlstring.stringByReplacingOccurrencesOfString("thumbnail", withString: "large") storedLargePictureURLs?.append(NSURL(string: largeurlstring)!) } } } } // 存储转发微博图片数组,或原创微博url数组 var storepictureURLs: [NSURL]? // 微博配图URL数组 var pictureURLs: [NSURL]? { return retweeted_status == nil ? storepictureURLs : retweeted_status?.storepictureURLs } // 定义大图URL数组 var storedLargePictureURLs: [NSURL]? // 返回大图URL数组 var largePictureURLs: [NSURL]? { return retweeted_status == nil ? storedLargePictureURLs : retweeted_status?.storedLargePictureURLs } // 用户模型 var user: UserModel? // 转发微博 var retweeted_status: Status? // 行高属性 var rowHight: CGFloat? // 把微博数据转换为数组 class func loadstatus(since_id: Int,max_id: Int,finish:(dataList: [Status]?,error: NSError?)->() ){ NetWorkShare.shareTools.loadStatus(since_id,max_id: max_id) { (resault, error) -> () in if error != nil{ return } if let array = resault?["statuses"] as? [[String: AnyObject]]{ // 实例化数组 var list = [Status]() // 遍历数组 for dict in array { // 字典转模型 list.append(Status(dict: dict)) } // 缓存图片 self.cacheImage(list, finish: finish) }else{ finish(dataList: nil, error: nil) } } } // 缓存网络图片,等缓存完毕,才能刷新数据 private class func cacheImage(list: [Status],finish:(dataList: [Status]?,error: NSError?)->()) { // 创建调度组 let group = dispatch_group_create() // 缓存图片大小 var dadtaLengh = 0 // 遍历数组 for status in list { guard let url = status.pictureURLs else { continue } // 遍历url数组,缓存图片 for imgurl in url { dispatch_group_enter(group) SDWebImageManager.sharedManager().downloadImageWithURL(imgurl, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _, _, _, _) -> Void in // 将图片转换为二进制 if image != nil { let data = UIImagePNGRepresentation(image)! dadtaLengh += data.length } // 出组 dispatch_group_leave(group) }) } } // 监听缓存操作通知 dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in print("缓存图片大小 \(dadtaLengh / 1024) K") // 回调 finish(dataList: list, error: nil) } } //字典转模型 init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forKey key: String) { if key == "user" { // 判断 value 是否是一个字典,应为微博用户信息是用字典封装的 if let dict = value as? [String: AnyObject] { user = UserModel(dict: dict) } return } if key == "retweeted_status" { if let dict = value as? [String: AnyObject] { retweeted_status = Status(dict: dict) } return } super.setValue(value, forKey: key) } override func setValue(value: AnyObject?, forUndefinedKey key: String) {} override var description: String { let keys = ["created_at","id","text","source","pic_urls"] return "\(dictionaryWithValuesForKeys(keys))" } }
6e594a61220742986f22f9f73e32e0c1
28.823529
178
0.512495
false
false
false
false
BjornRuud/HTTPSession
refs/heads/master
Example/Pods/Swifter/Sources/HttpServer.swift
gpl-3.0
3
// // HttpServer.swift // Swifter // // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved. // import Foundation public class HttpServer: HttpServerIO { public static let VERSION = "1.3.2" private let router = HttpRouter() public override init() { self.DELETE = MethodRoute(method: "DELETE", router: router) self.UPDATE = MethodRoute(method: "UPDATE", router: router) self.HEAD = MethodRoute(method: "HEAD", router: router) self.POST = MethodRoute(method: "POST", router: router) self.GET = MethodRoute(method: "GET", router: router) self.PUT = MethodRoute(method: "PUT", router: router) self.delete = MethodRoute(method: "DELETE", router: router) self.update = MethodRoute(method: "UPDATE", router: router) self.head = MethodRoute(method: "HEAD", router: router) self.post = MethodRoute(method: "POST", router: router) self.get = MethodRoute(method: "GET", router: router) self.put = MethodRoute(method: "PUT", router: router) } public var DELETE, UPDATE, HEAD, POST, GET, PUT : MethodRoute public var delete, update, head, post, get, put : MethodRoute public subscript(path: String) -> ((HttpRequest) -> HttpResponse)? { set { router.register(nil, path: path, handler: newValue) } get { return nil } } public var routes: [String] { return router.routes(); } public var notFoundHandler: ((HttpRequest) -> HttpResponse)? public var middleware = Array<(HttpRequest) -> HttpResponse?>() override public func dispatch(_ request: HttpRequest) -> ([String:String], (HttpRequest) -> HttpResponse) { for layer in middleware { if let response = layer(request) { return ([:], { _ in response }) } } if let result = router.route(request.method, path: request.path) { return result } if let notFoundHandler = self.notFoundHandler { return ([:], notFoundHandler) } return super.dispatch(request) } public struct MethodRoute { public let method: String public let router: HttpRouter public subscript(path: String) -> ((HttpRequest) -> HttpResponse)? { set { router.register(method, path: path, handler: newValue) } get { return nil } } } }
4988d8fb592b69878ade04f2f45317a0
32.693333
111
0.586466
false
false
false
false
Mqhong/SingularitySwiftR-Pod
refs/heads/master
Pod/Classes/MessageModel.swift
mit
1
// // MessageModel.swift // ChatDemo // // Created by mm on 16/1/13. // Copyright © 2016年 mm. All rights reserved. // import UIKit class MessageModel: NSObject { var chat_session_id:String? var chat_session_type:String? var sender_id:String? var message_id:String? var message:String? var message_time:String? var message_type:String? var message_token:String? func MessageModelMethodWithDict(Dict dict:Dictionary<String,AnyObject>)->MessageModel{ let model:MessageModel = MessageModel() model.chat_session_id = dict["chat_session_id"] as? String model.chat_session_type = String(dict["chat_session_type"]!) model.message = dict["message"] as? String model.message_id = dict["message_id"] as? String model.message_time = String(dict["message_time"]!) model.message_token = String(dict["message_token"]) model.message_type = String(dict["message_type"]!) model.sender_id = dict["sender_id"] as? String return model } func MessageModelMethodWithArrDict(ArrDict arrdict:Array<AnyObject>)->Array<MessageModel>{ var arr:Array<MessageModel> = Array() for dic in arrdict{ var model:MessageModel = MessageModel() model = model.MessageModelMethodWithDict(Dict: dic as! Dictionary<String, AnyObject>) arr.append(model) } return arr } }
25614fc1c51e830b73a9e9a76087896b
27.075472
94
0.627688
false
false
false
false
EaglesoftZJ/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorApp/AppDelegate.swift
agpl-3.0
1
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import ActorSDK import UIKit open class AppDelegate : ActorApplicationDelegate,CommonServiceDelegate { //# 小于服务器版本号{"welcomePage_bg":"http:\/\/61.175.100.14:5433\/photoImage\/bg1-2560.png","loginPage_bg":"http:\/\/61.175.100.14:5433\/photoImage\/bg-2560.png","loginPage_but":"http:\/\/61.175.100.14:5433\/photoImage\/login_but.png","version":1,"canUpdate":true} //# 大于,等于服务器版本号{"canUpdate":false} public func serviceSuccess(_ svc: CommonService!, object obj: Any!) { if svc == image { guard (obj as? NSDictionary) != nil else{return} let dic:[String:AnyObject] = obj as! Dictionary let defaults = UserDefaults.standard if dic["canUpdate"] as! Int == 1 { defaults.set(String(describing: dic["version"]), forKey: "version") defaults.set(dic["welcomePage_bg"], forKey: "welcomeImage") defaults.set(dic["loginPage_bg"], forKey: "loginImage") defaults.set(dic["loginPage_but"], forKey: "loginBtnImage") defaults.synchronize() } } else if svc == companyService { guard (obj as? NSDictionary) != nil else{return} let result_dict = obj as! NSDictionary UserDefaults.standard.set(result_dict, forKey: "ZZJG") UserDefaults.standard.synchronize() } } public func serviceFail(_ svc: CommonService!, info: String!) { } let image = PhoneImageService() let companyService = CompanyService() var window: UIWindow? override init() { super.init() ActorSDK.sharedActor().inviteUrlHost = "quit.email" ActorSDK.sharedActor().inviteUrlScheme = "actor" ActorSDK.sharedActor().style.searchStatusBarStyle = .default // Enabling experimental features ActorSDK.sharedActor().enableExperimentalFeatures = true ActorSDK.sharedActor().enableCalls = true ActorSDK.sharedActor().enableVideoCalls = true // Setting Development Push Id ActorSDK.sharedActor().apiPushId = 1 ActorSDK.sharedActor().authStrategy = .usernameOnly ActorSDK.sharedActor().style.dialogAvatarSize = 58 ActorSDK.sharedActor().autoJoinGroups = ["actor_news"] // Creating Actor ActorSDK.sharedActor().createActor() } open override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]?) -> Bool { let _ = super.application(application, didFinishLaunchingWithOptions: launchOptions) //#注册切换Root控制器通知 NotificationCenter.default.addObserver(self, selector: #selector(switchRootViewController), name: ActorSDK.sharedActor().switchRootController, object: nil) // ActorSDK.sharedActor().presentMessengerInNewWindow() window = UIWindow(frame:UIScreen.main.bounds) window?.backgroundColor = UIColor.white window?.rootViewController = WelcomeViewController() window?.makeKeyAndVisible() //#启动图 addLaunchController() //#组织架构 // companyService.delegate = self // companyService.chooseCompany() return true } // open override func actorRootControllers() -> [UIViewController]? { // return [AAContactsViewController(), AARecentViewController(), AASettingsViewController()] // } open override func actorRootInitialControllerIndex() -> Int? { return 0 } @objc func switchRootViewController(){ ActorSDK.sharedActor().presentMessengerInNewWindow() } private func addLaunchController() { image.delegate = self image.getLaunchImage() } }
1da13c35166de030c9086de9a7725b90
35.345794
262
0.639239
false
false
false
false
headione/criticalmaps-ios
refs/heads/release/4.0.0
CriticalMapsKit/Sources/Helpers/Reducer+Additions.swift
mit
1
import ComposableArchitecture extension Reducer { public func onChange<LocalState>( of toLocalState: @escaping (State) -> LocalState, perform additionalEffects: @escaping (LocalState, inout State, Action, Environment) -> Effect< Action, Never > ) -> Self where LocalState: Equatable { .init { state, action, environment in let previousLocalState = toLocalState(state) let effects = self.run(&state, action, environment) let localState = toLocalState(state) return previousLocalState != localState ? .merge(effects, additionalEffects(localState, &state, action, environment)) : effects } } public func onChange<LocalState>( of toLocalState: @escaping (State) -> LocalState, perform additionalEffects: @escaping (LocalState, LocalState, inout State, Action, Environment) -> Effect<Action, Never> ) -> Self where LocalState: Equatable { .init { state, action, environment in let previousLocalState = toLocalState(state) let effects = self.run(&state, action, environment) let localState = toLocalState(state) return previousLocalState != localState ? .merge( effects, additionalEffects(previousLocalState, localState, &state, action, environment)) : effects } } }
783360eb057153a9bc08cf6895d6ce3e
36.108108
101
0.658412
false
false
false
false
darthpelo/LottieProgressAnimation
refs/heads/master
LottieProgressAnimation/LottieProgressAnimation/LottiView.swift
mit
1
// // LottiView.swift // LottieProgressAnimation // // Created by Alessio Roberto on 28/06/2017. // Copyright © 2017 Alessio Roberto. All rights reserved. // import Foundation import UIKit import Lottie struct LottieView { /// Create and add as subView a new `LOTAnimationView` based on a json file. /// The `LOTAnimationView` is created with width and height of the container view /// and `contentMode` equal to `scaleAspectFill`. /// /// - Parameters: /// - name: The name of the JSON file with the animation /// - view: The container view that will contains the `LOTAnimationView` /// - Returns: The instance of the LOTAnimationView. Nil if the `name` is incorect. static func addAnimation(withName name: String, to view: UIView) -> LOTAnimationView? { guard let animationView = LOTAnimationView(name: name) else { return nil } animationView.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height) animationView.contentMode = .scaleAspectFill animationView.loopAnimation = false view.addSubview(animationView) return animationView } /// Create and add as subView a new `LOTAnimationView` based on a json file. /// The `LOTAnimationView` is created with width and height of the container view. /// /// - Parameters: /// - name: The name of the JSON file with the animation /// - view: The view to which to add the animation /// - contentMode: The content mode `UIViewContentMode` of `LOTAnimationView` /// - Returns: The instance of the LOTAnimationView. Nil if the `name` is incorect. static func addAnimation(withName name: String, to view: UIView, withContentMode contentMode: UIViewContentMode) -> LOTAnimationView? { guard let animationView = LOTAnimationView(name: name) else { return nil } animationView.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height) animationView.contentMode = contentMode animationView.loopAnimation = false view.addSubview(animationView) return animationView } }
24a1f13d6605d3a782037dab80b609e0
38.390625
99
0.592622
false
false
false
false
cc001/learnSwiftBySmallProjects
refs/heads/master
01-StopWatch/StopWatch/ViewController.swift
mit
1
// // ViewController.swift // StopWatch // // Created by 陈闯 on 2016/12/14. // Copyright © 2016年 CC. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var playBtn: UIButton! @IBOutlet weak var pauseBtn: UIButton! var counter = 0.0 var timer = Timer() var isPlaying = false override var preferredStatusBarStyle: UIStatusBarStyle{ get{ return .lightContent } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. timeLabel.text = String(counter) } @IBAction func resetBtnDidTouch(_ sender: UIButton) { timer.invalidate() isPlaying = false counter = 0 timeLabel.text = String(counter) playBtn.isEnabled = true pauseBtn.isEnabled = false } @IBAction func playBtnDidTouch(_ sender: UIButton) { if isPlaying { return } playBtn.isEnabled = false pauseBtn.isEnabled = true timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.UpdateTimer), userInfo: nil, repeats: true) isPlaying = true } @IBAction func pauseBtnDidTouch(_ sender: UIButton) { playBtn.isEnabled = true pauseBtn.isEnabled = false timer.invalidate() isPlaying = false } func UpdateTimer() { counter = counter + 0.1 timeLabel.text = String(format: "%.1f", counter) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
7f9be01b7d37c9236a4340797d1eccf6
23.026316
148
0.605148
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Gutenberg/Views/GutenGhostView.swift
gpl-2.0
1
import UIKit class GutenGhostView: UIView { override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } @IBOutlet var toolbarViews: [UIView]! @IBOutlet weak var toolbarTopBorderView: UIView! { didSet { if #available(iOS 12.0, *) { let isDarkStyle = traitCollection.userInterfaceStyle == .dark toolbarTopBorderView.isHidden = isDarkStyle } } } @IBOutlet var blockElementViews: [UIView]! { didSet { blockElementViews.forEach { (view) in view.backgroundColor = .ghostBlockBackground } } } @IBOutlet var buttonsViews: [UIView]! { didSet { buttonsViews.forEach { (view) in view.backgroundColor = .clear } } } @IBOutlet weak private var inserterView: UIView! { didSet { inserterView.layer.cornerRadius = inserterView.frame.height / 2 inserterView.clipsToBounds = true } } @IBOutlet private var roundedCornerViews: [UIView]! { didSet { roundedCornerViews.forEach { (view) in view.layer.cornerRadius = 6 view.clipsToBounds = true } } } @IBOutlet weak var toolbarBackgroundView: UIView! { didSet { toolbarBackgroundView.isGhostableDisabled = true toolbarBackgroundView.backgroundColor = .ghostToolbarBackground } } var hidesToolbar: Bool = false { didSet { toolbarViews.forEach({ $0.isHidden = hidesToolbar }) } } func startAnimation() { let style = GhostStyle(beatDuration: GhostStyle.Defaults.beatDuration, beatStartColor: .placeholderElement, beatEndColor: .beatEndColor) startGhostAnimation(style: style) } private func commonInit() { let bundle = Bundle(for: GutenGhostView.self) guard let nibViews = bundle.loadNibNamed("GutenGhostView", owner: self, options: nil), let contentView = nibViews.first as? UIView else { return } addSubview(contentView) contentView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate( contentView.constrainToSuperViewEdges() ) backgroundColor = .background } } private extension UIColor { static var ghostToolbarBackground: UIColor { if #available(iOS 13, *) { return UIColor(light: .clear, dark: UIColor.colorFromHex("2e2e2e")) } return .clear } static var ghostBlockBackground: UIColor { return UIColor(light: .clear, dark: .systemGray5) } static var beatEndColor: UIColor { return UIColor(light: .systemGray6, dark: .clear) } static var background: UIColor { return .systemBackground } }
9fbc811368fe789b461b713078d64132
25.939655
92
0.57984
false
false
false
false
ECP-CANDLE/Supervisor
refs/heads/master
python/eqpy/EQPy.swift
mit
1
/* EMEWS EQPy.swift */ import location; pragma worktypedef resident_work; @dispatch=resident_work (void v) _void_py(string code, string expr="\"\"") "turbine" "0.1.0" [ "turbine::python 1 <<code>> <<expr>> "]; @dispatch=resident_work (string output) _string_py(string code, string expr) "turbine" "0.1.0" [ "set <<output>> [ turbine::python 1 <<code>> <<expr>> ]" ]; string init_package_string = "import eqpy\nimport %s\n" + "import threading\n" + "p = threading.Thread(target=%s.run)\np.start()"; (void v) EQPy_init_package(location loc, string packageName){ printf("EQPy_init_package(%s) ...", packageName); string code = init_package_string % (packageName,packageName); //printf("Code is: \n%s", code); _void_py(code) => v = propagate(); } EQPy_stop(location loc){ // do nothing } string get_string = "result = eqpy.output_q.get()"; (string result) EQPy_get(location loc){ //printf("EQPy_get called"); string code = get_string; //printf("Code is: \n%s", code); result = _string_py(code, "result"); } string put_string = """ eqpy.input_q.put('%s')\n"" """; (void v) EQPy_put(location loc, string data){ // printf("EQPy_put called with: \n%s", data); string code = put_string % data; // printf("EQPy_put code: \n%s", code); _void_py(code) => v = propagate(); } // Local Variables: // c-basic-offset: 4 // End:
9b8d4da72109a2206da106a0982fbd53
24.218182
70
0.620764
false
false
false
false
inamiy/VTree
refs/heads/master
Sources/AppKit+Ext.swift
mit
1
#if os(macOS) // TODO: Not tested yet. import AppKit extension NSView { internal var backgroundColor: NSColor? { get { guard let layer = layer, let backgroundColor = layer.backgroundColor else { return nil } return NSColor(cgColor: backgroundColor) } set { self.wantsLayer = true self.layer?.backgroundColor = newValue?.cgColor } } internal func insertSubview(_ view: NSView, at index: Int) { self.addSubview(view, positioned: .above, relativeTo: self.subviews[index]) } } extension NSTextField { internal var text: String? { get { return self.stringValue } set { self.stringValue = newValue ?? "" } } internal var attributedText: NSAttributedString? { get { return self.attributedStringValue } set { self.attributedStringValue = newValue ?? NSAttributedString() } } internal var textAlignment: NSTextAlignment { get { return self.alignment } set { self.alignment = newValue } } } extension NSControl { internal func addHandler(_ handler: @escaping (NSControl) -> ()) { let target = self.vtree.associatedValue { _ in CocoaTarget<NSControl>(handler) { $0 as! NSControl } } self.target = target self.action = #selector(target.sendNext) } } #endif
3045c976423d013b4050bda10350f3c7
19.944444
109
0.566976
false
false
false
false
stevethemaker/WoodpeckerPole-ControlPanel-iOS
refs/heads/master
PoleControlPanel/RobotControllerModel.swift
mit
1
// // RobotControllerModel.swift // PoleControlPanel // // Created by Steven Knodl on 4/12/17. // Copyright © 2017 Steve Knodl. All rights reserved. // import Foundation import CoreBluetooth let robotDisconnectedNotification = Notification.Name("robot.bluetooth.disconnected") let robotConnectedNotification = Notification.Name("robot.bluetooth.connected") enum RobotControllerError : Error { case nonConnected } typealias FindDevicesClosure = (Result<[CBPeripheral]>) -> () typealias ConnectDeviceClosure = (Result<CBPeripheral>) -> () typealias DisconnectDeviceClosure = (Result<UUID>) -> () class RobotControllerModel { let robotServiceIdentifer = RobotDevice.ControlService.identifier static let shared = RobotControllerModel() let centralManager = CentralManagerWrapper.shared var connectedPeripheral: CBPeripheral? = nil var connectedPeripheralManager: RobotPeripheralManager? = nil init() { NotificationCenter.default.addObserver(self, selector: #selector(RobotControllerModel.centralManagerNotificationReceived), name: centralManagerNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc private func centralManagerNotificationReceived(notification: Notification) { if let userInfo = notification.userInfo, let centralNotification = userInfo["type"] as? CentralNotification { switch centralNotification { case .peripherialDisconnect(let peripheral): if peripheral == self.connectedPeripheral { self.connectedPeripheral = nil NotificationCenter.default.post(name: robotDisconnectedNotification, object: nil) } case .stateChange(_): break } } } //MARK: - Selection/Connection func scanForRobots(completion: @escaping FindDevicesClosure) { centralManager.scanForPeripherals(withServices: [robotServiceIdentifer]) { result in completion(result) } } func connect(toPeripheral peripheral: CBPeripheral, completion: @escaping ConnectDeviceClosure) { centralManager.connect(toPeripheral: peripheral) { result in switch result { case .success(let peripheral): self.connectedPeripheral = peripheral self.connectedPeripheralManager = RobotPeripheralManager(peripheral: peripheral) NotificationCenter.default.post(name: robotConnectedNotification, object: nil) case .failure: break } completion(result) } } func disconnect(fromPeripheral peripheral: CBPeripheral, completion: @escaping DisconnectDeviceClosure) { centralManager.disconnect(peripheral: peripheral) { result in switch result { case .success(_): self.connectedPeripheral = nil completion(Result.success(peripheral.identifier)) case .failure(let error): completion(Result.failure(error)) } } } //MARK: - Get (read) commands func getBatteryVoltage(completion: @escaping ((Result<Battery>) -> ())) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.readCharacteristicValue(forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.batteryVoltage, completion: { result in completion(result.flatMap({ (rawData:Data) -> Result<Battery> in return Result { try Battery(rawData: rawData) } }) )} )} func getRobotPosition(completion: @escaping ((Result<RobotPosition>) -> ())) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.readCharacteristicValue(forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.robotPosition, completion: { result in completion(result.flatMap({ (rawData:Data) -> Result<RobotPosition> in return Result { try RobotPosition(rawData: rawData) } }) )} )} func getLatchPosition(completion: @escaping ((Result<ServoPosition>) -> ())) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.readCharacteristicValue(forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.latchPosition, completion: { result in completion(result.flatMap({ (rawData:Data) -> Result<ServoPosition> in return Result { try ServoPosition(rawData: rawData) } }) )} )} func getLauncherPosition(completion: @escaping ((Result<ServoPosition>) -> ())) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.readCharacteristicValue(forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.launcherPosition, completion: { result in completion(result.flatMap({ (rawData:Data) -> Result<ServoPosition> in return Result { try ServoPosition(rawData: rawData) } }) )} )} func getMotorControlSetting(completion: @escaping ((Result<MotorControl>) -> ())) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.readCharacteristicValue(forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.motorControl, completion: { result in completion(result.flatMap({ (rawData:Data) -> Result<MotorControl> in return Result { try MotorControl(rawData: rawData) } }) )} )} //MARK: - Set (Write) commands func setMotorControlSetting(data: Data, confirmWrite: Bool, completion: @escaping WriteOperationClosure) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.writeCharacteristicValue(data: data, confirmWrite: confirmWrite, forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.motorControl, completion: { result in completion(result) }) } func setLatchPosition(data: Data, confirmWrite: Bool, completion: @escaping WriteOperationClosure) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.writeCharacteristicValue(data: data, confirmWrite: confirmWrite, forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.latchPosition, completion: { result in completion(result) }) } func setLauncherPosition(data: Data, confirmWrite: Bool, completion: @escaping WriteOperationClosure) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.writeCharacteristicValue(data: data, confirmWrite: confirmWrite, forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.launcherPosition, completion: { result in completion(result) }) } func readRSSIValue(completion: @escaping (Result<Data>) -> ()) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.readRSSIValue(completion: { result in completion(result) }) } }
1009a1309d453fa6b843cf4b79230328
47.106509
209
0.702706
false
false
false
false
mliudev/hayaku
refs/heads/master
xcode/Food Tracker/Food Tracker/MealTableViewController.swift
mit
1
// // MealTableViewController.swift // Food Tracker // // Created by Manwe on 4/16/16. // Copyright © 2016 Manwe. All rights reserved. // import UIKit class MealTableViewController: UITableViewController { // MARK: Properties var meals = [Meal]() override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = editButtonItem() // load sample data loadSampleMeals() } func loadSampleMeals() { let photo1 = UIImage(named: "meal1")! let meal1 = Meal(name: "Tasty", photo: photo1, rating: 4)! let photo2 = UIImage(named: "meal2")! let meal2 = Meal(name: "Gross", photo: photo2, rating: 5)! let photo3 = UIImage(named: "meal3")! let meal3 = Meal(name: "Too Full", photo: photo3, rating: 3)! meals += [meal1, meal2, meal3] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return meals.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "MealTableViewCell" let cell = tableView.dequeueReusableCellWithIdentifier( cellIdentifier, forIndexPath: indexPath) as! MealTableViewCell let meal = meals[indexPath.row] cell.nameLabel.text = meal.name cell.photoImageView.image = meal.photo cell.ratingControl.rating = meal.rating return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source meals.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowDetail" { let mealDetailViewController = segue.destinationViewController as! MealViewController if let selectedMealCell = sender as? MealTableViewCell { let indexPath = tableView.indexPathForCell(selectedMealCell)! let selectedMeal = meals[indexPath.row] mealDetailViewController.meal = selectedMeal } } else if segue.identifier == "AddItem" { print("Adding new meal.") } } // MARK: Actions @IBAction func unwindToMealList(sender: UIStoryboardSegue) { if let sourceViewController = sender.sourceViewController as? MealViewController, meal = sourceViewController.meal { if let selectedIndexPath = tableView.indexPathForSelectedRow { // Update an existing meal. meals[selectedIndexPath.row] = meal tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None) } else { // Add a new meal. let newIndexPath = NSIndexPath(forRow: meals.count, inSection: 0) meals.append(meal) tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom) } } } }
f31615b79dc550451862efb2839b98e5
34.414815
157
0.646936
false
false
false
false
pablogsIO/MadridShops
refs/heads/master
MadridShops/Util/UIView+Rotate.swift
mit
1
// // UIView+Rotate.swift // TestUiViewImageRotate // // Created by Pablo García on 13/09/2017. // Copyright © 2017 Pablo García. All rights reserved. // import UIKit extension UIView{ @IBInspectable var shadow: Bool { get { return layer.shadowOpacity > 0.0 } set { if newValue == true { self.addShadow() } } } @IBInspectable var cornerRadius: CGFloat { get { return self.layer.cornerRadius } set { self.layer.cornerRadius = newValue // Don't touch the masksToBound property if a shadow is needed in addition to the cornerRadius if shadow == false { self.layer.masksToBounds = true } } } func addShadow(shadowColor: CGColor = UIColor.black.cgColor, shadowOffset: CGSize = CGSize(width: 1.0, height: 2.0), shadowOpacity: Float = 0.4, shadowRadius: CGFloat = 3.0) { layer.shadowColor = shadowColor layer.shadowOffset = shadowOffset layer.shadowOpacity = shadowOpacity layer.shadowRadius = shadowRadius } func startRotating(duration: Double = 1) { let kAnimationKey = "rotation" if self.layer.animation(forKey: kAnimationKey) == nil { let animate = CABasicAnimation(keyPath: "transform.rotation.y") animate.duration = duration animate.repeatCount = Float.infinity animate.fromValue = 0.0 animate.toValue = Float(CGFloat.pi * 2.0) self.layer.add(animate, forKey: kAnimationKey) } } func stopRotating() { let kAnimationKey = "rotation" if self.layer.animation(forKey: kAnimationKey) != nil { self.layer.removeAnimation(forKey: kAnimationKey) } } }
55391bbd27f3460b8b10edc1a9d9ff05
22.128571
97
0.67449
false
false
false
false
atrick/swift
refs/heads/main
test/Generics/interdependent_protocol_conformance_example_4.swift
apache-2.0
3
// RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=on -requirement-machine-inferred-signatures=on // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-protocol-signatures=on -requirement-machine-inferred-signatures=on 2>&1 | %FileCheck %s // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -disable-requirement-machine-reuse -requirement-machine-protocol-signatures=on -requirement-machine-inferred-signatures=on 2>&1 | %FileCheck %s // CHECK-LABEL: .NonEmptyProtocol@ // CHECK-NEXT: Requirement signature: <Self where Self : Collection, Self.[NonEmptyProtocol]C : Collection, Self.[Sequence]Element == Self.[NonEmptyProtocol]C.[Sequence]Element, Self.[Collection]Index == Self.[NonEmptyProtocol]C.[Collection]Index> public protocol NonEmptyProtocol: Collection where Element == C.Element, Index == C.Index { associatedtype C: Collection } // CHECK-LABEL: .MultiPoint@ // CHECK-NEXT: Requirement signature: <Self where Self.[MultiPoint]C : CoordinateSystem, Self.[MultiPoint]P == Self.[MultiPoint]C.[CoordinateSystem]P, Self.[MultiPoint]X : NonEmptyProtocol, Self.[MultiPoint]C.[CoordinateSystem]P == Self.[MultiPoint]X.[Sequence]Element, Self.[MultiPoint]X.[NonEmptyProtocol]C : NonEmptyProtocol> public protocol MultiPoint { associatedtype C: CoordinateSystem associatedtype P where Self.P == Self.C.P associatedtype X: NonEmptyProtocol where X.C: NonEmptyProtocol, X.Element == Self.P } // CHECK-LABEL: .CoordinateSystem@ // CHECK-NEXT: Requirement signature: <Self where Self == Self.[CoordinateSystem]B.[BoundingBox]C, Self.[CoordinateSystem]B : BoundingBox, Self.[CoordinateSystem]L : Line, Self.[CoordinateSystem]P : Point, Self.[CoordinateSystem]S : Size, Self.[CoordinateSystem]B.[BoundingBox]C == Self.[CoordinateSystem]L.[MultiPoint]C, Self.[CoordinateSystem]L.[MultiPoint]C == Self.[CoordinateSystem]S.[Size]C> public protocol CoordinateSystem { associatedtype P: Point where Self.P.C == Self associatedtype S: Size where Self.S.C == Self associatedtype L: Line where Self.L.C == Self associatedtype B: BoundingBox where Self.B.C == Self } // CHECK-LABEL: .Line@ // CHECK-NEXT: Requirement signature: <Self where Self : MultiPoint, Self.[MultiPoint]C == Self.[MultiPoint]P.[Point]C> public protocol Line: MultiPoint {} // CHECK-LABEL: .Size@ // CHECK-NEXT: Requirement signature: <Self where Self == Self.[Size]C.[CoordinateSystem]S, Self.[Size]C : CoordinateSystem> public protocol Size { associatedtype C: CoordinateSystem where Self.C.S == Self } // CHECK-LABEL: .BoundingBox@ // CHECK-NEXT: Requirement signature: <Self where Self.[BoundingBox]C : CoordinateSystem> public protocol BoundingBox { associatedtype C: CoordinateSystem typealias P = Self.C.P typealias S = Self.C.S } // CHECK-LABEL: .Point@ // CHECK-NEXT: Requirement signature: <Self where Self == Self.[Point]C.[CoordinateSystem]P, Self.[Point]C : CoordinateSystem> public protocol Point { associatedtype C: CoordinateSystem where Self.C.P == Self } func sameType<T>(_: T, _: T) {} func conformsToPoint<T : Point>(_: T.Type) {} func testMultiPoint<T : MultiPoint>(_: T) { sameType(T.C.P.self, T.X.Element.self) conformsToPoint(T.P.self) } func testCoordinateSystem<T : CoordinateSystem>(_: T) { sameType(T.P.C.self, T.self) }
4bf50bcb43f2e45ba1f07528d9c85a83
43.946667
397
0.744883
false
false
false
false
wendyabrantes/WAInvisionProjectSpaceExample
refs/heads/master
WAInvisionProjectSpace/InvisionCollectionViewLayout.swift
mit
1
// // InvisionCollectionViewLayout.swift // WAInvisionSpaceExample // // Created by Wendy Abrantes on 20/02/2017. // Copyright © 2017 Wendy Abrantes. All rights reserved. // import UIKit class InvisionCollectionViewLayout: UICollectionViewLayout { var parallaxOffset: CGPoint? var itemSize: CGSize = .zero var minimumLineSpacing: CGFloat = 20.0 var baseLayoutAttributes = [InvisionCollectionViewLayoutAttributes]() var contentInset: UIEdgeInsets = .zero override class var layoutAttributesClass: AnyClass { return InvisionCollectionViewLayoutAttributes.self } override init() { super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepare() { super.prepare() baseLayoutAttributes = [InvisionCollectionViewLayoutAttributes]() let nbItems = collectionView?.numberOfItems(inSection: 0) ?? 0 for item in 0..<nbItems { let indexPath = IndexPath(item: item, section: 0) let yPosition = (collectionView!.frame.height - itemSize.height)/2.0 let position = CGPoint( x: contentInset.left + ((itemSize.width+minimumLineSpacing) * CGFloat(item)), y:yPosition) let frame = CGRect(origin: position, size: itemSize) let attributes = InvisionCollectionViewLayoutAttributes(forCellWith: indexPath) attributes.frame = frame baseLayoutAttributes.append(attributes) } } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let layoutAttributes = baseLayoutAttributes.filter { $0.frame.intersects(rect) } guard let collectionView = collectionView else { return layoutAttributes } for attribute in layoutAttributes { let offset = (attribute.frame.minX + contentInset.left) - collectionView.contentOffset.x let parallaxValue = offset / collectionView.bounds.width attribute.parallaxValue = parallaxValue } return layoutAttributes } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return baseLayoutAttributes[indexPath.row] } override var collectionViewContentSize: CGSize { get { let totalWidth = CGFloat(baseLayoutAttributes.count) * (itemSize.width + self.minimumLineSpacing) + (contentInset.left + contentInset.right) return CGSize(width: totalWidth, height: itemSize.height) } } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } }
5c44b7b26250f12d9d15b7089f1418dd
32.776316
146
0.728866
false
false
false
false
wadevanne/UuusKit
refs/heads/master
UuusKit/Others/UuusCoreAnimation.swift
mit
1
// // UuusCoreAnimation.swift // Example // // Created by 范炜佳 on 25/10/2017. // Copyright © 2017 com.uuus. All rights reserved. // import QuartzCore open class PieLayor: CAShapeLayer { // MARK: - Initialization public init(arcCenter center: CGPoint, radius: CGFloat, startAngle zero: CGFloat = 0, endAngle nine: CGFloat = CGFloat(uuus2mpi), clockwise: Bool = true, lineWidth width: CGFloat = 3, strokeColor color: CGColor = .lightGray) { super.init() /// rotate 90 degrees to 12‘c path = UIBezierPath(arcCenter: center, radius: radius, startAngle: zero - CGFloat(uuusm2pi), endAngle: nine - CGFloat(uuusm2pi), clockwise: clockwise).cgPath fillColor = .clear strokeColor = color strokeStart = 0 strokeEnd = 1 lineWidth = width } public required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension CATransition { // MARK: - Properties public static var fade: CATransition { let transition = CATransition() transition.type = CATransitionType.fade transition.subtype = CATransitionSubtype.fromTop transition.duration = 0.25 return transition } }
49b61bc806f972a1ee06257ba7b4a0e4
29.9
230
0.660194
false
false
false
false
PureSwift/Bluetooth
refs/heads/master
Sources/BluetoothHCI/HCILESetPeriodicAdvertisingParameters.swift
mit
1
// // HCILESetPeriodicAdvertisingParameters.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// LE Set Periodic Advertising Parameters Command /// /// The command is used by the Host to set the parameters for periodic advertising. func setSetPeriodicAdvertisingParameters(advertisingHandle: UInt8, periodicAdvertisingInterval: HCILESetPeriodicAdvertisingParameters.PeriodicAdvertisingInterval, advertisingEventProperties: HCILESetPeriodicAdvertisingParameters.AdvertisingEventProperties, timeout: HCICommandTimeout = .default) async throws { let parameters = HCILESetPeriodicAdvertisingParameters(advertisingHandle: advertisingHandle, periodicAdvertisingInterval: periodicAdvertisingInterval, advertisingEventProperties: advertisingEventProperties) try await deviceRequest(parameters, timeout: timeout) } } // MARK: - Command /// LE Set Periodic Advertising Parameters Command /// /// The command is used by the Host to set the parameters for periodic advertising. /// /// The Advertising_Handle parameter identifies the advertising set whose periodic advertising /// parameters are being configured. If the corresponding advertising set does not already exist, /// then the Controller shall return the error code Unknown Advertising Identifier (0x42). /// /// The Periodic_Advertising_Interval_Min parameter shall be less than or equal to the /// Periodic_Advertising_Interval_Max parameter. The Periodic_Advertising_Interval_Min and /// Periodic_Advertising_Interval_Max parameters should not be the same value to enable the Controller to /// determine the best advertising interval given other activities. /// /// The Periodic_Advertising_Properties parameter indicates which fields should be included in /// the advertising packet. /// /// If the advertising set identified by the Advertising_Handle specified anonymous advertising, /// the Controller shall return the error code Invalid HCI Parameters (0x12). /// /// If the Host issues this command when periodic advertising is enabled for the specified /// advertising set, the Controller shall return the error code Command Disallowed (0x0C). /// /// If the Advertising_Handle does not identify an advertising set that is already configured for periodic /// advertising and the Controller is unable to support more periodic advertising at present, the Controller /// shall return the error code Memory Capacity Exceeded (0x07). @frozen public struct HCILESetPeriodicAdvertisingParameters: HCICommandParameter { public static let command = HCILowEnergyCommand.setPeriodicAdvertisingParameters //0x003E /// Used to identify an advertising set public var advertisingHandle: UInt8 //Advertising_Handle public var periodicAdvertisingInterval: PeriodicAdvertisingInterval public var advertisingEventProperties: AdvertisingEventProperties public init(advertisingHandle: UInt8, periodicAdvertisingInterval: PeriodicAdvertisingInterval, advertisingEventProperties: AdvertisingEventProperties) { self.advertisingHandle = advertisingHandle self.periodicAdvertisingInterval = periodicAdvertisingInterval self.advertisingEventProperties = advertisingEventProperties } public var data: Data { let periodicAdvertisingIntervalMinBytes = periodicAdvertisingInterval.rawValue.lowerBound.littleEndian.bytes let periodicAdvertisingIntervalMaxBytes = periodicAdvertisingInterval.rawValue.upperBound.littleEndian.bytes let advertisingEventPropertiesytes = advertisingEventProperties.rawValue.littleEndian.bytes return Data([ advertisingHandle, periodicAdvertisingIntervalMinBytes.0, periodicAdvertisingIntervalMinBytes.1, periodicAdvertisingIntervalMaxBytes.0, periodicAdvertisingIntervalMaxBytes.1, advertisingEventPropertiesytes.0, advertisingEventPropertiesytes.1 ]) } public struct PeriodicAdvertisingInterval: RawRepresentable, Equatable { public typealias RawValue = CountableClosedRange<UInt16> /// Maximum interval range. public static let full = PeriodicAdvertisingInterval(rawValue: .min ... .max) public let rawValue: RawValue public init(rawValue: RawValue) { self.rawValue = rawValue } /// Time = N * 0.125 msec. public var miliseconds: ClosedRange<Double> { let miliseconds = Double(0.125) let min = Double(rawValue.lowerBound) * miliseconds let max = Double(rawValue.upperBound) * miliseconds return min ... max } // Equatable public static func == (lhs: PeriodicAdvertisingInterval, rhs: PeriodicAdvertisingInterval) -> Bool { return lhs.rawValue == rhs.rawValue } } /// The Advertising_Event_Properties parameter describes the type of advertising event that is being configured /// and its basic properties. public enum AdvertisingEventProperties: UInt16, BitMaskOption { /// Include TxPower in the extended header of the advertising PDU case includeTxPower = 0b100000 public static let allCases: [HCILESetPeriodicAdvertisingParameters.AdvertisingEventProperties] = [ .includeTxPower ] } }
4bcd30ef59524e2e068d179f6acbab44
42.451852
214
0.705251
false
false
false
false
taironas/gonawin-engine-ios
refs/heads/master
GonawinEngine/Predict.swift
mit
1
// // Predict.swift // GonawinEngine // // Created by Remy JOURDE on 15/04/2016. // Copyright © 2016 Remy Jourde. All rights reserved. // import SwiftyJSON final public class Predict: JSONAble { public let id: Int64 public let userId: Int64 public let matchId: Int64 public let homeTeamScore: Int64 public let awayTeamScore: Int64 public init(id: Int64, userId: Int64, matchId: Int64, homeTeamScore: Int64, awayTeamScore: Int64) { self.id = id self.userId = userId self.matchId = matchId self.homeTeamScore = homeTeamScore self.awayTeamScore = awayTeamScore } static func fromJSON(_ json: JSONDictionary) -> Predict { let json = JSON(json) return fromJSON(json) } static func fromJSON(_ json: JSON) -> Predict { let jsonPredict = json["Predict"] let id = jsonPredict["Id"].int64Value let userId = jsonPredict["UserId"].int64Value let matchId = jsonPredict["MatchId"].int64Value let homeTeamScore = jsonPredict["Result1"].int64Value let awayTeamScore = jsonPredict["Result2"].int64Value return Predict(id: id, userId: userId, matchId: matchId, homeTeamScore: homeTeamScore, awayTeamScore: awayTeamScore) } }
6671a4e3601d8d18ed93ab7399220dbf
29
124
0.643182
false
false
false
false
6ag/WeiboSwift-mvvm
refs/heads/master
WeiboSwift/Classes/View/Home/HomeViewController.swift
mit
1
// // HomeViewController.swift // WeiboSwift // // Created by 周剑峰 on 2017/1/16. // Copyright © 2017年 周剑峰. All rights reserved. // import UIKit fileprivate let ORIGINAL_CELL_IDENTIFIER = "ORIGINAL_CELL_IDENTIFIER" fileprivate let RETWEETED_CELL_IDENTIFIER = "RETWEETED_CELL_IDENTIFIER" class HomeViewController: BaseViewController { fileprivate var listViewModel = StatusListViewModel() override func viewDidLoad() { super.viewDidLoad() } /// 加载数据 override func loadData() { if !NetworkManager.shared.isLogin { print("用户未登录,无需加载数据") return } listViewModel.loadStatus(pullup: isPullup) { (isSuccess, isShouldRefresh) in self.refreshControl?.endRefreshing() self.isPullup = false // 有更多数据才刷新 if isShouldRefresh { self.tableView?.reloadData() } } } } // MARK: - 设置界面 extension HomeViewController { /// 准备UI override func prepareTableView() { super.prepareTableView() tableView?.register(UINib(nibName: "StatusNormalCell", bundle: nil), forCellReuseIdentifier: ORIGINAL_CELL_IDENTIFIER) tableView?.register(UINib(nibName: "StatusRetweetedCell", bundle: nil), forCellReuseIdentifier: RETWEETED_CELL_IDENTIFIER) tableView?.separatorStyle = .none // 预估行高 tableView?.estimatedRowHeight = 300 } } // MARK: - 数据源 extension HomeViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listViewModel.statusList.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let viewModel = listViewModel.statusList[indexPath.row] return viewModel.rowHeight } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let viewModel = listViewModel.statusList[indexPath.row] let cellId = viewModel.status.retweeted_status == nil ? ORIGINAL_CELL_IDENTIFIER : RETWEETED_CELL_IDENTIFIER let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! StatusCell cell.viewModel = viewModel return cell } }
f950c54a3881f6c147e0a6bd0b08e948
28.445783
116
0.634615
false
false
false
false
blstream/mEatUp
refs/heads/master
mEatUp/mEatUp/RoomListDataLoader.swift
apache-2.0
1
// // RoomDataLoader.swift // mEatUp // // Created by Paweł Knuth on 18.04.2016. // Copyright © 2016 BLStream. All rights reserved. // import UIKit import CloudKit class RoomListDataLoader { var cloudKitHelper: CloudKitHelper? let userSettings = UserSettings() var myRoom: [Room] = [] var joinedRooms: [Room] = [] var invitedRooms: [Room] = [] var publicRooms: [Room] = [] var currentRoomList: [Room] { get { return loadCurrentRoomList(dataScope, filter: filter) } } var dataScope: RoomDataScopes = .Public var filter: ((Room) -> Bool)? = nil var completionHandler: (() -> Void)? var errorHandler: (() -> Void)? var userRecordID: CKRecordID? init() { cloudKitHelper = CloudKitHelper() } func addNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(roomAddedNotification), name: "roomAdded", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(roomDeletedNotification), name: "roomDeleted", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(roomUpdatedNotification), name: "roomUpdated", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(userInRoomAddedNotification), name: "userInRoomAdded", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(userInRoomRemovedNotification), name: "userInRoomRemoved", object: nil) } func removeNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self) } @objc func userInRoomRemovedNotification(aNotification: NSNotification) { if let queryNotification = aNotification.object as? CKQueryNotification { if let userRecordName = queryNotification.recordFields?["userRecordID"] as? String, roomRecordName = queryNotification.recordFields?["roomRecordID"] as? String { if userRecordName == userRecordID?.recordName { cloudKitHelper?.loadRoomRecord(CKRecordID(recordName: roomRecordName), completionHandler: { room in guard let owner = room.owner?.recordID else { return } if owner != userRecordName { let message = "You have been kicked out of a room" AlertCreator.singleActionAlert("Info", message: message, actionTitle: "OK", actionHandler: nil) } }, errorHandler: nil) } } } } @objc func userInRoomAddedNotification(aNotification: NSNotification) { if let userInRoomRecordID = aNotification.object as? CKRecordID { cloudKitHelper?.loadUsersInRoomRecord(userInRoomRecordID, completionHandler: { userInRoom in if self.userRecordID == userInRoom.user?.recordID { guard let userRecordID = self.userRecordID else { return } let message = "You have been invited to a room. Check the 'Invited' section." self.invitedRooms.removeAll() self.loadInvitedRoomRecords(userRecordID) AlertCreator.singleActionAlert("Info", message: message, actionTitle: "OK", actionHandler: nil) } }, errorHandler: nil) } } @objc func roomUpdatedNotification(aNotification: NSNotification) { if let roomRecordID = aNotification.object as? CKRecordID { cloudKitHelper?.loadRoomRecord(roomRecordID, completionHandler: { room in self.replaceRoomInArray(&self.publicRooms, room: room) self.replaceRoomInArray(&self.joinedRooms, room: room) self.replaceRoomInArray(&self.invitedRooms, room: room) self.completionHandler?() }, errorHandler: nil) if let userRecordID = userRecordID { cloudKitHelper?.checkIfUserInRoom(roomRecordID, userRecordID: userRecordID, completionHandler: { inRoom in if inRoom != nil { self.cloudKitHelper?.loadRoomRecord(roomRecordID, completionHandler: { room in guard let didEnd = room.didEnd else { return } if didEnd { self.removeRoomFromArrays(roomRecordID) } let message = (didEnd ? "A room that you have joined has ended. Please check settlements tab and enter balance." : "A room that you have joined has been modified.") AlertCreator.singleActionAlert("Info", message: message, actionTitle: "OK", actionHandler: nil) }, errorHandler: nil) } }, errorHandler: nil) } } } func replaceRoomInArray(inout array: [Room], room: Room) { if let index = array.findIndex(room) { array.removeAtIndex(index) array.append(room) } } @objc func roomAddedNotification(aNotification: NSNotification) { if let roomRecordID = aNotification.object as? CKRecordID { cloudKitHelper?.loadRoomRecord(roomRecordID, completionHandler: { room in self.publicRooms.append(room) self.completionHandler?() }, errorHandler: nil) } } @objc func roomDeletedNotification(aNotification: NSNotification) { if let roomRecordID = aNotification.object as? CKRecordID, userRecordID = userRecordID { removeRoomFromArrays(roomRecordID) cloudKitHelper?.checkIfUserInRoom(roomRecordID, userRecordID: userRecordID, completionHandler: { inRoom in if inRoom != nil { AlertCreator.singleActionAlert("Info", message: "Room you were in has been deleted", actionTitle: "OK", actionHandler: nil) } }, errorHandler: nil) self.completionHandler?() } } func removeRoomFromArrays(roomRecordID: CKRecordID) { self.publicRooms = self.publicRooms.filter({return filterRemovedRoom($0, roomRecordID: roomRecordID)}) self.joinedRooms = self.joinedRooms.filter({return filterRemovedRoom($0, roomRecordID: roomRecordID)}) self.invitedRooms = self.invitedRooms.filter({return filterRemovedRoom($0, roomRecordID: roomRecordID)}) } func loadUserRecordFromCloudKit() { if let fbID = userSettings.facebookID() { cloudKitHelper?.loadUserRecordWithFbId(fbID, completionHandler: { userRecord in if let userRecordID = userRecord.recordID { self.userRecordID = userRecordID self.loadRoomsForRoomList(userRecordID) } }, errorHandler: { error in self.loadUserRecordFromCloudKit() }) } } func filterRemovedRoom(room: Room, roomRecordID: CKRecordID) -> Bool { if let recordID = room.recordID { return !(recordID == roomRecordID) } return false } func clearRooms() { myRoom.removeAll() joinedRooms.removeAll() invitedRooms.removeAll() publicRooms.removeAll() } func loadRoomsForRoomList(userRecordID: CKRecordID) { clearRooms() loadPublicRoomRecords() loadInvitedRoomRecords(userRecordID) loadUsersInRoomRecordsWithUserId(userRecordID) loadUserRoomRecord(userRecordID) } func loadPublicRoomRecords() { cloudKitHelper?.loadPublicRoomRecords({ room in if !room.eventOccured { self.publicRooms.append(room) self.completionHandler?() } }, errorHandler: {error in self.errorHandler?() }) } func loadInvitedRoomRecords(userRecordID: CKRecordID) { cloudKitHelper?.loadInvitedRoomRecords(userRecordID, completionHandler: { room in if let room = room where !room.eventOccured { self.invitedRooms.append(room) self.completionHandler?() } }, errorHandler: {error in self.errorHandler?() }) } func loadUsersInRoomRecordsWithUserId(userRecordID: CKRecordID) { cloudKitHelper?.loadUsersInRoomRecordWithUserId(userRecordID, completionHandler: { userRoom in if let userRoom = userRoom { self.joinedRooms.append(userRoom) self.completionHandler?() } }, errorHandler: {error in self.errorHandler?() }) } func loadUserRoomRecord(userRecordID: CKRecordID) { cloudKitHelper?.loadUserRoomRecord(userRecordID, completionHandler: { room in if let room = room { self.myRoom.append(room) self.completionHandler?() } }, errorHandler: {error in self.errorHandler?() }) } func loadCurrentRoomList(dataScope: RoomDataScopes, filter: ((Room) -> Bool)?) -> [Room] { switch dataScope { case .Joined: if let filter = filter { return joinedRooms.filter({filter($0)}) } else { return joinedRooms } case .Invited: if let filter = filter { return invitedRooms.filter({filter($0)}) } else { return invitedRooms } case .MyRoom: if let filter = filter { return myRoom.filter({filter($0)}) } else { return myRoom } case .Public: if let filter = filter { return publicRooms.filter({filter($0)}) } else { return publicRooms } } } }
f75e72cd571447aa28bb913cc10c7ec9
38.312268
192
0.567565
false
false
false
false
jeroendesloovere/examples-swift
refs/heads/master
Swift-Playgrounds/Protocols.playground/section-1.swift
mit
1
// Protocols import Foundation /* protocol SomeProtocol { // protocol definition goes here } struct SomeStructure: FirstProtocol, AnotherProtocol { // structure definition goes here } // If a class has a superclass, list the superclass name before any protocols it adopts, followed by a comma: class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol { // class definition goes here } */ // Property Requirements // Property requirements are always declared as variable properties, prefixed with the var keyword. protocol SomeProtocol { var mustBeSettable: Int { get set } var doesNotNeedToBeSettable: Int { get } } // Always prefix type property requirements with the class keyword when you define them in a protocol. This is true even though type property requirements are prefixed with the static keyword when implemented by a structure or enumeration: protocol AnotherProtocol { class var someTypeProperty: Int { get set } } protocol FullyNamed { var fullName: String { get } } struct Person: FullyNamed { var fullName: String } let john = Person(fullName: "John AppleSeed") class Starship: FullyNamed { var prefix: String? var name: String init(name: String, prefix: String? = nil) { self.name = name self.prefix = prefix } var fullName: String { return ((prefix != nil ? prefix! + " " : "") + name) } } var ncc1701 = Starship(name: "Enterprise", prefix: "USS") // Method Requirements /* protocol SomeProtocol { class func someTypeMethod() } */ protocol RandomNumberGenerator { func random() -> Double } // linear congruential generator: class LinearCongruentialGenerator: RandomNumberGenerator { var lastRandom = 42.0 let m = 139968.0 let a = 3877.0 let c = 29573.0 func random() -> Double { lastRandom = ((lastRandom * a + c) % m) return lastRandom / m } } let generator = LinearCongruentialGenerator() println("Here's a random number: \(generator.random())") println("And another one: \(generator.random())") // Mutating Method Requirements protocol Togglable { mutating func toggle() } enum OnOffSwitch: Togglable { case Off, On mutating func toggle() { switch self { case Off: self = On case On: self = Off } } } var lightSwitch = OnOffSwitch.Off lightSwitch.toggle() lightSwitch // Protocols as Types // Protocols do not actually implement any functionality themselves. Nonetheless, any protocol you create will become a fully-fledged type for use class Dice { let sides: Int let generator: RandomNumberGenerator init(sides: Int, generator: RandomNumberGenerator) { self.sides = sides self.generator = generator } func roll() -> Int { return Int(generator.random() * Double(sides)) + 1 } } var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator()) for _ in 1...5 { println("Random dice roll is \(d6.roll())") } // Delegation protocol DiceGame { var dice: Dice { get } func play() } protocol DiceGameDelegate { func gameDidStart(game: DiceGame) func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) func gameDidEnd(game: DiceGame) } class SnakesAndLadders: DiceGame { let finalSquare = 25 let dice = Dice(sides: 6, generator:LinearCongruentialGenerator()) var square = 0 var board: [Int] init() { board = [Int](count: finalSquare + 1, repeatedValue: 0) board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02; board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08 } var delegate: DiceGameDelegate? func play() { square = 0 delegate?.gameDidStart(self) gameLoop: while square != finalSquare { let diceRoll = dice.roll() delegate?.game(self, didStartNewTurnWithDiceRoll: diceRoll) switch square + diceRoll { case finalSquare: break gameLoop case let newSquare where newSquare > finalSquare: continue gameLoop default: square += diceRoll square += board[square] } } delegate?.gameDidEnd(self) } } class DiceGameTracker: DiceGameDelegate { var numberOfTurns = 0 func gameDidStart(game: DiceGame) { numberOfTurns = 0 if game is SnakesAndLadders { println("Started a new game of Snakes and Ladders") } println("The game is using a \(game.dice.sides)-sided dice") } func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) { ++numberOfTurns println("Rolled a \(diceRoll)") } func gameDidEnd(game: DiceGame) { println("The game lasted for \(numberOfTurns) turns") } } let tracker = DiceGameTracker() let game = SnakesAndLadders() game.delegate = tracker game.play() // Adding Protocol Conformance with an Extension protocol TextRepresentable { func asText() -> String } extension Dice: TextRepresentable { func asText() -> String { return "A \(sides)-sided dice" } } let d12 = Dice(sides: 12, generator: LinearCongruentialGenerator()) println(d12.asText()) d6.asText() extension SnakesAndLadders: TextRepresentable { func asText() -> String { return "A game of Snakes and Ladders with \(finalSquare) squares" } } println(game.asText()) // Declaring Protocol Adoption with an Extension // If a type already conforms to all of the requirements of a protocol, but has not yet stated that it adopts that protocol, you can make it adopt the protocol with an empty extension: struct Hamster { var name: String func asText() -> String { return "A hamster named \(name)" } } extension Hamster: TextRepresentable {} let simonTheHamster = Hamster(name: "Simon") let somethingTextRepresentable: TextRepresentable = simonTheHamster println(somethingTextRepresentable.asText()) // Collections of Protocol Types let things: [TextRepresentable] = [game, d12, simonTheHamster] for thing in things { println(thing.asText()) } // Note that the thing constant is of type TextRepresentable. It is not of type Dice, or DiceGame, or Hamster, even if the actual instance behind the scenes is of one of those types. // Protocol Inheritance /* protocol InheritingProtocol: SomeProtocol, Another Protocol { // protocol definition goes here } */ protocol PrettyTextRepresentable: TextRepresentable { func asPrettyText() -> String } // PrettyTextRepresentable must satisfy all of the requirements enforced by TextRepresentable, plus the additional requirements enforced by PrettyTextRepresentable. extension SnakesAndLadders: PrettyTextRepresentable { func asPrettyText() -> String { var output = asText() + ":\n" for index in 1...finalSquare { switch board[index] { case let ladder where ladder > 0: output += "▲ " case let snake where snake < 0: output += "▼ " default: output += "○ " } } return output } } println(game.asPrettyText()) // Protocol Composition protocol Named { var name: String { get } } protocol Aged { var age: Int { get } } struct Person2: Named, Aged { var name: String var age: Int } func wishHappyBirthday(celebrator: protocol<Named, Aged>) { println("Happy birthday \(celebrator.name) - you're \(celebrator.age)!") } let birthdayPerson = Person2(name:"Malcom", age: 21) wishHappyBirthday(birthdayPerson) // Checking for Protocol Conformance @objc protocol HasArea { var area: Double { get } } // You can check for protocol conformance only if your protocol is marked with the @objc attribute class Circle: HasArea { let pi = 3.1415927 var radius: Double var area: Double { return pi * radius * radius } init(radius: Double) { self.radius = radius } } class Country: HasArea { var area: Double init(area: Double) { self.area = area } } class Animal { var legs: Int init(legs: Int) { self.legs = legs } } let objects: [AnyObject] = [ Circle(radius: 2.0), Country(area: 243_610), Animal(legs: 4) ] for object in objects { if let objectWithArea = object as? HasArea { println("Area is \(objectWithArea.area)") } else { println("Something that doesn't have an area") } } // Note that the underlying objects are not changed by the casting process. They continue to be a Circle, a Country and an Animal. However, at the point that they are stored in the objectWithArea constant, they are only known to be of type HasArea, and so only their area property can be accessed. // Optional Protocol Requirements // Optional property requirements, and optional method requirements that return a value, will always return an optional value of the appropriate type when they are accessed or called, to reflect the fact that the optional requirement may not have been implemented. @objc protocol CounterDataSource { optional func incrementForCount(count: Int) -> Int optional var fixedIncrement: Int { get } } @objc class Counter { var count = 0 var dataSource: CounterDataSource? func increment() { if let amount = dataSource?.incrementForCount?(count) { count += amount } else if let amount = dataSource?.fixedIncrement? { count += amount } } } class ThreeSource: CounterDataSource { let fixedIncrement = 3 } var counter = Counter() counter.dataSource = ThreeSource() for _ in 1...4 { counter.increment() println(counter.count) } class TowardsZeroSource: CounterDataSource { func incrementForCount(count: Int) -> Int { if count == 0 { return 0 } else if count < 0 { return 1 } else { return -1 } } } counter.count = -4 counter.dataSource = TowardsZeroSource() for _ in 1...5 { counter.increment() println(counter.count) }
7dfd1e1c68c6969ad85b04ee383889c2
26.422764
298
0.664493
false
false
false
false
unsignedapps/Turms
refs/heads/master
Turms/Message.swift
mit
1
// // Message.swift // Turms // // Created by Robert Amos on 6/11/2015. // Copyright © 2015 Unsigned Apps. All rights reserved. // import UIKit public enum MessageType { case success case info case warning case error } public enum MessagePosition { case top case navBarOverlay case bottom } public enum MessageDuration { case automatic case endless } public struct Message: Equatable { public var type: MessageType public var title: String public var subtitle: String? public var duration: MessageDuration public var image: UIImage? public var position: MessagePosition public var dismissible: Bool public var animationDuration: TimeInterval = 0.34 public var displayTimeBase: TimeInterval = 1.5 public var displayTimePerPixel: TimeInterval = 0.03 public init (type: MessageType, message: String) { self.init(type: type, title: message); } public init (type: MessageType, title: String, subtitle: String? = nil, duration: MessageDuration = .automatic, image: UIImage? = nil, position: MessagePosition = .navBarOverlay, dismissible: Bool = true) { self.type = type; self.title = title; self.subtitle = subtitle; self.duration = duration; self.image = image; self.position = position; self.dismissible = dismissible; } var backgroundColor: UIColor { get { switch (self.type) { case .success: return UIColor(red: 118.0/255.0, green: 207.0/255.0, blue: 103.0/255, alpha: 1.0); case .info: return UIColor(red: 103.0/255.0, green: 163.0/255.0, blue: 207.0/255, alpha: 1.0); case .warning: return UIColor(red: 218.0/255.0, green: 196.0/255.0, blue: 60.0/255, alpha: 1.0); case .error: return UIColor(red: 221.0/255.0, green: 59.0/255.0, blue: 65.0/255, alpha: 1.0); } } } var shadowColor: UIColor { get { switch (self.type) { case .success: return UIColor(red: 103.0/255.0, green: 183.0/255.0, blue: 89.0/255, alpha: 1.0); case .info: return UIColor(red: 90.0/255.0, green: 145.0/255.0, blue: 184.0/255, alpha: 1.0); case .warning: return UIColor(red: 229.0/255.0, green: 216.0/255.0, blue: 124.0/255, alpha: 1.0); case .error: return UIColor(red: 129.0/255.0, green: 41.0/255.0, blue: 41.0/255, alpha: 1.0); } } } var textColor: UIColor { get { if self.type == .warning { return UIColor(red: 72.0/255.0, green: 70.0/255.0, blue: 56.0/255.0, alpha: 1.0); } return UIColor.white; } } var titleFontSize: CGFloat { get { return 14.0; } } var contentFontSize: CGFloat { get { return 12.0; } } var shadowOffset: CGSize { get { return CGSize(width: 0.0, height: -1.0); } } var icon: UIImage? { get { if let image = self.image { return image; } switch (self.type) { case .success: return UIImage(named: "MessageSuccessIcon", in: Bundle(for: MessageController.self), compatibleWith: nil)!; case .info: return nil; case .warning: return UIImage(named: "MessageWarningIcon", in: Bundle(for: MessageController.self), compatibleWith: nil)!; case .error: return UIImage(named: "MessageErrorIcon", in: Bundle(for: MessageController.self), compatibleWith: nil)!; } } } } public func == (lhs: Message, rhs: Message) -> Bool { return lhs.subtitle == rhs.title && lhs.subtitle == rhs.subtitle; }
2ad3883c8c6a26d86e147574d4999096
25.832258
208
0.530416
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat/External/RCEmojiKit/Emoji.swift
mit
1
// // Emoji.swift // Rocket.Chat // // Created by Matheus Cardoso on 1/5/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import Foundation public enum EmojiType { case standard case custom(imageUrl: String) } public struct Emoji: Codable { public let name: String public let shortname: String public let supportsTones: Bool public let alternates: [String] public let keywords: [String] public let imageUrl: String? public var type: EmojiType { if let imageUrl = imageUrl { return .custom(imageUrl: imageUrl) } return .standard } public init(_ name: String, _ shortname: String, _ supportsTones: Bool, _ alternates: [String], _ keywords: [String], _ imageUrl: String? = nil) { self.name = name self.shortname = shortname self.supportsTones = supportsTones self.alternates = alternates self.keywords = keywords self.imageUrl = imageUrl } }
ad706fd648b8598df275ef16fbe08492
23.243902
150
0.639839
false
false
false
false
netguru/inbbbox-ios
refs/heads/develop
Inbbbox/Source Files/Providers/Core Data Providers/Buckets/ManagedBucketsRequester.swift
gpl-3.0
1
// // ManagedBucketsRequester.swift // Inbbbox // // Created by Lukasz Wolanczyk on 2/23/16. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import UIKit import PromiseKit import CoreData import SwiftyJSON class ManagedBucketsRequester { let managedObjectContext: NSManagedObjectContext let managedObjectsProvider: ManagedObjectsProvider init(managedObjectContext: NSManagedObjectContext = (UIApplication.shared.delegate as? AppDelegate)!.managedObjectContext) { self.managedObjectContext = managedObjectContext managedObjectsProvider = ManagedObjectsProvider(managedObjectContext: managedObjectContext) } func addBucket(_ name: String, description: NSAttributedString?) -> Promise<BucketType> { let bucket = Bucket( identifier: ProcessInfo.processInfo.globallyUniqueString.replacingOccurrences(of: "-", with: ""), name: name, attributedDescription: description, shotsCount: 0, createdAt: Date(), owner: User(json: guestJSON) ) let managedBucket = managedObjectsProvider.managedBucket(bucket) return Promise<BucketType> { fulfill, reject in do { try managedObjectContext.save() fulfill(managedBucket) } catch { reject(error) } } } func addShot(_ shot: ShotType, toBucket bucket: BucketType) -> Promise<Void> { let managedBucket = managedObjectsProvider.managedBucket(bucket) let managedShot = managedObjectsProvider.managedShot(shot) if let _ = managedBucket.shots { managedBucket.addShot(managedShot) } else { managedBucket.shots = NSSet(object: managedShot) } managedBucket.mngd_shotsCount += 1 return Promise<Void> { fulfill, reject in do { fulfill(try managedObjectContext.save()) } catch { reject(error) } } } func removeShot(_ shot: ShotType, fromBucket bucket: BucketType) -> Promise<Void> { let managedBucket = managedObjectsProvider.managedBucket(bucket) let managedShot = managedObjectsProvider.managedShot(shot) if let managedShots = managedBucket.shots { let mutableShots = NSMutableSet(set: managedShots) mutableShots.remove(managedShot) managedBucket.shots = mutableShots.copy() as? NSSet managedBucket.mngd_shotsCount -= 1 } return Promise<Void> { fulfill, reject in do { fulfill(try managedObjectContext.save()) } catch { reject(error) } } } } var guestJSON: JSON { let guestDictionary = [ "id" : "guest.identifier", "name" : "guest.name", "username" : "guest.username", "avatar_url" : "guest.avatar.url", "shots_count" : 0, "param_to_omit" : "guest.param", "type" : "User" ] as [String : Any] return JSON(guestDictionary) }
16d549d1d2df437658278286235816f6
31.092784
128
0.615805
false
false
false
false
WeHUD/app
refs/heads/master
weHub-ios/Gzone_App/Gzone_App/ContactViewController.swift
bsd-3-clause
1
// // ContactViewController.swift // Gzone_App // // Created by Lyes Atek on 04/07/2017. // Copyright © 2017 Tracy Sablon. All rights reserved. // import UIKit class ContactViewController : UIViewController, UITableViewDataSource,UITableViewDelegate{ @IBOutlet var tableView: UITableView! var followers : [User] = [] var avatars : [UIImage] = [] let cellIdentifier = "FriendsSearchCustomCell" override func viewDidLoad() { super.viewDidLoad() self.tableView.delegate = self self.tableView.dataSource = self self.tableView.register(UINib(nibName: "FriendsSearchTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: cellIdentifier) self.tableView.estimatedRowHeight = UITableViewAutomaticDimension self.tableView.rowHeight = 90.0 self.tableView.dataSource = self self.tableView.delegate = self self.getUsers() self.tableView.reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView.reloadData() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let storyboard = UIStoryboard(name: "Home", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "ProfilUser") as! ProfilUserViewController controller.user = self.followers[(self.tableView.indexPathForSelectedRow?.row)!] navigationController?.pushViewController(controller, animated: true) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.followers.count; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCell(withIdentifier: "FriendsSearchCustomCell") as! FriendsSearchTableViewCell let follower = followers[indexPath.row] cell.userNameLbl.text = follower.username cell.userReplyLbl.text = "@" + follower.username cell.userAvatarImageView.image = self.avatars[indexPath.row] cell.UnfollowAction = { (cell) in self.unfollowAction(followerId: follower._id, row: tableView.indexPath(for: cell)!.row, indexPath: indexPath)} // cell.followBtn = { (cell) in self.unfollowAction(followerId: follower._id, row: tableView.indexPath(for: cell)!.row, indexPath: indexPath) return cell } func unfollowAction(followerId : String, row : Int,indexPath : IndexPath){ let followerWB = WBFollower() followerWB.deleteFollowerUser(userId: AuthenticationService.sharedInstance.currentUser!._id, followerId: followerId,accessToken: AuthenticationService.sharedInstance.accessToken!){ (result: Bool) in DispatchQueue.main.async(execute: { self.getUsers() }) print(result) } } func refreshTableView(){ DispatchQueue.main.async(execute: { self.tableView.reloadData() }) } func getUsers()->Void{ let userWB : WBUser = WBUser() userWB.getFollowedUser(accessToken: AuthenticationService.sharedInstance.accessToken!, userId : AuthenticationService.sharedInstance.currentUser!._id,offset: "0") { (result: [User]) in self.followers = result self.imageFromUrl(followers: self.followers) self.refreshTableView() } } func imageFromUrl(followers : [User]){ self.avatars.removeAll() for follower in followers { let imageUrlString = follower.avatar let imageUrl:URL = URL(string: imageUrlString!)! let imageData:NSData = NSData(contentsOf: imageUrl)! self.avatars.append(UIImage(data: imageData as Data)!) } } }
46e9fb788784c77f3dcaa36f477efc18
33.116667
188
0.637763
false
false
false
false
luoziyong/firefox-ios
refs/heads/master
Client/Frontend/Settings/AppSettingsOptions.swift
mpl-2.0
1
/* 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 Shared import Account import SwiftKeychainWrapper import LocalAuthentication // This file contains all of the settings available in the main settings screen of the app. private var ShowDebugSettings: Bool = false private var DebugSettingsClickCount: Int = 0 // For great debugging! class HiddenSetting: Setting { unowned let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var hidden: Bool { return !ShowDebugSettings } } // Sync setting for connecting a Firefox Account. Shown when we don't have an account. class ConnectSetting: WithoutAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Sign In to Firefox", comment: "Text message / button in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var accessibilityIdentifier: String? { return "SignInToFirefox" } override func onClick(_ navigationController: UINavigationController?) { let viewController = FxAContentViewController(profile: profile) viewController.delegate = self viewController.url = settings.profile.accountConfiguration.signInURL navigationController?.pushViewController(viewController, animated: true) } } // Sync setting for disconnecting a Firefox Account. Shown when we have an account. class DisconnectSetting: WithAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .none } override var textAlignment: NSTextAlignment { return .center } override var title: NSAttributedString? { return NSAttributedString(string: Strings.SettingsSignOutButton, attributes: [NSForegroundColorAttributeName: UIConstants.DestructiveRed]) } override var accessibilityIdentifier: String? { return "SignOut" } override func onClick(_ navigationController: UINavigationController?) { let alertController = UIAlertController( title: Strings.SettingsSignOutAlertTitle, message: NSLocalizedString("Firefox will stop syncing with your account, but won’t delete any of your browsing data on this device.", comment: "Text of the 'sign out firefox account' alert"), preferredStyle: UIAlertControllerStyle.alert) alertController.addAction( UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel) { (action) in // Do nothing. }) alertController.addAction( UIAlertAction(title: Strings.SettingsSignOutDestructiveAction, style: .destructive) { (action) in self.settings.profile.removeAccount() self.settings.settings = self.settings.generateSettings() self.settings.SELfirefoxAccountDidChange() LeanplumIntegration.sharedInstance.setUserAttributes(attributes: [UserAttributeKeyName.signedInSync.rawValue : self.profile.hasAccount()]) }) navigationController?.present(alertController, animated: true, completion: nil) } } class SyncNowSetting: WithAccountSetting { static let NotificationUserInitiatedSyncManually = "NotificationUserInitiatedSyncManually" fileprivate lazy var timestampFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter }() fileprivate var syncNowTitle: NSAttributedString { return NSAttributedString( string: NSLocalizedString("Sync Now", comment: "Sync Firefox Account"), attributes: [ NSForegroundColorAttributeName: self.enabled ? UIColor.black : UIColor.gray, NSFontAttributeName: DynamicFontHelper.defaultHelper.DefaultStandardFont ] ) } fileprivate let syncingTitle = NSAttributedString(string: Strings.SyncingMessageWithEllipsis, attributes: [NSForegroundColorAttributeName: UIColor.gray, NSFontAttributeName: UIFont.systemFont(ofSize: DynamicFontHelper.defaultHelper.DefaultStandardFontSize, weight: UIFontWeightRegular)]) override var accessoryType: UITableViewCellAccessoryType { return .none } override var style: UITableViewCellStyle { return .value1 } override var title: NSAttributedString? { guard let syncStatus = profile.syncManager.syncDisplayState else { return syncNowTitle } switch syncStatus { case .bad(let message): guard let message = message else { return syncNowTitle } return NSAttributedString(string: message, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowErrorTextColor, NSFontAttributeName: DynamicFontHelper.defaultHelper.DefaultStandardFont]) case .warning(let message): return NSAttributedString(string: message, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowWarningTextColor, NSFontAttributeName: DynamicFontHelper.defaultHelper.DefaultStandardFont]) case .inProgress: return syncingTitle default: return syncNowTitle } } override var status: NSAttributedString? { guard let timestamp = profile.syncManager.lastSyncFinishTime else { return nil } let formattedLabel = timestampFormatter.string(from: Date.fromTimestamp(timestamp)) let attributedString = NSMutableAttributedString(string: formattedLabel) let attributes = [NSForegroundColorAttributeName: UIColor.gray, NSFontAttributeName: UIFont.systemFont(ofSize: 12, weight: UIFontWeightRegular)] let range = NSRange(location: 0, length: attributedString.length) attributedString.setAttributes(attributes, range: range) return attributedString } override var enabled: Bool { return profile.hasSyncableAccount() } fileprivate lazy var troubleshootButton: UIButton = { let troubleshootButton = UIButton(type: UIButtonType.roundedRect) troubleshootButton.setTitle(Strings.FirefoxSyncTroubleshootTitle, for: .normal) troubleshootButton.addTarget(self, action: #selector(self.troubleshoot), for: .touchUpInside) troubleshootButton.tintColor = UIConstants.TableViewRowActionAccessoryColor troubleshootButton.titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultSmallFont troubleshootButton.sizeToFit() return troubleshootButton }() fileprivate lazy var warningIcon: UIImageView = { let imageView = UIImageView(image: UIImage(named: "AmberCaution")) imageView.sizeToFit() return imageView }() fileprivate lazy var errorIcon: UIImageView = { let imageView = UIImageView(image: UIImage(named: "RedCaution")) imageView.sizeToFit() return imageView }() fileprivate let syncSUMOURL = SupportUtils.URLForTopic("sync-status-ios") @objc fileprivate func troubleshoot() { let viewController = SettingsContentViewController() viewController.url = syncSUMOURL settings.navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { cell.textLabel?.attributedText = title cell.textLabel?.numberOfLines = 0 cell.textLabel?.lineBreakMode = .byWordWrapping if let syncStatus = profile.syncManager.syncDisplayState { switch syncStatus { case .bad(let message): if let _ = message { // add the red warning symbol // add a link to the MANA page cell.detailTextLabel?.attributedText = nil cell.accessoryView = troubleshootButton addIcon(errorIcon, toCell: cell) } else { cell.detailTextLabel?.attributedText = status cell.accessoryView = nil } case .warning(_): // add the amber warning symbol // add a link to the MANA page cell.detailTextLabel?.attributedText = nil cell.accessoryView = troubleshootButton addIcon(warningIcon, toCell: cell) case .good: cell.detailTextLabel?.attributedText = status fallthrough default: cell.accessoryView = nil } } else { cell.accessoryView = nil } cell.accessoryType = accessoryType cell.isUserInteractionEnabled = !profile.syncManager.isSyncing } fileprivate func addIcon(_ image: UIImageView, toCell cell: UITableViewCell) { cell.contentView.addSubview(image) cell.textLabel?.snp.updateConstraints { make in make.leading.equalTo(image.snp.trailing).offset(5) make.trailing.lessThanOrEqualTo(cell.contentView) make.centerY.equalTo(cell.contentView) } image.snp.makeConstraints { make in make.leading.equalTo(cell.contentView).offset(17) make.top.equalTo(cell.textLabel!).offset(2) } } override func onClick(_ navigationController: UINavigationController?) { NotificationCenter.default.post(name: Notification.Name(rawValue: SyncNowSetting.NotificationUserInitiatedSyncManually), object: nil) profile.syncManager.syncEverything(why: .syncNow) } } // Sync setting that shows the current Firefox Account status. class AccountStatusSetting: WithAccountSetting { override var accessoryType: UITableViewCellAccessoryType { if let account = profile.getAccount() { switch account.actionNeeded { case .needsVerification: // We link to the resend verification email page. return .disclosureIndicator case .needsPassword: // We link to the re-enter password page. return .disclosureIndicator case .none, .needsUpgrade: // In future, we'll want to link to /settings and an upgrade page, respectively. return .none } } return .disclosureIndicator } override var title: NSAttributedString? { if let account = profile.getAccount() { return NSAttributedString(string: account.email, attributes: [NSFontAttributeName: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } return nil } override var status: NSAttributedString? { if let account = profile.getAccount() { switch account.actionNeeded { case .none: return nil case .needsVerification: return NSAttributedString(string: NSLocalizedString("Verify your email address.", comment: "Text message in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) case .needsPassword: let string = NSLocalizedString("Enter your password to connect.", comment: "Text message in the settings table view") let range = NSRange(location: 0, length: string.characters.count) let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1) let attrs = [NSForegroundColorAttributeName: orange] let res = NSMutableAttributedString(string: string) res.setAttributes(attrs, range: range) return res case .needsUpgrade: let string = NSLocalizedString("Upgrade Firefox to connect.", comment: "Text message in the settings table view") let range = NSRange(location: 0, length: string.characters.count) let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1) let attrs = [NSForegroundColorAttributeName: orange] let res = NSMutableAttributedString(string: string) res.setAttributes(attrs, range: range) return res } } return nil } override func onClick(_ navigationController: UINavigationController?) { let viewController = FxAContentViewController(profile: profile) viewController.delegate = self if let account = profile.getAccount() { switch account.actionNeeded { case .needsVerification: var cs = URLComponents(url: account.configuration.settingsURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email)) viewController.url = try! cs?.asURL() case .needsPassword: var cs = URLComponents(url: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email)) viewController.url = try! cs?.asURL() case .none, .needsUpgrade: // In future, we'll want to link to /settings and an upgrade page, respectively. return } } navigationController?.pushViewController(viewController, animated: true) } } // For great debugging! class RequirePasswordDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount(), account.actionNeeded != FxAActionNeeded.needsPassword { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(_ navigationController: UINavigationController?) { profile.getAccount()?.makeSeparated() settings.tableView.reloadData() } } // For great debugging! class RequireUpgradeDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount(), account.actionNeeded != FxAActionNeeded.needsUpgrade { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(_ navigationController: UINavigationController?) { profile.getAccount()?.makeDoghouse() settings.tableView.reloadData() } } // For great debugging! class ForgetSyncAuthStateDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let _ = profile.getAccount() { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(_ navigationController: UINavigationController?) { profile.getAccount()?.syncAuthState.invalidate() settings.tableView.reloadData() } } class DeleteExportedDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let fileManager = FileManager.default do { let files = try fileManager.contentsOfDirectory(atPath: documentsPath) for file in files { if file.startsWith("browser.") || file.startsWith("logins.") { try fileManager.removeItemInDirectory(documentsPath, named: file) } } } catch { print("Couldn't delete exported data: \(error).") } } } class ExportBrowserDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] do { let log = Logger.syncLogger try self.settings.profile.files.copyMatching(fromRelativeDirectory: "", toAbsoluteDirectory: documentsPath) { file in log.debug("Matcher: \(file)") return file.startsWith("browser.") || file.startsWith("logins.") || file.startsWith("metadata.") } } catch { print("Couldn't export browser data: \(error).") } } } /* FeatureSwitchSetting is a boolean switch for features that are enabled via a FeatureSwitch. These are usually features behind a partial release and not features released to the entire population. */ class FeatureSwitchSetting: BoolSetting { let featureSwitch: FeatureSwitch let prefs: Prefs init(prefs: Prefs, featureSwitch: FeatureSwitch, with title: NSAttributedString) { self.featureSwitch = featureSwitch self.prefs = prefs super.init(prefs: prefs, defaultValue: featureSwitch.isMember(prefs), attributedTitleText: title) } override var hidden: Bool { return !ShowDebugSettings } override func displayBool(_ control: UISwitch) { control.isOn = featureSwitch.isMember(prefs) } override func writeBool(_ control: UISwitch) { self.featureSwitch.setMembership(control.isOn, for: self.prefs) } } class EnableActivtyStreamSetting: FeatureSwitchSetting { let profile: Profile init(settings: SettingsTableViewController) { self.profile = settings.profile let title = NSAttributedString(string: "Enable the New Tab Experience", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) super.init(prefs: settings.profile.prefs, featureSwitch: FeatureSwitches.activityStream, with: title) } } class EnableBookmarkMergingSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Enable Bidirectional Bookmark Sync ", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(_ navigationController: UINavigationController?) { AppConstants.shouldMergeBookmarks = true } } class ForceCrashSetting: HiddenSetting { override var title: NSAttributedString? { return NSAttributedString(string: "Debug: Force Crash", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(_ navigationController: UINavigationController?) { SentryIntegration.shared.crash() } } // Show the current version of Firefox class VersionSetting: Setting { unowned let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var title: NSAttributedString? { let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String let buildNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) cell.selectionStyle = .none } override func onClick(_ navigationController: UINavigationController?) { DebugSettingsClickCount += 1 if DebugSettingsClickCount >= 5 { DebugSettingsClickCount = 0 ShowDebugSettings = !ShowDebugSettings settings.tableView.reloadData() } } } // Opens the the license page in a new tab class LicenseAndAcknowledgementsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: URL? { return URL(string: WebServer.sharedInstance.URLForResource("license", module: "about")) } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens about:rights page in the content view controller class YourRightsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Your Rights", comment: "Your Rights settings section title"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: URL? { return URL(string: "https://www.mozilla.org/about/legal/terms/firefox/") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the on-boarding screen again class ShowIntroductionSetting: Setting { let profile: Profile override var accessibilityIdentifier: String? { return "ShowTour" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.dismiss(animated: true, completion: { if let appDelegate = UIApplication.shared.delegate as? AppDelegate { appDelegate.browserViewController.presentIntroViewController(true) } }) } } class SendFeedbackSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Menu item in settings used to open input.mozilla.org where people can submit feedback"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: URL? { let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String return URL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class SendAnonymousUsageDataSetting: BoolSetting { init(prefs: Prefs, delegate: SettingsDelegate?) { super.init( prefs: prefs, prefKey: "settings.sendUsageData", defaultValue: true, attributedTitleText: NSAttributedString(string: NSLocalizedString("Send Anonymous Usage Data", tableName: "SendAnonymousUsageData", comment: "See http://bit.ly/1SmEXU1")), attributedStatusText: NSAttributedString(string: NSLocalizedString("More Info…", tableName: "SendAnonymousUsageData", comment: "See http://bit.ly/1SmEXU1"), attributes: [NSForegroundColorAttributeName: UIConstants.HighlightBlue]), settingDidChange: { AdjustIntegration.setEnabled($0) LeanplumIntegration.sharedInstance.setUserAttributes(attributes: [UserAttributeKeyName.telemetryOptIn.rawValue : $0]) LeanplumIntegration.sharedInstance.setEnabled($0) } ) } override var url: URL? { return SupportUtils.URLForTopic("adjust") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the the SUMO page in a new tab class OpenSupportPageSetting: Setting { init(delegate: SettingsDelegate?) { super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.dismiss(animated: true) { if let url = URL(string: "https://support.mozilla.org/products/ios") { self.delegate?.settingsOpenURLInNewTab(url) } } } } // Opens the search settings pane class SearchSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) } override var accessibilityIdentifier: String? { return "Search" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class LoginsSetting: Setting { let profile: Profile var tabManager: TabManager! weak var navigationController: UINavigationController? weak var settings: AppSettingsTableViewController? override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "Logins" } init(settings: SettingsTableViewController, delegate: SettingsDelegate?) { self.profile = settings.profile self.tabManager = settings.tabManager self.navigationController = settings.navigationController self.settings = settings as? AppSettingsTableViewController let loginsTitle = NSLocalizedString("Logins", comment: "Label used as an item in Settings. When touched, the user will be navigated to the Logins/Password manager.") super.init(title: NSAttributedString(string: loginsTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]), delegate: delegate) } func deselectRow () { if let selectedRow = self.settings?.tableView.indexPathForSelectedRow { self.settings?.tableView.deselectRow(at: selectedRow, animated: true) } } override func onClick(_: UINavigationController?) { guard let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() else { settings?.navigateToLoginsList() LeanplumIntegration.sharedInstance.track(eventName: .openedLogins) return } if authInfo.requiresValidation() { AppAuthenticator.presentAuthenticationUsingInfo(authInfo, touchIDReason: AuthenticationStrings.loginsTouchReason, success: { self.settings?.navigateToLoginsList() LeanplumIntegration.sharedInstance.track(eventName: .openedLogins) }, cancel: { self.deselectRow() }, fallback: { AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self.settings) self.deselectRow() }) } else { settings?.navigateToLoginsList() LeanplumIntegration.sharedInstance.track(eventName: .openedLogins) } } } class TouchIDPasscodeSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "TouchIDPasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { self.profile = settings.profile self.tabManager = settings.tabManager let title: String if LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { title = AuthenticationStrings.touchIDPasscodeSetting } else { title = AuthenticationStrings.passcode } super.init(title: NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { let viewController = AuthenticationSettingsViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class ClearPrivateDataSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "ClearPrivateData" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager let clearTitle = Strings.SettingsClearPrivateDataSectionName super.init(title: NSAttributedString(string: clearTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = ClearPrivateDataTableViewController() viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class PrivacyPolicySetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: URL? { return URL(string: "https://www.mozilla.org/privacy/firefox/") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class ChinaSyncServiceSetting: WithoutAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .none } var prefs: Prefs { return settings.profile.prefs } let prefKey = "useChinaSyncService" override var title: NSAttributedString? { return NSAttributedString(string: "本地同步服务", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var status: NSAttributedString? { return NSAttributedString(string: "禁用后使用全球服务同步数据", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewHeaderTextColor]) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: #selector(ChinaSyncServiceSetting.switchValueChanged(_:)), for: UIControlEvents.valueChanged) control.isOn = prefs.boolForKey(prefKey) ?? self.profile.isChinaEdition cell.accessoryView = control cell.selectionStyle = .none } @objc func switchValueChanged(_ toggle: UISwitch) { prefs.setObject(toggle.isOn, forKey: prefKey) } } class StageSyncServiceDebugSetting: WithoutAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .none } var prefs: Prefs { return settings.profile.prefs } var prefKey: String = "useStageSyncService" override var hidden: Bool { if !ShowDebugSettings { return true } if let _ = profile.getAccount() { return true } return false } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: use stage servers", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var status: NSAttributedString? { // Derive the configuration we display from the profile, which knows about the prefKey. let configurationURL = settings.profile.accountConfiguration.authEndpointURL return NSAttributedString(string: configurationURL.absoluteString, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewHeaderTextColor]) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: #selector(StageSyncServiceDebugSetting.switchValueChanged(_:)), for: UIControlEvents.valueChanged) control.isOn = prefs.boolForKey(prefKey) ?? false cell.accessoryView = control cell.selectionStyle = .none } @objc func switchValueChanged(_ toggle: UISwitch) { prefs.setObject(toggle.isOn, forKey: prefKey) settings.tableView.reloadData() } } class HomePageSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "Homepage" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager super.init(title: NSAttributedString(string: Strings.SettingsHomePageSectionName, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = HomePageSettingsViewController() viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class NewTabPageSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "NewTab" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsNewTabSectionName, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = NewTabChoiceViewController(prefs: profile.prefs) navigationController?.pushViewController(viewController, animated: true) } } class OpenWithSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "OpenWith.Setting" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsOpenWithSectionName, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = OpenWithSettingsViewController(prefs: profile.prefs) navigationController?.pushViewController(viewController, animated: true) } }
bc1e12760213a7b84ee7857a6a25d316
41.676104
299
0.702863
false
false
false
false
borisyurkevich/ECAB
refs/heads/develop
ECAB/GameMenuViewController.swift
mit
1
// // GameMenuViewController.swift // ECAB // // Created by Boris Yurkevich on 29/05/2021. // Copyright © 2021 Oliver Braddick and Jan Atkinson. All rights reserved. // import UIKit import os final class GameMenuViewController: UIViewController { weak var delelgate: GameMenuDelegate? @IBOutlet private weak var menuView: MenuView! @IBOutlet private weak var menuStrip: UIView! @IBOutlet private weak var backLabel: UILabel! @IBOutlet private weak var forwardLabel: UILabel! @IBOutlet private weak var skipLabel: UILabel! @IBOutlet private weak var pauseLabel: UILabel! private let borderWidth: CGFloat = 1.0 private let borderColor: CGColor = UIColor.darkGray.cgColor private var buttonColor: UIColor? private var activity: UIActivityIndicatorView? override func viewDidLoad() { super.viewDidLoad() addMenuBorders() setTextColor() menuView.delegate = self buttonColor = backLabel.backgroundColor } func toggleNavigationButtons(isEnabled: Bool) { forwardLabel.isEnabled = isEnabled backLabel.isEnabled = isEnabled skipLabel.isEnabled = isEnabled } func updatePauseButtonState(isHidden: Bool) { pauseLabel.isHidden = isHidden } func updateBackButtonTitle(_ title: String) { backLabel.text = title } func startAnimatingPauseButton() { pauseLabel.text = "" activity = UIActivityIndicatorView(style: .medium) guard let activity = activity else { return } activity.startAnimating() pauseLabel.addSubview(activity) activity.translatesAutoresizingMaskIntoConstraints = false activity.centerYAnchor.constraint(equalTo: pauseLabel.centerYAnchor).isActive = true activity.centerXAnchor.constraint(equalTo: pauseLabel.centerXAnchor).isActive = true } func stopAnimatingPauseButton() { activity?.removeFromSuperview() self.pauseLabel.text = "Pause" self.pauseLabel.textColor = UIColor.label } // MARK: - Private private func addMenuBorders() { backLabel.layer.borderWidth = borderWidth backLabel.layer.borderColor = borderColor forwardLabel.layer.borderWidth = borderWidth forwardLabel.layer.borderColor = borderColor skipLabel.layer.borderWidth = borderWidth skipLabel.layer.borderColor = borderColor pauseLabel.layer.borderWidth = borderWidth pauseLabel.layer.borderColor = borderColor } private func setTextColor() { backLabel.textColor = UIColor.label forwardLabel.textColor = UIColor.label skipLabel.textColor = UIColor.label pauseLabel.textColor = UIColor.label } } extension GameMenuViewController: MenuViewDelegate { func reset(location: CGPoint) { DispatchQueue.main.async { [unowned self] in if location.x < forwardLabel.frame.origin.x { backLabel.backgroundColor = buttonColor backLabel.textColor = UIColor.label } else if location.x < skipLabel.frame.origin.x { forwardLabel.backgroundColor = buttonColor forwardLabel.textColor = UIColor.label } else if location.x <= skipLabel.frame.origin.x + skipLabel.frame.width { skipLabel.backgroundColor = buttonColor skipLabel.textColor = UIColor.label } else if location.x >= pauseLabel.frame.origin.x { pauseLabel.backgroundColor = buttonColor pauseLabel.textColor = UIColor.label } else { os_log(.debug, "touch outise buttons area: %@", location.debugDescription) } } } func highlight(location: CGPoint) { DispatchQueue.main.async { [unowned self] in if location.x < forwardLabel.frame.origin.x { if backLabel.isEnabled { backLabel.backgroundColor = view.tintColor backLabel.textColor = UIColor.lightText } } else if location.x < skipLabel.frame.origin.x { if forwardLabel.isEnabled { forwardLabel.backgroundColor = view.tintColor forwardLabel.textColor = UIColor.lightText } } else if location.x <= skipLabel.frame.origin.x + skipLabel.frame.width { if skipLabel.isEnabled { skipLabel.backgroundColor = view.tintColor skipLabel.textColor = UIColor.lightText } } else if location.x >= pauseLabel.frame.origin.x { if pauseLabel.isEnabled { pauseLabel.backgroundColor = view.tintColor pauseLabel.textColor = UIColor.lightText } } else { os_log(.debug, "touch outise buttons area: %@", location.debugDescription) } } } func handleTouch(location: CGPoint) { DispatchQueue.main.async { [unowned self] in if location.x < forwardLabel.frame.origin.x { if backLabel.isEnabled { backLabel.backgroundColor = buttonColor backLabel.textColor = UIColor.label delelgate?.presentPreviousScreen() } } else if location.x < skipLabel.frame.origin.x { if forwardLabel.isEnabled { forwardLabel.backgroundColor = buttonColor forwardLabel.textColor = UIColor.label delelgate?.presentNextScreen() } } else if location.x <= skipLabel.frame.origin.x + skipLabel.frame.width { if skipLabel.isEnabled { skipLabel.backgroundColor = buttonColor skipLabel.textColor = UIColor.label delelgate?.skip() } } else if location.x >= pauseLabel.frame.origin.x { if pauseLabel.isEnabled { pauseLabel.backgroundColor = buttonColor pauseLabel.textColor = UIColor.label delelgate?.presentPause() } } else { os_log(.debug, "touch outise buttons area: %@", location.debugDescription) } } } }
7f5ba15f1df1c13278cab622e3b2e468
33.481283
92
0.606855
false
false
false
false
syoung-smallwisdom/BridgeAppSDK
refs/heads/master
BridgeAppSDK/SBBScheduledActivity+Utilities.swift
bsd-3-clause
1
// // SBBScheduledActivity+Utilities.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import BridgeSDK public extension SBBScheduledActivity { public var isCompleted: Bool { return self.finishedOn != nil } public var isExpired: Bool { return (self.expiresOn != nil) && ((Date() as NSDate).earlierDate(self.expiresOn) == self.expiresOn) } public var isNow: Bool { return !isCompleted && ((self.scheduledOn == nil) || ((self.scheduledOn.timeIntervalSinceNow < 0) && !isExpired)) } var isToday: Bool { return SBBScheduledActivity.availableTodayPredicate().evaluate(with: self) } var isTomorrow: Bool { return SBBScheduledActivity.scheduledTomorrowPredicate().evaluate(with: self) } var scheduledTime: String { if isCompleted { return "" } else if isNow { return Localization.localizedString("SBA_NOW") } else { return DateFormatter.localizedString(from: scheduledOn, dateStyle: .none, timeStyle: .short) } } var expiresTime: String? { if expiresOn == nil { return nil } return DateFormatter.localizedString(from: expiresOn, dateStyle: .none, timeStyle: .short) } public dynamic var taskIdentifier: String? { return (self.activity.task != nil) ? self.activity.task.identifier : nil } public dynamic var surveyIdentifier: String? { guard self.activity.survey != nil else { return nil } return self.activity.survey.identifier } public dynamic var scheduleIdentifier: String { // Strip out the unique part of the guid if let range = self.guid.range(of: ":") { return self.guid.substring(to: range.lowerBound) } else { return self.guid } } }
08762d5d2b1b4f1d5474066cbfc792f8
37.247312
121
0.688502
false
false
false
false
flexih/Cafe
refs/heads/master
coffee/Cafe.swift
mit
1
// // Cafe.swift // coffee // // Created by flexih on 1/8/16. // Copyright © 2016 flexih. All rights reserved. // import Foundation import CoreLocation struct Cafe { let name: String let addr: String let posterURL: URL let oneword: String? let phones: [String]? let openingTime: String? let remarks: String? let lat: CLLocationDegrees let lng: CLLocationDegrees init(dict: [String: AnyObject]) { name = dict["name"] as? String ?? "" addr = dict["addr"] as? String ?? "" posterURL = (dict["poster"] as? String).map{URL(string: $0)!} ?? URL(string: "")! oneword = dict["oneword"] as? String phones = dict["phones"] as? [String] openingTime = dict["opening"] as? String remarks = dict["remarks"] as? String lat = (dict["lat"] as? String).map{CLLocationDegrees($0)!} ?? 0 lng = (dict["lng"] as? String).map{CLLocationDegrees($0)!} ?? 0 } }
8c069fcee64c2e52c5213728653c4b34
27.323529
89
0.589823
false
false
false
false
Allow2CEO/browser-ios
refs/heads/master
brave/src/frontend/sync/SyncCameraView.swift
mpl-2.0
1
/* 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 AVFoundation import Shared class SyncCameraView: UIView, AVCaptureMetadataOutputObjectsDelegate { var captureSession:AVCaptureSession? var videoPreviewLayer:AVCaptureVideoPreviewLayer? var cameraOverlayView: UIImageView! private lazy var cameraAccessButton: RoundInterfaceButton = { let button = self.createCameraButton() button.setTitle(Strings.GrantCameraAccess, for: .normal) button.addTarget(self, action: #selector(SEL_cameraAccess), for: .touchUpInside) return button }() private lazy var openSettingsButton: RoundInterfaceButton = { let button = self.createCameraButton() button.setTitle(Strings.Open_Settings, for: .normal) button.addTarget(self, action: #selector(openSettings), for: .touchUpInside) return button }() var scanCallback: ((_ data: String) -> Void)? override init(frame: CGRect) { super.init(frame: frame) cameraOverlayView = UIImageView(image: UIImage(named: "camera-overlay")?.withRenderingMode(.alwaysTemplate)) cameraOverlayView.contentMode = .center cameraOverlayView.tintColor = UIColor.white addSubview(cameraOverlayView) addSubview(cameraAccessButton) addSubview(openSettingsButton) [cameraAccessButton, openSettingsButton].forEach { button in button.snp.makeConstraints { make in make.centerX.equalTo(cameraOverlayView) make.centerY.equalTo(cameraOverlayView) make.width.equalTo(150) make.height.equalTo(40) } } switch AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) { case .authorized: cameraAccessButton.isHidden = true openSettingsButton.isHidden = true startCapture() case .denied: cameraAccessButton.isHidden = true openSettingsButton.isHidden = false default: cameraAccessButton.isHidden = false openSettingsButton.isHidden = true } } fileprivate func createCameraButton() -> RoundInterfaceButton { let button = RoundInterfaceButton(type: .roundedRect) button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFontWeightBold) button.setTitleColor(UIColor.white, for: .normal) button.backgroundColor = UIColor.clear button.layer.borderColor = UIColor.white.withAlphaComponent(0.4).cgColor button.layer.borderWidth = 1.5 return button } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { if let vpl = videoPreviewLayer { vpl.frame = bounds } cameraOverlayView.frame = bounds } func SEL_cameraAccess() { startCapture() } func openSettings() { UIApplication.shared.open(URL(string:UIApplicationOpenSettingsURLString)!) } func startCapture() { let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) let input: AVCaptureDeviceInput? do { input = try AVCaptureDeviceInput(device: captureDevice) as AVCaptureDeviceInput } catch let error as NSError { debugPrint(error) return } captureSession = AVCaptureSession() captureSession?.addInput(input! as AVCaptureInput) let captureMetadataOutput = AVCaptureMetadataOutput() captureSession?.addOutput(captureMetadataOutput) captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode] videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill videoPreviewLayer?.frame = layer.bounds layer.addSublayer(videoPreviewLayer!) captureSession?.startRunning() bringSubview(toFront: cameraOverlayView) AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted :Bool) -> Void in postAsyncToMain { self.cameraAccessButton.isHidden = true if granted { self.openSettingsButton.isHidden = true } else { self.openSettingsButton.isHidden = false self.bringSubview(toFront: self.openSettingsButton) } } }) } func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) { // Check if the metadataObjects array is not nil and it contains at least one object. if metadataObjects == nil || metadataObjects.count == 0 { return } let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject if metadataObj.type == AVMetadataObjectTypeQRCode { if let callback = scanCallback { callback(metadataObj.stringValue) } } } func cameraOverlayError() { NSObject.cancelPreviousPerformRequests(withTarget: self) cameraOverlayView.tintColor = UIColor.red perform(#selector(cameraOverlayNormal), with: self, afterDelay: 1.0) } func cameraOverlaySucess() { NSObject.cancelPreviousPerformRequests(withTarget: self) cameraOverlayView.tintColor = UIColor.green perform(#selector(cameraOverlayNormal), with: self, afterDelay: 1.0) } func cameraOverlayNormal() { cameraOverlayView.tintColor = UIColor.white } }
5401f5800fe12546896da1f629d1b705
36.644172
198
0.652705
false
false
false
false
brentsimmons/Evergreen
refs/heads/ios-candidate
Account/Sources/Account/CloudKit/CloudKitArticleStatusUpdate.swift
mit
1
// // CloudKitArticleStatusUpdate.swift // Account // // Created by Maurice Parker on 4/29/20. // Copyright © 2020 Ranchero Software, LLC. All rights reserved. // import Foundation import SyncDatabase import Articles struct CloudKitArticleStatusUpdate { enum Record { case all case new case statusOnly case delete } var articleID: String var statuses: [SyncStatus] var article: Article? init?(articleID: String, statuses: [SyncStatus], article: Article?) { self.articleID = articleID self.statuses = statuses self.article = article let rec = record // This is an invalid status update. The article is required for new and all if article == nil && (rec == .all || rec == .new) { return nil } } var record: Record { if statuses.contains(where: { $0.key == .deleted }) { return .delete } if statuses.count == 1, statuses.first!.key == .new { return .new } if let article = article { if article.status.read == false || article.status.starred == true { return .all } } return .statusOnly } var isRead: Bool { if let article = article { return article.status.read } return true } var isStarred: Bool { if let article = article { return article.status.starred } return false } }
e7cb7c553a544e31cb3119f8f3df0bfb
17.385714
79
0.661228
false
false
false
false
pendowski/PopcornTimeIOS
refs/heads/master
Popcorn Time/UI/Collection View Controllers/TVShowsCollectionViewController.swift
gpl-3.0
1
import UIKit import AlamofireImage class TVShowsCollectionViewController: ItemOverview, UIPopoverPresentationControllerDelegate, GenresDelegate, ItemOverviewDelegate { var shows = [PCTShow]() var currentGenre = TVAPI.genres.All { didSet { shows.removeAll() collectionView?.reloadData() currentPage = 1 loadNextPage(currentPage) } } var currentFilter = TVAPI.filters.Trending { didSet { shows.removeAll() collectionView?.reloadData() currentPage = 1 loadNextPage(currentPage) } } @IBAction func searchBtnPressed(sender: UIBarButtonItem) { presentViewController(searchController, animated: true, completion: nil) } @IBAction func filter(sender: AnyObject) { self.collectionView?.performBatchUpdates({ self.filterHeader!.hidden = !self.filterHeader!.hidden }, completion: nil) } override func viewDidLoad() { super.viewDidLoad() delegate = self loadNextPage(currentPage) } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let collectionView = object as? UICollectionView where collectionView == self.collectionView! && keyPath! == "frame" { collectionView.performBatchUpdates(nil, completion: nil) } } func segmentedControlDidChangeSegment(segmentedControl: UISegmentedControl) { currentFilter = TVAPI.filters.arrayValue[segmentedControl.selectedSegmentIndex] } // MARK: - ItemOverviewDelegate func loadNextPage(pageNumber: Int, searchTerm: String? = nil, removeCurrentData: Bool = false) { guard isLoading else { isLoading = true hasNextPage = false TVAPI.sharedInstance.load(currentPage, filterBy: currentFilter, genre: currentGenre, searchTerm: searchTerm) { result in self.isLoading = false guard case .success(let items) = result else { return } if removeCurrentData { self.shows.removeAll() } self.shows += items if items.isEmpty // If the array passed in is empty, there are no more results so the content inset of the collection view is reset. { self.collectionView?.contentInset = UIEdgeInsetsMake(69, 0, 0, 0) } else { self.hasNextPage = true } self.collectionView?.reloadData() } return } } func didDismissSearchController(searchController: UISearchController) { self.shows.removeAll() collectionView?.reloadData() self.currentPage = 1 loadNextPage(self.currentPage) } func search(text: String) { self.shows.removeAll() collectionView?.reloadData() self.currentPage = 1 self.loadNextPage(self.currentPage, searchTerm: text) } func shouldRefreshCollectionView() -> Bool { return shows.isEmpty } // MARK: - Navigation @IBAction func genresButtonTapped(sender: UIBarButtonItem) { let controller = cache.objectForKey(TraktTVAPI.type.Shows.rawValue) as? UINavigationController ?? (storyboard?.instantiateViewControllerWithIdentifier("GenresNavigationController"))! as! UINavigationController cache.setObject(controller, forKey: TraktTVAPI.type.Shows.rawValue) controller.modalPresentationStyle = .Popover controller.popoverPresentationController?.barButtonItem = sender controller.popoverPresentationController?.backgroundColor = UIColor(red: 30.0/255.0, green: 30.0/255.0, blue: 30.0/255.0, alpha: 1.0) (controller.viewControllers[0] as! GenresTableViewController).delegate = self presentViewController(controller, animated: true, completion: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { fixIOS9PopOverAnchor(segue) if segue.identifier == "showDetail" { let showDetail = segue.destinationViewController as! TVShowDetailViewController let cell = sender as! CoverCollectionViewCell showDetail.currentItem = shows[(collectionView?.indexPathForCell(cell)?.row)!] } } // MARK: - Collection view data source override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { collectionView.backgroundView = nil if shows.count == 0 { if error != nil { let background = NSBundle.mainBundle().loadNibNamed("TableViewBackground", owner: self, options: nil).first as! TableViewBackground background.setUpView(error: error!) collectionView.backgroundView = background } else if isLoading { let indicator = UIActivityIndicatorView(activityIndicatorStyle: .White) indicator.center = collectionView.center collectionView.backgroundView = indicator indicator.sizeToFit() indicator.startAnimating() } else { let background = NSBundle.mainBundle().loadNibNamed("TableViewBackground", owner: self, options: nil).first as! TableViewBackground background.setUpView(image: UIImage(named: "Search")!, title: "No results found.", description: "No search results found for \(searchController.searchBar.text!). Please check the spelling and try again.") collectionView.backgroundView = background } } return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return shows.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CoverCollectionViewCell cell.titleLabel.text = shows[indexPath.row].title cell.yearLabel.text = String(shows[indexPath.row].year) cell.coverImage.af_setImageWithURL(NSURL(string: shows[indexPath.row].coverImageAsString)!, placeholderImage: UIImage(named: "Placeholder"), imageTransition: .CrossDissolve(animationLength)) return cell } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { filterHeader = filterHeader ?? { let reuseableView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "filter", forIndexPath: indexPath) as! FilterCollectionReusableView reuseableView.segmentedControl?.removeAllSegments() for (index, filterValue) in TVAPI.filters.arrayValue.enumerate() { reuseableView.segmentedControl?.insertSegmentWithTitle(filterValue.title, atIndex: index, animated: false) } reuseableView.hidden = true reuseableView.segmentedControl?.addTarget(self, action: #selector(segmentedControlDidChangeSegment(_:)), forControlEvents: .ValueChanged) reuseableView.segmentedControl?.selectedSegmentIndex = 0 return reuseableView }() return filterHeader! } // MARK: - GenresDelegate func finished(genreArrayIndex: Int) { navigationItem.title = TVAPI.genres.arrayValue[genreArrayIndex].rawValue if TVAPI.genres.arrayValue[genreArrayIndex] == .All { navigationItem.title = "Shows" } currentGenre = TVAPI.genres.arrayValue[genreArrayIndex] } func populateDataSourceArray(inout array: [String]) { for genre in TVAPI.genres.arrayValue { array.append(genre.rawValue) } } }
27860f861d14052a2afa327e2f216f14
43.064171
220
0.654369
false
false
false
false
sabbek/EasySwift
refs/heads/master
EasySwift/EasySwift/UIButton.swift
mit
1
// // UIButton.swift // EasySwift // // Created by Sabbe on 21/03/17. // Copyright © 2017 sabbe.kev. All rights reserved. // // MIT License // // Copyright (c) 2017 sabbek // // 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 // MARK: - Extensions - extension UIButton { // MARK: - Button with Text title convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, titleColor: UIColor?, bgColor: UIColor?, title: String?, alignment: UIControlContentHorizontalAlignment?, selector: Selector?, superView: UIView?) { self.init() self.frame = CGRect(x: x, y: y, w: w, h: h) if titleColor != nil { self.setTitleColor(titleColor, for: .normal) } if bgColor != nil { self.backgroundColor = bgColor } if title != nil { self.setTitle(title, for: .normal) } if alignment != nil { self.contentHorizontalAlignment = alignment! } if selector != nil { self.addTarget(nil, action: selector!, for: .touchUpInside) } if superView != nil { superView!.addSubview(self) } } // MARK: - Button with Image convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, bgColor: UIColor?, image: UIImage?, contentMode: UIViewContentMode?, insets: UIEdgeInsets?, selector: Selector?, superView: UIView?) { self.init() self.frame = CGRect(x: x, y: y, w: w, h: h) if image != nil { self.setImage(image!, for: .normal) } if contentMode != nil { self.contentMode = contentMode! } if insets != nil { self.imageEdgeInsets = insets! } if selector != nil { self.addTarget(nil, action: selector!, for: .touchUpInside) } if superView != nil { superView!.addSubview(self) } } // MARK: - Properties func setProperties(text: String, size: CGFloat, color: UIColor?) { self.setTitle(text, for: .normal) self.titleLabel!.font = UIFont(name: self.titleLabel!.font.fontName, size: size) color != nil ? self.setTitleColor(color, for: .normal) : () } func setAction(action: Selector, tag: Int?) { self.addTarget(nil, action: action, for: .touchUpInside) if tag != nil { self.tag = tag! } } }
a869075b1bd68c94bfdb8fc83c62e6d3
31.371681
89
0.5924
false
false
false
false
KrishMunot/swift
refs/heads/master
test/IDE/comment_brief.swift
apache-2.0
8
// RUN: %target-swift-ide-test -print-comments -source-filename %s | FileCheck %s // REQUIRES: no_asan /// func briefLine1() {} /// Aaa. func briefLine2() {} /// Aaa. /// Bbb. func briefLine3() {} /// Aaa. /// /// Bbb. func briefLine4() {} /***/ func briefBlock1() {} /** */ func briefBlock2() {} /** Aaa. */ func briefBlock3() {} /** Aaa. */ func briefBlock4() {} /** Aaa. Bbb. */ func briefBlock5() {} /** Aaa. Bbb. */ func briefBlock6() {} /** Aaa. * Bbb. */ func briefBlock7() {} /** Aaa. * Bbb. * Ccc. */ func briefBlock8() {} /** Aaa. * Bbb. Ccc. */ func briefBlock9() {} /** * Aaa. */ func briefBlockWithASCIIArt1() {} /** * */ func briefBlockWithASCIIArt2() {} /** * Aaa. * Bbb. */ func briefBlockWithASCIIArt3() {} /** *Aaa. */ func briefBlockWithASCIIArt4() {} /** * Aaa. Bbb. *Ccc. */ func briefBlockWithASCIIArt5() {} /** * Aaa. * Bbb. */ func briefBlockWithASCIIArt6() {} /// Aaa. /** Bbb. */ func briefMixed1() {} /// Aaa. /** Bbb. */ func briefMixed2() {} /** Aaa. */ /** Bbb. */ func briefMixed3() {} struct Indentation { /** * Aaa. */ func briefBlockWithASCIIArt1() {} } // CHECK: Func/briefLine1 {{.*}} BriefComment=none // CHECK-NEXT: Func/briefLine2 {{.*}} BriefComment=[Aaa.] // CHECK-NEXT: Func/briefLine3 {{.*}} BriefComment=[Aaa. Bbb.] // CHECK-NEXT: Func/briefLine4 {{.*}} BriefComment=[Aaa.] // CHECK-NEXT: Func/briefBlock1 {{.*}} BriefComment=none // CHECK-NEXT: Func/briefBlock2 {{.*}} BriefComment=none // CHECK-NEXT: Func/briefBlock3 {{.*}} BriefComment=[Aaa.] // CHECK-NEXT: Func/briefBlock4 {{.*}} BriefComment=[Aaa.] // CHECK-NEXT: Func/briefBlock5 {{.*}} BriefComment=[Aaa. Bbb.] // CHECK-NEXT: Func/briefBlock6 {{.*}} BriefComment=[Aaa.] // CHECK-NEXT: Func/briefBlock7 {{.*}} BriefComment=[Aaa.] // CHECK-NEXT: Func/briefBlock8 {{.*}} BriefComment=[Aaa.] // CHECK-NEXT: Func/briefBlock9 {{.*}} BriefComment=[Aaa.] // CHECK-NEXT: Func/briefBlockWithASCIIArt1 {{.*}} BriefComment=[Aaa.] // CHECK-NEXT: Func/briefBlockWithASCIIArt2 {{.*}} BriefComment=none // CHECK-NEXT: Func/briefBlockWithASCIIArt3 {{.*}} BriefComment=[Aaa. Bbb.] // CHECK-NEXT: Func/briefBlockWithASCIIArt4 {{.*}} BriefComment=[*Aaa.] // CHECK-NEXT: Func/briefBlockWithASCIIArt5 {{.*}} BriefComment=[Aaa. Bbb. *Ccc.] // CHECK-NEXT: Func/briefBlockWithASCIIArt6 {{.*}} BriefComment=[Aaa.] // CHECK-NEXT: Func/briefMixed1 {{.*}} BriefComment=[Aaa. Bbb.] // CHECK-NEXT: Func/briefMixed2 {{.*}} BriefComment=[Aaa.] // CHECK-NEXT: Func/briefMixed3 {{.*}} BriefComment=[Aaa.] // CHECK-NEXT: Struct/Indentation RawComment=none // CHECK-NEXT: Func/Indentation.briefBlockWithASCIIArt1 {{.*}} BriefComment=[Aaa.]
78b162f876ddee15d85adbc2aea23c81
16.697368
82
0.619331
false
false
false
false
mperovic/my41
refs/heads/master
MODsView.swift
bsd-3-clause
1
// // MODsView.swift // my41 // // Created by Miroslav Perovic on 30.1.21.. // Copyright © 2021 iPera. All rights reserved. // import SwiftUI struct MODsView: View { var port: HPPort { didSet { filePath = port.getFilePath() } } var filePath: String? @ObservedObject var settingsState: SettingsState var onPress: (HPPort) -> () = {_ in } // @ViewBuilder var body: some View { GeometryReader { geometry in if getModule() == nil { Button(action: { onPress(port) }, label: { Image(systemName: "pencil") .font(.system(size: 32)) }) .frame(width: geometry.size.width, height: geometry.size.height) .clipShape(RoundedRectangle(cornerRadius: 5.0, style: .continuous)) .foregroundColor(.white) } else { VStack { Spacer() MODDetailsView(module: getModule()!, short: true) .padding([.leading, .trailing], 5) Spacer() HStack { Spacer() Button(action: { switch port { case .port1: settingsState.module1 = nil case .port2: settingsState.module2 = nil case .port3: settingsState.module3 = nil case .port4: settingsState.module4 = nil } }, label: { Image(systemName: "trash") .font(.system(size: 26)) .foregroundColor(.white) }) .padding(.trailing, 10) .padding(.bottom, 5) } } .frame(width: geometry.size.width, height: geometry.size.height) } } } func onPress(_ callback: @escaping (HPPort) -> ()) -> some View { MODsView(port: port, settingsState: settingsState, onPress: callback) } func getModule() -> MOD? { switch port { case .port1: return settingsState.module1 case .port2: return settingsState.module2 case .port3: return settingsState.module3 case .port4: return settingsState.module4 } } } struct MODsView_Previews: PreviewProvider { static var previews: some View { MODsView(port: .port1, settingsState: SettingsState()) } }
5f0aed14cc00fedfe89fbf972d71c713
20.956522
71
0.616337
false
false
false
false
naokits/my-programming-marathon
refs/heads/master
Bluemix/StrongLoopDemo/StrongLoopClientDemo/StrongLoopClientDemo/DetailViewController.swift
mit
1
// // DetailViewController.swift // StrongLoopClientDemo // // Created by Naoki Tsutsui on 5/12/16. // Copyright © 2016 Naoki Tsutsui. All rights reserved. // import UIKit //import Result class DetailViewController: UIViewController { @IBOutlet weak var detailDescriptionLabel: UILabel! var detailItem: Int = 0 { didSet { // Update the view. self.configureView() } } func configureView() { // Update the user interface for the detail item. } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() switch self.detailItem { case 0: self.detailDescriptionLabel.text = "ユーザ登録" self.signup() case 1: self.detailDescriptionLabel.text = "ログイン" self.login() case 2: self.detailDescriptionLabel.text = "ログアウト" self.logout() case 3: self.detailDescriptionLabel.text = "ユーザ情報取得" self.fetchUsers() case 4: self.detailDescriptionLabel.text = "プロフィール情報取得" self.fetchUser() default: self.detailDescriptionLabel.text = "その他" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Functions func signup() { APIClient.createUser(email: "[email protected]", password: "hogehoge") { (user, error) in if let e = error { print("ユーザ登録エラー: \(e)") return } print("ユーザ登録結果: \(user)") } } func login() { debugPrint("ログインを開始します。") APIClient.login(email: "[email protected]", password: "hogehoge") { (result, error) in if let e = error { print("ログインエラー: \(e)") return } print("ログイン結果: \(result)") } } func logout() { // print("読み込み結果: \(APIClient.loadCurrentUser())") APIClient.logout { (result) in switch result { case .Success(let value): print(value) case .Failure(DemoAPIClientError.NotLogined(let errorMessage)): print(errorMessage) case .Failure(DemoAPIClientError.NotFoundToken(let errorMessage)): print(errorMessage) case .Failure(DemoAPIClientError.AlamoFireError(let error)): print(error) default: print("対象がない") } } // APIClient.logout { (error) in // if let e = error { // print("ログアウト失敗: \(e)") // return // } // print("ログアウト成功") // } } func fetchUser() { APIClient.fetchUserWithUserID("1") { (user, error) in if let e = error { print("ユーザ情報取得エラー: \(e)") return } print("ユーザ情報取得結果: \(user)") } } func fetchUserProfile() { APIClient.fetchUserProfileWithUserID("1") { (profile, error) in if let e = error { print("プロフィール取得エラー: \(e)") return } print("プロフィール情報取得結果: \(profile)") } } // MARK: - Alamofire版 func fetchUsers() { APIClient.fetchUsersRequest() } }
b734aae16106921557f78416c1020dc2
24.942029
92
0.506704
false
false
false
false
grafiti-io/SwiftCharts
refs/heads/master
SwiftCharts/Layers/ChartDividersLayer.swift
apache-2.0
1
// // ChartDividersLayer.swift // SwiftCharts // // Created by ischuetz on 21/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public struct ChartDividersLayerSettings { let linesColor: UIColor let linesWidth: CGFloat let start: CGFloat // points from start to axis, axis is 0 let end: CGFloat // points from axis to end, axis is 0 public init(linesColor: UIColor = UIColor.gray, linesWidth: CGFloat = 0.3, start: CGFloat = 5, end: CGFloat = 5) { self.linesColor = linesColor self.linesWidth = linesWidth self.start = start self.end = end } } public enum ChartDividersLayerAxis { case x, y, xAndY } open class ChartDividersLayer: ChartCoordsSpaceLayer { fileprivate let settings: ChartDividersLayerSettings let axis: ChartDividersLayerAxis fileprivate let xAxisLayer: ChartAxisLayer fileprivate let yAxisLayer: ChartAxisLayer public init(xAxisLayer: ChartAxisLayer, yAxisLayer: ChartAxisLayer, axis: ChartDividersLayerAxis = .xAndY, settings: ChartDividersLayerSettings) { self.axis = axis self.settings = settings self.xAxisLayer = xAxisLayer self.yAxisLayer = yAxisLayer super.init(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis) } fileprivate func drawLine(context: CGContext, color: UIColor, width: CGFloat, p1: CGPoint, p2: CGPoint) { ChartDrawLine(context: context, p1: p1, p2: p2, width: width, color: color) } override open func chartViewDrawing(context: CGContext, chart: Chart) { let xScreenLocs = xAxisLayer.axisValuesScreenLocs let yScreenLocs = yAxisLayer.axisValuesScreenLocs if axis == .x || axis == .xAndY { for xScreenLoc in xScreenLocs { let x1 = xScreenLoc let y1 = xAxisLayer.lineP1.y + (xAxisLayer.low ? -settings.end : settings.end) let x2 = xScreenLoc let y2 = xAxisLayer.lineP1.y + (xAxisLayer.low ? settings.start : -settings.start) drawLine(context: context, color: settings.linesColor, width: settings.linesWidth, p1: CGPoint(x: x1, y: y1), p2: CGPoint(x: x2, y: y2)) } } if axis == .y || axis == .xAndY { for yScreenLoc in yScreenLocs { let x1 = yAxisLayer.lineP1.x + (yAxisLayer.low ? -settings.start : settings.start) let y1 = yScreenLoc let x2 = yAxisLayer.lineP1.x + (yAxisLayer.low ? settings.end : settings.end) let y2 = yScreenLoc drawLine(context: context, color: settings.linesColor, width: settings.linesWidth, p1: CGPoint(x: x1, y: y1), p2: CGPoint(x: x2, y: y2)) } } } }
f05219f7fca6ffbd0b38ba77ca398a52
36
152
0.631935
false
false
false
false
Johennes/firefox-ios
refs/heads/master
Client/Frontend/Browser/URLBarView.swift
mpl-2.0
1
/* 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 import XCGLogger private let log = Logger.browserLogger 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 // A larger offset is needed when viewing URL bar in overlay mode to get the corners right static let URLBarCurveOverlayOffset: CGFloat = 8 static let URLBarMinimumOffsetToAnimate: CGFloat = 30 // buffer so we dont see edges when animation overshoots with spring static let URLBarCurveBounceBuffer: CGFloat = 8 static let ProgressTintColor = UIColor(red:1, green:0.32, blue:0, alpha:1) 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 let Themes: [String: Theme] = { var themes = [String: Theme]() var theme = Theme() theme.borderColor = UIConstants.PrivateModeLocationBorderColor theme.activeBorderColor = UIConstants.PrivateModePurple theme.tintColor = UIConstants.PrivateModePurple theme.textColor = UIColor.whiteColor() theme.buttonTintColor = UIConstants.PrivateModeActionButtonTintColor themes[Theme.PrivateMode] = theme theme = Theme() theme.borderColor = TextFieldBorderColor theme.activeBorderColor = TextFieldActiveBorderColor theme.tintColor = ProgressTintColor theme.textColor = UIColor.blackColor() theme.buttonTintColor = UIColor.darkGrayColor() themes[Theme.NormalMode] = theme return themes }() 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) func urlBarDisplayTextForURL(url: NSURL?) -> String? } class URLBarView: UIView { // Additional UIAppearance-configurable properties dynamic var locationBorderColor: UIColor = URLBarViewUX.TextFieldBorderColor { didSet { if !inOverlayMode { locationContainer.layer.borderColor = locationBorderColor.CGColor } } } dynamic var locationActiveBorderColor: UIColor = URLBarViewUX.TextFieldActiveBorderColor { didSet { if inOverlayMode { locationContainer.layer.borderColor = locationActiveBorderColor.CGColor } } } weak var delegate: URLBarDelegate? weak var tabToolbarDelegate: TabToolbarDelegate? var helper: TabToolbarHelper? 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 } } } private var currentTheme: String = Theme.NormalMode var toolbarIsShowing = false var topTabsIsShowing = false { didSet { curveShape.hidden = topTabsIsShowing } } private var locationTextField: ToolbarTextField? /// 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: TabLocationView = { let locationView = TabLocationView() locationView.translatesAutoresizingMaskIntoConstraints = false locationView.readerModeState = ReaderModeState.Unavailable locationView.delegate = self return locationView }() 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 = self.locationBorderColor.CGColor locationContainer.layer.cornerRadius = URLBarViewUX.TextFieldCornerRadius locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidth return locationContainer }() private lazy var tabsButton: TabsButton = { let tabsButton = TabsButton.tabTrayButton() tabsButton.addTarget(self, action: #selector(URLBarView.SELdidClickAddTab), forControlEvents: UIControlEvents.TouchUpInside) tabsButton.accessibilityIdentifier = "URLBarView.tabsButton" return tabsButton }() private lazy var progressBar: UIProgressView = { let progressBar = UIProgressView() progressBar.progressTintColor = URLBarViewUX.ProgressTintColor 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: "Label for Cancel button") cancelButton.setTitle(cancelTitle, forState: UIControlState.Normal) cancelButton.titleLabel?.font = UIConstants.DefaultChromeFont cancelButton.addTarget(self, action: #selector(URLBarView.SELdidClickCancel), forControlEvents: UIControlEvents.TouchUpInside) cancelButton.titleEdgeInsets = UIEdgeInsetsMake(10, 12, 10, 12) cancelButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal) cancelButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal) cancelButton.alpha = 0 return cancelButton }() private lazy var curveShape: CurveView = { return CurveView() }() private lazy var scrollToTopButton: UIButton = { let button = UIButton() button.addTarget(self, action: #selector(URLBarView.SELtappedScrollToTopArea), forControlEvents: UIControlEvents.TouchUpInside) return button }() lazy var shareButton: UIButton = { return UIButton() }() lazy var menuButton: 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 homePageButton: UIButton = { return UIButton() }() lazy var actionButtons: [UIButton] = { return [self.shareButton, self.menuButton, self.forwardButton, self.backButton, self.stopReloadButton, self.homePageButton] }() 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(menuButton) addSubview(homePageButton) addSubview(forwardButton) addSubview(backButton) addSubview(stopReloadButton) locationContainer.addSubview(locationView) addSubview(locationContainer) helper = TabToolbarHelper(toolbar: self) setupConstraints() // Make sure we hide any views that shouldn't be showing in non-overlay mode. updateViewsForOverlayModeAndToolbarChanges() } 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.snp_makeConstraints { make in make.centerY.equalTo(self.locationContainer) make.trailing.equalTo(self) make.size.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) } 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.menuButton.snp_left) make.centerY.equalTo(self) make.size.equalTo(backButton) } homePageButton.snp_makeConstraints { make in make.center.equalTo(shareButton) make.size.equalTo(shareButton) } menuButton.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 { if (topTabsIsShowing) { tabsButton.snp_remakeConstraints { make in make.centerY.equalTo(self.locationContainer) make.leading.equalTo(self.snp_trailing) make.size.equalTo(UIConstants.ToolbarHeight) } } else { tabsButton.snp_remakeConstraints { make in make.centerY.equalTo(self.locationContainer) make.trailing.equalTo(self) make.size.equalTo(UIConstants.ToolbarHeight) } } 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) } } } func createLocationTextField() { guard locationTextField == nil else { return } locationTextField = ToolbarTextField() guard let locationTextField = locationTextField else { return } 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.font = UIConstants.DefaultChromeFont 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 locationContainer.addSubview(locationTextField) locationTextField.snp_makeConstraints { make in make.edges.equalTo(self.locationView.urlTextField) } locationTextField.applyTheme(currentTheme) } func removeLocationTextField() { locationTextField?.removeFromSuperview() locationTextField = nil } // 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, animated: Bool = true) { self.tabsButton.updateTabCount(count, animated: animated) } func updateProgressBar(progress: Float) { if progress == 1.0 { self.progressBar.setProgress(progress, animated: !isTransitioning) UIView.animateWithDuration(1.5, animations: { self.progressBar.alpha = 0.0 }) } 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) { createLocationTextField() // 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.menuButton.hidden = !self.toolbarIsShowing self.forwardButton.hidden = !self.toolbarIsShowing self.backButton.hidden = !self.toolbarIsShowing self.stopReloadButton.hidden = !self.toolbarIsShowing self.homePageButton.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.menuButton.alpha = inOverlayMode ? 0 : 1 self.forwardButton.alpha = inOverlayMode ? 0 : 1 self.backButton.alpha = inOverlayMode ? 0 : 1 self.stopReloadButton.alpha = inOverlayMode ? 0 : 1 self.homePageButton.alpha = inOverlayMode ? 0 : 1 let borderColor = inOverlayMode ? locationActiveBorderColor : locationBorderColor 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.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.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.menuButton.hidden = !self.toolbarIsShowing || inOverlayMode self.forwardButton.hidden = !self.toolbarIsShowing || inOverlayMode self.backButton.hidden = !self.toolbarIsShowing || inOverlayMode self.stopReloadButton.hidden = !self.toolbarIsShowing || inOverlayMode self.tabsButton.hidden = self.topTabsIsShowing } func animateToOverlayState(overlayMode overlay: Bool, didCancel cancel: Bool = false) { prepareOverlayAnimation() layoutIfNeeded() inOverlayMode = overlay if !overlay { removeLocationTextField() } 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: TabToolbarProtocol { 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) { helper?.updateReloadStatus(isLoading) 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) { stopReloadButton.enabled = isWebPage shareButton.enabled = isWebPage } override var accessibilityElements: [AnyObject]? { get { if inOverlayMode { guard let locationTextField = locationTextField else { return nil } return [locationTextField, cancelButton] } else { if toolbarIsShowing { return [backButton, forwardButton, stopReloadButton, locationView, shareButton, menuButton, tabsButton, progressBar] } else { return [locationView, tabsButton, progressBar] } } } set { super.accessibilityElements = newValue } } } extension URLBarView: TabLocationViewDelegate { func tabLocationViewDidLongPressReaderMode(tabLocationView: TabLocationView) -> Bool { return delegate?.urlBarDidLongPressReaderMode(self) ?? false } func tabLocationViewDidTapLocation(tabLocationView: TabLocationView) { var locationText = delegate?.urlBarDisplayTextForURL(locationView.url) if let host = locationView.url?.host { locationText = locationView.url?.absoluteString?.stringByReplacingOccurrencesOfString(host, withString: host.asciiHostToUTF8()) } enterOverlayMode(locationText, pasted: false) } func tabLocationViewDidLongPressLocation(tabLocationView: TabLocationView) { delegate?.urlBarDidLongPressLocation(self) } func tabLocationViewDidTapReload(tabLocationView: TabLocationView) { delegate?.urlBarDidPressReload(self) } func tabLocationViewDidTapStop(tabLocationView: TabLocationView) { delegate?.urlBarDidPressStop(self) } func tabLocationViewDidTapReaderMode(tabLocationView: TabLocationView) { delegate?.urlBarDidPressReaderMode(self) } func tabLocationViewLocationAccessibilityActions(tabLocationView: TabLocationView) -> [UIAccessibilityCustomAction]? { return delegate?.urlBarLocationAccessibilityActions(self) } } extension URLBarView: AutocompleteTextFieldDelegate { func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool { guard let text = locationTextField?.text else { return true } if !text.stringByTrimmingCharactersInSet(.whitespaceCharacterSet()).isEmpty { delegate?.urlBar(self, didSubmitText: text) return true } else { return false } } 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 } } // MARK: UIAppearance extension URLBarView { dynamic var progressBarTint: UIColor? { get { return progressBar.progressTintColor } set { progressBar.progressTintColor = newValue } } dynamic var cancelTextColor: UIColor? { get { return cancelButton.titleColorForState(UIControlState.Normal) } set { return cancelButton.setTitleColor(newValue, forState: UIControlState.Normal) } } dynamic var actionButtonTintColor: UIColor? { get { return helper?.buttonTintColor } set { guard let value = newValue else { return } helper?.buttonTintColor = value } } } extension URLBarView: Themeable { func applyTheme(themeName: String) { locationView.applyTheme(themeName) locationTextField?.applyTheme(themeName) guard let theme = URLBarViewUX.Themes[themeName] else { log.error("Unable to apply unknown theme \(themeName)") return } currentTheme = themeName locationBorderColor = theme.borderColor! locationActiveBorderColor = theme.activeBorderColor! progressBarTint = theme.tintColor cancelTextColor = theme.textColor actionButtonTintColor = theme.buttonTintColor tabsButton.applyTheme(themeName) } } extension URLBarView: AppStateDelegate { func appDidUpdateState(appState: AppState) { if toolbarIsShowing { let showShareButton = HomePageAccessors.isButtonInMenu(appState) homePageButton.hidden = showShareButton shareButton.hidden = !showShareButton || inOverlayMode homePageButton.enabled = HomePageAccessors.isButtonEnabled(appState) } else { homePageButton.hidden = true shareButton.hidden = 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) { guard let context = UIGraphicsGetCurrentContext() else { return } CGContextSaveGState(context) CGContextClearRect(context, rect) CGContextSetFillColorWithColor(context, URLBarViewUX.backgroundColorWithAlpha(1).CGColor) getPath().fill() leftCurvePath.fill() CGContextDrawPath(context, CGPathDrawingMode.Fill) CGContextRestoreGState(context) } } class ToolbarTextField: AutocompleteTextField { static let Themes: [String: Theme] = { var themes = [String: Theme]() var theme = Theme() theme.backgroundColor = UIConstants.PrivateModeLocationBackgroundColor theme.textColor = UIColor.whiteColor() theme.buttonTintColor = UIColor.whiteColor() theme.highlightColor = UIConstants.PrivateModeInputHighlightColor themes[Theme.PrivateMode] = theme theme = Theme() theme.backgroundColor = UIColor.whiteColor() theme.textColor = UIColor.blackColor() theme.highlightColor = AutocompleteTextFieldUX.HighlightColor themes[Theme.NormalMode] = theme return themes }() dynamic var clearButtonTintColor: UIColor? { didSet { // Clear previous tinted image that's cache and ask for a relayout tintedClearImage = nil setNeedsLayout() } } private var tintedClearImage: UIImage? override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() // Since we're unable to change the tint color of the clear image, we need to iterate through the // subviews, find the clear button, and tint it ourselves. Thanks to Mikael Hellman for the tip: // http://stackoverflow.com/questions/27944781/how-to-change-the-tint-color-of-the-clear-button-on-a-uitextfield for view in subviews as [UIView] { if let button = view as? UIButton { if let image = button.imageForState(.Normal) { if tintedClearImage == nil { tintedClearImage = tintImage(image, color: clearButtonTintColor) } if button.imageView?.image != tintedClearImage { button.setImage(tintedClearImage, forState: .Normal) } } } } } private func tintImage(image: UIImage, color: UIColor?) -> UIImage { guard let color = color else { return image } let size = image.size UIGraphicsBeginImageContextWithOptions(size, false, 2) let context = UIGraphicsGetCurrentContext()! image.drawAtPoint(CGPointZero, blendMode: CGBlendMode.Normal, alpha: 1.0) CGContextSetFillColorWithColor(context, color.CGColor) CGContextSetBlendMode(context, CGBlendMode.SourceIn) CGContextSetAlpha(context, 1.0) let rect = CGRectMake( CGPointZero.x, CGPointZero.y, image.size.width, image.size.height) CGContextFillRect(context, rect) let tintedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return tintedImage } } extension ToolbarTextField: Themeable { func applyTheme(themeName: String) { guard let theme = ToolbarTextField.Themes[themeName] else { log.error("Unable to apply unknown theme \(themeName)") return } backgroundColor = theme.backgroundColor textColor = theme.textColor clearButtonTintColor = theme.buttonTintColor highlightColor = theme.highlightColor! } }
7b31b16b94f5c524633e9ee27c8c46d6
37.460526
198
0.670744
false
false
false
false
WhisperSystems/Signal-iOS
refs/heads/master
Signal/src/ViewControllers/Registration/Onboarding2FAViewController.swift
gpl-3.0
1
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import UIKit @objc public class Onboarding2FAViewController: OnboardingBaseViewController { // When the users attempts remaining falls below this number, // we will show an alert with more detail about the risks. private let attemptsAlertThreshold = 4 private let pinTextField = UITextField() private lazy var pinStrokeNormal = pinTextField.addBottomStroke() private lazy var pinStrokeError = pinTextField.addBottomStroke(color: .ows_destructiveRed, strokeWidth: 2) private let validationWarningLabel = UILabel() enum PinAttemptState { case unattempted case invalid(remainingAttempts: UInt32?) case exhausted case valid var isInvalid: Bool { switch self { case .unattempted, .valid: return false case .invalid, .exhausted: return true } } } private var attemptState: PinAttemptState = .unattempted { didSet { updateValidationWarnings() } } override public func loadView() { super.loadView() view.backgroundColor = Theme.backgroundColor view.layoutMargins = .zero let titleText: String let explanationText: String if (FeatureFlags.pinsForEveryone) { titleText = NSLocalizedString("ONBOARDING_PIN_TITLE", comment: "Title of the 'onboarding PIN' view.") explanationText = NSLocalizedString("ONBOARDING_PIN_EXPLANATION", comment: "Title of the 'onboarding PIN' view.") } else { titleText = NSLocalizedString("ONBOARDING_2FA_TITLE", comment: "Title of the 'onboarding 2FA' view.") let explanationText1 = NSLocalizedString("ONBOARDING_2FA_EXPLANATION_1", comment: "The first explanation in the 'onboarding 2FA' view.") let explanationText2 = NSLocalizedString("ONBOARDING_2FA_EXPLANATION_2", comment: "The first explanation in the 'onboarding 2FA' view.") explanationText = explanationText1 + "\n\n" + explanationText2 } let titleLabel = self.titleLabel(text: titleText) let explanationLabel = self.explanationLabel(explanationText: explanationText) explanationLabel.font = UIFont.ows_dynamicTypeSubheadlineClamped explanationLabel.accessibilityIdentifier = "onboarding.2fa." + "explanationLabel" pinTextField.delegate = self pinTextField.isSecureTextEntry = true pinTextField.keyboardType = .numberPad pinTextField.textColor = Theme.primaryColor pinTextField.font = .ows_dynamicTypeBodyClamped pinTextField.isSecureTextEntry = true pinTextField.defaultTextAttributes.updateValue(5, forKey: .kern) pinTextField.keyboardAppearance = Theme.keyboardAppearance pinTextField.setContentHuggingHorizontalLow() pinTextField.setCompressionResistanceHorizontalLow() pinTextField.autoSetDimension(.height, toSize: 40) pinTextField.accessibilityIdentifier = "onboarding.2fa.pinTextField" validationWarningLabel.textColor = .ows_destructiveRed validationWarningLabel.font = UIFont.ows_dynamicTypeCaption1Clamped validationWarningLabel.accessibilityIdentifier = "onboarding.2fa.validationWarningLabel" validationWarningLabel.numberOfLines = 0 validationWarningLabel.setCompressionResistanceHigh() let forgotPinLink = self.linkButton(title: NSLocalizedString("ONBOARDING_2FA_FORGOT_PIN_LINK", comment: "Label for the 'forgot 2FA PIN' link in the 'onboarding 2FA' view."), selector: #selector(forgotPinLinkTapped)) forgotPinLink.accessibilityIdentifier = "onboarding.2fa." + "forgotPinLink" let pinStack = UIStackView(arrangedSubviews: [ pinTextField, UIView.spacer(withHeight: 10), validationWarningLabel, UIView.spacer(withHeight: 10), forgotPinLink ]) pinStack.axis = .vertical pinStack.alignment = .fill let pinStackRow = UIView() pinStackRow.addSubview(pinStack) pinStack.autoHCenterInSuperview() pinStack.autoPinHeightToSuperview() pinStack.autoSetDimension(.width, toSize: 227) pinStackRow.setContentHuggingVerticalHigh() let nextButton = self.button(title: NSLocalizedString("BUTTON_NEXT", comment: "Label for the 'next' button."), selector: #selector(nextPressed)) nextButton.accessibilityIdentifier = "onboarding.2fa." + "nextButton" let topSpacer = UIView.vStretchingSpacer() let bottomSpacer = UIView.vStretchingSpacer() let stackView = UIStackView(arrangedSubviews: [ titleLabel, UIView.spacer(withHeight: 10), explanationLabel, topSpacer, pinStackRow, bottomSpacer, nextButton ]) stackView.axis = .vertical stackView.alignment = .fill stackView.layoutMargins = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16) stackView.isLayoutMarginsRelativeArrangement = true view.addSubview(stackView) stackView.autoPinWidthToSuperview() stackView.autoPin(toTopLayoutGuideOf: self, withInset: 0) autoPinView(toBottomOfViewControllerOrKeyboard: stackView, avoidNotch: true) // Ensure whitespace is balanced, so inputs are vertically centered. topSpacer.autoMatch(.height, to: .height, of: bottomSpacer) updateValidationWarnings() } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) _ = pinTextField.becomeFirstResponder() } // MARK: - Events @objc func forgotPinLinkTapped() { Logger.info("") OWSAlerts.showAlert( title: NSLocalizedString("REGISTER_2FA_FORGOT_PIN_ALERT_TITLE", comment: "Alert title explaining what happens if you forget your 'two-factor auth pin'."), message: NSLocalizedString("REGISTER_2FA_FORGOT_PIN_ALERT_MESSAGE", comment: "Alert message explaining what happens if you forget your 'two-factor auth pin'.") ) } @objc func nextPressed() { Logger.info("") tryToVerify() } private func tryToVerify(testTruncatedPin: Bool = false) { Logger.info("") var pinToUse = pinTextField.text // If true, we're doing a fallback verification to test if this is a // legacy pin that was created with >16 characters and then truncated. if testTruncatedPin { assert((pinToUse?.count ?? 0) > kLegacyTruncated2FAv1PinLength) pinToUse = pinToUse?.substring(to: Int(kLegacyTruncated2FAv1PinLength)) } guard let pin = pinToUse?.ows_stripped(), pin.count >= kMin2FAPinLength else { // Check if we're already in an invalid state, if so we can do nothing guard !attemptState.isInvalid else { return } attemptState = .invalid(remainingAttempts: nil) return } // v1 pins also have a max length, but we'll rely on the server to verify that // since we do not know if this is a v1 or a v2 pin at registration time. onboardingController.update(twoFAPin: pin) onboardingController.submitVerification(fromViewController: self, completion: { (outcome) in switch outcome { case .invalid2FAPin: // In the past, we used to truncate pins. To support legacy users, // also attempt the truncated version of the pin if the original // did not match. This error only occurs for v1 registration locks, // the variant that includes remaining attempts is used for v2 locks // which should not have this problem. guard pin.count <= kLegacyTruncated2FAv1PinLength || testTruncatedPin else { return self.tryToVerify(testTruncatedPin: true) } self.attemptState = .invalid(remainingAttempts: nil) case .invalidV2RegistrationLockPin(let remainingAttempts): self.attemptState = .invalid(remainingAttempts: remainingAttempts) case .exhaustedV2RegistrationLockAttempts: self.attemptState = .exhausted self.showAccountLocked() case .success: self.attemptState = .valid case .invalidVerificationCode: owsFailDebug("Invalid verification code in 2FA view.") } }) } private func showAccountLocked() { guard let navigationController = navigationController else { owsFailDebug("Missing navigationController") return } let vc = OnboardingAccountLockedViewController(onboardingController: onboardingController) navigationController.pushViewController(vc, animated: true) } private func updateValidationWarnings() { AssertIsOnMainThread() pinStrokeNormal.isHidden = attemptState.isInvalid pinStrokeError.isHidden = !attemptState.isInvalid validationWarningLabel.isHidden = !attemptState.isInvalid switch attemptState { case .exhausted: validationWarningLabel.text = NSLocalizedString("ONBOARDING_2FA_ATTEMPTS_EXHAUSTED", comment: "Label indicating that the 2fa pin is exhausted in the 'onboarding 2fa' view.") case .invalid(let remainingAttempts): guard let remaining = remainingAttempts else { validationWarningLabel.text = NSLocalizedString("ONBOARDING_2FA_INVALID_PIN", comment: "Label indicating that the 2fa pin is invalid in the 'onboarding 2fa' view.") break } // If there are less than the threshold attempts remaining, also show an alert with more detail. if remaining < attemptsAlertThreshold { let formatMessage: String if remaining == 1 { formatMessage = NSLocalizedString("REGISTER_2FA_INVALID_PIN_ALERT_MESSAGE_SINGLE", comment: "Alert message explaining what happens if you get your pin wrong and have one attempt remaining 'two-factor auth pin'.") } else { formatMessage = NSLocalizedString("REGISTER_2FA_INVALID_PIN_ALERT_MESSAGE_PLURAL_FORMAT", comment: "Alert message explaining what happens if you get your pin wrong and have multiple attempts remaining 'two-factor auth pin'.") } OWSAlerts.showAlert( title: NSLocalizedString("REGISTER_2FA_INVALID_PIN_ALERT_TITLE", comment: "Alert title explaining what happens if you forget your 'two-factor auth pin'."), message: String(format: formatMessage, remaining) ) } let formatMessage: String if remaining == 1 { formatMessage = NSLocalizedString("ONBOARDING_2FA_INVALID_PIN_SINGLE", comment: "Label indicating that the 2fa pin is invalid with a retry count of one in the 'onboarding 2fa' view.") } else { formatMessage = NSLocalizedString("ONBOARDING_2FA_INVALID_PIN_PLURAL_FORMAT", comment: "Label indicating that the 2fa pin is invalid with a retry count other than one in the 'onboarding 2fa' view.") } validationWarningLabel.text = String(format: formatMessage, remaining) default: break } } } // MARK: - extension Onboarding2FAViewController: UITextFieldDelegate { public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { ViewControllerUtils.ows2FAPINTextField(textField, shouldChangeCharactersIn: range, replacementString: string) // Reset the attempt state to clear errors, since the user is trying again attemptState = .unattempted return false } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { tryToVerify() return false } }
4c319ff3db084324006ba29432244587
42.911864
189
0.625058
false
false
false
false
JadenGeller/Chemical
refs/heads/master
Sources/Reaction.swift
mit
1
// // Reaction.swift // Chemical // // Created by Jaden Geller on 2/20/16. // Copyright © 2016 Jaden Geller. All rights reserved. // import Handbag import Stochastic import Orderly #if os(Linux) import Glibc #else import Darwin.C #endif public struct Reaction<Molecule: Hashable> { public var reactants: Bag<Molecule> public var products: Bag<Molecule> public var rate: Float public init(reactants: Bag<Molecule>, products: Bag<Molecule>, rate: Float = 1) { self.reactants = reactants self.products = products self.rate = rate } } extension Interaction where Molecule: Hashable { public init(_ reaction: Reaction<Molecule>) { self.init(moleculeCount: reaction.reactants.count) { molecules in guard reaction.reactants == Bag(molecules) else { return nil } return Array(reaction.products) } } } extension Behavior where Molecule: Hashable { public init(_ reactions: [Reaction<Molecule>]) { let sortedReactions = SortedArray(unsorted: reactions, isOrderedBefore: { $0.rate < $1.rate }) let _integratedReactions = sortedReactions.reduce((0, [])) { pair, element in return (pair.0 + element.rate, pair.1 + [Reaction(reactants: element.reactants, products: element.products, rate: element.rate + pair.0)]) } // GROSS^^^ let integratedReactions = SortedArray(unsafeSorted: _integratedReactions.1, isOrderedBefore: { $0.rate < $1.rate }) let integral = _integratedReactions.0 self.init { let value = Float.random(between: 0...integral) let index = integratedReactions.insertionIndexOf(Reaction(reactants: [], products: [], rate: value)) // ^This is gross.. :P return Interaction(sortedReactions[index]) } } public init(_ reactions: Reaction<Molecule>...) { self.init(reactions) } } // MARK: Helpers extension Float { private static func random() -> Float { #if os(Linux) return Float(rand()) / Float(RAND_MAX) #else return Float(arc4random()) / Float(UInt32.max) #endif } private static func random(between between: ClosedInterval<Float>) -> Float { return between.start + (between.end - between.start) * random() } }
8f699701b93238b031ea69afeb698802
29.519481
150
0.634468
false
false
false
false
LYM-mg/MGDS_Swift
refs/heads/master
MGDS_Swift/MGDS_Swift/Class/Music/Controller/MGRankListDetailViewController.swift
mit
1
// // MGRankListDetailViewController.swift // MGDS_Swift // // Created by i-Techsys.com on 17/3/1. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit import MJRefresh class MGRankListDetailViewController: UITableViewController { var songGroup: SongGroup? lazy var dataSource = [SongDetail]() /** 记录右边边TableView是否滚动到的位置的Y坐标 */ fileprivate lazy var lastOffsetY: CGFloat = 0 /** 记录tableView是否向下滚动 */ fileprivate lazy var isScrollDown: Bool = true override func viewDidLoad() { super.viewDidLoad() self.title = "音乐列表" // tableView.estimatedRowHeight = 70 // tableView.rowHeight = UITableView.automaticDimension tableView.rowHeight = 90 setUpMainView() setUpRefresh() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } init(songGroup: SongGroup) { super.init(style: .plain) self.songGroup = songGroup } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func setUpMainView() { let bg = UIImageView(frame: self.view.frame) bg.setImageWithURLString(songGroup?.pic_s444, placeholder: #imageLiteral(resourceName: "mybk1")) let effect = UIBlurEffect(style: .light) let effectView = UIVisualEffectView(effect: effect) effectView.frame = bg.frame bg.addSubview(effectView) self.tableView.backgroundView = bg let headerView = UIView(frame: CGRect(x: 0, y: 0, width: MGScreenW, height: MGScreenW*0.5)) let image = UIImageView(frame: headerView.frame) image.setImageWithURLString(songGroup?.pic_s444, placeholder: #imageLiteral(resourceName: "mybk1")) let nameLable = UILabel(frame: CGRect(x: 20, y: MGScreenW*0.42, width: MGScreenW, height: 25)) nameLable.textColor = UIColor.white nameLable.text = self.songGroup?.name headerView.addSubview(image) headerView.addSubview(nameLable) tableView.tableHeaderView = headerView self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(self.searchClick)) } @objc fileprivate func searchClick() { show(SearchMusicViewController(), sender: nil) } } // MARK: - LoadData extension MGRankListDetailViewController { fileprivate func setUpRefresh() { weak var weakSelf = self // 头部刷新 self.tableView.mj_header = MJRefreshGifHeader(refreshingBlock: { let strongSelf = weakSelf strongSelf?.loadData() }) // 设置自动切换透明度(在导航栏下面自动隐藏) tableView.mj_header?.isAutomaticallyChangeAlpha = true self.tableView.mj_header?.beginRefreshing() } fileprivate func loadData() { let parameters: [String: Any] = ["method":"baidu.ting.billboard.billList","offset":"0","size":"100","type":self.songGroup!.type,"from":"ios","version":"5.5.6","channel":"appstore","operator":"1","format":"json"] NetWorkTools.requestData(type: .get, urlString: "http://tingapi.ting.baidu.com/v1/restserver/ting",parameters: parameters,succeed: { [weak self] (result, err) in // 1.将result转成字典类型 guard let resultDict = result as? [String : Any] else { return } // 2.根据song_list该key,获取数组 guard let dataArray = resultDict["song_list"] as? [[String : Any]] else { return } for mdict in dataArray { self!.dataSource.append(SongDetail(dict: mdict)) } self!.tableView.reloadData() self!.tableView.mj_header?.endRefreshing() }) { (err) in if err != nil { self.showHint(hint: "网络请求错误❌") } self.tableView.mj_header?.endRefreshing() } } } extension MGRankListDetailViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 1.创建cell let cell = SongDetailListCell.cellWithTableView(tabView: tableView) // 2.给cell赋值 cell.model = self.dataSource[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { _ = self.dataSource[indexPath.row] let vc = UIStoryboard(name: "Music", bundle: nil).instantiateInitialViewController() as! MGMusicPlayViewController vc.setSongIdArray(musicArr: dataSource, currentIndex: indexPath.row) show(vc, sender: nil) } // MARK: - 动画 override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if isScrollDown { // startAnimation(view: cell, offsetY: 90, duration: 2.0) let rect = cell.convert((cell.bounds), to: nil) if (rect.origin.y) > MGScreenW*0.5 { cell.transform = CGAffineTransform(translationX: 0, y: 1.5*cell.mg_height) UIView.animate(withDuration: 0.5, delay: 0.1, options: .curveEaseInOut, animations: { cell.transform = CGAffineTransform.identity }, completion: nil) } } } override func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView.contentOffset.y <= scrollView.contentSize.height { isScrollDown = lastOffsetY < scrollView.contentOffset.y lastOffsetY = scrollView.contentOffset.y } } private func startAnimation(view: UIView, offsetY: CGFloat, duration: TimeInterval) { view.transform = CGAffineTransform(translationX: 0, y: offsetY) UIView.animate(withDuration: duration, animations: { () -> Void in view.transform = CGAffineTransform.identity }) } }
6a4cced0187fd3db0b76ed613a6cff01
36.963855
219
0.63456
false
false
false
false
vector-im/vector-ios
refs/heads/master
RiotSwiftUI/Modules/Room/RoomAccess/RoomAccessTypeChooser/Service/Mock/MockRoomAccessTypeChooserService.swift
apache-2.0
1
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import Combine @available(iOS 14.0, *) class MockRoomAccessTypeChooserService: RoomAccessTypeChooserServiceProtocol { static let mockAccessItems: [RoomAccessTypeChooserAccessItem] = [ RoomAccessTypeChooserAccessItem(id: .private, isSelected: true, title: VectorL10n.private, detail: VectorL10n.roomAccessSettingsScreenPrivateMessage, badgeText: nil), RoomAccessTypeChooserAccessItem(id: .restricted, isSelected: false, title: VectorL10n.createRoomTypeRestricted, detail: VectorL10n.roomAccessSettingsScreenRestrictedMessage, badgeText: VectorL10n.roomAccessSettingsScreenUpgradeRequired), RoomAccessTypeChooserAccessItem(id: .public, isSelected: false, title: VectorL10n.public, detail: VectorL10n.roomAccessSettingsScreenPublicMessage, badgeText: nil), ] private(set) var accessItemsSubject: CurrentValueSubject<[RoomAccessTypeChooserAccessItem], Never> private(set) var roomUpgradeRequiredSubject: CurrentValueSubject<Bool, Never> private(set) var waitingMessageSubject: CurrentValueSubject<String?, Never> private(set) var errorSubject: CurrentValueSubject<Error?, Never> private(set) var selectedType: RoomAccessTypeChooserAccessType = .private var currentRoomId: String = "!aaabaa:matrix.org" var versionOverride: String? { return "9" } init(accessItems: [RoomAccessTypeChooserAccessItem] = mockAccessItems) { accessItemsSubject = CurrentValueSubject(accessItems) roomUpgradeRequiredSubject = CurrentValueSubject(false) waitingMessageSubject = CurrentValueSubject(nil) errorSubject = CurrentValueSubject(nil) } func simulateUpdate(accessItems: [RoomAccessTypeChooserAccessItem]) { self.accessItemsSubject.send(accessItems) } func updateSelection(with selectedType: RoomAccessTypeChooserAccessType) { } func updateRoomId(with roomId: String) { currentRoomId = roomId } func applySelection(completion: @escaping () -> Void) { } }
0f1b11c69484966cccd73d348aa252af
41.790323
245
0.753487
false
false
false
false
JGiola/swift
refs/heads/main
test/decl/protocol/conforms/placement.swift
apache-2.0
9
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend %S/Inputs/placement_module_A.swift -emit-module -parse-as-library -o %t // RUN: %target-swift-frontend -I %t %S/Inputs/placement_module_B.swift -emit-module -parse-as-library -o %t // RUN: %target-swift-frontend -typecheck -primary-file %s %S/Inputs/placement_2.swift -I %t -verify // Tests for the placement of conformances as well as conflicts // between conformances that come from different sources. import placement_module_A import placement_module_B protocol P1 { } protocol P2a : P1 { } protocol P3a : P2a { } protocol P2b : P1 { } protocol P3b : P2b { } protocol P4 : P3a, P3b { } protocol AnyObjectRefinement : AnyObject { } // =========================================================================== // Tests within a single source file // =========================================================================== // --------------------------------------------------------------------------- // Multiple explicit conformances to the same protocol // --------------------------------------------------------------------------- struct Explicit1 : P1 { } // expected-note{{'Explicit1' declares conformance to protocol 'P1' here}} extension Explicit1 : P1 { } // expected-error{{redundant conformance of 'Explicit1' to protocol 'P1'}} struct Explicit2 { } extension Explicit2 : P1 { } // expected-note 2{{'Explicit2' declares conformance to protocol 'P1' here}} extension Explicit2 : P1 { } // expected-error{{redundant conformance of 'Explicit2' to protocol 'P1'}} extension Explicit2 : P1 { } // expected-error{{redundant conformance of 'Explicit2' to protocol 'P1'}} // --------------------------------------------------------------------------- // Multiple implicit conformances, with no ambiguities // --------------------------------------------------------------------------- struct MultipleImplicit1 : P2a { } extension MultipleImplicit1 : P3a { } struct MultipleImplicit2 : P4 { } struct MultipleImplicit3 : P4 { } extension MultipleImplicit3 : P1 { } // --------------------------------------------------------------------------- // Multiple implicit conformances, ambiguity resolved because they // land in the same context. // --------------------------------------------------------------------------- struct MultipleImplicit4 : P2a, P2b { } struct MultipleImplicit5 { } extension MultipleImplicit5 : P2a, P2b { } struct MultipleImplicit6 : P4 { } extension MultipleImplicit6 : P3a { } struct MultipleImplicit7 : P2a { } extension MultipleImplicit7 : P2b { } // --------------------------------------------------------------------------- // Multiple implicit conformances, ambiguity resolved via explicit conformance // --------------------------------------------------------------------------- struct ExplicitMultipleImplicit1 : P2a { } extension ExplicitMultipleImplicit1 : P2b { } extension ExplicitMultipleImplicit1 : P1 { } // resolves ambiguity // --------------------------------------------------------------------------- // Implicit conformances superseded by inherited conformances // --------------------------------------------------------------------------- class ImplicitSuper1 : P3a { } class ImplicitSub1 : ImplicitSuper1 { } extension ImplicitSub1 : P4 { } // okay, introduces new conformance to P4; the rest are superseded // --------------------------------------------------------------------------- // Synthesized conformances superseded by implicit conformances // --------------------------------------------------------------------------- enum SuitA { case Spades, Hearts, Clubs, Diamonds } func <(lhs: SuitA, rhs: SuitA) -> Bool { return false } extension SuitA : Comparable {} // okay, implied conformance to Equatable here is preferred. enum SuitB: Equatable { case Spades, Hearts, Clubs, Diamonds } func <(lhs: SuitB, rhs: SuitB) -> Bool { return false } extension SuitB : Comparable {} // okay, explicitly declared earlier. enum SuitC { case Spades, Hearts, Clubs, Diamonds } func <(lhs: SuitC, rhs: SuitC) -> Bool { return false } extension SuitC : Equatable, Comparable {} // okay, explicitly declared here. // --------------------------------------------------------------------------- // Explicit conformances conflicting with inherited conformances // --------------------------------------------------------------------------- class ExplicitSuper1 : P3a { } class ExplicitSub1 : ImplicitSuper1 { } // expected-note{{'ExplicitSub1' inherits conformance to protocol 'P1' from superclass here}} extension ExplicitSub1 : P1 { } // expected-error{{redundant conformance of 'ExplicitSub1' to protocol 'P1'}} // --------------------------------------------------------------------------- // Suppression of synthesized conformances // --------------------------------------------------------------------------- class SynthesizedClass1 : AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} class SynthesizedClass2 { } extension SynthesizedClass2 : AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} class SynthesizedClass3 : AnyObjectRefinement { } class SynthesizedClass4 { } extension SynthesizedClass4 : AnyObjectRefinement { } class SynthesizedSubClass1 : SynthesizedClass1, AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} class SynthesizedSubClass2 : SynthesizedClass2 { } extension SynthesizedSubClass2 : AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} class SynthesizedSubClass3 : SynthesizedClass1, AnyObjectRefinement { } class SynthesizedSubClass4 : SynthesizedClass2 { } extension SynthesizedSubClass4 : AnyObjectRefinement { } enum SynthesizedEnum1 : Int, RawRepresentable { case none = 0 } enum SynthesizedEnum2 : Int { case none = 0 } extension SynthesizedEnum2 : RawRepresentable { } // =========================================================================== // Tests across different source files // =========================================================================== // --------------------------------------------------------------------------- // Multiple explicit conformances to the same protocol // --------------------------------------------------------------------------- struct MFExplicit1 : P1 { } extension MFExplicit2 : P1 { } // expected-error{{redundant conformance of 'MFExplicit2' to protocol 'P1'}} // --------------------------------------------------------------------------- // Multiple implicit conformances, with no ambiguities // --------------------------------------------------------------------------- extension MFMultipleImplicit1 : P3a { } struct MFMultipleImplicit2 : P4 { } extension MFMultipleImplicit3 : P1 { } extension MFMultipleImplicit4 : P3a { } extension MFMultipleImplicit5 : P2b { } // --------------------------------------------------------------------------- // Explicit conformances conflicting with inherited conformances // --------------------------------------------------------------------------- class MFExplicitSuper1 : P3a { } extension MFExplicitSub1 : P1 { } // expected-error{{redundant conformance of 'MFExplicitSub1' to protocol 'P1'}} // --------------------------------------------------------------------------- // Suppression of synthesized conformances // --------------------------------------------------------------------------- class MFSynthesizedClass1 { } extension MFSynthesizedClass2 : AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} class MFSynthesizedClass4 { } extension MFSynthesizedClass4 : AnyObjectRefinement { } extension MFSynthesizedSubClass2 : AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} extension MFSynthesizedSubClass3 : AnyObjectRefinement { } class MFSynthesizedSubClass4 : MFSynthesizedClass2 { } extension MFSynthesizedEnum1 : RawRepresentable { } enum MFSynthesizedEnum2 : Int { case none = 0 } // =========================================================================== // Tests with conformances in imported modules // =========================================================================== extension MMExplicit1 : MMP1 { } // expected-warning{{conformance of 'MMExplicit1' to protocol 'MMP1' was already stated in the type's module 'placement_module_A'}} extension MMExplicit1 : MMP2a { } // expected-warning{{MMExplicit1' to protocol 'MMP2a' was already stated in the type's module 'placement_module_A}} extension MMExplicit1 : MMP3a { } // expected-warning{{conformance of 'MMExplicit1' to protocol 'MMP3a' was already stated in the type's module 'placement_module_A'}} extension MMExplicit1 : MMP3b { } // okay extension MMSuper1 : MMP1 { } // expected-warning{{conformance of 'MMSuper1' to protocol 'MMP1' was already stated in the type's module 'placement_module_A'}} extension MMSuper1 : MMP2a { } // expected-warning{{conformance of 'MMSuper1' to protocol 'MMP2a' was already stated in the type's module 'placement_module_A'}} extension MMSuper1 : MMP3b { } // okay extension MMSub1 : AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} extension MMSub2 : MMP1 { } // expected-warning{{conformance of 'MMSub2' to protocol 'MMP1' was already stated in the type's module 'placement_module_A'}} extension MMSub2 : MMP2a { } // expected-warning{{conformance of 'MMSub2' to protocol 'MMP2a' was already stated in the type's module 'placement_module_A'}} extension MMSub2 : MMP3b { } // okay extension MMSub2 : MMAnyObjectRefinement { } // okay extension MMSub3 : MMP1 { } // expected-warning{{conformance of 'MMSub3' to protocol 'MMP1' was already stated in the type's module 'placement_module_A'}} extension MMSub3 : MMP2a { } // expected-warning{{conformance of 'MMSub3' to protocol 'MMP2a' was already stated in the type's module 'placement_module_A'}} extension MMSub3 : MMP3b { } // okay extension MMSub3 : AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} extension MMSub4 : MMP1 { } // expected-warning{{conformance of 'MMSub4' to protocol 'MMP1' was already stated in the type's module 'placement_module_B'}} extension MMSub4 : MMP2a { } // expected-warning{{conformance of 'MMSub4' to protocol 'MMP2a' was already stated in the type's module 'placement_module_B'}} extension MMSub4 : MMP3b { } // okay extension MMSub4 : AnyObjectRefinement { } // okay
ca11cf1be7ff4c9695d8d154d72c65aa
46.976959
166
0.581692
false
false
false
false
yannickl/FlowingMenu
refs/heads/master
Example/FlowingMenuExample/ViewController.swift
mit
1
// // ViewController.swift // FlowingMenuExample // // Created by Yannick LORIOT on 02/12/15. // Copyright © 2015 Yannick LORIOT. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, FlowingMenuDelegate { @IBOutlet weak var topBar: UINavigationBar! @IBOutlet weak var userTableView: UITableView! @IBOutlet var flowingMenuTransitionManager: FlowingMenuTransitionManager! let PresentSegueName = "PresentMenuSegue" let DismissSegueName = "DismissMenuSegue" let CellName = "UserContactCell" let users = User.dummyUsers() let mainColor = UIColor(hex: 0x804C5F) let derivatedColor = UIColor(hex: 0x794759) var menu: UIViewController? override func viewDidLoad() { super.viewDidLoad() flowingMenuTransitionManager.setInteractivePresentationView(view) flowingMenuTransitionManager.delegate = self topBar.tintColor = .white topBar.barTintColor = mainColor topBar.titleTextAttributes = [ NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-Light", size: 22)!, NSAttributedString.Key.foregroundColor: UIColor.white ] userTableView.backgroundColor = mainColor view.backgroundColor = mainColor } // MARK: - Interacting with Storyboards and Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == PresentSegueName { let vc = segue.destination vc.transitioningDelegate = flowingMenuTransitionManager flowingMenuTransitionManager.setInteractiveDismissView(vc.view) menu = vc } } @IBAction func unwindToMainViewController(_ sender: UIStoryboardSegue) { } // MARK: - Managing the Status Bar override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } // MARK: - FlowingMenu Delegate Methods func colorOfElasticShapeInFlowingMenu(_ flowingMenu: FlowingMenuTransitionManager) -> UIColor? { return mainColor } func flowingMenuNeedsPresentMenu(_ flowingMenu: FlowingMenuTransitionManager) { performSegue(withIdentifier: PresentSegueName, sender: self) } func flowingMenuNeedsDismissMenu(_ flowingMenu: FlowingMenuTransitionManager) { menu?.performSegue(withIdentifier: DismissSegueName, sender: self) } // MARK: - UITableView DataSource Methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return users.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: CellName) as! UserContactCellView let user = users[(indexPath as NSIndexPath).row] cell.displayNameLabel.text = user.displayName() cell.avatarImageView.image = user.avatarImage() cell.contentView.backgroundColor = (indexPath as NSIndexPath).row % 2 == 0 ? derivatedColor : mainColor return cell } }
5b88a696c367a83b31dd5599b7843ea5
29.571429
107
0.732644
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
WMF Framework/Widget/WidgetContentFetcher.swift
mit
1
import Foundation public final class WidgetContentFetcher { // MARK: - Nested Types public enum FetcherError: Error { case urlFailure case contentFailure case unsupportedLanguage } public typealias FeaturedContentResult = Result<WidgetFeaturedContent, WidgetContentFetcher.FetcherError> // MARK: - Properties public static let shared = WidgetContentFetcher() let session = Session(configuration: .current) // From supported language list at https://www.mediawiki.org/wiki/Wikifeeds private let supportedFeaturedArticleLanguageCodes = ["bg", "bn", "bs", "cs", "de", "el", "en", "fa", "he", "hu", "ja", "la", "no", "sco", "sd", "sv", "ur", "vi", "zh"] // MARK: - Public - Featured Article Widget public func fetchFeaturedContent(forDate date: Date, siteURL: URL, languageCode: String, languageVariantCode: String? = nil, completion: @escaping (FeaturedContentResult) -> Void) { guard supportedFeaturedArticleLanguageCodes.contains(languageCode) else { completion(.failure(.unsupportedLanguage)) return } var featuredURL = WMFFeedContentFetcher.feedContentURL(forSiteURL: siteURL, on: date, configuration: .current) featuredURL.wmf_languageVariantCode = languageVariantCode let task = session.dataTask(with: featuredURL) { data, _, error in if let data = data, var decoded = try? JSONDecoder().decode(WidgetFeaturedContent.self, from: data) { decoded.fetchDate = Date() completion(.success(decoded)) } else { completion(.failure(.contentFailure)) } } guard let dataTask = task else { completion(.failure(.urlFailure)) return } dataTask.resume() } public func fetchImageDataFrom(imageSource: WidgetFeaturedContent.FeaturedArticleContent.ImageSource, completion: @escaping (Result<Data, FetcherError>) -> Void) { guard let imageURL = URL(string: imageSource.source) else { completion(.failure(.urlFailure)) return } let task = session.dataTask(with: imageURL) { data, _, error in if let data = data { completion(.success(data)) } else { completion(.failure(.contentFailure)) } } guard let dataTask = task else { completion(.failure(.urlFailure)) return } dataTask.resume() } }
2cb94f9b9d304435522d39b7f742b8c9
28.851351
182
0.717067
false
false
false
false
sambhav7890/RecurrenceRuleUI-iOS
refs/heads/master
RecurrenceRuleUI-iOS/Classes/MonthOrDaySelectorCell.swift
mit
1
// // MonthOrDaySelectorCell.swift // RecurrenceRuleUI // // Created by Sambhav on 16/8/7. // Copyright © 2016 Practo. All rights reserved. // import UIKit internal enum MonthOrDaySelectorStyle { case day case month } internal protocol MonthOrDaySelectorCellDelegate { func monthOrDaySelectorCell(_ cell: MonthOrDaySelectorCell, didSelectMonthday monthday: Int) func monthOrDaySelectorCell(_ cell: MonthOrDaySelectorCell, didDeselectMonthday monthday: Int) func monthOrDaySelectorCell(_ cell: MonthOrDaySelectorCell, shouldDeselectMonthday monthday: Int) -> Bool func monthOrDaySelectorCell(_ cell: MonthOrDaySelectorCell, didSelectMonth month: Int) func monthOrDaySelectorCell(_ cell: MonthOrDaySelectorCell, didDeselectMonth month: Int) func monthOrDaySelectorCell(_ cell: MonthOrDaySelectorCell, shouldDeselectMonth month: Int) -> Bool } internal class MonthOrDaySelectorCell: UITableViewCell { @IBOutlet weak var selectorView: UICollectionView! internal var delegate: MonthOrDaySelectorCellDelegate? internal var style: MonthOrDaySelectorStyle = .day { didSet { setNeedsDisplay() selectorView.reloadData() selectorView.collectionViewLayout = GridSelectorLayout(style: style) } } internal var bymonthday = [Int]() internal var bymonth = [Int]() override func awakeFromNib() { super.awakeFromNib() selectionStyle = .none accessoryType = .none selectorView.clipsToBounds = false let bundle = Bundle.recurrencePickerBundle() ?? Bundle.main selectorView.register(UINib(nibName: "SelectorItemCell", bundle: bundle), forCellWithReuseIdentifier: CellID.SelectorItemCell) } override func layoutSubviews() { super.layoutSubviews() for subview in subviews { if NSStringFromClass(type(of: subview)) == "_UITableViewCellSeparatorView" { subview.removeFromSuperview() } } } override func draw(_ rect: CGRect) { super.draw(rect) drawGridLines() } } extension MonthOrDaySelectorCell { fileprivate func drawGridLines() { func removeAllGridLines() { guard let sublayers = layer.sublayers else { return } for sublayer in sublayers { if sublayer.name == Constant.GridLineName { sublayer.removeFromSuperlayer() } } } let itemSize = GridSelectorLayout.itemSizeWithStyle(style, selectorViewWidth: frame.width) removeAllGridLines() switch style { case .day: // draw vertical lines for index in 1...6 { let xPosition = CGFloat(index) * itemSize.width - Constant.GridLineWidth / 2 let height = index < 4 ? (itemSize.height * CGFloat(5) + Constant.GridLineWidth) : (itemSize.height * CGFloat(4) + Constant.GridLineWidth) let lineFrame = CGRect(x: xPosition, y: Constant.SelectorVerticalPadding - Constant.GridLineWidth / 2, width: Constant.GridLineWidth, height: height) let line = CAShapeLayer() line.name = Constant.GridLineName line.frame = lineFrame line.backgroundColor = Constant.GridLineColor.cgColor layer.addSublayer(line) } // draw horizontal lines for index in 0...5 { let yPosition = Constant.SelectorVerticalPadding + CGFloat(index) * itemSize.height - Constant.GridLineWidth / 2 let width = index < 5 ? frame.width : (itemSize.width * CGFloat(3) + Constant.GridLineWidth / 2) let lineFrame = CGRect(x: 0, y: yPosition, width: width, height: Constant.GridLineWidth) let line = CAShapeLayer() line.name = Constant.GridLineName line.frame = lineFrame line.backgroundColor = Constant.GridLineColor.cgColor layer.addSublayer(line) } case .month: // draw vertical lines for index in 1...3 { let xPosition = CGFloat(index) * itemSize.width - Constant.GridLineWidth / 2 let lineFrame = CGRect(x: xPosition, y: Constant.SelectorVerticalPadding - Constant.GridLineWidth / 2, width: Constant.GridLineWidth, height: (itemSize.height * CGFloat(3) + Constant.GridLineWidth)) let line = CAShapeLayer() line.name = Constant.GridLineName line.frame = lineFrame line.backgroundColor = Constant.GridLineColor.cgColor layer.addSublayer(line) } // draw horizontal lines for index in 0...3 { let yPosition = Constant.SelectorVerticalPadding + CGFloat(index) * itemSize.height - Constant.GridLineWidth / 2 let lineFrame = CGRect(x: 0, y: yPosition, width: frame.width, height: Constant.GridLineWidth) let line = CAShapeLayer() line.name = Constant.GridLineName line.frame = lineFrame line.backgroundColor = Constant.GridLineColor.cgColor layer.addSublayer(line) } } } } extension MonthOrDaySelectorCell: UICollectionViewDataSource, UICollectionViewDelegate { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return style == .day ? 31 : 12 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellID.SelectorItemCell, for: indexPath) as! SelectorItemCell cell.tintColor = tintColor switch style { case .day: cell.textLabel.text = String((indexPath as NSIndexPath).row + 1) cell.setItemSelected(bymonthday.contains((indexPath as NSIndexPath).row + 1)) case .month: cell.textLabel.text = Constant.shortMonthSymbols()[(indexPath as NSIndexPath).row] cell.setItemSelected(bymonth.contains((indexPath as NSIndexPath).row + 1)) } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let cell = collectionView.cellForItem(at: indexPath) as? SelectorItemCell else { return } switch style { case .day: let monthday = (indexPath as NSIndexPath).row + 1 if cell.isItemSelected { let shouldDeselectDay = delegate?.monthOrDaySelectorCell(self, shouldDeselectMonthday: monthday) ?? true if shouldDeselectDay { cell.setItemSelected(false) if let index = bymonthday.index(of: monthday) { bymonthday.remove(at: index) } delegate?.monthOrDaySelectorCell(self, didDeselectMonthday: monthday) } } else { cell.setItemSelected(true) bymonthday.append(monthday) delegate?.monthOrDaySelectorCell(self, didSelectMonthday: monthday) } case .month: let month = (indexPath as NSIndexPath).row + 1 if cell.isItemSelected { let shouldDeselectMonth = delegate?.monthOrDaySelectorCell(self, shouldDeselectMonth: month) ?? true if shouldDeselectMonth { cell.setItemSelected(false) if let index = bymonth.index(of: month) { bymonth.remove(at: index) } delegate?.monthOrDaySelectorCell(self, didDeselectMonth: month) } } else { cell.setItemSelected(true) bymonth.append(month) delegate?.monthOrDaySelectorCell(self, didSelectMonth: month) } } } }
67cce446e05f08035373f2141112e1b2
41.386598
214
0.618752
false
false
false
false
byu-oit-appdev/ios-byuSuite
refs/heads/dev
byuSuite/Apps/Parking/controller/MyVehiclesViewController.swift
apache-2.0
1
// // MyVehiclesViewController.swift // byuSuite // // Created by Erik Brady on 11/17/17. // Copyright © 2017 Brigham Young University. All rights reserved. // let VEHICLE_CHANGE_NOTIFICATION = NSNotification.Name("VehicleChangeMade") let UNWIND_TO_MY_VEHICLES = "unwindToMyVehicles" private let PEEK_SWIPE_KEY = "PARKING_POP_UP" private let VEHICLE_CELL_ID = "vehicleCell" private let NO_VEHICLE_CELL_ID = "noVehicleCell" private let PAYMENT_SEGUE_ID = "pay" private let CELL_HEIGHT: CGFloat = 60 class MyVehiclesViewController: ByuTableDataViewController, VehicleViewControllerDelegate { //MARK: Outlets @IBOutlet private weak var toolBarView: UIToolbar! @IBOutlet private weak var privilegeButton: UIBarButtonItem! @IBOutlet private weak var payForParkingButton: UIBarButtonItem! @IBOutlet private weak var addVehicleButton: UIBarButtonItem! @IBOutlet private weak var spinner: UIActivityIndicatorView! //MARK: Public Properties let ACTIVE_VEHICLES_INFO_TEXT = "Swipe left to deactivate." var INACTIVE_VEHICLES_INFO_TEXT: String { if #available(iOS 11, *) { return "Swipe right to activate.\nSwipe left to delete." } else { return "Swipe left to delete or activate" } } //MARK: Private Properties private var clientCallbackCounter = 0 private var activeVehicles = [Vehicle]() private var inactiveVehicles = [Vehicle]() private var eligibility: AddVehicleEligibility? private var privilegeWrapper: PrivilegeWrapper? override func viewDidLoad() { super.viewDidLoad() tableView.hideEmptyCells() //Listen for local notification to reload data NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: VEHICLE_CHANGE_NOTIFICATION, object: nil) //Load all vehicles, historic vehicles, vehicle limit and privilege info loadData() } deinit { NotificationCenter.default.removeObserver(self, name: VEHICLE_CHANGE_NOTIFICATION, object: nil) } //MARK: Navigation override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { if identifier == PAYMENT_SEGUE_ID && !(privilegeWrapper?.showPayButton ?? false) { super.displayAlert(title: "Not eligible for payment", message: privilegeWrapper?.eligibilityText, alertHandler: nil) return false } else if identifier == "vehicle" && clientCallbackCounter != 0 { //Vehicle segue depends on 3 of the 4 callbacks to complete so wait for cleintCallbackCounter to reach 0 return false } return true } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "vehicle", let vc = segue.destination as? VehicleViewController, let vehicle: Vehicle = objectForSender(tableView: tableView, cellSender: sender) { vc.delegate = self vc.vehicle = vehicle vc.eligibility = eligibility } else if segue.identifier == "addVehicle", let vc = segue.destination as? AddEditVehicleViewController { vc.eligibility = eligibility } else if segue.identifier == "privileges", let vc = segue.destination as? ParkingLotsViewController { vc.wrapper = privilegeWrapper } else if segue.identifier == PAYMENT_SEGUE_ID, let navVc = segue.destination as? UINavigationController, let vc = navVc.topViewController as? PaymentSourceViewController { vc.feature = .parking } } //MARK: UITableViewDataSource/Delegate Methods override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if let headerCell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as? VehicleHeaderTableViewCell { headerCell.setUpHeaderCell(view: self, text: super.tableView(tableView, titleForHeaderInSection: section), active: section == 0) //TODO: Returning the entire cell makes iOS 9/10 swipe the headers when any other cell is swiped. It can be fixed by returning headerCell.contentView, but that will // make the info buttons not clickable (since they're attached to the cell, not the contentView. Figure out something else? Wait for iOS 9/10 to be obsolete? return headerCell } else { return super.tableView(tableView, viewForHeaderInSection: section) } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = tableData.row(forIndexPath: indexPath) if let vehicle: Vehicle = tableData.object(forIndexPath: indexPath), let cellId = row.cellId { if cellId == VEHICLE_CELL_ID { let cell = tableView.dequeueReusableCell(for: indexPath, identifier: cellId) cell.textLabel?.text = vehicle.makeCode?.descr cell.textLabel?.backgroundColor = .clear cell.detailTextLabel?.text = vehicle.licensePlate cell.detailTextLabel?.backgroundColor = .clear cell.backgroundColor = vehicle.active ? .byuGreenFaded : .byuRedFaded return cell } else { let cell = tableView.dequeueReusableCell(for: indexPath, identifier: cellId) cell.textLabel?.text = row.text return cell } } else if row.cellId == NO_VEHICLE_CELL_ID { return tableData.cell(forTableView:tableView, atIndexPath:indexPath) } else { return UITableViewCell() } } @available(iOS 11.0, *) func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { var actions = [UIContextualAction]() if indexPath.section == 1, let vehicle: Vehicle = tableData.object(forIndexPath: indexPath) { let activateAction = UIContextualAction(style: .normal, title: "Activate", handler: { (_, _, _) in self.startActivating(vehicle: vehicle) }) activateAction.backgroundColor = .byuGreen actions = [activateAction] } return UISwipeActionsConfiguration(actions: actions) } @available(iOS 11.0, *) func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { var actions = [UIContextualAction]() if let vehicle: Vehicle = tableData.object(forIndexPath: indexPath) { if indexPath.section == 0 { let deactivateAction = UIContextualAction(style: .normal, title: "Deactivate", handler: { (_, _, _) in self.deactivateButtonSelected(vehicle: vehicle) }) deactivateAction.backgroundColor = .orange actions = [deactivateAction] } else if indexPath.section == 1 { actions = [UIContextualAction(style: .destructive, title: "Delete", handler: { (_, _, _) in self.deleteButtonSelected(vehicle: vehicle) })] } } return UISwipeActionsConfiguration(actions: actions) } //Only for iOS 9/10 func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { var actions = [UITableViewRowAction]() if let vehicle: Vehicle = tableData.object(forIndexPath: indexPath) { if indexPath.section == 0 { let deactivateAction = UITableViewRowAction(style: .normal, title: "Deactivate", handler: { (_, _) in self.deactivateButtonSelected(vehicle: vehicle) }) deactivateAction.backgroundColor = .orange actions = [deactivateAction] } else if indexPath.section == 1 { let activateAction = UITableViewRowAction(style: .normal, title: "Activate", handler: { (_, _) in self.startActivating(vehicle: vehicle) }) activateAction.backgroundColor = UIColor.byuGreen let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete", handler: { (_, _) in self.deleteButtonSelected(vehicle: vehicle) }) //This order is reversed when displayed actions = [activateAction, deleteAction] } } return actions } //MARK: IBActions @IBAction func reloadData(_ segue: UIStoryboardSegue) { loadData() } @IBAction func addVehicleButtonTapped(_ sender: Any) { if let eligibility = eligibility, eligibility.canRegisterPerm { performSegue(withIdentifier: "addVehicle", sender: sender) } else { super.displayAlert(title: "Unable to Add Vehicle", message: "You have reached your registration limit. Please deactivate a vehicle in order to add a new vehicle.", alertHandler: nil) } } //MARK: VehicleViewControllerDelegate Methods func startActivating(vehicle: Vehicle) { guard let eligibility = eligibility else { super.displayAlert(title: "Error", message: "There was an error loading your eligibility. Please try again later.") return } let activate: ((Vehicle) -> Void) = { vehicle in self.tableView.isUserInteractionEnabled = false ParkingRegistrationClient.registerVehicle(vehicle: vehicle) { (_, error) in if error == nil { self.loadData() super.displayAlert(title: "Success", message: "Successfully activated vehicle. Be aware that it can take up to 15 minutes in some cases for privileges to reflect on this vehicle.", alertHandler: nil) } else { //Stop the spinner here since no further client calls will be made. self.spinner.stopAnimating() self.tableView.isUserInteractionEnabled = true super.displayAlert(error: error, title: "Activation Failed", alertHandler: nil) } } } spinner.startAnimating() if eligibility.canRegisterPerm { activate(vehicle) } else { //They could be here because they have too many vehicles so remove the last OR because they aren't allowed to register vehicles at all if let vehicleToDeactivate = activeVehicles.last { //Deactivate last vehicle tableView.isUserInteractionEnabled = false ParkingRegistrationClient.unregisterVehicle(vehicle: vehicleToDeactivate, callback: { (callbackVehicle, error) in if callbackVehicle != nil { activate(vehicle) } else { //Stop the spinner here since no further cleint calls will be made. self.spinner.stopAnimating() self.tableView.isUserInteractionEnabled = true super.displayAlert(error: error, message: "Failed to deactivate the oldest active vehicle before activating the new vehicle. Please try again later.", alertHandler: nil) } }) } else { super.displayAlert(title: "Not Eligible", message: "You are currently ineligible to active a vehicle. If you believe this is in error, please contact the BYU Parking Office.", alertHandler: nil) } } } //MARK: Custom Methods private func loadData() { //Start the spinner spinner.startAnimating() //Reset the callback counter and disable the tableView clientCallbackCounter = 4 tableView.isUserInteractionEnabled = false ParkingRegistrationClient.getAllVehicles { (vehicles, error) in if let vehicles = vehicles { self.activeVehicles = vehicles } else { super.displayAlert(error: error, title: "Error Loading Vehicles") } self.stopSpinnerIfReady() } ParkingRegistrationClient.getAllInactiveVehicles { (vehicles, error) in if let vehicles = vehicles { self.inactiveVehicles = vehicles } else { super.displayAlert(error: error, title: "Error Loading Inactive Vehicles") } self.stopSpinnerIfReady() } ParkingRegistrationClient.getVehicleLimitInfo { (eligibility, error) in if let eligibility = eligibility { self.eligibility = eligibility self.addVehicleButton.isEnabled = true } else { super.displayAlert(error: error, title: "Error Loading Vehicle Information") } self.stopSpinnerIfReady() } ParkingRegistrationClient.getPrivilegeInfo { (wrapper, error) in if let wrapper = wrapper { self.privilegeWrapper = wrapper self.payForParkingButton.isEnabled = true self.privilegeButton.isEnabled = true } else { super.displayAlert(error: error, title: "Error Loading Privilege Information") } self.stopSpinnerIfReady() } } private func stopSpinnerIfReady() { //Decrement for each callback that has been received clientCallbackCounter -= 1 if clientCallbackCounter == 0 { setupTableData() spinner.stopAnimating() } } private func setupTableData() { var activeVehicleRows: [Row] if activeVehicles.count == 0 { activeVehicleRows = [Row(text: "You have no currently activated vehicles", cellId: NO_VEHICLE_CELL_ID, enabled: false, height: CELL_HEIGHT)] } else { activeVehicleRows = activeVehicles.map { return Row(text: $0.makeCode?.descr, detailText: $0.licensePlate, cellId: VEHICLE_CELL_ID, height: CELL_HEIGHT, object: $0) } } tableData = TableData(sections: [Section(title: "Active Vehicles", height: 40, rows: activeVehicleRows)]) //Only add section for inactive vehicles if there are any if inactiveVehicles.count > 0 { tableData.add(section: Section(title: "Inactive Vehicles", height: 40, rows: inactiveVehicles.map { return Row(text: $0.makeCode?.descr, detailText: $0.licensePlate, cellId: VEHICLE_CELL_ID, height: CELL_HEIGHT, object: $0) })) } tableView.reloadData() tableView.isUserInteractionEnabled = true //Peek the swipe options (if they haven't seen them before, and they actually have an inactive vehicle to peek) let defaults = UserDefaults.standard if !defaults.bool(forKey: PEEK_SWIPE_KEY) { defaults.set(true, forKey: PEEK_SWIPE_KEY) super.displayAlert(title: "New Shortcuts", message: "Active Vehicles:\n\(ACTIVE_VEHICLES_INFO_TEXT)\n\nInactive Vehicles:\n\(INACTIVE_VEHICLES_INFO_TEXT)") { _ in if self.inactiveVehicles.count > 0, self.tableData.rows(inSection: 1).count > 0 { let indexPathToPeek = IndexPath(row: 0, section: 1) if #available(iOS 11, *) { //Peek left, then peek right super.tableView.peekSwipeOptions(indexPath: indexPathToPeek, buttonOptions: [("Delete", UIColor.red)]) { super.tableView.peekSwipeOptions(onRight: false, indexPath: indexPathToPeek, buttonOptions: [("Activate", UIColor.byuGreen)]) } } else { //Peek right with both buttons super.tableView.peekSwipeOptions(indexPath: indexPathToPeek, buttonOptions: [("Delete", UIColor.red), ("Activate", UIColor.byuGreen)]) } } } } } private func deleteButtonSelected(vehicle: Vehicle) { //Display an alert to confirm that the user wants to delete the vehicle let alert = UIAlertController(title: "Delete Confirm", message: "Do you really want to delete this vehicle? This action cannot be undone.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Confirm", style: .default) { (_) in self.spinner.startAnimating() self.tableView.isUserInteractionEnabled = false if let vehicleId = vehicle.vehicleId { ParkingRegistrationClient.deleteVehicle(vehicleId: vehicleId, callback: { (error) in if let error = error { super.displayAlert(error: error, alertHandler: nil) } else { self.loadData() } }) } }) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { (_) in self.tableView.reloadData() }) present(alert, animated: true, completion: nil) } private func deactivateButtonSelected(vehicle: Vehicle) { tableView.isUserInteractionEnabled = false spinner.startAnimating() ParkingRegistrationClient.unregisterVehicle(vehicle: vehicle, callback: { (callbackVehicle, error) in self.spinner.stopAnimating() self.tableView.isUserInteractionEnabled = true if let error = error { super.displayAlert(error: error, message: "Failed to deactivate the vehicle. Please try again later.", alertHandler: nil) } else { self.loadData() } }) } }
1e2e5ab72264fd9557b30494b5c98f84
39.15748
230
0.73
false
false
false
false
aleckretch/Bloom
refs/heads/master
iOS/Bloom/Bloom/Shared/AppDelegate.swift
mit
1
// // AppDelegate.swift // Bloom // // Created by Alec Kretch on 10/21/17. // Copyright © 2017 Alec Kretch. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Bloom") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
e64ad5b6ff43c4c3ffbebb41dd79806d
48.301075
285
0.685278
false
false
false
false