repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
omondigeno/ActionablePushMessages
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQUIView+IQKeyboardToolbar.swift
5
46675
// // IQUIView+IQKeyboardToolbar.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit private var kIQShouldHideTitle = "kIQShouldHideTitle" private var kIQPreviousInvocationTarget = "kIQPreviousInvocationTarget" private var kIQPreviousInvocationSelector = "kIQPreviousInvocationSelector" private var kIQNextInvocationTarget = "kIQNextInvocationTarget" private var kIQNextInvocationSelector = "kIQNextInvocationSelector" private var kIQDoneInvocationTarget = "kIQDoneInvocationTarget" private var kIQDoneInvocationSelector = "kIQDoneInvocationSelector" /** UIView category methods to add IQToolbar on UIKeyboard. */ public extension UIView { ///------------------------- /// MARK: Title and Distance ///------------------------- /** If shouldHideTitle is YES, then title will not be added to the toolbar. Default to NO. */ public var shouldHideTitle: Bool? { get { let aValue: AnyObject? = objc_getAssociatedObject(self, &kIQShouldHideTitle) if aValue == nil { return false } else { return aValue as? Bool } } set(newValue) { objc_setAssociatedObject(self, &kIQShouldHideTitle, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let toolbar = self.inputAccessoryView as? IQToolbar { if let textField = self as? UITextField { toolbar.title = textField.placeholder } else if let textView = self as? IQTextView { toolbar.title = textView.placeholder } } } } ///----------------------------------------- /// TODO: Customised Invocation Registration ///----------------------------------------- /** Additional target & action to do get callback action. Note that setting custom `previous` selector doesn't affect native `previous` functionality, this is just used to notifiy user to do additional work according to need. @param target Target object. @param action Target Selector. */ public func setCustomPreviousTarget(target: AnyObject?, selector: Selector?) { previousInvocation = (target, selector) } /** Additional target & action to do get callback action. Note that setting custom `next` selector doesn't affect native `next` functionality, this is just used to notifiy user to do additional work according to need. @param target Target object. @param action Target Selector. */ public func setCustomNextTarget(target: AnyObject?, selector: Selector?) { nextInvocation = (target, selector) } /** Additional target & action to do get callback action. Note that setting custom `done` selector doesn't affect native `done` functionality, this is just used to notifiy user to do additional work according to need. @param target Target object. @param action Target Selector. */ public func setCustomDoneTarget(target: AnyObject?, selector: Selector?) { doneInvocation = (target, selector) } /** Customized Invocation to be called on previous arrow action. previousInvocation is internally created using setCustomPreviousTarget: method. */ public var previousInvocation : (target: AnyObject?, selector: Selector?) { get { let target: AnyObject? = objc_getAssociatedObject(self, &kIQPreviousInvocationTarget) var selector : Selector? if let selectorString = objc_getAssociatedObject(self, &kIQPreviousInvocationSelector) as? String { selector = NSSelectorFromString(selectorString) } return (target: target, selector: selector) } set(newValue) { objc_setAssociatedObject(self, &kIQPreviousInvocationTarget, newValue.target, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let unwrappedSelector = newValue.selector { objc_setAssociatedObject(self, &kIQPreviousInvocationSelector, NSStringFromSelector(unwrappedSelector), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } else { objc_setAssociatedObject(self, &kIQPreviousInvocationSelector, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } /** Customized Invocation to be called on next arrow action. nextInvocation is internally created using setCustomNextTarget: method. */ public var nextInvocation : (target: AnyObject?, selector: Selector?) { get { let target: AnyObject? = objc_getAssociatedObject(self, &kIQNextInvocationTarget) var selector : Selector? if let selectorString = objc_getAssociatedObject(self, &kIQNextInvocationSelector) as? String { selector = NSSelectorFromString(selectorString) } return (target: target, selector: selector) } set(newValue) { objc_setAssociatedObject(self, &kIQNextInvocationTarget, newValue.target, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let unwrappedSelector = newValue.selector { objc_setAssociatedObject(self, &kIQNextInvocationSelector, NSStringFromSelector(unwrappedSelector), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } else { objc_setAssociatedObject(self, &kIQNextInvocationSelector, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } /** Customized Invocation to be called on done action. doneInvocation is internally created using setCustomDoneTarget: method. */ public var doneInvocation : (target: AnyObject?, selector: Selector?) { get { let target: AnyObject? = objc_getAssociatedObject(self, &kIQDoneInvocationTarget) var selector : Selector? if let selectorString = objc_getAssociatedObject(self, &kIQDoneInvocationSelector) as? String { selector = NSSelectorFromString(selectorString) } return (target: target, selector: selector) } set(newValue) { objc_setAssociatedObject(self, &kIQDoneInvocationTarget, newValue.target, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let unwrappedSelector = newValue.selector { objc_setAssociatedObject(self, &kIQDoneInvocationSelector, NSStringFromSelector(unwrappedSelector), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } else { objc_setAssociatedObject(self, &kIQDoneInvocationSelector, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } ///--------------------- /// MARK: Private helper ///--------------------- public static func flexibleBarButtonItem () -> IQBarButtonItem { struct Static { static let nilButton = IQBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) } return Static.nilButton } ///------------ /// MARK: Done ///------------ /** Helper function to add Done button on keyboard. @param target Target object for selector. @param action Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. */ public func addDoneOnKeyboardWithTarget(target : AnyObject?, action : Selector) { addDoneOnKeyboardWithTarget(target, action: action, titleText: nil) } /** Helper function to add Done button on keyboard. @param target Target object for selector. @param action Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addDoneOnKeyboardWithTarget (target : AnyObject?, action : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] //Title button let title = IQTitleBarButtonItem(title: shouldHideTitle == true ? nil : titleText) items.append(title) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Done button let doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: target, action: action) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } } } /** Helper function to add Done button on keyboard. @param target Target object for selector. @param action Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. */ public func addDoneOnKeyboardWithTarget (target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addDoneOnKeyboardWithTarget(target, action: action, titleText: title) } ///------------ /// MARK: Right ///------------ /** Helper function to add Right button on keyboard. @param image Image icon to use as right button. @param target Target object for selector. @param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addRightButtonOnKeyboardWithImage (image : UIImage, target : AnyObject?, action : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] //Title button let title = IQTitleBarButtonItem(title: shouldHideTitle == true ? nil : titleText) items.append(title) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Right button let doneButton = IQBarButtonItem(image: image, style: UIBarButtonItemStyle.Done, target: target, action: action) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } } } /** Helper function to add Right button on keyboard. @param image Image icon to use as right button. @param target Target object for selector. @param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. */ public func addRightButtonOnKeyboardWithImage (image : UIImage, target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addRightButtonOnKeyboardWithImage(image, target: target, action: action, titleText: title) } /** Helper function to add Right button on keyboard. @param text Title for rightBarButtonItem, usually 'Done'. @param target Target object for selector. @param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. */ public func addRightButtonOnKeyboardWithText (text : String, target : AnyObject?, action : Selector) { addRightButtonOnKeyboardWithText(text, target: target, action: action, titleText: nil) } /** Helper function to add Right button on keyboard. @param text Title for rightBarButtonItem, usually 'Done'. @param target Target object for selector. @param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addRightButtonOnKeyboardWithText (text : String, target : AnyObject?, action : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] //Title button let title = IQTitleBarButtonItem(title: shouldHideTitle == true ? nil : titleText) items.append(title) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Right button let doneButton = IQBarButtonItem(title: text, style: UIBarButtonItemStyle.Done, target: target, action: action) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } } } /** Helper function to add Right button on keyboard. @param text Title for rightBarButtonItem, usually 'Done'. @param target Target object for selector. @param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. */ public func addRightButtonOnKeyboardWithText (text : String, target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addRightButtonOnKeyboardWithText(text, target: target, action: action, titleText: title) } ///------------------ /// MARK: Cancel/Done ///------------------ /** Helper function to add Cancel and Done button on keyboard. @param target Target object for selector. @param cancelAction Cancel button action name. Usually 'cancelAction:(IQBarButtonItem*)item'. @param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. */ public func addCancelDoneOnKeyboardWithTarget (target : AnyObject?, cancelAction : Selector, doneAction : Selector) { addCancelDoneOnKeyboardWithTarget(target, cancelAction: cancelAction, doneAction: doneAction, titleText: nil) } /** Helper function to add Cancel and Done button on keyboard. @param target Target object for selector. @param cancelAction Cancel button action name. Usually 'cancelAction:(IQBarButtonItem*)item'. @param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addCancelDoneOnKeyboardWithTarget (target : AnyObject?, cancelAction : Selector, doneAction : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] //Cancel button let cancelButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: target, action: cancelAction) items.append(cancelButton) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Title let title = IQTitleBarButtonItem(title: shouldHideTitle == true ? nil : titleText) items.append(title) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Done button let doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: target, action: doneAction) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } } } /** Helper function to add Cancel and Done button on keyboard. @param target Target object for selector. @param cancelAction Cancel button action name. Usually 'cancelAction:(IQBarButtonItem*)item'. @param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. */ public func addCancelDoneOnKeyboardWithTarget (target : AnyObject?, cancelAction : Selector, doneAction : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addCancelDoneOnKeyboardWithTarget(target, cancelAction: cancelAction, doneAction: doneAction, titleText: title) } ///----------------- /// MARK: Right/Left ///----------------- /** Helper function to add Left and Right button on keyboard. @param target Target object for selector. @param leftButtonTitle Title for leftBarButtonItem, usually 'Cancel'. @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. @param leftButtonAction Left button action name. Usually 'cancelAction:(IQBarButtonItem*)item'. @param rightButtonAction Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. */ public func addRightLeftOnKeyboardWithTarget( target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector) { addRightLeftOnKeyboardWithTarget(target, leftButtonTitle: leftButtonTitle, rightButtonTitle: rightButtonTitle, rightButtonAction: rightButtonAction, leftButtonAction: leftButtonAction, titleText: nil) } /** Helper function to add Left and Right button on keyboard. @param target Target object for selector. @param leftButtonTitle Title for leftBarButtonItem, usually 'Cancel'. @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. @param leftButtonAction Left button action name. Usually 'cancelAction:(IQBarButtonItem*)item'. @param rightButtonAction Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addRightLeftOnKeyboardWithTarget( target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] //Left button let cancelButton = IQBarButtonItem(title: leftButtonTitle, style: UIBarButtonItemStyle.Plain, target: target, action: leftButtonAction) items.append(cancelButton) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Title button let title = IQTitleBarButtonItem(title: shouldHideTitle == true ? nil : titleText) items.append(title) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Right button let doneButton = IQBarButtonItem(title: rightButtonTitle, style: UIBarButtonItemStyle.Done, target: target, action: rightButtonAction) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } } } /** Helper function to add Left and Right button on keyboard. @param target Target object for selector. @param leftButtonTitle Title for leftBarButtonItem, usually 'Cancel'. @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. @param leftButtonAction Left button action name. Usually 'cancelAction:(IQBarButtonItem*)item'. @param rightButtonAction Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. */ public func addRightLeftOnKeyboardWithTarget( target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addRightLeftOnKeyboardWithTarget(target, leftButtonTitle: leftButtonTitle, rightButtonTitle: rightButtonTitle, rightButtonAction: rightButtonAction, leftButtonAction: leftButtonAction, titleText: title) } ///------------------------- /// MARK: Previous/Next/Done ///------------------------- /** Helper function to add ArrowNextPrevious and Done button on keyboard. @param target Target object for selector. @param previousAction Previous button action name. Usually 'previousAction:(id)item'. @param nextAction Next button action name. Usually 'nextAction:(id)item'. @param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. */ public func addPreviousNextDoneOnKeyboardWithTarget ( target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector) { addPreviousNextDoneOnKeyboardWithTarget(target, previousAction: previousAction, nextAction: nextAction, doneAction: doneAction, titleText: nil) } /** Helper function to add ArrowNextPrevious and Done button on keyboard. @param target Target object for selector. @param previousAction Previous button action name. Usually 'previousAction:(id)item'. @param nextAction Next button action name. Usually 'nextAction:(id)item'. @param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addPreviousNextDoneOnKeyboardWithTarget ( target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] let prev : IQBarButtonItem let next : IQBarButtonItem // Get the top level "bundle" which may actually be the framework var bundle = NSBundle(forClass: IQKeyboardManager.self) if let resourcePath = bundle.pathForResource("IQKeyboardManager", ofType: "bundle") { if let resourcesBundle = NSBundle(path: resourcePath) { bundle = resourcesBundle } } prev = IQBarButtonItem(image: UIImage(named: "IQButtonBarArrowLeft", inBundle: bundle, compatibleWithTraitCollection: nil), style: UIBarButtonItemStyle.Plain, target: target, action: previousAction) next = IQBarButtonItem(image: UIImage(named: "IQButtonBarArrowRight", inBundle: bundle, compatibleWithTraitCollection: nil), style: UIBarButtonItemStyle.Plain, target: target, action: nextAction) //Previous button items.append(prev) //Fixed space let fixed = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil) fixed.width = 23 items.append(fixed) //Next button items.append(next) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Title button let title = IQTitleBarButtonItem(title: shouldHideTitle == true ? nil : titleText) items.append(title) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Done button let doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: target, action: doneAction) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } } } /** Helper function to add ArrowNextPrevious and Done button on keyboard. @param target Target object for selector. @param previousAction Previous button action name. Usually 'previousAction:(id)item'. @param nextAction Next button action name. Usually 'nextAction:(id)item'. @param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. */ public func addPreviousNextDoneOnKeyboardWithTarget ( target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addPreviousNextDoneOnKeyboardWithTarget(target, previousAction: previousAction, nextAction: nextAction, doneAction: doneAction, titleText: title) } ///-------------------------- /// MARK: Previous/Next/Right ///-------------------------- /** Helper function to add ArrowNextPrevious and Right button on keyboard. @param target Target object for selector. @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. @param previousAction Previous button action name. Usually 'previousAction:(id)item'. @param nextAction Next button action name. Usually 'nextAction:(id)item'. @param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addPreviousNextRightOnKeyboardWithTarget( target : AnyObject?, rightButtonImage : UIImage, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, titleText : String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] let prev : IQBarButtonItem let next : IQBarButtonItem // Get the top level "bundle" which may actually be the framework var bundle = NSBundle(forClass: IQKeyboardManager.self) if let resourcePath = bundle.pathForResource("IQKeyboardManager", ofType: "bundle") { if let resourcesBundle = NSBundle(path: resourcePath) { bundle = resourcesBundle } } prev = IQBarButtonItem(image: UIImage(named: "IQButtonBarArrowLeft", inBundle: bundle, compatibleWithTraitCollection: nil), style: UIBarButtonItemStyle.Plain, target: target, action: previousAction) next = IQBarButtonItem(image: UIImage(named: "IQButtonBarArrowRight", inBundle: bundle, compatibleWithTraitCollection: nil), style: UIBarButtonItemStyle.Plain, target: target, action: previousAction) //Previous button items.append(prev) //Fixed space let fixed = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil) fixed.width = 23 items.append(fixed) //Next button items.append(next) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Title button let title = IQTitleBarButtonItem(title: shouldHideTitle == true ? nil : titleText) items.append(title) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Right button let doneButton = IQBarButtonItem(image: rightButtonImage, style: UIBarButtonItemStyle.Done, target: target, action: rightButtonAction) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } } } // /** // Helper function to add ArrowNextPrevious and Right button on keyboard. // // @param target Target object for selector. // @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. // @param previousAction Previous button action name. Usually 'previousAction:(id)item'. // @param nextAction Next button action name. Usually 'nextAction:(id)item'. // @param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'. // @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. // */ public func addPreviousNextRightOnKeyboardWithTarget( target : AnyObject?, rightButtonImage : UIImage, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, shouldShowPlaceholder : Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addPreviousNextRightOnKeyboardWithTarget(target, rightButtonImage: rightButtonImage, previousAction: previousAction, nextAction: nextAction, rightButtonAction: rightButtonAction, titleText: title) } /** Helper function to add ArrowNextPrevious and Right button on keyboard. @param target Target object for selector. @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. @param previousAction Previous button action name. Usually 'previousAction:(id)item'. @param nextAction Next button action name. Usually 'nextAction:(id)item'. @param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'. */ public func addPreviousNextRightOnKeyboardWithTarget( target : AnyObject?, rightButtonTitle : String, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector) { addPreviousNextRightOnKeyboardWithTarget(target, rightButtonTitle: rightButtonTitle, previousAction: previousAction, nextAction: nextAction, rightButtonAction: rightButtonAction, titleText: nil) } /** Helper function to add ArrowNextPrevious and Right button on keyboard. @param target Target object for selector. @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. @param previousAction Previous button action name. Usually 'previousAction:(id)item'. @param nextAction Next button action name. Usually 'nextAction:(id)item'. @param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addPreviousNextRightOnKeyboardWithTarget( target : AnyObject?, rightButtonTitle : String, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, titleText : String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] let prev : IQBarButtonItem let next : IQBarButtonItem // Get the top level "bundle" which may actually be the framework var bundle = NSBundle(forClass: IQKeyboardManager.self) if let resourcePath = bundle.pathForResource("IQKeyboardManager", ofType: "bundle") { if let resourcesBundle = NSBundle(path: resourcePath) { bundle = resourcesBundle } } prev = IQBarButtonItem(image: UIImage(named: "IQButtonBarArrowLeft", inBundle: bundle, compatibleWithTraitCollection: nil), style: UIBarButtonItemStyle.Plain, target: target, action: previousAction) next = IQBarButtonItem(image: UIImage(named: "IQButtonBarArrowRight", inBundle: bundle, compatibleWithTraitCollection: nil), style: UIBarButtonItemStyle.Plain, target: target, action: previousAction) //Previous button items.append(prev) //Fixed space let fixed = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil) fixed.width = 23 items.append(fixed) //Next button items.append(next) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Title button let title = IQTitleBarButtonItem(title: shouldHideTitle == true ? nil : titleText) items.append(title) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Right button let doneButton = IQBarButtonItem(title: rightButtonTitle, style: UIBarButtonItemStyle.Done, target: target, action: rightButtonAction) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black default: toolbar.barStyle = UIBarStyle.Default } } } } // /** // Helper function to add ArrowNextPrevious and Right button on keyboard. // // @param target Target object for selector. // @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. // @param previousAction Previous button action name. Usually 'previousAction:(id)item'. // @param nextAction Next button action name. Usually 'nextAction:(id)item'. // @param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'. // @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. // */ public func addPreviousNextRightOnKeyboardWithTarget( target : AnyObject?, rightButtonTitle : String, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, shouldShowPlaceholder : Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addPreviousNextRightOnKeyboardWithTarget(target, rightButtonTitle: rightButtonTitle, previousAction: previousAction, nextAction: nextAction, rightButtonAction: rightButtonAction, titleText: title) } ///----------------------------------- /// MARK: Enable/Disable Previous/Next ///----------------------------------- /** Helper function to enable and disable previous next buttons. @param isPreviousEnabled BOOL to enable/disable previous button on keyboard. @param isNextEnabled BOOL to enable/disable next button on keyboard.. */ public func setEnablePrevious ( isPreviousEnabled : Bool, isNextEnabled : Bool) { // Getting inputAccessoryView. if let inputAccessoryView = self.inputAccessoryView as? IQToolbar { // If it is IQToolbar and it's items are greater than zero. if inputAccessoryView.items?.count > 3 { if let items = inputAccessoryView.items { if let prevButton = items[0] as? IQBarButtonItem { if let nextButton = items[2] as? IQBarButtonItem { if prevButton.enabled != isPreviousEnabled { prevButton.enabled = isPreviousEnabled } if nextButton.enabled != isNextEnabled { nextButton.enabled = isNextEnabled } } } } } } } }
apache-2.0
c621396116dc598796e063c82fd2c29c
42.703184
225
0.61714
5.997045
false
false
false
false
RxSwiftCommunity/RxSwiftExt
Source/RxSwift/pausableBuffered.swift
2
3545
// // pausableBuffered.swift // RxSwiftExt // // Created by Tanguy Helesbeux on 24/05/2017. // Copyright © 2017 RxSwift Community. All rights reserved. // import Foundation import RxSwift extension ObservableType { /** Pauses the elements of the source observable sequence based on the latest element from the second observable sequence. While paused, elements from the source are buffered, limited to a maximum number of element. When resumed, all buffered elements are flushed as single events in a contiguous stream. - seealso: [pausable operator on reactivex.io](http://reactivex.io/documentation/operators/backpressure.html) - parameter pauser: The observable sequence used to pause the source observable sequence. - parameter limit: The maximum number of element buffered. Pass `nil` to buffer all elements without limit. Default 1. - parameter flushOnCompleted: If `true` buffered elements will be flushed when the source completes. Default `true`. - parameter flushOnError: If `true` buffered elements will be flushed when the source errors. Default `true`. - returns: The observable sequence which is paused and resumed based upon the pauser observable sequence. */ public func pausableBuffered<Pauser: ObservableType> (_ pauser: Pauser, limit: Int? = 1, flushOnCompleted: Bool = true, flushOnError: Bool = true) -> Observable<Element> where Pauser.Element == Bool { return Observable<Element>.create { observer in var buffer: [Element] = [] if let limit = limit { buffer.reserveCapacity(limit) } var paused = true var flushIndex = 0 let lock = NSRecursiveLock() let flush = { while flushIndex < buffer.count { flushIndex += 1 observer.onNext(buffer[flushIndex - 1]) } if buffer.count > 0 { flushIndex = 0 buffer.removeAll(keepingCapacity: limit != nil) } } let boundaryDisposable = pauser.distinctUntilChanged(==).subscribe { event in lock.lock(); defer { lock.unlock() } switch event { case .next(let resume): if resume && buffer.count > 0 { flush() } paused = !resume case .completed: observer.onCompleted() case .error(let error): observer.onError(error) } } let disposable = self.subscribe { event in lock.lock(); defer { lock.unlock() } switch event { case .next(let element): if paused { buffer.append(element) if let limit = limit, buffer.count > limit { buffer.remove(at: 0) } } else { observer.onNext(element) } case .completed: if flushOnCompleted { flush() } observer.onCompleted() case .error(let error): if flushOnError { flush() } observer.onError(error) } } return Disposables.create([disposable, boundaryDisposable]) } } }
mit
4434a5ab66444e310cf85475b1465989
36.305263
204
0.545147
5.353474
false
false
false
false
YaQiongLu/LYQdyzb
LYQdyzb/LYQdyzb/Classes/Main/View/PageTitleView.swift
1
7243
// // PageTitleView.swift // LYQdyzb // // Created by 芦亚琼 on 2016/11/7. // Copyright © 2016年 芦亚琼. All rights reserved. // import UIKit //在swift 3中,新增加了一个 fileprivate来显式的表明,这个元素的访问权限为文件内私有。过去的private对应现在的fileprivate。现在的private则是真正的私有,离开了这个类或者结构体的作用域外面就无法访问。 //open则是弥补public语义上的不足。 //现在的访问权限则依次为:open,public,internal,fileprivate,private。 //定义协议 protocol PageTitleViewDelegate : class {//写class表示协议只能被类遵守,不能被结构体、枚举等遵守 func pageTitleView(titleView :PageTitleView, selectedIndex index : Int) } //定义属性 let kScrkllLineH : CGFloat = 2.0 fileprivate let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85) fileprivate let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0) //定义类 class PageTitleView: UIView { //定义属性 fileprivate var currentIndex = 0 //记录当前选中label的下标,默认选中第0个下标 fileprivate var titles : [String] weak var delegate :PageTitleViewDelegate?//代理属性 用weak //懒加载数组 fileprivate lazy var titleLabels : [UILabel] = [UILabel]() //懒加载创建的控件 fileprivate lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() //懒加载创建scrollView fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() //自定义构造函数 init(frame: CGRect, titles : [String]) { self.titles = titles super.init(frame: frame) setupUI() } //自定义构造函数必须写的方法 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageTitleView{ fileprivate func setupUI(){ //1.添加滚动视图 addSubview(scrollView) scrollView.frame = bounds //2.设置标题文字 setupTitelLabels() //3.设置底线和滚动的滑块 setbottomLine() } private func setupTitelLabels() { // for i in 0..<titles.count // { // // // } //把可以直接创建的属性写在循环外面 提高性能 let labelW : CGFloat = frame.width / CGFloat (titles.count) let labelH : CGFloat = frame.height - kScrkllLineH let labelY : CGFloat = 0 for (index, title) in titles.enumerated() { //1.创建label let label = UILabel() //2.设置label的属性 label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16.0) label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) label.textAlignment = .center //3.设置label的frame let labelX : CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) //4.将label添加到scrollView中 scrollView.addSubview(label) //创建的label加到数组中,以便获取第一个 titleLabels.append(label) //5.给label添加手势 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:))) label.addGestureRecognizer(tapGes) } } private func setbottomLine(){ //1.添加底部的横线 let view = UIView() view.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 view.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(view) //获取数组中的第一个Label guard let firstLabel = titleLabels.first else {return} firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) //2.添加滚动的滑块 scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrkllLineH, width: firstLabel.frame.width, height: kScrkllLineH) } } //MARK: - 监听label点击 extension PageTitleView{ //事件监听 前面要加@objc @objc fileprivate func titleLabelClick(tapGes : UITapGestureRecognizer){ //1.获取当前label guard let currentLabel = tapGes.view as? UILabel else { return } //2.获取之前的label let oldLabel = titleLabels[currentIndex] //3.切换文字颜色 currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) //4.保存最新label的下标值 currentIndex = currentLabel.tag //5.滚动条位置发生改变 let scrollLinex = CGFloat(currentIndex) * scrollLine.frame.size.width UIView.animate(withDuration: 0.15) { //一个view的frame 包含它的矩形形状(size)的长和宽。和它在父视图中的坐标原点(origin)x和y坐标 self.scrollLine.frame.origin.x = scrollLinex } //6.通知代理 delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex) } } //MARK: - 对外暴露的方法 extension PageTitleView{ func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int) { //1.取出sourceLabel/targetlabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] //2.处理滑块的逻辑 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX //3.颜色渐变 //3.1取出变化的范围 let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2) //3.2变化sourceLabel sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress) //3.3变化targetLabel targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) //4.记录最新的index currentIndex = targetIndex } }
mit
4233114e45a63d7e6e5a40b1ac57fabc
28.962441
174
0.618928
4.220899
false
false
false
false
nissivm/DemoShop
Demo Shop/Container Views/AuthenticationContainerView.swift
1
11284
// // AuthenticationContainerView.swift // Demo Shop // // Created by Nissi Vieira Miranda on 1/19/16. // Copyright © 2016 Nissi Vieira Miranda. All rights reserved. // import UIKit class AuthenticationContainerView: UIViewController, UIGestureRecognizerDelegate, UITextFieldDelegate { @IBOutlet weak var tapView: UIView! @IBOutlet weak var nameTxtField: UITextField! @IBOutlet weak var usernameTxtField: UITextField! @IBOutlet weak var passwordTxtField: UITextField! @IBOutlet weak var emailTxtField: UITextField! @IBOutlet weak var shopLogo: UIImageView! @IBOutlet weak var shopName: UILabel! @IBOutlet weak var headerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var dividerOneTopConstraint: NSLayoutConstraint! @IBOutlet weak var dividerTwoTopConstraint: NSLayoutConstraint! @IBOutlet weak var dividerThreeTopConstraint: NSLayoutConstraint! @IBOutlet weak var signUpButton: UIButton! @IBOutlet weak var signInButton: UIButton! @IBOutlet weak var containerTopConstraint: NSLayoutConstraint! @IBOutlet weak var containerHeightConstraint: NSLayoutConstraint! var tappedTextField : UITextField? let backend = Backend() var multiplier: CGFloat = 1 override func viewDidLoad() { super.viewDidLoad() let tapRecognizer = UITapGestureRecognizer(target: self, action:Selector("handleTap:")) tapRecognizer.delegate = self tapView.addGestureRecognizer(tapRecognizer) if Device.IS_IPHONE_4 || Device.IS_IPHONE_6 || Device.IS_IPHONE_6_PLUS { containerHeightConstraint.constant = self.view.frame.size.height } if Device.IS_IPHONE_6 { multiplier = Constants.multiplier6 adjustForBiggerScreen() } if Device.IS_IPHONE_6_PLUS { multiplier = Constants.multiplier6plus adjustForBiggerScreen() } } //-------------------------------------------------------------------------// // MARK: Sign Up //-------------------------------------------------------------------------// @IBAction func signUpButtonTapped(sender: UIButton) { guard Reachability.connectedToNetwork() else { Auxiliar.presentAlertControllerWithTitle("No Internet Connection", andMessage: "Make sure your device is connected to the internet.", forViewController: self) return } let name = nameTxtField.text! let username = usernameTxtField.text! let password = passwordTxtField.text! let email = emailTxtField.text! if name.characters.count > 0 && username.characters.count > 0 && password.characters.count > 0 && email.characters.count > 0 { Auxiliar.showLoadingHUDWithText("Signing up...", forView: self.view) signUp(name, username: username, password: password, email: email) } else { Auxiliar.presentAlertControllerWithTitle("Error", andMessage: "Please fill in all fields", forViewController: self) } } func signUp(name: String, username: String, password: String, email: String) { backend.name = name backend.username = username backend.password = password backend.email = email backend.registerUser({ [unowned self](status, message) -> Void in dispatch_async(dispatch_get_main_queue()) { Auxiliar.hideLoadingHUDInView(self.view) if status == "Success" { self.nameTxtField.text = "" self.usernameTxtField.text = "" self.passwordTxtField.text = "" self.emailTxtField.text = "" NSNotificationCenter.defaultCenter().postNotificationName("SessionStarted", object: nil) return } Auxiliar.presentAlertControllerWithTitle(status, andMessage: message, forViewController: self) } }) } //-------------------------------------------------------------------------// // MARK: Sign In //-------------------------------------------------------------------------// @IBAction func signInButtonTapped(sender: UIButton) { guard Reachability.connectedToNetwork() else { Auxiliar.presentAlertControllerWithTitle("No Internet Connection", andMessage: "Make sure your device is connected to the internet.", forViewController: self) return } let username = usernameTxtField.text! let password = passwordTxtField.text! if username.characters.count > 0 && password.characters.count > 0 { Auxiliar.showLoadingHUDWithText("Signing in...", forView: self.view) signIn(username, password: password) } else { Auxiliar.presentAlertControllerWithTitle("Error", andMessage: "Please insert username and password", forViewController: self) } } func signIn(username: String, password: String) { backend.username = username backend.password = password backend.signInUser({ [unowned self](status, message) -> Void in dispatch_async(dispatch_get_main_queue()) { Auxiliar.hideLoadingHUDInView(self.view) if status == "Success" { self.nameTxtField.text = "" self.usernameTxtField.text = "" self.passwordTxtField.text = "" self.emailTxtField.text = "" NSNotificationCenter.defaultCenter().postNotificationName("SessionStarted", object: nil) return } Auxiliar.presentAlertControllerWithTitle(status, andMessage: message, forViewController: self) } }) } //-------------------------------------------------------------------------// // MARK: UITextFieldDelegate //-------------------------------------------------------------------------// func textFieldDidBeginEditing(textField: UITextField) { tappedTextField = textField let textFieldY = tappedTextField!.frame.origin.y let textFieldHeight = tappedTextField!.frame.size.height let total = textFieldY + textFieldHeight if total > (self.view.frame.size.height/2) { let difference = total - (self.view.frame.size.height/2) var newConstraint = containerTopConstraint.constant - difference if textField.tag == 13 // Email { newConstraint -= 30 } animateConstraint(containerTopConstraint, toValue: newConstraint) } } func textFieldShouldReturn(textField: UITextField) -> Bool { tappedTextField!.resignFirstResponder() tappedTextField = nil animateConstraint(containerTopConstraint, toValue: 0) return true } //-------------------------------------------------------------------------// // MARK: Tap gesture recognizer //-------------------------------------------------------------------------// func handleTap(recognizer : UITapGestureRecognizer) { if tappedTextField != nil { tappedTextField!.resignFirstResponder() tappedTextField = nil animateConstraint(containerTopConstraint, toValue: 0) } } //-------------------------------------------------------------------------// // MARK: Animations //-------------------------------------------------------------------------// func animateConstraint(constraint : NSLayoutConstraint, toValue value : CGFloat) { UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseOut, animations: { constraint.constant = value self.view.layoutIfNeeded() }, completion: { (finished: Bool) in }) } //-------------------------------------------------------------------------// // MARK: Ajust for bigger screen //-------------------------------------------------------------------------// func adjustForBiggerScreen() { for constraint in shopLogo.constraints { constraint.constant *= multiplier } for constraint in shopName.constraints { constraint.constant *= multiplier } for constraint in nameTxtField.constraints { constraint.constant *= multiplier } for constraint in usernameTxtField.constraints { constraint.constant *= multiplier } for constraint in passwordTxtField.constraints { constraint.constant *= multiplier } for constraint in emailTxtField.constraints { constraint.constant *= multiplier } for constraint in signUpButton.constraints { constraint.constant *= multiplier } for constraint in signInButton.constraints { constraint.constant *= multiplier } headerHeightConstraint.constant *= multiplier dividerOneTopConstraint.constant *= multiplier dividerTwoTopConstraint.constant *= multiplier dividerThreeTopConstraint.constant *= multiplier var fontSize = 25.0 * multiplier shopName.font = UIFont(name: "HelveticaNeue", size: fontSize) fontSize = 17.0 * multiplier nameTxtField.font = UIFont(name: "HelveticaNeue", size: fontSize) usernameTxtField.font = UIFont(name: "HelveticaNeue", size: fontSize) passwordTxtField.font = UIFont(name: "HelveticaNeue", size: fontSize) emailTxtField.font = UIFont(name: "HelveticaNeue", size: fontSize) signUpButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Bold", size: fontSize) signInButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Bold", size: fontSize) } //-------------------------------------------------------------------------// // MARK: Memory Warning //-------------------------------------------------------------------------// override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
590f5153815ad8eb87c1ba9f31ffbcdf
33.294833
108
0.518302
6.342327
false
false
false
false
nathawes/swift
test/Interpreter/bridged_casts_folding.swift
4
18100
// RUN: %target-run-simple-swift(-Onone) | %FileCheck %s // RUN: %target-run-simple-swift(-O) | %FileCheck -check-prefix=CHECK-OPT %s // NOTE: We use FileCheck for the crashing test cases to make sure we crash for // the correct reason in the test. We want to separate a memory management error // from a cast error which prints a nice error message. // FIXME: we should run this test if the OS-provided stdlib is recent enough. // UNSUPPORTED: use_os_stdlib // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation import StdlibUnittest // At the end of the file, run all of the tests. var Tests = TestSuite("BridgedCastFolding") defer { runAllTests() } public func forcedCast<NS, T>(_ ns: NS) -> T { return ns as! T } public func condCast<NS, T>(_ ns: NS) -> T? { return ns as? T } // Check optimizations of casts from NSString to String let nsString: NSString = "string🍕" let swiftString: String = "string🍕" let cfString: CFString = "string🍕" as CFString Tests.test("NSString => String") { do { let o: String = forcedCast(nsString) expectEqual(o, swiftString) } do { let o: String? = condCast(nsString) expectEqual(o!, swiftString) } } Tests.test("NSString => Array<Int>. Crashing test case") { do { let o: Array<Int>? = condCast(nsString) expectNil(o) } // CHECK-LABEL: [ RUN ] BridgedCastFolding.NSString => Array<Int>. Crashing test case // CHECK: stderr>>> Could not cast value of type '{{.*}}' (0x{{[0-9a-f]*}}) to 'NSArray' (0x{{[0-9a-f]*}}). // CHECK: stderr>>> OK: saw expected "crashed: sigabrt" // CHECK: [ OK ] BridgedCastFolding.NSString => Array<Int>. Crashing test case // CHECK-OPT-LABEL: [ RUN ] BridgedCastFolding.NSString => Array<Int>. Crashing test case // CHECK-OPT: stderr>>> OK: saw expected "crashed: sig{{ill|trap}}" // CHECK-OPT: [ OK ] BridgedCastFolding.NSString => Array<Int>. Crashing test case expectCrashLater() do { let o: Array<Int> = forcedCast(nsString) expectEqual(o.count, 0) } } // Check optimizations of casts from NSNumber to Int let nsIntNumber = NSNumber(value: 1) let swiftIntNumber: Int = 1 let cfIntNumber: CFNumber = 1 as CFNumber Tests.test("NSNumber => Int") { do { let o: Int = forcedCast(nsIntNumber) expectEqual(o, swiftIntNumber) } do { let o: Int? = condCast(nsIntNumber) expectEqual(o!, swiftIntNumber) } } // Check optimizations of casts from NSNumber to Double let nsDoubleNumber = NSNumber(value: 1.234) let swiftDoubleNumber: Double = 1.234 let swiftDoubleNumberWithInt: Double = 1 Tests.test("NSNumber => Double") { do { let o: Double = forcedCast(nsDoubleNumber) expectEqual(o, swiftDoubleNumber) } do { let o: Double? = condCast(nsDoubleNumber) expectEqual(o!, swiftDoubleNumber) } } // Check optimizations from NSNumber (Int) -> Double Tests.test("NSNumber (Int) -> Double") { do { let o: Double = forcedCast(nsIntNumber) expectEqual(o, swiftDoubleNumberWithInt) } do { let o: Double? = condCast(nsIntNumber) expectEqual(o, swiftDoubleNumberWithInt) } } // Check that we fail when casting an NSNumber -> String Tests.test("NSNumber (Int) -> String. Crashing test.") { do { let o: String? = condCast(nsIntNumber) expectNil(o) } // CHECK-LABEL: [ RUN ] BridgedCastFolding.NSNumber (Int) -> String. Crashing test. // CHECK: stderr>>> Could not cast value of type '{{.*}}' (0x{{[0-9a-f]*}}) to 'NSString' (0x{{[0-9a-f]*}}). // CHECK: stderr>>> OK: saw expected "crashed: sigabrt" // CHECK: [ OK ] BridgedCastFolding.NSNumber (Int) -> String. Crashing test. // CHECK-OPT-LABEL: [ RUN ] BridgedCastFolding.NSNumber (Int) -> String. Crashing test. // CHECK-OPT: stderr>>> OK: saw expected "crashed: sig{{ill|trap}}" // CHECK-OPT: [ OK ] BridgedCastFolding.NSNumber (Int) -> String. Crashing test. expectCrashLater() do { let o: String = forcedCast(nsIntNumber) expectEqual(o.count, 5) } } // Check optimization of casts from NSArray to Swift Array let nsArrInt: NSArray = [1, 2, 3, 4] let nsArrDouble: NSArray = [1.1, 2.2, 3.3, 4.4] let nsArrString: NSArray = ["One🍕", "Two🍕", "Three🍕", "Four🍕"] let swiftArrInt: [Int] = [1, 2, 3, 4] let swiftArrDouble: [Double] = [1.1, 2.2, 3.3, 4.4] let swiftArrString: [String] = ["One🍕", "Two🍕", "Three🍕", "Four🍕"] let cfArrInt: CFArray = [1, 2, 3, 4] as CFArray let cfArrDouble: CFArray = [1.1, 2.2, 3.3, 4.4] as CFArray let cfArrString: CFArray = ["One🍕", "Two🍕", "Three🍕", "Four🍕"] as CFArray Tests.test("NSArray -> Swift Array") { do { let arr: [Int] = forcedCast(nsArrInt) expectEqual(arr, swiftArrInt) } do { let arrOpt: [Int]? = condCast(nsArrInt) expectEqual(arrOpt!, swiftArrInt) } do { let arr: [Double] = forcedCast(nsArrDouble) expectEqual(arr, swiftArrDouble) } do { let arrOpt: [Double]? = condCast(nsArrDouble) expectEqual(arrOpt!, swiftArrDouble) } do { let arr: [String] = forcedCast(nsArrString) expectEqual(arr, swiftArrString) } do { let arrOpt: [String]? = condCast(nsArrString) expectEqual(arrOpt!, swiftArrString) } } Tests.test("NSArray (String) -> Swift Array (Int). Crashing.") { do { let arrOpt: [Int]? = condCast(nsArrString) expectNil(arrOpt) } // CHECK-LABEL: [ RUN ] BridgedCastFolding.NSArray (String) -> Swift Array (Int). Crashing. // CHECK: stderr>>> Could not cast value of type '{{.*}}' (0x{{[0-9a-f]*}}) to 'NSNumber' (0x{{[0-9a-f]*}}). // CHECK: stderr>>> OK: saw expected "crashed: sigabrt" // CHECK: [ OK ] BridgedCastFolding.NSArray (String) -> Swift Array (Int). Crashing. // CHECK-OPT-LABEL: [ RUN ] BridgedCastFolding.NSArray (String) -> Swift Array (Int). Crashing. // CHECK-OPT: stderr>>> Could not cast value of type '{{.*}}' (0x{{[0-9a-f]*}}) to 'NSNumber' (0x{{[0-9a-f]*}}). // CHECK-OPT: stderr>>> OK: saw expected "crashed: sigabrt" // CHECK-OPT: [ OK ] BridgedCastFolding.NSArray (String) -> Swift Array (Int). Crashing. expectCrashLater() do { let arr: [Int] = forcedCast(nsArrString) expectEqual(arr, swiftArrInt) } } Tests.test("NSArray (String) -> Swift Array (Double). Crashing.") { do { let arrOpt: [Double]? = condCast(nsArrString) expectNil(arrOpt) } // CHECK-LABEL: [ RUN ] BridgedCastFolding.NSArray (String) -> Swift Array (Double). Crashing. // CHECK: stderr>>> Could not cast value of type '{{.*}}' (0x{{[0-9a-f]*}}) to 'NSNumber' (0x{{[0-9a-f]*}}). // CHECK: stderr>>> OK: saw expected "crashed: sigabrt" // CHECK: [ OK ] BridgedCastFolding.NSArray (String) -> Swift Array (Double). Crashing. // CHECK-OPT-LABEL: [ RUN ] BridgedCastFolding.NSArray (String) -> Swift Array (Double). Crashing. // CHECK-OPT: stderr>>> Could not cast value of type '{{.*}}' (0x{{[0-9a-f]*}}) to 'NSNumber' (0x{{[0-9a-f]*}}). // CHECK-OPT: stderr>>> OK: saw expected "crashed: sigabrt" // CHECK-OPT: [ OK ] BridgedCastFolding.NSArray (String) -> Swift Array (Double). Crashing. expectCrashLater() do { let arr: [Double] = forcedCast(nsArrString) expectEqual(arr, swiftArrDouble) } } Tests.test("NSArray (Int) -> Swift Array (String). Crashing.") { do { let arrOpt: [String]? = condCast(nsArrInt) expectNil(arrOpt) } // CHECK-LABEL: [ RUN ] BridgedCastFolding.NSArray (Int) -> Swift Array (String). Crashing. // CHECK: stderr>>> Could not cast value of type '{{.*}}' (0x{{[0-9a-f]*}}) to 'NSString' (0x{{[0-9a-f]*}}). // CHECK: stderr>>> OK: saw expected "crashed: sigabrt" // CHECK: [ OK ] BridgedCastFolding.NSArray (Int) -> Swift Array (String). Crashing. // CHECK-OPT-LABEL: [ RUN ] BridgedCastFolding.NSArray (Int) -> Swift Array (String). Crashing. // CHECK-OPT: stderr>>> Could not cast value of type '{{.*}}' (0x{{[0-9a-f]*}}) to 'NSString' (0x{{[0-9a-f]*}}). // CHECK-OPT: stderr>>> OK: saw expected "crashed: sigabrt" // CHECK-OPT: [ OK ] BridgedCastFolding.NSArray (Int) -> Swift Array (String). Crashing. expectCrashLater() do { let arr: [String] = forcedCast(nsArrInt) expectEqual(arr, swiftArrString) } } // Check optimization of casts from NSDictionary to Swift Dictionary let swiftDictInt: [Int: Int] = [1:1, 2:2, 3:3, 4:4] let swiftDictDouble: [Double: Double] = [1.1 : 1.1, 2.2 : 2.2, 3.3 : 3.3, 4.4 : 4.4] let swiftDictString: [String: String] = ["One🍕":"One🍕", "Two":"Two", "Three":"Three", "Four":"Four"] let nsDictInt: NSDictionary = [1:1, 2:2, 3:3, 4:4] let nsDictDouble: NSDictionary = [1.1 : 1.1, 2.2 : 2.2, 3.3 : 3.3, 4.4 : 4.4] let nsDictString: NSDictionary = ["One🍕":"One🍕", "Two":"Two", "Three":"Three", "Four":"Four"] let cfDictInt: CFDictionary = [1:1, 2:2, 3:3, 4:4] as CFDictionary let cfDictDouble: CFDictionary = [1.1 : 1.1, 2.2 : 2.2, 3.3 : 3.3, 4.4 : 4.4] as CFDictionary let cfDictString: CFDictionary = ["One🍕":"One🍕", "Two":"Two", "Three":"Three", "Four":"Four"] as CFDictionary Tests.test("NSDictionary -> Swift (Dictionary)") { do { let dict: [Int: Int] = forcedCast(nsDictInt) expectEqual(dict, swiftDictInt) } do { let dictOpt: [Int: Int]? = condCast(nsDictInt) expectEqual(dictOpt!, swiftDictInt) } do { let dict: [Double: Double] = forcedCast(nsDictDouble) expectEqual(dict, swiftDictDouble) } do { let dictOpt: [Double: Double]? = condCast(nsDictDouble) expectEqual(dictOpt!, swiftDictDouble) } do { let dict: [String: String] = forcedCast(nsDictString) expectEqual(dict, swiftDictString) } do { let dictOpt: [String: String]? = condCast(nsDictString) expectEqual(dictOpt!, swiftDictString) } do { let dictOpt: [Int: Int]? = condCast(nsDictString) expectNil(dictOpt) } } Tests.test("NSDictionary -> Swift (Dictionary). Crashing Test Cases") { do { // Will this crash? let dictOpt: [Int: Int]? = condCast(nsDictString) expectNil(dictOpt) } // CHECK-LABEL: [ RUN ] BridgedCastFolding.NSDictionary -> Swift (Dictionary). Crashing Test Cases // CHECK: stderr>>> Could not cast value of type '{{.*}}' (0x{{[0-9a-f]*}}) to 'NSNumber' (0x{{[0-9a-f]*}}). // CHECK: stderr>>> OK: saw expected "crashed: sigabrt" // CHECK: [ OK ] BridgedCastFolding.NSDictionary -> Swift (Dictionary). Crashing Test Cases // // CHECK-OPT-LABEL: [ RUN ] BridgedCastFolding.NSDictionary -> Swift (Dictionary). Crashing Test Cases // CHECK-OPT: stderr>>> Could not cast value of type '{{.*}}' (0x{{[0-9a-f]*}}) to 'NSNumber' (0x{{[0-9a-f]*}}). // CHECK-OPT: stderr>>> OK: saw expected "crashed: sigabrt" // CHECK-OPT: [ OK ] BridgedCastFolding.NSDictionary -> Swift (Dictionary). Crashing Test Cases expectCrashLater() do { // Will this crash? let dictOpt: [Int: Int] = forcedCast(nsDictString) expectEqual(dictOpt.count, 4) } } // Check optimization of casts from NSSet to Swift Set let swiftSetInt: Set<Int> = [1, 2, 3, 4] let swiftSetDouble: Set<Double> = [1.1, 2.2, 3.3, 4.4] let swiftSetString: Set<String> = ["One🍕", "Two🍕", "Three🍕", "Four🍕"] let nsSetInt: NSSet = [1, 2, 3, 4] let nsSetDouble: NSSet = [1.1, 2.2, 3.3, 4.4] let nsSetString: NSSet = ["One🍕", "Two🍕", "Three🍕", "Four🍕"] let cfSetInt: CFSet = [1, 2, 3, 4] as NSSet let cfSetDouble: CFSet = [1.1, 2.2, 3.3, 4.4] as NSSet let cfSetString: CFSet = ["One🍕", "Two🍕", "Three🍕", "Four🍕"] as NSSet Tests.test("NSSet -> Swift Set") { do { let s: Set<Int> = forcedCast(nsSetInt) expectEqual(s, swiftSetInt) } do { let s: Set<Int>? = condCast(nsSetInt) expectEqual(s!, swiftSetInt) } do { let s: Set<Double> = forcedCast(nsSetDouble) expectEqual(s, swiftSetDouble) } do { let s: Set<Double>? = condCast(nsSetDouble) expectEqual(s!, swiftSetDouble) } do { let s: Set<String> = forcedCast(nsSetString) expectEqual(s, swiftSetString) } do { let s: Set<String>? = condCast(nsSetString) expectEqual(s, swiftSetString) } } // Check optimizations of casts from String to NSString Tests.test("String -> NSString") { do { let o: NSString = forcedCast(swiftString) expectEqual(o, nsString) } do { let o: NSString? = condCast(swiftString) expectEqual(o!, nsString) } } // Check crashing case from String -> NSNumber Tests.test("String -> NSNumber. Crashing Test Case") { do { let o: NSNumber! = condCast(swiftString) expectNil(o) } // CHECK-LABEL: [ RUN ] BridgedCastFolding.String -> NSNumber. Crashing Test Case // CHECK: stderr>>> Could not cast value of type '{{.*}}' (0x{{[0-9a-f]*}}) to 'NSNumber' (0x{{[0-9a-f]*}}). // CHECK: stderr>>> OK: saw expected "crashed: sigabrt" // CHECK: [ OK ] BridgedCastFolding.String -> NSNumber. Crashing Test Case // CHECK-OPT-LABEL: [ RUN ] BridgedCastFolding.String -> NSNumber. Crashing Test Case // CHECK-OPT: stderr>>> OK: saw expected "crashed: sig{{ill|trap}}" // CHECK-OPT: [ OK ] BridgedCastFolding.String -> NSNumber. Crashing Test Case expectCrashLater() do { let o: NSNumber = forcedCast(swiftString) expectEqual(o, 123) } } // Check optimizations of casts from Int to NSNumber Tests.test("Int -> NSNumber") { do { let o: NSNumber = forcedCast(swiftIntNumber) expectEqual(o, nsIntNumber) } do { let o: NSNumber? = condCast(swiftIntNumber) expectEqual(o!, nsIntNumber) } } // Check optimizations of casts from Double to NSNumber Tests.test("Double -> NSNumber") { do { let o: NSNumber = forcedCast(swiftDoubleNumber) expectEqual(o, nsDoubleNumber) } do { let o: NSNumber? = condCast(swiftDoubleNumber) expectEqual(o!, nsDoubleNumber) } } // Check optimization of casts from Swift Array to NSArray Tests.test("Swift<Int> -> NSArray (NSNumber)") { do { let arr: NSArray = forcedCast(swiftArrInt) expectEqual(arr, nsArrInt) } do { let arrOpt: NSArray? = condCast(swiftArrInt) expectEqual(arrOpt!, nsArrInt) } do { let arr: NSArray = forcedCast(swiftArrDouble) expectEqual(arr, nsArrDouble) } do { let arrOpt: NSArray? = condCast(swiftArrDouble) expectEqual(arrOpt!, nsArrDouble) } do { let arr: NSArray = forcedCast(swiftArrString) expectEqual(arr, nsArrString) } do { let arrOpt: NSArray? = condCast(swiftArrString) expectEqual(arrOpt!, nsArrString) } } // Check optimization of casts from Swift Dict to NSDict Tests.test("Swift Dict -> NSDict.") { do { let dict: NSDictionary = forcedCast(swiftDictInt) expectEqual(dict, nsDictInt) } do { let dictOpt: NSDictionary? = condCast(swiftDictInt) expectEqual(dictOpt!, nsDictInt) } do { let dict: NSDictionary = forcedCast(swiftDictDouble) expectEqual(dict, nsDictDouble) } do { let dictOpt: NSDictionary? = condCast(swiftDictDouble) expectEqual(dictOpt!, nsDictDouble) } do { let dict: NSDictionary = forcedCast(swiftDictString) expectEqual(dict, nsDictString) } do { let dictOpt: NSDictionary? = condCast(swiftDictString) expectEqual(dictOpt!, nsDictString) } } // Check optimization of casts from Swift Set to NSSet Tests.test("Swift Set -> NSSet") { do { let d: NSSet = forcedCast(swiftSetInt) expectEqual(d, nsSetInt) } do { let setOpt: NSSet? = condCast(swiftSetInt) expectEqual(setOpt!, nsSetInt) } do { let set: NSSet = forcedCast(swiftSetDouble) expectEqual(set, nsSetDouble) } do { let setOpt: NSSet? = condCast(swiftSetDouble) expectEqual(setOpt!, nsSetDouble) } do { let set: NSSet = forcedCast(swiftSetString) expectEqual(set, nsSetString) } do { let setOpt: NSSet? = condCast(swiftSetString) expectEqual(setOpt!, nsSetString) } } // Check optimizations of casts from String to CFString Tests.test("String -> CFString") { do { let o: CFString = forcedCast(swiftString) expectEqual(o, cfString) } do { let o: CFString? = condCast(swiftString) expectEqual(o!, cfString) } } // Check optimizations of casts from Int to CFNumber Tests.test("Int -> CFNumber") { do { let o: CFNumber = forcedCast(swiftIntNumber) expectEqual(o, cfIntNumber) } do { let o: CFNumber? = condCast(swiftIntNumber) expectEqual(o!, cfIntNumber) } } // Check optimization of casts from Swift Array to CFArray Tests.test("Swift Array -> CFArray") { do { let arr: CFArray = forcedCast(swiftArrInt) expectEqual(arr, cfArrInt) } do { let arrOpt: CFArray? = condCast(swiftArrInt) expectEqual(arrOpt!, cfArrInt) } } // Check optimization of casts from Swift Dict to CFDictionary Tests.test("Swift Dict -> CFDictionary") { do { let dict: CFDictionary = forcedCast(swiftDictInt) expectEqual(dict, cfDictInt) } do { let dictOpt: CFDictionary? = condCast(swiftDictInt) expectEqual(dictOpt!, cfDictInt) } } // Check optimization of casts from Swift Set to CFSet Tests.test("Swift Set -> CFSet") { do { let set: CFSet = forcedCast(swiftSetInt) expectEqual(set, cfSetInt) } do { let setOpt: CFSet? = condCast(swiftSetInt) expectEqual(setOpt! as NSSet, swiftSetInt as NSSet) } } // Check AnyHashable. We do not support this today... so just make sure we do // not miscompile. public class NSObjectSubclass : NSObject { } let anyHashable: AnyHashable = 0 class MyThing: Hashable { let name: String init(name: String) { self.name = name } deinit { Swift.print("Deinit \(name)") } func hash(into hasher: inout Hasher) {} static func ==(lhs: MyThing, rhs: MyThing) -> Bool { return false } } @inline(never) func doSomethingWithAnyHashable(_ item: AnyHashable) -> MyThing? { return item as? MyThing } Tests.test("AnyHashable") { do { let x = MyThing(name: "B") let r = doSomethingWithAnyHashable(x) expectEqual(r!.name, x.name) } }
apache-2.0
1ec8e9fcadd7ebe8b4ce3b39c24a690a
27.038941
114
0.646131
3.365302
false
true
false
false
Legoless/iOS-Course
2015-1/Lesson9/Gamebox/Gamebox/GameViewController.swift
1
1746
// // GameViewController.swift // Gamebox // // Created by Dal Rupnik on 08/11/15. // Copyright © 2015 Unified Sense. All rights reserved. // import UIKit class GameViewController: UIViewController { var currentGame : Game? let fontSize : CGFloat = 20.0 @IBOutlet weak var descriptionLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() if currentGame == nil { currentGame = Game(name: "My first game", priority: 2) currentGame?.notes = "My game note" } if let game = currentGame { let displayString = NSMutableAttributedString() displayString.appendAttributedString(NSAttributedString(string: "Name: ", attributes: [NSFontAttributeName : UIFont.systemFontOfSize(fontSize)])) displayString.appendAttributedString(NSAttributedString(string: "\(game.name)\n", attributes: [NSFontAttributeName : UIFont.boldSystemFontOfSize(fontSize)])) displayString.appendAttributedString(NSAttributedString(string: "Priority: ", attributes: [NSFontAttributeName : UIFont.systemFontOfSize(fontSize)])) if let notes = game.notes { displayString.appendAttributedString(NSAttributedString(string: "\nNotes:\n", attributes: [NSFontAttributeName : UIFont.systemFontOfSize(fontSize), NSForegroundColorAttributeName : UIColor.purpleColor(), NSKernAttributeName : 50.0])) displayString.appendAttributedString(NSAttributedString(string: notes, attributes: [NSFontAttributeName : UIFont.boldSystemFontOfSize(fontSize)])) } descriptionLabel.attributedText = displayString } } }
mit
955ee4c6824080b64b1be95bcb3112ff
40.547619
249
0.669914
5.684039
false
false
false
false
sleifer/SKLBits
bits/XCGNSLoggerDestination.swift
1
53226
// // XCGNSLoggerDestination.swift // NSLoggerSrc // // Created by Simeon Leifer on 7/15/16. // Copyright © 2016 droolingcat.com. All rights reserved. // import Foundation #if !os(watchOS) // constants from NSLogger // Constants for the "part key" field let partKeyMessageType: UInt8 = 0 let partKeyTimestampS: UInt8 = 1 // "seconds" component of timestamp let partKeyTimestampMS: UInt8 = 2 // milliseconds component of timestamp (optional, mutually exclusive with partKeyTimestampUS) let partKeyTimestampUS: UInt8 = 3 // microseconds component of timestamp (optional, mutually exclusive with partKeyTimestampMS) let partKeyThreadID: UInt8 = 4 let partKeyTag: UInt8 = 5 let partKeyLevel: UInt8 = 6 let partKeyMessage: UInt8 = 7 let partKeyImagWidth: UInt8 = 8 // messages containing an image should also contain a part with the image size let partKeyImageHeight: UInt8 = 9 // (this is mainly for the desktop viewer to compute the cell size without having to immediately decode the image) let partKeyMessageSeq: UInt8 = 10 // the sequential number of this message which indicates the order in which messages are generated let partKeyFilename: UInt8 = 11 // when logging, message can contain a file name let partKeyLinenumber: UInt8 = 12 // as well as a line number let partKeyFunctionname: UInt8 = 13 // and a function or method name // Constants for parts in logMsgTypeClientInfo let partKeyClientName: UInt8 = 20 let partKeyClientVersion: UInt8 = 21 let partKeyOSName: UInt8 = 22 let partKeyOSVersion: UInt8 = 23 let partKeyClientModel: UInt8 = 24 // For iPhone, device model (i.e 'iPhone', 'iPad', etc) let partKeyUniqueID: UInt8 = 25 // for remote device identification, part of logMsgTypeClientInfo // Area starting at which you may define your own constants let partKeyUserDefined: UInt8 = 100 // Constants for the "partType" field let partTypeString: UInt8 = 0 // Strings are stored as UTF-8 data let partTypeBinary: UInt8 = 1 // A block of binary data let partTypeInt16: UInt8 = 2 let partTypeInt32: UInt8 = 3 let partTypeInt64: UInt8 = 4 let partTypeImage: UInt8 = 5 // An image, stored in PNG format // Data values for the partKeyMessageType parts let logMsgTypeLog: UInt8 = 0 // A standard log message let logMsgTypeBlockStart: UInt8 = 1 // The start of a "block" (a group of log entries) let logMsgTypeBlockEnd: UInt8 = 2 // The end of the last started "block" let logMsgTypeClientInfo: UInt8 = 3 // Information about the client app let logMsgTypeDisconnect: UInt8 = 4 // Pseudo-message on the desktop side to identify client disconnects let logMsgTypeMark: UInt8 = 5 // Pseudo-message that defines a "mark" that users can place in the log flow let loggerServiceTypeSSL = "_nslogger-ssl._tcp" let loggerServiceType = "_nslogger._tcp" let loggerServiceDomain = "local." /* NSLogger packet format 4b total packet length not including this length value 2b part count part(s) 1b part key 1b part type nb part data */ // --- public struct XGNSLoggerNotification { public static let ConnectChanged = NSNotification.Name("XGNSLoggerNotification_ConnectChanged") } let ringBufferCapacity: UInt32 = 5000000 // 5 MB extension Array { mutating func orderedInsert(_ elem: Element, isOrderedBefore: (Element, Element) -> Bool) { var lo = 0 var hi = self.count - 1 while lo <= hi { let mid = (lo + hi)/2 if isOrderedBefore(self[mid], elem) { lo = mid + 1 } else if isOrderedBefore(elem, self[mid]) { hi = mid - 1 } else { self.insert(elem, at:mid) // found at position mid return } } self.insert(elem, at:lo) // not found, would be inserted at position lo } } class MessageBuffer: CustomStringConvertible, Equatable { private(set) var seq: Int32 private(set) var timestamp: CFAbsoluteTime private var buffer: [UInt8] init(_ leader: Bool = false) { if leader == true { self.seq = 0 } else { self.seq = 1 } self.timestamp = CFAbsoluteTimeGetCurrent() self.buffer = [UInt8]() if seq == 0 { append(toByteArray(CFSwapInt32HostToBig(UInt32(2)))) append(toByteArray(CFSwapInt16HostToBig(UInt16(0)))) } else { append(toByteArray(CFSwapInt32HostToBig(UInt32(8)))) append(toByteArray(CFSwapInt16HostToBig(UInt16(1)))) append(partKeyMessageSeq) append(partTypeInt32) append(toByteArray(CFSwapInt32HostToBig(UInt32(seq)))) } addTimestamp() addThreadID() } init?(_ fp: FileHandle?) { if let fp = fp { let atomSize = MemoryLayout<UInt32>.size let seqData = fp.readData(ofLength: atomSize) if seqData.count != atomSize { return nil } let seqValue = seqData.withUnsafeBytes { (bytes: UnsafePointer<UInt32>) -> Int32 in return Int32(CFSwapInt32HostToBig(bytes.pointee)) } self.seq = seqValue self.timestamp = 0 self.buffer = [UInt8]() let lenData = fp.readData(ofLength: atomSize) if lenData.count != atomSize { return nil } let lenValue = lenData.withUnsafeBytes { (bytes: UnsafePointer<UInt32>) -> Int32 in return Int32(CFSwapInt32HostToBig(bytes.pointee)) } let packetData = fp.readData(ofLength: Int(lenValue)) if packetData.count != Int(lenValue) { return nil } append(toByteArray(CFSwapInt32HostToBig(UInt32(lenValue)))) packetData.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Void in append(UnsafeBufferPointer(start: bytes, count: Int(lenValue))) } extractTimestamp() } else { return nil } } init(_ raw: [UInt8]) { let seqExtract: UInt32 = UnsafePointer(raw).withMemoryRebound(to: UInt32.self, capacity: 1) { return $0[0] } self.seq = Int32(CFSwapInt32HostToBig(seqExtract)) self.timestamp = 0 let data = raw[4..<raw.count] self.buffer = [UInt8]() self.buffer.append(contentsOf: data) extractTimestamp() } private func extractTimestamp() { var bytePtr = ptr() bytePtr = bytePtr.advanced(by: 4) var partCount: UInt16 = 0 UnsafeMutablePointer(bytePtr).withMemoryRebound(to: UInt16.self, capacity: 1) { partCount = CFSwapInt16HostToBig($0[0]) } if partCount >= 3 { bytePtr = bytePtr.advanced(by: 2) if bytePtr[0] == partKeyMessageSeq && bytePtr[1] == partTypeInt32 { bytePtr = bytePtr.advanced(by: 6) } var s: Double = 0 var us: Double = 0 #if __LP64__ if bytePtr[0] == partKeyTimestampS && bytePtr[1] == partTypeInt64 { bytePtr = bytePtr.advanced(by: 2) var high: UInt32 = 0 var low: UInt32 = 0 UnsafeMutablePointer(bytePtr).withMemoryRebound(to: UInt32.self, capacity: 1) { high = CFSwapInt32HostToBig($0[0]) } bytePtr = bytePtr.advanced(by: 4) UnsafeMutablePointer(bytePtr).withMemoryRebound(to: UInt32.self, capacity: 1) { low = CFSwapInt32HostToBig($0[0]) } bytePtr = bytePtr.advanced(by: 4) let u64: UInt64 = (UInt64(high) << 32) + UInt64(low) s = Double(u64) } #else if bytePtr[0] == partKeyTimestampS && bytePtr[1] == partTypeInt32 { bytePtr = bytePtr.advanced(by: 2) UnsafeMutablePointer(bytePtr).withMemoryRebound(to: UInt32.self, capacity: 1) { s = Double(CFSwapInt32HostToBig($0[0])) } bytePtr = bytePtr.advanced(by: 4) } #endif #if __LP64__ if bytePtr[0] == partKeyTimestampUS && bytePtr[1] == partTypeInt64 { bytePtr = bytePtr.advanced(by: 2) var high: UInt32 = 0 var low: UInt32 = 0 UnsafeMutablePointer(bytePtr).withMemoryRebound(to: UInt32.self, capacity: 1) { high = CFSwapInt32HostToBig($0[0]) } bytePtr = bytePtr.advanced(by: 4) UnsafeMutablePointer(bytePtr).withMemoryRebound(to: UInt32.self, capacity: 1) { low = CFSwapInt32HostToBig($0[0]) } bytePtr = bytePtr.advanced(by: 4) let u64: UInt64 = (UInt64(high) << 32) + UInt64(low) us = Double(u64) } #else if bytePtr[0] == partKeyTimestampUS && bytePtr[1] == partTypeInt32 { bytePtr = bytePtr.advanced(by: 2) UnsafeMutablePointer(bytePtr).withMemoryRebound(to: UInt32.self, capacity: 1) { us = Double(CFSwapInt32HostToBig($0[0])) / 1000000.0 } bytePtr = bytePtr.advanced(by: 4) } #endif self.timestamp = s + us } } func updateSeq(_ seq: Int32) { self.seq = seq var bytePtr = ptr() bytePtr = bytePtr.advanced(by: 4) var partCount: UInt16 = 0 UnsafeMutablePointer(bytePtr).withMemoryRebound(to: UInt16.self, capacity: 1) { partCount = CFSwapInt16HostToBig($0[0]) } if partCount >= 2 { bytePtr = bytePtr.advanced(by: 2) if bytePtr[0] == partKeyMessageSeq && bytePtr[1] == partTypeInt32 { bytePtr = bytePtr.advanced(by: 2) UnsafeMutablePointer(bytePtr).withMemoryRebound(to: UInt32.self, capacity: 1) { let newValue = UInt32(seq) $0[0] = CFSwapInt32HostToBig(newValue) } } } } func raw() -> [UInt8] { var rawArray: [UInt8] = toByteArray(CFSwapInt32HostToBig(UInt32(self.seq))) rawArray.append(contentsOf: buffer) return rawArray } private func toByteArray<T>(_ value: T) -> [UInt8] { var data = [UInt8](repeating: 0, count: MemoryLayout<T>.size) data.withUnsafeMutableBufferPointer { UnsafeMutableRawPointer($0.baseAddress!).storeBytes(of: value, as: T.self) } return data } private func append(_ value: UInt8) { buffer.append(value) } private func append<C: Collection>(_ newElements: C) where C.Iterator.Element == UInt8 { buffer.append(contentsOf: newElements) } private func append<S: Sequence>(_ newElements: S) where S.Iterator.Element == UInt8 { buffer.append(contentsOf: newElements) } func ptr() -> UnsafeMutablePointer<UInt8> { return UnsafeMutablePointer<UInt8>(mutating: buffer) } func count() -> Int { return buffer.count } private func prepareForPart(ofSize byteCount: Int) { var bytePtr = ptr() UnsafeMutablePointer(bytePtr).withMemoryRebound(to: UInt32.self, capacity: 1) { let currentValue = CFSwapInt32HostToBig($0[0]) let newValue = currentValue + UInt32(byteCount) $0[0] = CFSwapInt32HostToBig(newValue) } bytePtr = bytePtr.advanced(by: 4) UnsafeMutablePointer(bytePtr).withMemoryRebound(to: UInt16.self, capacity: 1) { let currentValue = CFSwapInt16HostToBig($0[0]) let newValue = currentValue + 1 $0[0] = CFSwapInt16HostToBig(newValue) } } func addInt16(_ value: UInt16, key: UInt8) { prepareForPart(ofSize: 4) append(key) append(partTypeInt16) append(toByteArray(CFSwapInt16HostToBig(value))) } func addInt32(_ value: UInt32, key: UInt8) { prepareForPart(ofSize: 6) append(key) append(partTypeInt32) append(toByteArray(CFSwapInt32HostToBig(value))) } #if __LP64__ func addInt64(_ value: UInt64, key: UInt8) { prepareForPart(ofSize: 10) append(key) append(partTypeInt64) append(toByteArray(CFSwapInt32HostToBig(UInt32(value >> 32)))) append(toByteArray(CFSwapInt32HostToBig(UInt32(value)))) } #endif func addString(_ value: String, key: UInt8) { let bytes = value.utf8 let len = bytes.count prepareForPart(ofSize: 6 + len) append(key) append(partTypeString) append(toByteArray(CFSwapInt32HostToBig(UInt32(len)))) if len > 0 { append(bytes) } } func addData(_ value: Data, key: UInt8, type: UInt8) { let len = value.count prepareForPart(ofSize: 6 + len) append(key) append(type) append(toByteArray(CFSwapInt32HostToBig(UInt32(len)))) if len > 0 { value.withUnsafeBytes({ (uptr: UnsafePointer<UInt8>) -> Void in append(UnsafeBufferPointer(start: uptr, count: len)) }) } } func addTimestamp() { let t = self.timestamp let s = floor(t) let us = floor((t - s) * 1000000) #if __LP64__ addInt64(s, key: partKeyTimestampS) addInt64(us, key: partKeyTimestampUS) #else addInt32(UInt32(s), key: partKeyTimestampS) addInt32(UInt32(us), key: partKeyTimestampUS) #endif } func addThreadID() { var name: String = "unknown" if Thread.isMainThread { name = "main" } else { if let threadName = Thread.current.name, !threadName.isEmpty { name = threadName } else if let queueName = String(validatingUTF8: __dispatch_queue_get_label(nil)), !queueName.isEmpty { name = queueName } else { name = String(format:"%p", Thread.current) } } addString(name, key: partKeyThreadID) } var description: String { return "\(type(of: self)), seq #\(seq)" } } func == (lhs: MessageBuffer, rhs: MessageBuffer) -> Bool { return lhs === rhs } #if os(iOS) || os(tvOS) import UIKit public typealias ImageType = UIImage #elseif os(OSX) import AppKit public typealias ImageType = NSImage #endif public enum XCGNSLoggerOfflineOption { case drop case inMemory case runFile case ringFile } public class XCGNSLoggerDestination: NSObject, XCGLogDestinationProtocol, NetServiceBrowserDelegate { public var owner: XCGLogger public var identifier: String = "" public var outputLogLevel: XCGLogger.LogLevel = .debug public override var debugDescription: String { return "\(extractClassName(self)): \(identifier) - LogLevel: \(outputLogLevel)" } public init(owner: XCGLogger, identifier: String = "") { self.owner = owner self.identifier = identifier } public func processLogDetails(_ logDetails: XCGLogDetails) { output(logDetails) } public func processInternalLogDetails(_ logDetails: XCGLogDetails) { output(logDetails) } public func isEnabledForLogLevel (_ logLevel: XCGLogger.LogLevel) -> Bool { return logLevel >= self.outputLogLevel } private func convertLogLevel(_ level: XCGLogger.LogLevel) -> Int { switch level { case .severe: return 0 case .error: return 1 case .warning: return 2 case .info: return 3 case .debug: return 4 case .verbose: return 5 case .none: return 3 } } func output(_ logDetails: XCGLogDetails) { if logDetails.logLevel == .none { return } logMessage(logDetails.logMessage, filename: logDetails.fileName, lineNumber: logDetails.lineNumber, functionName: logDetails.functionName, domain: nil, level: convertLogLevel(logDetails.logLevel)) } /** If set, will only connect to receiver with name 'hostName' */ public var hostName: String? public var offlineBehavior: XCGNSLoggerOfflineOption = .drop private var runFilePath: String? private var runFileIndex: UInt64 = 0 private var runFileCount: Int = 0 private var ringFile: RingBufferFile? private let queue = DispatchQueue(label: "message queue") private var browser: NetServiceBrowser? private var service: NetService? private var logStream: CFWriteStream? private var connected: Bool = false private var messageSeq: Int32 = 1 private var messageQueue: [MessageBuffer] = [] private var messageBeingSent: MessageBuffer? private var sentCount: Int = 0 public var isBrowsing: Bool { if self.browser == nil { return true } return false } public var isConnected: Bool { return self.connected } #if DEBUG public func resetSeq() { messageSeq = 1 } #endif public func startBonjourBrowsing() { self.browser = NetServiceBrowser() if let browser = self.browser { browser.delegate = self browser.searchForServices(ofType: loggerServiceType, inDomain: loggerServiceDomain) } } public func stopBonjourBrowsing() { if let browser = self.browser { browser.stop() self.browser = nil } } func connect(to service: NetService) { print("found service: \(service)") let serviceName = service.name if let hostName = self.hostName { if hostName.caseInsensitiveCompare(serviceName) != .orderedSame { print("service name: \(serviceName) does not match requested service name: \(hostName)") return } } else { if let txtData = service.txtRecordData() { // swiftlint:disable:next force_cast if let txtDict = CFNetServiceCreateDictionaryWithTXTData(nil, txtData as CFData) as! CFDictionary? { var mismatch: Bool = true if let value = CFDictionaryGetValue(txtDict, "filterClients") as CFTypeRef? { // swiftlint:disable:next force_cast if CFGetTypeID(value) == CFStringGetTypeID() && CFStringCompare(value as! CFString, "1" as CFString!, CFStringCompareFlags(rawValue: CFOptionFlags(0))) == .compareEqualTo { mismatch = false } } if mismatch { print("service: \(serviceName) requested that only clients looking for it do connect") return } } } } self.service = service if tryConnect() == false { print("connection attempt failed") } } func disconnect(from service: NetService) { if self.service == service { print("NetService went away: \(service)") service.stop() self.service = nil } } func tryConnect() -> Bool { if self.logStream != nil { return true } if let service = self.service { var outputStream: OutputStream? service.getInputStream(nil, outputStream: &outputStream) self.logStream = outputStream let eventTypes: CFStreamEventType = [.openCompleted, .canAcceptBytes, .errorOccurred, .endEncountered] let options: CFOptionFlags = eventTypes.rawValue let info = Unmanaged.passUnretained(self).toOpaque() var context: CFStreamClientContext = CFStreamClientContext(version: 0, info: info, retain: nil, release: nil, copyDescription: nil) CFWriteStreamSetClient(self.logStream, options, { (_ ws: CFWriteStream?, _ event: CFStreamEventType, _ info: UnsafeMutableRawPointer?) in let me = Unmanaged<XCGNSLoggerDestination>.fromOpaque(info!).takeUnretainedValue() if let logStream = me.logStream, let ws = ws, ws == logStream { switch event { case CFStreamEventType.openCompleted: me.connected = true NotificationCenter.default.post(name: XGNSLoggerNotification.ConnectChanged, object: me) me.stopBonjourBrowsing() me.pushClientInfoToQueue() me.writeMoreData() case CFStreamEventType.canAcceptBytes: me.writeMoreData() case CFStreamEventType.errorOccurred: let error: CFError = CFWriteStreamCopyError(ws) print("Logger stream error: \(error)") me.streamTerminated() case CFStreamEventType.endEncountered: print("Logger stream end encountered") me.streamTerminated() default: print("Logger should not be here") break } } }, &context) CFWriteStreamScheduleWithRunLoop(self.logStream, CFRunLoopGetCurrent(), CFRunLoopMode.commonModes) if CFWriteStreamOpen(self.logStream) { print("stream open attempt, waiting for open completion") return true } print("stream open failed.") CFWriteStreamSetClient(self.logStream, 0, nil, nil) if CFWriteStreamGetStatus(self.logStream) == .open { CFWriteStreamClose(self.logStream) } CFWriteStreamUnscheduleFromRunLoop(self.logStream, CFRunLoopGetCurrent(), CFRunLoopMode.commonModes) stopBonjourBrowsing() startBonjourBrowsing() } return false } public func disconnect() { if let logStream = self.logStream { CFWriteStreamSetClient(logStream, 0, nil, nil) CFWriteStreamClose(logStream) CFWriteStreamUnscheduleFromRunLoop(logStream, CFRunLoopGetCurrent(), CFRunLoopMode.commonModes) self.logStream = nil } self.connected = false queue.async { self.reconcileOfflineStatus() } NotificationCenter.default.post(name: XGNSLoggerNotification.ConnectChanged, object: self) } func writeMoreData() { queue.async { self.reconcileOfflineStatus() if let logStream = self.logStream { if CFWriteStreamCanAcceptBytes(logStream) == true { self.reconcileOnlineStatus() if self.messageBeingSent == nil && self.messageQueue.count > 0 { self.messageBeingSent = self.messageQueue.first if let msg = self.messageBeingSent { msg.updateSeq(self.messageSeq) self.messageSeq += 1 } self.sentCount = 0 } if let msg = self.messageBeingSent { if self.sentCount < msg.count() { let ptr = msg.ptr().advanced(by: self.sentCount) let toWrite = msg.count() - self.sentCount let written = CFWriteStreamWrite(logStream, ptr, toWrite) if written < 0 { print("CFWriteStreamWrite returned error: \(written)") self.messageBeingSent = nil } else { self.sentCount += written if self.sentCount == msg.count() { if let idx = self.messageQueue.index(where: { $0 == self.messageBeingSent }) { self.messageQueue.remove(at: idx) } self.messageBeingSent = nil self.queue.async { self.writeMoreData() } } } } } } } } } func streamTerminated() { disconnect() if tryConnect() == false { print("connection attempt failed") } } func pushClientInfoToQueue() { let bundle = Bundle.main var encoder = MessageBuffer(true) encoder.addInt32(UInt32(logMsgTypeClientInfo), key: partKeyMessageType) if let version = bundle.infoDictionary?[kCFBundleVersionKey as String] as? String { encoder.addString(version, key: partKeyClientVersion) } if let name = bundle.infoDictionary?[kCFBundleNameKey as String] as? String { encoder.addString(name, key: partKeyClientName) } #if os(iOS) if Thread.isMainThread || Thread.isMultiThreaded() { autoreleasepool { let device = UIDevice.current encoder.addString(device.name, key: partKeyUniqueID) encoder.addString(device.systemVersion, key: partKeyOSVersion) encoder.addString(device.systemName, key: partKeyOSName) encoder.addString(device.model, key: partKeyClientModel) } } #elseif os(OSX) var osName: String? var osVersion: String? autoreleasepool { if let versionString = NSDictionary(contentsOfFile: "/System/Library/CoreServices/SystemVersion.plist")?.object(forKey: "ProductVersion") as? String, !versionString.isEmpty { osName = "macOS" osVersion = versionString } } var u: utsname = utsname() if uname(&u) == 0 { osName = withUnsafePointer(to: &u.sysname, { (ptr) -> String? in let int8Ptr = unsafeBitCast(ptr, to: UnsafePointer<Int8>.self) return String(validatingUTF8: int8Ptr) }) osVersion = withUnsafePointer(to: &u.release, { (ptr) -> String? in let int8Ptr = unsafeBitCast(ptr, to: UnsafePointer<Int8>.self) return String(validatingUTF8: int8Ptr) }) } else { osName = "macOS" osVersion = "" } encoder.addString(osVersion!, key: partKeyOSVersion) encoder.addString(osName!, key: partKeyOSName) encoder.addString("<unknown>", key: partKeyClientModel) #endif pushMessageToQueue(encoder) } func appendToRunFile(_ encoder: MessageBuffer) { if runFilePath == nil { do { let fm = FileManager.default let urls = fm.urls(for: .cachesDirectory, in: .userDomainMask) let identifier = Bundle.main.bundleIdentifier if let identifier = identifier, urls.count > 0 { let fileName = identifier + ".xcgnsrun" var url = urls[0] url.appendPathComponent(fileName) runFilePath = url.path if let runFilePath = runFilePath { if fm.fileExists(atPath: runFilePath) { try fm.removeItem(atPath: runFilePath) } let created = fm.createFile(atPath: runFilePath, contents: nil, attributes: nil) if created == false { self.runFilePath = nil } else { self.runFileIndex = 0 self.runFileCount = 0 } } } } catch { } } if let runFilePath = runFilePath { let fp = FileHandle(forWritingAtPath: runFilePath) fp?.seekToEndOfFile() var seq = CFSwapInt32HostToBig(UInt32(encoder.seq)) let data1 = Data(buffer: UnsafeBufferPointer<UInt32>(start: &seq, count: 1)) fp?.write(data1) let data2 = Data(bytesNoCopy: encoder.ptr(), count: encoder.count(), deallocator: .none) fp?.write(data2) fp?.closeFile() self.runFileCount += 1 } } func readFromRunFile() -> MessageBuffer? { var encoder: MessageBuffer? = nil if let runFilePath = self.runFilePath, runFileCount > 0 { let fp = FileHandle(forUpdatingAtPath: runFilePath) fp?.seek(toFileOffset: runFileIndex) encoder = MessageBuffer(fp) if let encoder = encoder { self.runFileCount -= 1 self.runFileIndex += UInt64(encoder.count() + MemoryLayout<Int32>.size) if self.runFileCount == 0 { fp?.truncateFile(atOffset: 0) } } fp?.closeFile() } return encoder } func createRingFile() throws { let fm = FileManager.default let urls = fm.urls(for: .cachesDirectory, in: .userDomainMask) let identifier = Bundle.main.bundleIdentifier if let identifier = identifier, urls.count > 0 { let fileName = identifier + ".xcgnsring" var url = urls[0] url.appendPathComponent(fileName) self.ringFile = RingBufferFile(capacity: ringBufferCapacity, filePath: url.path) } } func appendToRingFile(_ encoder: MessageBuffer) throws { if ringFile == nil { try createRingFile() } if let ringFile = self.ringFile { ringFile.push(encoder.raw()) } } func readFromRingFile() throws -> MessageBuffer? { if ringFile == nil { try createRingFile() } if let ringFile = self.ringFile { if let data: [UInt8] = ringFile.pop() { return MessageBuffer(data) } } return nil } func reconcileOfflineStatus() { if connected == false { switch offlineBehavior { case .drop: self.messageQueue.removeAll() case .inMemory: // nothing to do, MessageBuffer(s) are put in messageQueue by default break case .runFile: for msg in self.messageQueue { appendToRunFile(msg) } self.messageQueue.removeAll() case .ringFile: do { for msg in self.messageQueue { try appendToRingFile(msg) } } catch { print("Error: \(error)") } self.messageQueue.removeAll() } } } func reconcileOnlineStatus() { if connected == true { if self.messageBeingSent == nil { if offlineBehavior == .runFile, let encoder = readFromRunFile() { self.messageQueue.orderedInsert(encoder) { $0.timestamp < $1.timestamp } } do { if offlineBehavior == .ringFile, let encoder = try readFromRingFile() { self.messageQueue.orderedInsert(encoder) { $0.timestamp < $1.timestamp } } } catch { print("Error: \(error)") } } } } func pushMessageToQueue(_ encoder: MessageBuffer) { queue.async { self.messageQueue.orderedInsert(encoder) { $0.timestamp < $1.timestamp } self.writeMoreData() } } func logMessage(_ message: String?, filename: String?, lineNumber: Int?, functionName: String?, domain: String?, level: Int?) { let encoder = MessageBuffer() encoder.addInt32(UInt32(logMsgTypeLog), key: partKeyMessageType) if let domain = domain, domain.characters.count > 0 { encoder.addString(domain, key: partKeyTag) } if let level = level, level != 0 { encoder.addInt16(UInt16(level), key: partKeyLevel) } if let filename = filename, filename.characters.count > 0 { encoder.addString(filename, key: partKeyFilename) } if let lineNumber = lineNumber, lineNumber != 0 { encoder.addInt32(UInt32(lineNumber), key: partKeyLinenumber) } if let functionName = functionName, functionName.characters.count > 0 { encoder.addString(functionName, key: partKeyFunctionname) } if let message = message, message.characters.count > 0 { encoder.addString(message, key: partKeyMessage) } else { encoder.addString("", key: partKeyMessage) } pushMessageToQueue(encoder) } func logMark(_ message: String?) { let encoder = MessageBuffer() encoder.addInt32(UInt32(logMsgTypeMark), key: partKeyMessageType) if let message = message, message.characters.count > 0 { encoder.addString(message, key: partKeyMessage) } else { let df = CFDateFormatterCreate(nil, nil, .shortStyle, .mediumStyle) if let str = CFDateFormatterCreateStringWithAbsoluteTime(nil, df, CFAbsoluteTimeGetCurrent()) as String? { encoder.addString(str, key: partKeyMessage) } } pushMessageToQueue(encoder) } func logBlockStart(_ message: String?) { let encoder = MessageBuffer() encoder.addInt32(UInt32(logMsgTypeBlockStart), key: partKeyMessageType) if let message = message, message.characters.count > 0 { encoder.addString(message, key: partKeyMessage) } pushMessageToQueue(encoder) } func logBlockEnd() { let encoder = MessageBuffer() encoder.addInt32(UInt32(logMsgTypeBlockEnd), key: partKeyMessageType) pushMessageToQueue(encoder) } func logImage(_ image: ImageType?, filename: String?, lineNumber: Int?, functionName: String?, domain: String?, level: Int?) { let encoder = MessageBuffer() encoder.addInt32(UInt32(logMsgTypeLog), key: partKeyMessageType) if let domain = domain, domain.characters.count > 0 { encoder.addString(domain, key: partKeyTag) } if let level = level, level != 0 { encoder.addInt16(UInt16(level), key: partKeyLevel) } if let filename = filename, filename.characters.count > 0 { encoder.addString(filename, key: partKeyFilename) } if let lineNumber = lineNumber, lineNumber != 0 { encoder.addInt32(UInt32(lineNumber), key: partKeyLinenumber) } if let functionName = functionName, functionName.characters.count > 0 { encoder.addString(functionName, key: partKeyFunctionname) } if let image = image { var data: Data? var width: UInt32 = 0 var height: UInt32 = 0 #if os(iOS) data = UIImagePNGRepresentation(image) width = UInt32(image.size.width) height = UInt32(image.size.height) #elseif os(OSX) image.lockFocus() let bitmap = NSBitmapImageRep(focusedViewRect: NSRect(x: 0, y: 0, width: image.size.width, height: image.size.height)) image.unlockFocus() width = UInt32(image.size.width) height = UInt32(image.size.height) data = bitmap?.representation(using: .PNG, properties: [:]) #endif if let data = data { encoder.addInt32(width, key: partKeyImagWidth) encoder.addInt32(height, key: partKeyImageHeight) encoder.addData(data, key: partKeyMessage, type: partTypeImage) } } pushMessageToQueue(encoder) } func logData(_ data: Data?, filename: String?, lineNumber: Int?, functionName: String?, domain: String?, level: Int?) { let encoder = MessageBuffer() encoder.addInt32(UInt32(logMsgTypeLog), key: partKeyMessageType) if let domain = domain, domain.characters.count > 0 { encoder.addString(domain, key: partKeyTag) } if let level = level, level != 0 { encoder.addInt16(UInt16(level), key: partKeyLevel) } if let filename = filename, filename.characters.count > 0 { encoder.addString(filename, key: partKeyFilename) } if let lineNumber = lineNumber, lineNumber != 0 { encoder.addInt32(UInt32(lineNumber), key: partKeyLinenumber) } if let functionName = functionName, functionName.characters.count > 0 { encoder.addString(functionName, key: partKeyFunctionname) } if let data = data { encoder.addData(data, key: partKeyMessage, type: partTypeBinary) } pushMessageToQueue(encoder) } // MARK: NetServiceBrowserDelegate public func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) { connect(to: service) } public func netServiceBrowser(_ browser: NetServiceBrowser, didRemove service: NetService, moreComing: Bool) { disconnect(from: service) } } extension XCGLogger { class func convertLogLevel(_ level: XCGLogger.LogLevel) -> Int { switch level { case .severe: return 0 case .error: return 1 case .warning: return 2 case .info: return 3 case .debug: return 4 case .verbose: return 5 case .none: return 3 } } func convertLogLevel(_ level: XCGLogger.LogLevel) -> Int { switch level { case .severe: return 0 case .error: return 1 case .warning: return 2 case .info: return 3 case .debug: return 4 case .verbose: return 5 case .none: return 3 } } func onAllNSLogger(_ level: XCGLogger.LogLevel, closure: (XCGNSLoggerDestination) -> Void) { for logDestination in self.logDestinations { if logDestination.isEnabledForLogLevel(level) { if let logger = logDestination as? XCGNSLoggerDestination { closure(logger) } } } } func onAllNonNSLogger(_ level: XCGLogger.LogLevel, closure: (XCGLogDestinationProtocol) -> Void) { for logDestination in self.logDestinations { if logDestination.isEnabledForLogLevel(level) { if logDestination is XCGNSLoggerDestination == false { closure(logDestination) } } } } // MARK: mark public class func mark( _ closure: @autoclosure () -> String?) { self.defaultInstance().mark(closure) } public func mark( _ closure: @autoclosure () -> String?) { if let value = closure() { onAllNSLogger(.none) { logger in logger.logMark(value) } onAllNonNSLogger(.none) { logger in let logDetails = XCGLogDetails(logLevel: .none, date: Date(), logMessage: "<mark: \(value)>", functionName: "", fileName: "", lineNumber: 0) logger.processLogDetails(logDetails) } } } // MARK: block start public class func blockStart( _ closure: @autoclosure () -> String?) { self.defaultInstance().blockStart(closure) } public func blockStart( _ closure: @autoclosure () -> String?) { if let value = closure() { onAllNSLogger(.none) { logger in logger.logBlockStart(value) } onAllNonNSLogger(.none) { logger in let logDetails = XCGLogDetails(logLevel: .none, date: Date(), logMessage: "<block start: \(value)>", functionName: "", fileName: "", lineNumber: 0) logger.processLogDetails(logDetails) } } } // MARK: block end public class func blockEnd() { self.defaultInstance().blockEnd() } public func blockEnd() { onAllNSLogger(.none) { logger in logger.logBlockEnd() } onAllNonNSLogger(.none) { logger in let logDetails = XCGLogDetails(logLevel: .none, date: Date(), logMessage: "<block end>", functionName: "", fileName: "", lineNumber: 0) logger.processLogDetails(logDetails) } } // MARK: verbose public class func verbose( _ closure: @autoclosure () -> ImageType?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().verbose(closure()) } public class func verbose(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> ImageType?) { self.defaultInstance().verbose(closure()) } public func verbose( _ closure: @autoclosure () -> ImageType?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { if let value = closure() { onAllNSLogger(.verbose) { logger in logger.logImage(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.verbose)) } onAllNonNSLogger(.verbose) { logger in let logDetails = XCGLogDetails(logLevel: .verbose, date: Date(), logMessage: "<image>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public func verbose(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> ImageType?) { if let value = closure() { onAllNSLogger(.verbose) { logger in logger.logImage(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.verbose)) } onAllNonNSLogger(.verbose) { logger in let logDetails = XCGLogDetails(logLevel: .verbose, date: Date(), logMessage: "<image>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public class func verbose( _ closure: @autoclosure () -> Data?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().verbose(closure()) } public class func verbose(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> Data?) { self.defaultInstance().verbose(closure()) } public func verbose( _ closure: @autoclosure () -> Data?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { if let value = closure() { onAllNSLogger(.verbose) { logger in logger.logData(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.verbose)) } onAllNonNSLogger(.verbose) { logger in let logDetails = XCGLogDetails(logLevel: .verbose, date: Date(), logMessage: "<data>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public func verbose(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> Data?) { if let value = closure() { onAllNSLogger(.verbose) { logger in logger.logData(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.verbose)) } onAllNonNSLogger(.verbose) { logger in let logDetails = XCGLogDetails(logLevel: .verbose, date: Date(), logMessage: "<data>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } // MARK: debug public class func debug( _ closure: @autoclosure () -> ImageType?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().debug(closure()) } public class func debug(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> ImageType?) { self.defaultInstance().debug(closure()) } public func debug( _ closure: @autoclosure () -> ImageType?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { if let value = closure() { onAllNSLogger(.debug) { logger in logger.logImage(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.debug)) } onAllNonNSLogger(.debug) { logger in let logDetails = XCGLogDetails(logLevel: .debug, date: Date(), logMessage: "<image>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public func debug(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> ImageType?) { if let value = closure() { onAllNSLogger(.debug) { logger in logger.logImage(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.debug)) } onAllNonNSLogger(.debug) { logger in let logDetails = XCGLogDetails(logLevel: .debug, date: Date(), logMessage: "<image>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public class func debug( _ closure: @autoclosure () -> Data?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().debug(closure()) } public class func debug(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> Data?) { self.defaultInstance().debug(closure()) } public func debug( _ closure: @autoclosure () -> Data?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { if let value = closure() { onAllNSLogger(.debug) { logger in logger.logData(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.debug)) } onAllNonNSLogger(.debug) { logger in let logDetails = XCGLogDetails(logLevel: .debug, date: Date(), logMessage: "<data>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public func debug(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> Data?) { if let value = closure() { onAllNSLogger(.debug) { logger in logger.logData(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.debug)) } onAllNonNSLogger(.debug) { logger in let logDetails = XCGLogDetails(logLevel: .debug, date: Date(), logMessage: "<data>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } // MARK: info public class func info( _ closure: @autoclosure () -> ImageType?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().info(closure()) } public class func info(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> ImageType?) { self.defaultInstance().info(closure()) } public func info( _ closure: @autoclosure () -> ImageType?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { if let value = closure() { onAllNSLogger(.info) { logger in logger.logImage(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.info)) } onAllNonNSLogger(.info) { logger in let logDetails = XCGLogDetails(logLevel: .info, date: Date(), logMessage: "<image>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public func info(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> ImageType?) { if let value = closure() { onAllNSLogger(.info) { logger in logger.logImage(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.info)) } onAllNonNSLogger(.info) { logger in let logDetails = XCGLogDetails(logLevel: .info, date: Date(), logMessage: "<image>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public class func info( _ closure: @autoclosure () -> Data?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().info(closure()) } public class func info(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> Data?) { self.defaultInstance().info(closure()) } public func info( _ closure: @autoclosure () -> Data?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { if let value = closure() { onAllNSLogger(.info) { logger in logger.logData(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.info)) } onAllNonNSLogger(.info) { logger in let logDetails = XCGLogDetails(logLevel: .info, date: Date(), logMessage: "<data>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public func info(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> Data?) { if let value = closure() { onAllNSLogger(.info) { logger in logger.logData(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.info)) } onAllNonNSLogger(.info) { logger in let logDetails = XCGLogDetails(logLevel: .verbose, date: Date(), logMessage: "<data>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } // MARK: warning public class func warning( _ closure: @autoclosure () -> ImageType?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().warning(closure()) } public class func warning(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> ImageType?) { self.defaultInstance().warning(closure()) } public func warning( _ closure: @autoclosure () -> ImageType?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { if let value = closure() { onAllNSLogger(.warning) { logger in logger.logImage(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.warning)) } onAllNonNSLogger(.warning) { logger in let logDetails = XCGLogDetails(logLevel: .warning, date: Date(), logMessage: "<image>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public func warning(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> ImageType?) { if let value = closure() { onAllNSLogger(.warning) { logger in logger.logImage(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.warning)) } onAllNonNSLogger(.warning) { logger in let logDetails = XCGLogDetails(logLevel: .warning, date: Date(), logMessage: "<image>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public class func warning( _ closure: @autoclosure () -> Data?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().warning(closure()) } public class func warning(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> Data?) { self.defaultInstance().warning(closure()) } public func warning( _ closure: @autoclosure () -> Data?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { if let value = closure() { onAllNSLogger(.warning) { logger in logger.logData(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.warning)) } onAllNonNSLogger(.warning) { logger in let logDetails = XCGLogDetails(logLevel: .warning, date: Date(), logMessage: "<data>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public func warning(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> Data?) { if let value = closure() { onAllNSLogger(.warning) { logger in logger.logData(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.warning)) } onAllNonNSLogger(.warning) { logger in let logDetails = XCGLogDetails(logLevel: .warning, date: Date(), logMessage: "<data>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } // MARK: error public class func error( _ closure: @autoclosure () -> ImageType?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().error(closure()) } public class func error(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> ImageType?) { self.defaultInstance().error(closure()) } public func error( _ closure: @autoclosure () -> ImageType?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { if let value = closure() { onAllNSLogger(.error) { logger in logger.logImage(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.error)) } onAllNonNSLogger(.error) { logger in let logDetails = XCGLogDetails(logLevel: .error, date: Date(), logMessage: "<image>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public func error(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> ImageType?) { if let value = closure() { onAllNSLogger(.error) { logger in logger.logImage(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.error)) } onAllNonNSLogger(.error) { logger in let logDetails = XCGLogDetails(logLevel: .error, date: Date(), logMessage: "<image>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public class func error( _ closure: @autoclosure () -> Data?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().error(closure()) } public class func error(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> Data?) { self.defaultInstance().error(closure()) } public func error( _ closure: @autoclosure () -> Data?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { if let value = closure() { onAllNSLogger(.error) { logger in logger.logData(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.error)) } onAllNonNSLogger(.error) { logger in let logDetails = XCGLogDetails(logLevel: .error, date: Date(), logMessage: "<data>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public func error(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> Data?) { if let value = closure() { onAllNSLogger(.error) { logger in logger.logData(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.error)) } onAllNonNSLogger(.error) { logger in let logDetails = XCGLogDetails(logLevel: .error, date: Date(), logMessage: "<data>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } // MARK: severe public class func severe( _ closure: @autoclosure () -> ImageType?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().severe(closure()) } public class func severe(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> ImageType?) { self.defaultInstance().severe(closure()) } public func severe( _ closure: @autoclosure () -> ImageType?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { if let value = closure() { onAllNSLogger(.severe) { logger in logger.logImage(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.severe)) } onAllNonNSLogger(.severe) { logger in let logDetails = XCGLogDetails(logLevel: .severe, date: Date(), logMessage: "<image>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public func severe(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> ImageType?) { if let value = closure() { onAllNSLogger(.severe) { logger in logger.logImage(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.severe)) } onAllNonNSLogger(.severe) { logger in let logDetails = XCGLogDetails(logLevel: .severe, date: Date(), logMessage: "<image>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public class func severe( _ closure: @autoclosure () -> Data?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { self.defaultInstance().severe(closure()) } public class func severe(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> Data?) { self.defaultInstance().severe(closure()) } public func severe( _ closure: @autoclosure () -> Data?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) { if let value = closure() { onAllNSLogger(.severe) { logger in logger.logData(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.severe)) } onAllNonNSLogger(.severe) { logger in let logDetails = XCGLogDetails(logLevel: .severe, date: Date(), logMessage: "<data>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } public func severe(_ functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> Data?) { if let value = closure() { onAllNSLogger(.severe) { logger in logger.logData(value, filename: fileName, lineNumber: lineNumber, functionName: functionName, domain: nil, level: convertLogLevel(.severe)) } onAllNonNSLogger(.severe) { logger in let logDetails = XCGLogDetails(logLevel: .severe, date: Date(), logMessage: "<data>", functionName: functionName, fileName: fileName, lineNumber: lineNumber) logger.processLogDetails(logDetails) } } } } #endif
mit
bfd49a79413fee7d21ce4951a7c017bf
33.053103
198
0.699746
3.562822
false
false
false
false
songzhw/2iOS
ServerAndWebView/ServerAndWebView/webServer.swift
1
982
import Foundation import GCDWebServer class Server { let server = GCDWebServer() func initWebServer() -> URL?{ server.addDefaultHandler(forMethod: "GET", request: GCDWebServerRequest.self, processBlock: { request in print("szw request = \(request.url), path = \(request.path), query = \(request.query)") let html = """ <html> <head> <style type="text/css">@font-face { font-family: 'jb'; src: url('/fonts/abc.ttf');} </style> <title>my t itle</title> </head> <body> <h1>hello world: ${request.url}</h1><p/> <span style="font-family:'jb'; font-size:25px">second line</span><p/> <img src="/a.png"/> </body> </html> """ return GCDWebServerDataResponse(html: html) }) server.start(withPort: 8322, bonjourName: "MyServer") return server.serverURL } func stop() { if(server.isRunning){ server.stop() } } func isRunning() -> Bool{ return server.isRunning } }
apache-2.0
a8d807554e570001ad9037bd3e1c6d32
23.55
108
0.602851
3.507143
false
false
false
false
BridgeTheGap/KRWalkThrough
KRWalkThrough/Classes/TutorialView.swift
1
6869
// // TutorialView.swift // ZwiModule // // Created by Joshua Park on 17/11/2017. // import UIKit private protocol ActionItem { var action: (() -> Void)? { get } } open class TutorialView: UIView { private enum TouchArea { case view(UIView) case rect(CGRect) } private enum MaskArea { case rect(insets: UIEdgeInsets, cornerRadius: CGFloat) case radiusInset(CGFloat) } private struct Focus: ActionItem { let touch: TouchArea let mask: MaskArea let action: (() -> Void)? } private struct Block: ActionItem { let rect: CGRect let action: (() -> Void)? } open internal(set) weak var item: TutorialItem! @IBOutlet open weak var prevButton: UIButton? @IBOutlet open weak var nextButton: UIButton? open override var backgroundColor: UIColor? { get { return fillColor } set { if let color = newValue { fillColor = color } } } private var fillColor = UIColor(white: 0.0, alpha: 0.5) private var actionItemList = [ActionItem]() open func makeAvailable(view: UIView, action: (() -> Void)? = nil) { makeAvailable(view: view, insets: UIEdgeInsets.zero, cornerRadius: 0.0, action: action) } open func makeAvailable(view: UIView, insets: UIEdgeInsets, cornerRadius: CGFloat, action: (() -> Void)? = nil) { let focus = Focus(touch: .view(view), mask: .rect(insets: insets, cornerRadius: cornerRadius), action: action) actionItemList.append(focus) } //: Makes a circle-shaped available area with the given radius inset open func makeAvailable(view: UIView, radiusInset: CGFloat, action: (() -> Void)? = nil) { let focus = Focus(touch: .view(view), mask: .radiusInset(radiusInset), action: action) actionItemList.append(focus) } open func makeAvailable(rect: CGRect, action: (() -> Void)? = nil) { makeAvailable(rect: rect, insets: UIEdgeInsets.zero, cornerRadius: 0.0, action: action) } open func makeAvailable(rect: CGRect, insets: UIEdgeInsets, cornerRadius: CGFloat, action: (() -> Void)? = nil) { let focus = Focus(touch: .rect(rect), mask: .rect(insets: insets, cornerRadius: cornerRadius), action: action) actionItemList.append(focus) } open func makeAvailable(rect: CGRect, radiusInset: CGFloat, action: (() -> Void)? = nil) { let focus = Focus(touch: .rect(rect), mask: .radiusInset(radiusInset), action: action) actionItemList.append(focus) } open func makeUnavailable(rect: CGRect, action: (() -> Void)? = nil) { let block = Block(rect: rect, action: action) actionItemList.append(block) } open override func layoutSubviews() { super.layoutSubviews() for layer in self.layer.sublayers ?? [] { if layer.name == "TutorialView.backgroundLayer" { layer.removeFromSuperlayer() } } let path = UIBezierPath(rect: bounds) for item in actionItemList { guard let focus = item as? Focus else { continue } var rect: CGRect = { switch focus.touch { case .rect(rect: let rect): return rect case .view(view: let view): return self.convert(view.frame, from: view.superview) } }() switch focus.mask { case .rect(insets: let insets, cornerRadius: let cornerRadius): rect.origin.x -= insets.left rect.origin.y -= insets.top rect.size.width += insets.left + insets.right rect.size.height += insets.top + insets.bottom path.append(UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius)) case .radiusInset(radiusInset: let radiusInset): let center = CGPoint(x: rect.midX, y: rect.midY) let rawDiameter = sqrt(pow(rect.width, 2) + pow(rect.height, 2)) let diameter = round(rawDiameter) + radiusInset * 2.0 let radius = round(diameter / 2.0) let x = center.x - radius let y = center.y - radius let circleRect = CGRect(x: x, y: y, width: diameter, height: diameter) path.append(UIBezierPath(roundedRect: circleRect, cornerRadius: radius)) } } let backgroundLayer = CAShapeLayer() backgroundLayer.fillColor = fillColor.cgColor backgroundLayer.fillRule = kCAFillRuleEvenOdd backgroundLayer.frame = bounds backgroundLayer.name = "TutorialView.backgroundLayer" backgroundLayer.path = path.cgPath layer.insertSublayer(backgroundLayer, at: 0) } open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { for item in actionItemList { if let block = item as? Block { if block.rect.contains(point) { block.action?() return super.hitTest(point, with: event) } } else { let focus = item as! Focus let bypassRect: CGRect = { switch focus.touch { case .rect(rect: let rect): return rect case .view(view: let view): return self.convert(view.frame, from: view.superview) } }() if bypassRect.contains(point) { focus.action?() return nil } } } return super.hitTest(point, with: event) } }
mit
17384d18d66199efe280200e1064646a
31.709524
88
0.478672
5.291988
false
false
false
false
fitpay/fitpay-ios-sdk
FitpaySDK/Rest/Models/Commit/Commit.swift
1
4056
import Foundation open class Commit: NSObject, ClientModel, Serializable, SecretApplyable { open var commitType: CommitType? { return CommitType(rawValue: commitTypeString ?? "") ?? .unknown } open var commitTypeString: String? open var payload: Payload? open var created: CLong? open var previousCommit: String? open var commitId: String? open var executedDuration: Int? weak var client: RestClient? { didSet { payload?.creditCard?.client = client } } var links: [String: Link]? var encryptedData: String? private static let apduResponseResourceKey = "apduResponse" private static let confirmResourceKey = "confirm" private enum CodingKeys: String, CodingKey { case links = "_links" case commitTypeString = "commitType" case created = "createdTs" case previousCommit case commitId case encryptedData } // MARK: - Lifecycle public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) links = try? container.decode(.links) commitTypeString = try? container.decode(.commitTypeString) created = try? container.decode(.created) previousCommit = try? container.decode(.previousCommit) commitId = try? container.decode(.commitId) encryptedData = try? container.decode(.encryptedData) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try? container.encodeIfPresent(links, forKey: .links) try? container.encode(commitTypeString, forKey: .commitTypeString) try? container.encode(created, forKey: .created) try? container.encode(previousCommit, forKey: .previousCommit) try? container.encode(commitId, forKey: .commitId) try? container.encode(encryptedData, forKey: .encryptedData) } // MARK: - Functions func applySecret(_ secret: Data, expectedKeyId: String?) { payload = JWE.decrypt(encryptedData, expectedKeyId: expectedKeyId, secret: secret) payload?.creditCard?.client = client } func confirmNonAPDUCommitWith(result: NonAPDUCommitState, completion: @escaping RestClient.ConfirmHandler) { let resource = Commit.confirmResourceKey guard commitType != CommitType.apduPackage else { log.error("COMMIT: Trying send confirm for APDU commit but should be non APDU.") completion(ErrorResponse.unhandledError(domain: Commit.self)) return } guard let url = links?[resource]?.href else { completion(nil) return } guard let client = client else { completion(composeError(resource)) return } log.verbose("COMMIT: Confirming Non-APDU commit - \(String(describing: commitId))") client.confirm(url, executionResult: result, completion: completion) } func confirmAPDU(_ completion: @escaping RestClient.ConfirmHandler) { let resource = Commit.apduResponseResourceKey guard commitType == CommitType.apduPackage, let apduPackage = payload?.apduPackage else { completion(ErrorResponse.unhandledError(domain: Commit.self)) return } guard let url = links?[resource]?.href, let client = client else { completion(composeError(resource)) return } log.verbose("COMMIT: Confirming APDU commit - \(String(describing: commitId))") client.confirmAPDUPackage(url, package: apduPackage, completion: completion) } // MARK: - Private Functions func composeError(_ resource: String) -> ErrorResponse? { return ErrorResponse.clientUrlError(domain: Commit.self, client: client, url: links?[resource]?.href, resource: resource) } }
mit
d3b49a69d2305ab7b0d0e21c86c66297
34.578947
129
0.643245
4.863309
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureNFT/Sources/FeatureNFTUI/View/AssetList/AssetListViewReducer.swift
1
3301
import Combine import ComposableArchitecture import FeatureNFTDomain import SwiftUI import ToolKit private enum AssetListCancellation { struct RequestAssetsKeyId: Hashable {} struct RequestPageAssetsKeyId: Hashable {} } public let assetListReducer = Reducer.combine( assetDetailReducer .optional() .pullback( state: \.assetDetailViewState, action: /AssetListViewAction.assetDetailsViewAction, environment: { _ in .init() } ), Reducer< AssetListViewState, AssetListViewAction, AssetListViewEnvironment > { state, action, environment in switch action { case .onAppear: state.isLoading = true return environment .assetProviderService .fetchAssetsFromEthereumAddress() .receive(on: environment.mainQueue) .catchToEffect() .map(AssetListViewAction.fetchedAssets) .cancellable( id: AssetListCancellation.RequestAssetsKeyId(), cancelInFlight: true ) case .fetchedAssets(let result): switch result { case .success(let value): let assets: [Asset] = state.assets + value.assets state.assets = assets state.next = value.cursor case .failure(let error): state.error = error } state.isLoading = false state.isPaginating = false return .none case .assetTapped(let asset): state.assetDetailViewState = .init(asset: asset) return .enter(into: .details) case .route(let route): state.route = route return .none case .increaseOffset: guard !state.isPaginating else { return .none } guard state.next != nil else { return .none } return Effect(value: .fetchNextPageIfNeeded) case .fetchNextPageIfNeeded: state.isPaginating = true guard let cursor = state.next else { impossible("Cannot page without cursor") } return environment .assetProviderService .fetchAssetsFromEthereumAddressWithCursor(cursor) .receive(on: environment.mainQueue) .catchToEffect() .map(AssetListViewAction.fetchedAssets) .cancellable( id: AssetListCancellation.RequestPageAssetsKeyId(), cancelInFlight: true ) case .copyEthereumAddressTapped: return environment .assetProviderService .address .receive(on: environment.mainQueue) .catchToEffect() .map(AssetListViewAction.copyEthereumAddress) case .copyEthereumAddress(let result): guard let address = try? result.get() else { return .none } environment.pasteboard.string = address return .none case .assetDetailsViewAction(let action): switch action { case .viewOnWebTapped: return .none } } } )
lgpl-3.0
bc7e69ce587c582d665bbd4daad817d9
34.494624
71
0.561042
5.501667
false
false
false
false
361425281/swift-snia
Swift-Sina/Classs/Oauth/DQOauthViewController.swift
1
2602
// // DQOauthViewController.swift // Swift-Sina // // Created by 熊德庆 on 15/10/31. // Copyright © 2015年 熊德庆. All rights reserved. // import UIKit import SVProgressHUD class DQOauthViewController: UIViewController { override func loadView() { view = webView webView.delegate = self } override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close") //加载网页 let request = NSURLRequest(URL: DQToolsNetWorking.defaultInstance.OauthURL()) webView.loadRequest(request) } //关闭控制器 func close() { SVProgressHUD.dismiss() dismissViewControllerAnimated(false, completion: nil) } //懒加载 private lazy var webView = UIWebView() } extension DQOauthViewController: UIWebViewDelegate { func webViewDidStartLoad(webView: UIWebView) { SVProgressHUD.showWithStatus("正在玩命加载。。。", maskType: SVProgressHUDMaskType.Black) } func webViewDidFinishLoad(webView: UIWebView) { SVProgressHUD.dismiss() } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { let urlStr = request.URL!.absoluteString print("urlStr:\(urlStr)") if !urlStr.hasPrefix(DQToolsNetWorking.defaultInstance.redirect_uri) { return true } if let query = request.URL?.query { let codeStr = "code=" if query.hasPrefix(codeStr) { let nsQuery = query as NSString let code = nsQuery.substringFromIndex(codeStr.characters.count) print("code:\(code)") } } return false } func loaaAccessToken(code:String) { DQToolsNetWorking.defaultInstance.loadAccessToken(code) { (result,error) -> () in if error != nil || result == nil { SVProgressHUD.showWithStatus("网络不给力。。", maskType: SVProgressHUDMaskType.Black) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in self.close() }) return } } } }
apache-2.0
255356c4b295bccd89077d092f160c1f
28.741176
138
0.573407
5.013889
false
false
false
false
cnkaptan/SwiftLessons
Properties.playground/Contents.swift
1
868
//: Playground - noun: a place where people can play import UIKit class Legs { var count: Int = 0 } //default olarak strong class Animal { var name: String = "" var legs: Legs = Legs() // Bu yapiya computed proporty denir disardan bir property gibi gorunur ve davranir ama icerde hicbirseyi depolamaz var upperCaseName: String { return name.uppercaseString } var lowerCaseName: String{ get{ return name.lowercaseString } set{ name = newValue } } } class LegVet{ weak var legs: Legs? = nil } var dog: Animal? = Animal() let vel = LegVet() //dog objesi nil olursa vel.legs te nil olur , Veldeki Legs weak referans oldugu icin , eger strong type olsaydi Legleri nil olmayacakti cunku o objeye sahip olcakti vel.legs = dog?.legs dog = nil vel.legs
mit
6247d345eb32950eab6a345b842fa8c2
19.186047
165
0.640553
3.32567
false
false
false
false
innominds-mobility/swift-custom-ui-elements
swift-custom-ui/InnoUI/ToastMessageUI/UIView+InnoToastMessageUI.swift
1
11518
// // UIView+InnoToastMessageUI.swift // swift-custom-ui // // Created by Deepthi Muramshetty on 16/05/17. // Copyright © 2017 Innominds Mobility. All rights reserved. // import UIKit // MARK: Toast Message UIview properties /// Toast Default position let toastPositionDefault = "bottom" /// Toast Top position let toastPositionTop = "top" /// Toast Center position let toastPositionCenter = "center" /// Toast Horizontal margin let toastHorizontalMargin: CGFloat = 10.0 /// Toats Vertical Margin let toastVerticalMargin: CGFloat = 10.0 /// Toast Default duration time let toastDefaultDuration = 2.0 /// Toast fading duration time let toastFadeDuration = 0.2 /// Toast Message font size let messageFontSize: CGFloat = 19.0 // Toast message label settings /// Toast view maximum width let toastMaxWidth: CGFloat = 0.8; //80% of ParentView width /// Toast view maximum height let toastMaxHeight: CGFloat = 0.8 /// Toast message maximum number of lines let toastMaxMessageLines = 0 // Toast shadow appearance /// Toast shadow opacity value let toastShadowOpacity: CGFloat = 0.8 /// Toast shadow radius let toastShadowRadius: CGFloat = 6.0 /// Toast shadow offset let toastShadowOffset: CGSize = CGSize(width: CGFloat(4.0), height: CGFloat(4.0)) /// Toast view opacity let toastOpacity: CGFloat = 0.9 /// Toast view corner radius let toastCornerRadius: CGFloat = 8.0 /// Toast timer var toastTimer: UnsafePointer<Timer>? /// Toast view var toastView: UnsafePointer<UIView>? /// Toast hides on tap let toastHidesOnTap = true /// Toast display shadow let toastDisplayShadow = true // MARK: - Toast Message UIView extension /* Extension for UIView. Get the toast message from app, prepare the toast message label according to that message's width & height. Add that message label to the view with different background color. */ public extension UIView { // Making the toast message /// Making a toast view /// /// - Parameter msg: Message to be displayed in toast func makeToast(message msg: String) { /// Get toast view UI with message let toast = self.viewForMessage(msg) showToast(toast: toast!, duration: toastDefaultDuration, position: toastPositionDefault as AnyObject) } /// Showing the Toast message. /// /// - Parameters: /// - toast: Toast view with message /// - duration: time interval for the toast to display /// - position: at which position toast to be displayed fileprivate func showToast(toast: UIView, duration: Double, position: AnyObject) { toast.center = centerPointForPosition(position, toast: toast) toast.alpha = 0.0 // Tap gesture is added for toast message, on tap of it toast will be hidden if toastHidesOnTap { /// Tap gesture for toast let tapRecognizer = UITapGestureRecognizer(target: toast, action: #selector(UIView.handleToastTapped(_:))) toast.addGestureRecognizer(tapRecognizer) toast.isUserInteractionEnabled = true toast.isExclusiveTouch = true } addSubview(toast) objc_setAssociatedObject(self, &toastView, toast, .OBJC_ASSOCIATION_RETAIN) //On completion timer is fired, after certain duration toast will be hidden UIView.animate(withDuration: toastFadeDuration, delay: 0.0, options: ([.curveEaseOut, .allowUserInteraction]), animations: { toast.alpha = 1.0 }, completion: { (_: Bool) in let timer = Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false) objc_setAssociatedObject(toast, &toastTimer, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }) } /// Hiding the toast message. /// /// - Parameter toast: View with toast message. func hideToast(toast: UIView) { hideToast(toast: toast, force: false) } /// Hides toast message. /// /// - Parameters: /// - toast: View with toast message. /// - force: true if hiding toast without animation. If false, hides with animation. func hideToast(toast: UIView, force: Bool) { let completeClosure = { (finish: Bool) -> Void in toast.removeFromSuperview() objc_setAssociatedObject(self, &toastTimer, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } if force { completeClosure(true) } else { UIView.animate(withDuration: toastFadeDuration, delay: 0.0, options: ([.curveEaseIn, .beginFromCurrentState]), animations: { toast.alpha = 0.0 }, completion:completeClosure) } } /// Timer finish handle method /// /// - Parameter timer: Timer func toastTimerDidFinish(_ timer: Timer) { hideToast(toast: (timer.userInfo as? UIView)!) } /// Tap gesture handle method /// /// - Parameter recognizer: The gesture recognizer is attached to view. func handleToastTapped(_ recognizer: UITapGestureRecognizer) { /// Timer for toast let timer = objc_getAssociatedObject(self, &toastTimer) as? Timer! timer?.invalidate() hideToast(toast: recognizer.view!) } /// This function decides where to display the Toast message i.e top or center or bottom /// /// - Parameters: /// - position: Top or center or bottom /// - toast: View with toast message /// - Returns: Position for toast to be displayed fileprivate func centerPointForPosition(_ position: AnyObject, toast: UIView) -> CGPoint { if position is String { /// Toast size let toastSize = toast.bounds.size /// View size let viewSize = self.bounds.size if position.lowercased == toastPositionTop { return CGPoint(x: viewSize.width/2, y: toastSize.height/2 + toastVerticalMargin) } else if position.lowercased == toastPositionDefault { return CGPoint(x: viewSize.width/2, y: viewSize.height - toastSize.height/2 - toastVerticalMargin) } else if position.lowercased == toastPositionCenter { return CGPoint(x: viewSize.width/2, y: viewSize.height/2) } } else if position is NSValue { return position.cgPointValue } print("Warning! Invalid position for toast.") return self.centerPointForPosition(toastPositionDefault as AnyObject, toast: toast) } /// Creating the view for Toast. A shadow is created for the toast view. /// Message label dimensions are calculated dynamically based on given toast message. /// /// - Parameter msg: Toast message /// - Returns: View with toats message UI fileprivate func viewForMessage(_ msg: String?) -> UIView? { if msg == nil { return nil } /// Message label var msgLabel: UILabel? /// Toast view let wrapperToastView = UIView() wrapperToastView.autoresizingMask = ( [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]) wrapperToastView.layer.cornerRadius = toastCornerRadius wrapperToastView.backgroundColor = UIColor.black.withAlphaComponent(toastOpacity) if toastDisplayShadow { wrapperToastView.layer.shadowColor = UIColor.black.cgColor wrapperToastView.layer.shadowOpacity = Float(toastShadowOpacity) wrapperToastView.layer.shadowRadius = toastShadowRadius wrapperToastView.layer.shadowOffset = toastShadowOffset } if msg != nil { msgLabel = UILabel(); msgLabel!.numberOfLines = toastMaxMessageLines msgLabel!.font = UIFont(name: "Optima-Regular", size: messageFontSize) //Any font msgLabel!.lineBreakMode = .byWordWrapping msgLabel!.textAlignment = .center msgLabel!.textColor = UIColor.white msgLabel!.backgroundColor = UIColor.clear msgLabel!.alpha = 1.0 msgLabel!.text = msg /// Message Text size let maxSizeMessage = CGSize(width: (self.bounds.size.width * toastMaxWidth), height: self.bounds.size.height * toastMaxHeight) /// Expected height for message label let expectedHeight = msg!.toastStringHeightWithFontSize(messageFontSize, width: maxSizeMessage.width) msgLabel!.frame = CGRect(x: 0.0, y: 0.0, width: maxSizeMessage.width, height: expectedHeight) } /// Message width, height, top, left var msgWidth: CGFloat, msgHeight: CGFloat, msgTop: CGFloat, msgLeft: CGFloat if msgLabel != nil { msgWidth = msgLabel!.bounds.size.width;msgHeight = msgLabel!.bounds.size.height msgTop = toastVerticalMargin ;msgLeft = toastHorizontalMargin } else { msgWidth = 0.0; msgHeight = 0.0; msgTop = 0.0; msgLeft = 0.0 } /// Maximum width. ; maximum left. let largerWidth = max(0, msgWidth); let largerLeft = max(0, msgLeft) /// Toast view width. let wrapperWidth = max(toastHorizontalMargin * 2, largerLeft + largerWidth + toastHorizontalMargin) /// Toast view height. let wrapperHeight = max(msgTop + msgHeight + toastVerticalMargin, toastVerticalMargin * 2) wrapperToastView.frame = CGRect(x: 0.0, y: 0.0, width: wrapperWidth, height: wrapperHeight) // add subviews if msgLabel != nil { msgLabel!.frame = CGRect(x: msgLeft, y: msgTop, width: msgWidth, height: msgHeight) wrapperToastView.addSubview(msgLabel!) } return wrapperToastView } } /* Extension for String, Getting height for toast message dynamically. Need to provide font name and size for the toast message to calculate the height. */ // MARK: - Message String Extension public extension String { /// Calculate height dynamically for the given message. /// /// - Parameters: /// - fontSize: Font size for given message. /// - width: Width of message label. /// - Returns: Height of message. func toastStringHeightWithFontSize(_ fontSize: CGFloat, width: CGFloat) -> CGFloat { /// Font of message. let font = UIFont(name: "Optima-Regular", size: messageFontSize)// Use any Font like "Helvetica" /// Size of message. let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) /// Paragraph style. let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = .byWordWrapping /// Attributes for bounding rect. let attributes = [NSFontAttributeName: font!, NSParagraphStyleAttributeName: paragraphStyle.copy()] /// Text let text = self as NSString /// Rect for given text with properties to calculte height let rect = text.boundingRect(with: size, options:.usesLineFragmentOrigin, attributes: attributes, context:nil) return rect.size.height } }
gpl-3.0
f664dffa95b441cbc5382527f71baea7
41.973881
118
0.635235
4.824885
false
false
false
false
matsprea/omim
iphone/Maps/UI/PlacePage/Components/TaxiViewController.swift
1
1198
protocol TaxiViewControllerDelegate: AnyObject { func didPressOrder() } class TaxiViewController: UIViewController { @IBOutlet var taxiImageView: UIImageView! @IBOutlet var taxiNameLabel: UILabel! var taxiProvider: PlacePageTaxiProvider = .none weak var delegate: TaxiViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() switch taxiProvider { case .none: assertionFailure() case .uber: taxiImageView.image = UIImage(named: "icTaxiUber") taxiNameLabel.text = L("uber") case .yandex: taxiImageView.image = UIImage(named: "ic_taxi_logo_yandex") taxiNameLabel.text = L("yandex_taxi_title") case .maxim: taxiImageView.image = UIImage(named: "ic_taxi_logo_maksim") taxiNameLabel.text = L("maxim_taxi_title") case .rutaxi: taxiImageView.image = UIImage(named: "ic_taxi_logo_vezet") taxiNameLabel.text = L("vezet_taxi") case .freenow: taxiImageView.image = UIImage(named: "ic_logo_freenow") taxiNameLabel.text = L("freenow_taxi_title") @unknown default: fatalError() } } @IBAction func onOrder(_ sender: UIButton) { delegate?.didPressOrder() } }
apache-2.0
92f8db302753074c8534fbf16722d0e5
28.219512
65
0.685309
3.686154
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothGATT/GATTSupportedNewAlertCategory.swift
1
2101
// // GATTSupportedNewAlertCategory.swift // Bluetooth // // Created by Carlos Duclos on 6/13/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /** Supported New Alert Category Category that the server supports for new alert. This characteristic uses the Alert Category ID Bit Mask Characteristic. If bit(s) is/are set, it means the server supports the corresponded categories for new incoming alert. • Example: The value 0x0a is interpreted that this server supports “Call” and “Email” categories. - SeeAlso: [Supported New Alert Category](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.supported_new_alert_category.xml) */ @frozen public struct GATTSupportedNewAlertCategory: GATTCharacteristic { public typealias Category = GATTAlertCategoryBitMask.Category public static var uuid: BluetoothUUID { return .supportedNewAlertCategory } public var categories: BitMaskOptionSet<Category> public init(categories: BitMaskOptionSet<Category> = []) { self.categories = categories } public init?(data: Data) { guard let bitmask = Category.RawValue(bitmaskArray: data) else { return nil } self.categories = BitMaskOptionSet<Category>(rawValue: bitmask) } public var data: Data { return categories.rawValue.bitmaskArray } public var characteristic: GATTAttribute.Characteristic { return GATTAttribute.Characteristic(uuid: type(of: self).uuid, value: data, permissions: [.read], properties: [.read], descriptors: []) } } extension GATTSupportedNewAlertCategory: Equatable { public static func == (lhs: GATTSupportedNewAlertCategory, rhs: GATTSupportedNewAlertCategory) -> Bool { return lhs.categories == rhs.categories } }
mit
f9e563e7388144e767feb9497a787c71
29.735294
175
0.644498
5.036145
false
false
false
false
tranhieutt/Swiftz
SwiftzTests/UserExample.swift
1
1047
// // UserExample.swift // Swiftz // // Created by Maxwell Swadling on 9/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // import Swiftz // A user example // an example of why we need SYB, Generics or macros public class User : JSONDecodable { let name : String let age : Int let tweets : [String] let attr : String public init(_ n : String, _ a : Int, _ t : [String], _ r : String) { name = n age = a tweets = t attr = r } // JSON public class func create(x : String) -> Int -> ([String] -> String -> User) { return { y in { z in { User(x, y, z, $0) } } } } public class func fromJSON(x : JSONValue) -> User? { let p1 : String? = x <? "name" let p2 : Int? = x <? "age" let p3 : [String]? = x <? "tweets" let p4 : String? = x <? "attrs" <> "one" // A nested keypath return User.create <^> p1 <*> p2 <*> p3 <*> p4 } } public func ==(lhs : User, rhs : User) -> Bool { return lhs.name == rhs.name && lhs.age == rhs.age && lhs.tweets == rhs.tweets && lhs.attr == rhs.attr }
bsd-3-clause
a48cc2d38509f432efe3d7b41489a37d
21.76087
102
0.574976
2.82973
false
false
false
false
Instagram/IGListKit
Examples/Examples-iOS/IGListKitExamples/Models/FeedItem.swift
1
858
/* * Copyright (c) Meta Platforms, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import IGListKit final class FeedItem: ListDiffable { let pk: Int let user: User let comments: [String] init(pk: Int, user: User, comments: [String]) { self.pk = pk self.user = user self.comments = comments } // MARK: ListDiffable func diffIdentifier() -> NSObjectProtocol { return pk as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { guard self !== object else { return true } guard let object = object as? FeedItem else { return false } return user.isEqual(toDiffableObject: object.user) && comments == object.comments } }
mit
95b1f01556a8d9a85b476aba58b33fc6
24.235294
89
0.646853
4.445596
false
false
false
false
zach-freeman/swift-localview
ThirdPartyLib/Alamofire/Example/Source/DetailViewController.swift
2
7006
// // DetailViewController.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // 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 Alamofire import UIKit class DetailViewController: UITableViewController { enum Sections: Int { case headers, body } var request: Alamofire.Request? { didSet { oldValue?.cancel() title = request?.description refreshControl?.endRefreshing() headers.removeAll() body = nil elapsedTime = nil } } var headers: [String: String] = [:] var body: String? var elapsedTime: TimeInterval? var segueIdentifier: String? static let numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal return formatter }() // MARK: View Lifecycle override func awakeFromNib() { super.awakeFromNib() refreshControl?.addTarget(self, action: #selector(DetailViewController.refresh), for: .valueChanged) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) refresh() } // MARK: IBActions @IBAction func refresh() { guard let request = request else { return } refreshControl?.beginRefreshing() let start = CACurrentMediaTime() let requestComplete: (HTTPURLResponse?, Result<String>) -> Void = { response, result in let end = CACurrentMediaTime() self.elapsedTime = end - start if let response = response { for (field, value) in response.allHeaderFields { self.headers["\(field)"] = "\(value)" } } if let segueIdentifier = self.segueIdentifier { switch segueIdentifier { case "GET", "POST", "PUT", "DELETE": self.body = result.value case "DOWNLOAD": self.body = self.downloadedBodyString() default: break } } self.tableView.reloadData() self.refreshControl?.endRefreshing() } if let request = request as? DataRequest { request.responseString { response in requestComplete(response.response, response.result) } } else if let request = request as? DownloadRequest { request.responseString { response in requestComplete(response.response, response.result) } } } private func downloadedBodyString() -> String { let fileManager = FileManager.default let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] do { let contents = try fileManager.contentsOfDirectory( at: cachesDirectory, includingPropertiesForKeys: nil, options: .skipsHiddenFiles ) if let fileURL = contents.first, let data = try? Data(contentsOf: fileURL) { let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) let prettyData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) if let prettyString = String(data: prettyData, encoding: String.Encoding.utf8) { try fileManager.removeItem(at: fileURL) return prettyString } } } catch { // No-op } return "" } } // MARK: - UITableViewDataSource extension DetailViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch Sections(rawValue: section)! { case .headers: return headers.count case .body: return body == nil ? 0 : 1 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch Sections(rawValue: (indexPath as NSIndexPath).section)! { case .headers: let cell = tableView.dequeueReusableCell(withIdentifier: "Header")! let field = headers.keys.sorted(by: <)[indexPath.row] let value = headers[field] cell.textLabel?.text = field cell.detailTextLabel?.text = value return cell case .body: let cell = tableView.dequeueReusableCell(withIdentifier: "Body")! cell.textLabel?.text = body return cell } } } // MARK: - UITableViewDelegate extension DetailViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if self.tableView(tableView, numberOfRowsInSection: section) == 0 { return "" } switch Sections(rawValue: section)! { case .headers: return "Headers" case .body: return "Body" } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch Sections(rawValue: (indexPath as NSIndexPath).section)! { case .body: return 300 default: return tableView.rowHeight } } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { if Sections(rawValue: section) == .body, let elapsedTime = elapsedTime { let elapsedTimeText = DetailViewController.numberFormatter.string(from: elapsedTime as NSNumber) ?? "???" return "Elapsed Time: \(elapsedTimeText) sec" } return "" } }
mit
2ea3824eecbaf255f5d822dcce03bc4c
32.04717
117
0.610049
5.323708
false
false
false
false
sfsam/Snk
Snk/AppDelegate.swift
1
5798
// Created Sanjay Madan on May 26, 2015 // Copyright (c) 2015 mowglii.com import Cocoa // MARK: Main window final class MainWindow: NSWindow { // The main window is non-resizable and non-zoomable. // Its fixed size is determined by the MainVC's view. // The window uses the NSFullSizeContentViewWindowMask // so that we can draw our own custom title bar. convenience init() { self.init(contentRect: NSZeroRect, styleMask: [.titled, .closable, .miniaturizable, .fullSizeContentView], backing: .buffered, defer: false) self.titlebarAppearsTransparent = true self.standardWindowButton(.zoomButton)?.alphaValue = 0 } // The app terminates when the main window is closed. override func close() { NSApplication.shared.terminate(nil) } // Fade the contentView when the window resigns Main. override func becomeMain() { super.becomeMain() contentView?.alphaValue = 1 } override func resignMain() { super.resignMain() contentView?.alphaValue = 0.6 } } // MARK: - App delegate // // AppDelegate handles the main window (it owns the main // window controller), clears the high scores, and toggles // the board size. @NSApplicationMain final class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet var themesMenu: NSMenu? let mainWC = NSWindowController(window: MainWindow()) func applicationWillFinishLaunching(_ notification: Notification) { // Prevent "Enter Full Screen" from appearing in menu. // stackoverflow.com/a/52158264/111418 UserDefaults.standard.set(false, forKey: "NSFullScreenMenuItemEverywhere") } func applicationDidFinishLaunching(_ aNotification: Notification) { UserDefaults.standard.register(defaults: [ kHiScoreSlowKey: 0, kHiScoreMediumKey: 0, kHiScoreFastKey: 0, kEnableSoundsKey: true, kEnableMusicKey: true, kBigBoardKey: false, ]) setupThemesMenu() showMainWindow() } func showMainWindow() { // If we are re-showing the window (because the // user toggled its size or changed its theme), // first make sure it is not miniturized and // not showing. if mainWC.window?.isMiniaturized == true { mainWC.window?.deminiaturize(nil) } mainWC.window?.orderOut(nil) mainWC.contentViewController = MainVC() // Fade the window in. mainWC.window?.alphaValue = 0 mainWC.showWindow(self) mainWC.window?.center() moDispatch(after: 0.1) { self.mainWC.window?.animator().alphaValue = 1 } } @IBAction func clearScores(_ sender: AnyObject) { // Called from the Clear Scores... menu item. // Show an alert to confirm the user really // wants to erase their saved high scores. let alert = NSAlert() alert.messageText = NSLocalizedString("Clear scores?", comment: "") alert.informativeText = NSLocalizedString("Do you really want to clear your best scores?", comment: "") alert.addButton(withTitle: NSLocalizedString("No", comment: "")) alert.addButton(withTitle: NSLocalizedString("Yes", comment: "")) if alert.runModal() == NSApplication.ModalResponse.alertSecondButtonReturn { UserDefaults.standard.set(0, forKey: kHiScoreSlowKey) UserDefaults.standard.set(0, forKey: kHiScoreMediumKey) UserDefaults.standard.set(0, forKey: kHiScoreFastKey) } } @IBAction func toggleSize(_ sender: AnyObject) { // Called from Toggle Size menu item. // Toggle between standard and big board size. // Set the user default to the new value, set // kScale and kStep to their new values, hide // the main window and then re-show it. // Re-showing the window will re-instantiate // MainVC with the new sizes. SharedAudio.stopEverything() let bigBoard = kScale == 1 ? true : false UserDefaults.standard.set(bigBoard, forKey: kBigBoardKey) kScale = bigBoard ? 2 : 1 kStep = kBaseStep * Int(kScale) showMainWindow() } @objc func selectTheme(_ sender: NSMenuItem) { let newIndex = sender.tag let oldIndex = SharedTheme.themeIndex guard newIndex != oldIndex else { return } // Uncheck old theme menu item, check new one. themesMenu?.item(at: oldIndex)?.state = NSControl.StateValue(rawValue: 0) themesMenu?.item(at: newIndex)?.state = NSControl.StateValue(rawValue: 1) // Save the theme name and set the theme manager // to use the new one. let savedName = SharedTheme.themes[newIndex].name.rawValue UserDefaults.standard.set(savedName, forKey: kThemeNameKey) SharedTheme.setTheme(savedName: savedName) showMainWindow() } func setupThemesMenu() { // Set the theme manager to use the saved theme. SharedTheme.setTheme(savedName: UserDefaults.standard.string(forKey: kThemeNameKey)) // Create menu items for the themes in the theme // manager's 'themes' array. for (index, theme) in SharedTheme.themes.enumerated() { let item = NSMenuItem() item.title = theme.name.rawValue item.state = NSControl.StateValue(rawValue: index == SharedTheme.themeIndex ? 1 : 0) item.tag = index item.action = #selector(selectTheme(_:)) themesMenu?.addItem(item) } } }
mit
b8bd2e3e6056f33d294d1b92bc133fb7
33.927711
148
0.625216
4.642114
false
false
false
false
yzhou65/DSWeibo
DSWeibo/Classes/Main/MainViewController.swift
1
6268
// // MainViewController.swift // DSWeibo // // Created by Yue on 9/6/16. // Copyright © 2016 fda. All rights reserved. // import UIKit /** command + j -> 定位到目录文杰 ⬆️⬇️键选择文件夹 按回车 -> command+c 拷贝文件名称 command + n:创建文件 */ class MainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() //设置当前控制器对应tabBar的颜色 //注意:在ios7以前如果设置了tintColor只有文字会变,而图片不会变 // tabBar.tintColor = UIColor.orangeColor() // 添加子控制器 addChildControllers() //从ios7开始就不推荐大家在viewDidLoad中设置frame,而应在viewWillAppear设置 // print(tabBar.subviews) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // print("-----------------") // print(tabBar.subviews) //添加+号按钮 setupComposeBtn() } /** 监听+号按钮的点击 注意:此方法不能是private,否则会崩溃。因为这个方法不是在当前类中触发的,而是runtime中CFRunLoop监听且以消息机制传递的,所以不能设置为private */ func composeBtnClick(){ let composeVC = ComposeViewController() let nav = UINavigationController(rootViewController: composeVC) presentViewController(nav, animated: true, completion: nil) } //MARK: 内部控制方法 /** 添加+号按钮 */ private func setupComposeBtn() { tabBar.addSubview(composeBtn) //调整+号按钮的位置 let width = UIScreen.mainScreen().bounds.size.width / CGFloat(viewControllers!.count) let rect = CGRect(x: 2 * width, y: 0, width: width, height: 49) composeBtn.frame = rect } /** 添加所有子控制器 */ private func addChildControllers() { //获取json文件的路径 let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil) //通过文件路径创建NSData if let jsonPath = path { let jsonData = NSData(contentsOfFile: jsonPath) do { //有可能发生异常的代码放到这里 //序列化json数据->Array //try:发生异常会跳到catch中继续执行 //try!:发生异常程序直接就崩溃 let dictArr = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers) //遍历数组,动态创建控制器和设置数据 //Swift中,如果需要遍历一个数组,必须先明确数据类型 for dict in dictArr as! [[String: String]] { //报错的原因:addChildViewController方法的参数必须有值,但是字典的返回值是可选类型,所以全部要加上返回值 addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!) } } catch { //发生异常之后会执行的 print(error) //从本地创建控制器 addChildViewController("HomeTableViewController", title: "首页", imageName: "tabbar_home") addChildViewController("MessageTableViewController", title: "消息", imageName: "tabbar_message_center") //添加一个占位控制器(为中间的+号) addChildViewController("NullViewController", title: "", imageName: "") addChildViewController("DiscoverTableViewController", title: "发现", imageName: "tabbar_discover") addChildViewController("ProfileTableViewController", title: "我", imageName: "tabbar_profile") } } } /** 初始化子控制器。需要传入子控制器对象,标题和图片 */ private func addChildViewController(childControllerName: String, title:String, imageName:String) { // <DSWeibo.HomeTableViewController: 0x7ff3a15967c0> //动态获取命名空间 let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String //将CFBundleExecutable的value取出来赋给一个String变量 //将字符串转换为类(要注意类的命名空间) //默认情况下,命名空间就是项目名称,但是命名空间可以被修改,所以要动态获取命名空间 let cls:AnyClass? = NSClassFromString(ns + "." + childControllerName) //通过类创建对象. 要将AnyClass转换为UIViewController的类型 let vcCls = cls as! UIViewController.Type let vc = vcCls.init() //设置首页tabbar对应的数据 vc.tabBarItem.image = UIImage(named: imageName) vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted") vc.title = title //给首页包装一个导航控制器 let nav = UINavigationController() nav.addChildViewController(vc) //将导航控制器添加到当前控制器 addChildViewController(nav) } //MARK: 懒加载 private lazy var composeBtn: UIButton = { let btn = UIButton() //设置前景背景图片 btn.setImage(UIImage(named:"tabbar_compose_icon_add"), forState: UIControlState.Normal) btn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted) btn.setBackgroundImage(UIImage(named:"tabbar_compose_button"), forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted) //添加监听 btn.addTarget(self, action: #selector(composeBtnClick), forControlEvents: UIControlEvents.TouchUpInside) return btn }() }
apache-2.0
fbf96a3b25af8862d1ccd4b4c72f6ba2
32.025478
132
0.5973
4.584439
false
false
false
false
galapagos/ComputableRectangle
ComputableRectangleTests/CGRectTests.swift
1
6170
import XCTest @testable import ComputableRectangle final class CGRectTests: XCTestCase { private let baseRect = CGRect(x: 1, y: 1, width: 1, height: 1) func test_addToCGFloat() { let expect = CGRect(x: 2, y: 2, width: 2, height: 2) let actual = baseRect + 1 XCTAssertEqual(expect, actual) } func test_subToCGFloat() { let expect = CGRect.zero let actual = baseRect - 1 XCTAssertEqual(expect, actual) } func test_mulToCGFloat() { let expect = CGRect(x: 5, y: 5, width: 5, height: 5) let actual = baseRect * 5 XCTAssertEqual(expect, actual) } func test_divToCGFloat() { let expect = CGRect(x: 0.5, y: 0.5, width: 0.5, height: 0.5) let actual = baseRect / 2 XCTAssertEqual(expect, actual) } func test_addToCGPoint() { let expect = CGRect(x: 2, y: 3, width: 1, height: 1) let actual = baseRect + CGPoint(x: 1, y: 2) XCTAssertEqual(expect, actual) } func test_subToCGPoint() { let expect = CGRect(x: 0, y: -1, width: 1, height: 1) let actual = baseRect - CGPoint(x: 1, y: 2) XCTAssertEqual(expect, actual) } func test_mulToCGPoint() { let expect = CGRect(x: 5, y: 10, width: 1, height: 1) let actual = baseRect * CGPoint(x: 5, y: 10) XCTAssertEqual(expect, actual) } func test_divToCGPoint() { let expect = CGRect(x: 0.5, y: 0.25, width: 1, height: 1) let actual = baseRect / CGPoint(x: 2, y: 4) XCTAssertEqual(expect, actual) } func test_addToCGSize() { let expect = CGRect(x: 1, y: 1, width: 2, height: 3) let actual = baseRect + CGSize(width: 1, height: 2) XCTAssertEqual(expect, actual) } func test_subToCGSize() { let expect = CGRect(x: 1, y: 1, width: 0, height: -1) let actual = baseRect - CGSize(width: 1, height: 2) XCTAssertEqual(expect, actual) } func test_mulToCGSize() { let expect = CGRect(x: 1, y: 1, width: 5, height: 10) let actual = baseRect * CGSize(width: 5, height: 10) XCTAssertEqual(expect, actual) } func test_divToCGSize() { let expect = CGRect(x: 1, y: 1, width: 0.5, height: 0.25) let actual = baseRect / CGSize(width: 2, height: 4) XCTAssertEqual(expect, actual) } func test_addToCGRect() { let expect = CGRect(x: 2, y: 3, width: 4, height: 5) let actual = baseRect + CGRect(x: 1, y: 2, width: 3, height: 4) XCTAssertEqual(expect, actual) } func test_subToCGRect() { let expect = CGRect(x: 0, y: -1, width: -2, height: -3) let actual = baseRect - CGRect(x: 1, y: 2, width: 3, height: 4) XCTAssertEqual(expect, actual) } func test_mulToCGRect() { let expect = CGRect(x: 2, y: 3, width: 4, height: 5) let actual = baseRect * CGRect(x: 2, y: 3, width: 4, height: 5) XCTAssertEqual(expect, actual) } func test_divToCGRect() { let expect = CGRect(x: 0.5, y: 0.25, width: 0.2, height: 0.1) let actual = baseRect / CGRect(x: 2, y: 4, width: 5, height: 10) XCTAssertEqual(expect, actual) } func test_addToOriginX() { let expect = CGRect(x: 2, y: 1, width: 1, height: 1) let actual = baseRect + OriginX(1) XCTAssertEqual(expect, actual) } func test_subToOriginX() { let expect = CGRect(x: 0, y: 1, width: 1, height: 1) let actual = baseRect - OriginX(1) XCTAssertEqual(expect, actual) } func test_mulToOriginX() { let expect = CGRect(x: 5, y: 1, width: 1, height: 1) let actual = baseRect * OriginX(5) XCTAssertEqual(expect, actual) } func test_divToOriginX() { let expect = CGRect(x: 0.5, y: 1, width: 1, height: 1) let actual = baseRect / OriginX(2) XCTAssertEqual(expect, actual) } func test_addToOriginY() { let expect = CGRect(x: 1, y: 2, width: 1, height: 1) let actual = baseRect + OriginY(1) XCTAssertEqual(expect, actual) } func test_subToOriginY() { let expect = CGRect(x: 1, y: 0, width: 1, height: 1) let actual = baseRect - OriginY(1) XCTAssertEqual(expect, actual) } func test_mulToOriginY() { let expect = CGRect(x: 1, y: 5, width: 1, height: 1) let actual = baseRect * OriginY(5) XCTAssertEqual(expect, actual) } func test_divToOriginY() { let expect = CGRect(x: 1, y: 0.5, width: 1, height: 1) let actual = baseRect / OriginY(2) XCTAssertEqual(expect, actual) } func test_addToWidth() { let expect = CGRect(x: 1, y: 1, width: 2, height: 1) let actual = baseRect + SizeOfWidth(1) XCTAssertEqual(expect, actual) } func test_subToWidth() { let expect = CGRect(x: 1, y: 1, width: 0, height: 1) let actual = baseRect - SizeOfWidth(1) XCTAssertEqual(expect, actual) } func test_mulToWidth() { let expect = CGRect(x: 1, y: 1, width: 5, height: 1) let actual = baseRect * SizeOfWidth(5) XCTAssertEqual(expect, actual) } func test_divToWidth() { let expect = CGRect(x: 1, y: 1, width: 0.5, height: 1) let actual = baseRect / SizeOfWidth(2) XCTAssertEqual(expect, actual) } func test_addToHeight() { let expect = CGRect(x: 1, y: 1, width: 1, height: 2) let actual = baseRect + SizeOfHeight(1) XCTAssertEqual(expect, actual) } func test_subToHeight() { let expect = CGRect(x: 1, y: 1, width: 1, height: 0) let actual = baseRect - SizeOfHeight(1) XCTAssertEqual(expect, actual) } func test_mulToHeight() { let expect = CGRect(x: 1, y: 1, width: 1, height: 5) let actual = baseRect * SizeOfHeight(5) XCTAssertEqual(expect, actual) } func test_divToHeight() { let expect = CGRect(x: 1, y: 1, width: 1, height: 0.5) let actual = baseRect / SizeOfHeight(2) XCTAssertEqual(expect, actual) } }
bsd-3-clause
12fc573043a60fe53124c9841fe411c9
29.85
72
0.571799
3.4335
false
true
false
false
GitHubStuff/SwiftIntervals
SwiftEvents/JSONUtil.swift
1
2255
// // JSONUtil.swift // SwiftEvents // // Created by Steven Smith on 1/9/17. // Copyright © 2017 LTMM. All rights reserved. // // Convert Swift structs to JSON import Foundation //: ### Defining the protocols protocol JSONRepresentable { var JSONRepresentation: AnyObject { get } } protocol JSONSerializable: JSONRepresentable { } //: ### Implementing the functionality through protocol extensions extension JSONSerializable { var JSONRepresentation: AnyObject { var representation = [String: AnyObject]() //discover and interate over the list of properties of the struct for case let (label?, value) in Mirror(reflecting: self).children { switch value { case let value as Dictionary<String, AnyObject>: representation[label] = value as AnyObject? case let value as Array<AnyObject>: representation[label] = value as AnyObject? case let value as AnyObject: representation[label] = value case let value as Dictionary<String, JSONSerializable>: representation[label] = value.map({$0.value.JSONRepresentation}) as AnyObject? case let value as Array<JSONSerializable>: representation[label] = value.map({$0.JSONRepresentation}) as AnyObject? case let value as JSONRepresentable: representation[label] = value.JSONRepresentation default: // Ignore any unserializable properties break } } return representation as AnyObject } } extension JSONSerializable { func toString() -> String? { let representation = JSONRepresentation guard JSONSerialization.isValidJSONObject(representation) else { return nil } do { let data = try JSONSerialization.data(withJSONObject: representation, options: .prettyPrinted) return String(data: data, encoding: .utf8) } catch { return nil } } }
unlicense
420ab7d026b20b6a98d37f503c3546fb
27.897436
106
0.57764
5.839378
false
false
false
false
MaartenBrijker/project
project/External/AudioKit-master/AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Clipper.xcplaygroundpage/Contents.swift
2
1429
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Clip //: ## import XCPlayground import AudioKit let bundle = NSBundle.mainBundle() let file = bundle.pathForResource("drumloop", ofType: "wav") var player = AKAudioPlayer(file!) player.looping = true var clipper = AKClipper(player) //: Set the initial limit of the clipper here clipper.limit = 0.1 AudioKit.output = clipper AudioKit.start() player.play() class PlaygroundView: AKPlaygroundView { var limitLabel: Label? override func setup() { addTitle("Clipper") addLabel("Audio Player") addButton("Start", action: #selector(start)) addButton("Stop", action: #selector(stop)) limitLabel = addLabel("Limit: \(clipper.limit)") addSlider(#selector(setLimit), value: clipper.limit) } func start() { player.play() } func stop() { player.stop() } func setLimit(slider: Slider) { clipper.limit = Double(slider.value) let limit = String(format: "%0.1f", clipper.limit) limitLabel!.text = "Limit: \(limit)" } } let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: 500, height: 350)) XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = view //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
apache-2.0
499ad2752ce70aa2122dc00fabdb188f
23.637931
77
0.630511
3.831099
false
false
false
false
brave/browser-ios
Client/Frontend/Settings/ClearPrivateDataTableViewController.swift
2
9092
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Deferred private let SectionToggles = 0 private let SectionButton = 1 private let NumberOfSections = 2 private let SectionHeaderFooterIdentifier = "SectionHeaderFooterIdentifier" private let TogglesPrefKey = "clearprivatedata.toggles" private let log = Logger.browserLogger private let HistoryClearableIndex = 0 class ClearPrivateDataTableViewController: UITableViewController { fileprivate var clearButton: UITableViewCell? var profile: Profile! fileprivate var gotNotificationDeathOfAllWebViews = false fileprivate typealias DefaultCheckedState = Bool fileprivate lazy var clearables: [(clearable: Clearable, checked: DefaultCheckedState)] = { return [ (HistoryClearable(), true), (CacheClearable(), true), (CookiesClearable(), true), (PasswordsClearable(profile: self.profile), true), ] }() fileprivate lazy var toggles: [Bool] = { if let savedToggles = self.profile.prefs.arrayForKey(TogglesPrefKey) as? [Bool] { return savedToggles } return self.clearables.map { $0.checked } }() fileprivate var clearButtonEnabled = true { didSet { clearButton?.textLabel?.textColor = clearButtonEnabled ? UIConstants.DestructiveRed : UIColor.lightGray } } override func viewDidLoad() { super.viewDidLoad() title = Strings.ClearPrivateData tableView.register(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderFooterIdentifier) tableView.separatorColor = UIConstants.TableViewSeparatorColor tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor let footer = SettingsTableSectionHeaderFooterView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: UIConstants.TableViewHeaderFooterHeight)) footer.showBottomBorder = false tableView.tableFooterView = footer } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil) if indexPath.section == SectionToggles { cell.textLabel?.text = clearables[indexPath.item].clearable.label let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: #selector(ClearPrivateDataTableViewController.switchValueChanged(_:)), for: UIControlEvents.valueChanged) control.isOn = toggles[indexPath.item] cell.accessoryView = control cell.selectionStyle = .none control.tag = indexPath.item } else { assert(indexPath.section == SectionButton) cell.textLabel?.text = Strings.ClearPrivateData cell.textLabel?.textAlignment = NSTextAlignment.center cell.textLabel?.textColor = UIConstants.DestructiveRed cell.accessibilityTraits = UIAccessibilityTraitButton cell.accessibilityIdentifier = "ClearPrivateData" clearButton = cell } return cell } override func numberOfSections(in tableView: UITableView) -> Int { return NumberOfSections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == SectionToggles { return clearables.count } assert(section == SectionButton) return 1 } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { guard indexPath.section == SectionButton else { return false } // Highlight the button only if it's enabled. return clearButtonEnabled } static func clearPrivateData(_ clearables: [Clearable], secondAttempt: Bool = false) -> Deferred<Void> { let deferred = Deferred<Void>() clearables.enumerated().map { clearable in print("Clearing \(clearable.element).") if "\(clearable.element)" == "Client.HistoryClearable" { let prefs: Prefs? = getApp().profile?.prefs prefs?.setBool(true, forKey: "ClearedBrowsingHistory") } let res = Success() succeed().upon() { _ in // move off main thread clearable.element.clear().upon() { result in res.fill(result) } } return res } .allSucceed() .upon { result in if !result.isSuccess && !secondAttempt { print("Private data NOT cleared successfully") postAsyncToMain(0.5) { // For some reason, a second attempt seems to always succeed clearPrivateData(clearables, secondAttempt: true).upon() { _ in deferred.fill(()) } } return } if !result.isSuccess { print("Private data NOT cleared after 2 attempts") } deferred.fill(()) } return deferred } @objc fileprivate func allWebViewsKilled() { gotNotificationDeathOfAllWebViews = true postAsyncToMain(0.5) { // for some reason, even after all webviews killed, an big delay is needed before the filehandles are unlocked var clear = [Clearable]() for i in 0..<self.clearables.count { if self.toggles[i] { clear.append(self.clearables[i].clearable) } } if PrivateBrowsing.singleton.isOn { PrivateBrowsing.singleton.exit().upon { ClearPrivateDataTableViewController.clearPrivateData(clear).upon { postAsyncToMain(0.1) { PrivateBrowsing.singleton.enter() getApp().tabManager.addTabAndSelect() } } } } else { ClearPrivateDataTableViewController.clearPrivateData(clear).uponQueue(DispatchQueue.main) { // TODO: add API to avoid add/remove getApp().tabManager.removeTab(getApp().tabManager.addTab()!, createTabIfNoneLeft: true) } } getApp().braveTopViewController.dismissAllSidePanels() } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard indexPath.section == SectionButton else { return } tableView.deselectRow(at: indexPath, animated: false) let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let clearAction = UIAlertAction(title: Strings.ClearPrivateData, style: .destructive) { (_) in getApp().profile?.prefs.setObject(self.toggles, forKey: TogglesPrefKey) self.clearButtonEnabled = false NotificationCenter.default.removeObserver(self) NotificationCenter.default.addObserver(self, selector: #selector(self.allWebViewsKilled), name: NSNotification.Name(rawValue: kNotificationAllWebViewsDeallocated), object: nil) if (BraveWebView.allocCounter == 0) { self.allWebViewsKilled() } else { getApp().tabManager.removeAll() postAsyncToMain(0.5, closure: { if !self.gotNotificationDeathOfAllWebViews { getApp().tabManager.tabs.internalTabList.forEach { $0.deleteWebView(true) } self.allWebViewsKilled() } }) } } actionSheet.addAction(clearAction) actionSheet.addAction(.init(title: Strings.Cancel, style: .cancel, handler: nil)) present(actionSheet, animated: true, completion: nil) } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderFooterIdentifier) as! SettingsTableSectionHeaderFooterView } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return UIConstants.TableViewHeaderFooterHeight } @objc func switchValueChanged(_ toggle: UISwitch) { toggles[toggle.tag] = toggle.isOn // Dim the clear button if no clearables are selected. clearButtonEnabled = toggles.contains(true) } }
mpl-2.0
05b19e6948bb4d0660bdc56b6d34a407
39.408889
188
0.618896
5.588199
false
false
false
false
apple/swift
test/SILOptimizer/performance-annotations.swift
5
4601
// RUN: %target-swift-frontend -experimental-performance-annotations -emit-sil %s -o /dev/null -verify // REQUIRES: swift_stdlib_no_asserts,optimized_stdlib protocol P { func protoMethod(_ a: Int) -> Int } open class Cl { open func classMethod() {} final func finalMethod() {} } func initFunc() -> Int { return 3 } struct Str : P { let x: Int func protoMethod(_ a: Int) -> Int { return a + x } static let s = 27 static var s2 = 10 + s static var s3 = initFunc() // expected-error {{global/static variable initialization can cause locking}} } struct AllocatingStr : P { func protoMethod(_ a: Int) -> Int { _ = Cl() // expected-error {{Using type 'Cl' can cause metadata allocation or locks}} return 0 } } /* Currently disabled: rdar://90495704 func noRTCallsForArrayGet(_ a: [Str], _ i: Int) -> Int { return a[i].x } @_noLocks func callArrayGet(_ a: [Str]) -> Int { return noRTCallsForArrayGet(a, 0) } */ @_noLocks func arcOperations(_ x: Cl) -> Cl { return x // expected-error {{this code performs reference counting operations which can cause locking}} } func genFunc<T: P>(_ t: T, _ a: Int) -> Int { let s = t return t.protoMethod(a) + s.protoMethod(a) // expected-note {{called from here}} } @_noAllocation func callMethodGood(_ a: Int) -> Int { return genFunc(Str(x: 1), a) } @_noAllocation func callMethodBad(_ a: Int) -> Int { return genFunc(AllocatingStr(), a) // expected-note {{called from here}} } @_noAllocation func callClassMethod(_ c: Cl) { return c.classMethod() // expected-error {{called function is not known at compile time and can have unpredictable performance}} } @_noAllocation func callFinalMethod(_ c: Cl) { return c.finalMethod() } @_noAllocation func callProtocolMethod(_ p: P) -> Int { return p.protoMethod(0) // expected-error {{this code pattern can cause metadata allocation or locks}} } @_noAllocation func dynamicCast(_ a: AnyObject) -> Cl? { return a as? Cl // expected-error {{dynamic casting can lock or allocate}} } @_noAllocation func testUnsafePerformance(_ idx: Int) -> [Int] { return _unsafePerformance { [10, 20, 30, 40] } } @_noAllocation func testMemoryLayout() -> Int { return MemoryLayout<Int>.size + MemoryLayout<Int>.stride + MemoryLayout<Int>.alignment } class MyError : Error {} @_noLocks func noDiagnosticsInThrowPath(_ b: Bool) throws -> Int { if b { return 28 } throw MyError() } @_noLocks func noDiagnosticsInCatch(_ b: Bool) throws -> Int? { do { return try noDiagnosticsInThrowPath(true) } catch let e as MyError { print(e) return nil } } @_noLocks func testRecursion(_ i: Int) -> Int { if i > 0 { return testRecursion(i - 1) } return 0 } @_noLocks func testGlobal() -> Int { return Str.s + Str.s2 } @_noLocks func testGlobalWithComplexInit() -> Int { return Str.s3 // expected-note {{called from here}} } func metatypeArg<T>(_ t: T.Type, _ b: Bool) { // expected-error {{Using type 'Int' can cause metadata allocation or locks}} } @_noAllocation func callFuncWithMetatypeArg() { metatypeArg(Int.self, false) // expected-note {{called from here}} } @_noAllocation func intConversion() { let x = 42 _ = UInt(x) } @_noAllocation func integerRange() { for _ in 0 ..< 10 { } } struct GenStruct<A> { var a: A } @_noAllocation func memoryLayout() -> Int? { return MemoryLayout<GenStruct<Int>>.size } class H { var hash: Int { 27 } } struct MyStruct { static var v: Int = { // expected-note {{called from here}} return H().hash // expected-error {{Using type 'H' can cause metadata allocation or locks}} }() } @_noAllocation func globalWithInitializer(x: MyStruct) { _ = MyStruct.v // expected-note {{called from here}} } @_noAllocation func callBadClosure(closure: ()->Int) -> Int { return closure() } @_noAllocation func badClosure() { _ = callBadClosure(closure: { // expected-note {{called from here}} _ = Cl() // expected-error {{Using type 'Cl' can cause metadata allocation or locks}} return 42 }) } func badClosure2() { _ = callBadClosure(closure: { // expected-note {{called from here}} _ = Cl() // expected-error {{Using type 'Cl' can cause metadata allocation or locks}} return 42 }) } @_noAllocation func callGoodClosure(closure: ()->Int) -> Int { return closure() } @_noAllocation func goodClosure() { _ = callBadClosure(closure: { return 42 }) } func goodClosure2() { _ = callBadClosure(closure: { return 42 }) }
apache-2.0
15e21502edbf9eb9f88cac3e65d4aaae
20.4
130
0.64399
3.383088
false
false
false
false
tomerciucran/ExerciseDemo
ExerciseDemo/ExerciseViewModel.swift
1
822
// // ExerciseViewModel.swift // ExerciseDemo // // Created by Tomer Ciucran on 02/10/15. // Copyright © 2015 tomerciucran. All rights reserved. // import UIKit class ExerciseViewModel: NSObject { struct Exercise { var name: String! var videoIdentifier: String! var variation: String! init(name: String, videoIdentifier: String, variation: String) { self.name = name self.videoIdentifier = videoIdentifier self.variation = variation } } var exerciseModel: Exercise! let numberOfComponentsInPicker = 1 let numberOfRowsInPicker = 30 override init() { super.init() exerciseModel = Exercise(name: "Squats", videoIdentifier: "squats_to_chair", variation: "to chair") } }
mit
a42c9c5eee57365968d186521ca2ce2d
23.147059
107
0.618758
4.276042
false
false
false
false
alemar11/Console
Tests/ConsoleTests.swift
1
13587
// ConsoleTests.swift // // Copyright © 2016 Alessandro Marzoli. All rights reserved. // import XCTest @testable import Console class ConsoleTests: XCTestCase { override func setUp() { super.setUp() Console.minimumSeverityLevel = .verbose Console.tags = [] Console.printer = { _ in } Console.formatter = { _ in return nil } } override func tearDown() { super.tearDown() } func testSeverityLevelFiltering() { do { Console.minimumSeverityLevel = .verbose var times: Int = 0 Console.debug{ times += 1; return nil } XCTAssert(times == 1, "Fail: Didn't execute the closure exactly once.") Console.verbose{ times += 1; return nil } XCTAssert(times == 2, "Fail: Didn't execute the closure exactly twice.") Console.info{ times += 1; return nil } XCTAssert(times == 3, "Fail: Didn't execute the closure exactly thrice.") Console.warning{ times += 1; return nil } XCTAssert(times == 4, "Fail: Didn't execute the closure exactly 4 times.") Console.error{ times += 1; return nil } XCTAssert(times == 5, "Fail: Didn't execute the closure exactly 5 times.") } do { Console.minimumSeverityLevel = .error var times: Int = 0 Console.verbose{ times += 1; return nil } Console.debug{ times += 1; return nil } Console.info{ times += 1; return nil } Console.warning{ times += 1; return nil } XCTAssert(times == 0, "Fail: No closure should have been executed.") } do { var times: Int = 0 Console.minimumSeverityLevel = .debug let fakeFormatter: messageFormatter = { _ in times += 1 return nil } Console.formatter = fakeFormatter Console.error(".") Console.error(".") Console.warning(".") Console.warning(".") Console.info(".") Console.info(".") Console.debug("", tag: "TAG.") Console.debug("", tag: "TAG.") Console.verbose("", tag: "TAG.") Console.verbose("", tag: "TAG.") XCTAssert(times == 8, "Fail: No closure should have been executed.") } } func testStringInterpolation() { Console.minimumSeverityLevel = .warning class DummyObject: CustomStringConvertible { var descriptionCalled = false var description: String { descriptionCalled = true return "Object" } } do { let dummy = DummyObject() Console.verbose("Description of \(dummy).") Console.info("Description of \(dummy).") XCTAssert(!dummy.descriptionCalled, "Fail: String was interpolated when it shouldn't have been.") Console.error("The description of \(dummy) is really expensive to create.") XCTAssert(dummy.descriptionCalled, "Fail: String was interpolated when it shouldn't have been.") } do { let dummy = DummyObject() Console.verbose{return "Description of \(dummy)."} Console.info{return "Description of \(dummy)."} XCTAssert(!dummy.descriptionCalled, "Fail: String was interpolated when it shouldn't have been.") Console.error{return "Description of \(dummy)."} XCTAssert(dummy.descriptionCalled, "Fail: String was interpolated when it shouldn't have been.") } } func testTagsFiltering() { Console.minimumSeverityLevel = .verbose let tag1 = "TAG1" let tag2 = "TAG2" let tag3 = "TAG3" let tag4 = "TAG4" do { Console.tags = [tag1, tag2, tag3] var times: Int = 0 Console.debug(tag: tag1) { times += 1; return nil } XCTAssert(times == 1, "Fail: Didn't execute the closure exactly once.") } do { Console.tags = [tag1, tag2, tag3] var times: Int = 0 Console.debug(tag: tag1) { times += 1; return nil } Console.error(tag: tag2) { times += 1; return nil } Console.error { times += 1; return nil } XCTAssert(times == 2, "Fail: Didn't execute the closure exactly twice.") } do { Console.tags = [tag1, tag2, tag3] var times: Int = 0 Console.debug(tag: tag3) { times += 1; return nil } Console.info(tag: tag4) { times += 1; return nil } Console.info(tag: tag1) { times += 1; return nil } XCTAssert(times == 2, "Fail: Didn't execute the closure exactly twice.") } do { Console.tags = [tag1, tag2, tag3] var times: Int = 0 Console.debug(tag: tag4) { times += 1; return nil } Console.info(tag: tag4) { times += 1; return nil } Console.info(tag: tag4) { times += 1; return nil } Console.info { times += 1; return nil } XCTAssert(times == 0, "Fail: No closures should have been executed.") } do { Console.tags = [] //no tags var times: Int = 0 Console.debug(tag: tag4) { times += 1; return nil } Console.info(tag: tag4) { times += 1; return nil } Console.info(tag: tag4) { times += 1; return nil } XCTAssert(times == 3, "Fail: Didn't execute the closure exactly thrice.") } } func testNoPrinter() { Console.minimumSeverityLevel = .verbose Console.printer = nil var times: Int = 0 Console.verbose{ times += 1; return nil } Console.debug{ times += 1; return nil } Console.info{ times += 1; return nil } Console.warning{ times += 1; return nil } Console.error{ times += 1; return nil } XCTAssert(times == 0, "Fail: Without a console printer no closure should have been executed.") } func testOutputsCount() { Console.minimumSeverityLevel = .info let expectedOutputs = 100 var times: Int = 0 let fakeFormatter: messageFormatter = { _ in times += 1 return nil } Console.formatter = fakeFormatter for i in 1...expectedOutputs { if ( i % 2 == 0) { Console.info(i) } else { Console.warning(i) } } XCTAssert(times == expectedOutputs, "Fail: Didn't produce \(expectedOutputs) outputs.") } func testFormattedOutput() { do { Console.formatter = { level, date, message, tag, thread, function, file, line, column in return message } var result = false let message = "hello world 😀" Console.printer = { result = ($0 == message) } Console.verbose(message) XCTAssertTrue(result, "Fail: Wrong formatted console message") } do { Console.formatter = { level, date, message, tag, thread, function, file, line, column in return tag } var result = false let tag = "TAG" Console.printer = { result = ($0 == tag) } Console.verbose(tag:"TAG") XCTAssertTrue(result, "Fail: Wrong formatted console message") } do { Console.formatter = { level, date, message, tag, thread, function, file, line, column in return tag } var result = false let tag = "TAG" Console.printer = { result = ($0 == tag) } Console.verbose(tag: "TAG2") XCTAssertFalse(result, "Fail: Wrong formatted console message") } do { Console.formatter = { level, date, message, tag, thread, function, file, line, column in return function } var result = false Console.printer = { result = ($0 == #function) } Console.verbose() XCTAssertTrue(result, "Fail: Wrong formatted console message") } do { Console.formatter = { level, date, message, tag, thread, function, file, line, column in return "\(line)" } var result = false let line = 1 Console.printer = { result = ($0 == "\(line)") } Console.verbose(line: line) XCTAssertTrue(result, "Fail: Wrong formatted console message") } do { Console.formatter = { level, date, message, tag, thread, function, file, line, column in return file } var result = false let filename = "filename" Console.printer = { result = ($0 == filename) } Console.verbose(file: filename) XCTAssertTrue(result, "Fail: Wrong formatted console message") } do { Console.formatter = { level, date, message, tag, thread, function, file, line, column in return "\(column)" } var result = false let column = 1 Console.printer = { result = ($0 == "\(column)") } Console.verbose(column: column) XCTAssertTrue(result, "Fail: Wrong formatted console message") } do { Console.formatter = { level, date, message, tag, thread, function, file, line, column in return level.description } var result = false Console.printer = { result = ($0 == Level.verbose.description) } Console.verbose() XCTAssertTrue(result, "Fail: Wrong formatted console message") } do { Console.formatter = { level, date, message, tag, thread, function, file, line, column in return message?.formattedForXcodeColors(withForeground: Color.redColor() ) } let message = "hello world 😀" let coloredMessage = message.formattedForXcodeColors(withForeground: Color.redColor() ) var result = false Console.printer = { result = ($0 == coloredMessage) } Console.verbose(message) XCTAssertTrue(result, "Fail: Wrong formatted console message") } do { Console.formatter = { level, date, message, tag, thread, function, file, line, column in return message?.formattedForXcodeColors(withForeground: Color.redColor(), andBackground: Color.greenColor() ) } let message = "hello world 😀" let coloredMessage = message.formattedForXcodeColors(withForeground: Color.redColor(), andBackground: Color.greenColor() ) var result = false Console.printer = { result = ($0 == coloredMessage) } Console.verbose(message) XCTAssertTrue(result, "Fail: Wrong formatted console message") } do { let hello = "hello" let world = "world" let closure = { return hello + world } var result = false Console.printer = { result = ($0 == closure()) } Console.formatter = { level, date, message, tag, thread, function, file, line, column in return message } Console.verbose(closure: closure) XCTAssertTrue(result, "Fail: Wrong formatted console message") } } func testMessageFormatters() { let customFormatter: messageFormatter = { level, date, message, tag, thread, function, file, line, column in return ["\(level)", message, tag, thread].flatMap{$0}.map{$0.lowercaseString}.joinWithSeparator(", ") // "level, message, tag, thread" } let coloredCustomFormatter: messageFormatter = { level, date, message, tag, thread, function, file, line, column in return customFormatter(level: level, date: date, message: message, tag: tag, thread: thread, function: function, file: file, line: line, column: column)?.formattedForXcodeColors(withForeground: level.color) // "level, message, tag, thread" } Console.formatter = { level, date, message, tag, thread, function, file, line, column in let text = customFormatter(level: level, date: date, message: message, tag: tag, thread: thread, function: function, file: file, line: line, column: column) return text } do { var result = false let message = "test" let queue = "main" Console.printer = { result = ( $0 == customFormatter(level: Level.verbose, date: NSDate(), message: message, tag: nil, thread: queue, function: "function", file: "file", line: 1, column: 1) ) } Console.verbose(message) XCTAssertTrue(result, "Fail: Wrong formatted console message") } do { var result = false let message = "test" let tag = "tag" let queue = "main" Console.printer = { result = ( $0 == customFormatter(level: Level.verbose, date: NSDate(), message: message, tag: tag, thread: queue, function: "function", file: "file", line: 1, column: 1) ) } Console.verbose(message, tag: tag) XCTAssertTrue(result, "Fail: Wrong formatted console message") } do { var result = false let message = "test" let tag = "tag" let queueLabel = "com.test.serial.queue" Console.printer = { result = ( $0 == customFormatter(level: Level.verbose, date: NSDate(), message: message, tag: tag, thread: queueLabel, function: "function", file: "file", line: 1, column: 1) ) } let expectation = expectationWithDescription("Serial Queue") dispatch_async(dispatch_queue_create(queueLabel, DISPATCH_QUEUE_SERIAL)) { Console.verbose(message, tag: tag) expectation.fulfill() } waitForExpectationsWithTimeout(5.0, handler:nil) XCTAssertTrue(result, "Fail: Wrong formatted console message") } do { let message = "test" Console.formatter = { level, date, message, tag, thread, function, file, line, column in let text = coloredCustomFormatter(level: level, date: date, message: message, tag: tag, thread: thread, function: function, file: file, line: line, column: column) return text } var colored = false Console.printer = { colored = $0.hasXcodeColorsFormatting } Console.verbose(message) XCTAssertTrue(colored, "Fail: Wrong color formatting") } } }
mit
b38139b0d4e57c5594ddcbf798b358ca
32.034063
245
0.606025
4.228278
false
false
false
false
WorldDownTown/ZoomTransitioning
ZoomTransitioning/ZoomNavigationControllerDelegate.swift
1
2642
// // ZoomNavigationControllerDelegate.swift // ZoomTransitioning // // Created by WorldDownTown on 07/16/2016. // Copyright © 2016 WorldDownTown. All rights reserved. // import UIKit public final class ZoomNavigationControllerDelegate: NSObject { private let zoomInteractiveTransition: ZoomInteractiveTransition = .init() private let zoomPopGestureRecognizer: UIScreenEdgePanGestureRecognizer = .init() } // MARK: - UINavigationControllerDelegate extension ZoomNavigationControllerDelegate: UINavigationControllerDelegate { public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { if zoomPopGestureRecognizer.delegate !== zoomInteractiveTransition { zoomPopGestureRecognizer.delegate = zoomInteractiveTransition zoomPopGestureRecognizer.addTarget(zoomInteractiveTransition, action: #selector(ZoomInteractiveTransition.handle(recognizer:))) zoomPopGestureRecognizer.edges = .left navigationController.view.addGestureRecognizer(zoomPopGestureRecognizer) zoomInteractiveTransition.zoomPopGestureRecognizer = zoomPopGestureRecognizer } if let interactivePopGestureRecognizer = navigationController.interactivePopGestureRecognizer, interactivePopGestureRecognizer.delegate !== zoomInteractiveTransition { zoomInteractiveTransition.navigationController = navigationController interactivePopGestureRecognizer.delegate = zoomInteractiveTransition } } public func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return zoomInteractiveTransition.interactionController } public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if let source = fromVC as? ZoomTransitionSourceDelegate, let destination = toVC as? ZoomTransitionDestinationDelegate, operation == .push { return ZoomTransitioning(source: source, destination: destination, forward: true) } else if let source = toVC as? ZoomTransitionSourceDelegate, let destination = fromVC as? ZoomTransitionDestinationDelegate, operation == .pop { return ZoomTransitioning(source: source, destination: destination, forward: false) } return nil } }
mit
9e6a5677e3a8f9e9a64f1f790884ac9d
54.020833
253
0.786445
7.023936
false
false
false
false
qingtianbuyu/Mono
Moon/Classes/Explore/Model/MNMusicEntityList.swift
1
698
// // MNMusicEntityList.swift // Moon // // Created by YKing on 16/6/2. // Copyright © 2016年 YKing. All rights reserved. // import UIKit class MNMusicEntityList: NSObject { var start: Int = 0 var meows: [MNMeow]? func loadMusicData() { let path = Bundle.main.path(forResource: "explore-music.plist", ofType: nil) let videoEntityDict = NSDictionary(contentsOfFile: path!) as! [String: AnyObject] let videoDictArray = videoEntityDict["meows"] as! NSArray var videoArray = [MNMeow]() for videoDict in videoDictArray { let tmp = videoDict as! [String: AnyObject] videoArray.append(MNMeow(dict: tmp)) } self.meows = videoArray } }
mit
a108039d7d1243bde637a8ded31465de
24.740741
88
0.664748
3.423645
false
false
false
false
brentdax/swift
test/decl/overload.swift
4
18156
// RUN: %target-typecheck-verify-swift var var_redecl1: Int // expected-note {{previously declared here}} var_redecl1 = 0 var var_redecl1: UInt // expected-error {{invalid redeclaration of 'var_redecl1'}} var var_redecl2: Int // expected-note {{previously declared here}} var_redecl2 = 0 var var_redecl2: Int // expected-error {{invalid redeclaration of 'var_redecl2'}} var var_redecl3: (Int) -> () { get {} } // expected-note {{previously declared here}} var var_redecl3: () -> () { get {} } // expected-error {{invalid redeclaration of 'var_redecl3'}} var var_redecl4: Int // expected-note 2{{previously declared here}} var var_redecl4: Int // expected-error {{invalid redeclaration of 'var_redecl4'}} var var_redecl4: Int // expected-error {{invalid redeclaration of 'var_redecl4'}} let let_redecl1: Int = 0 // expected-note {{previously declared here}} let let_redecl1: UInt = 0 // expected-error {{invalid redeclaration}} let let_redecl2: Int = 0 // expected-note {{previously declared here}} let let_redecl2: Int = 0 // expected-error {{invalid redeclaration}} class class_redecl1 {} // expected-note {{previously declared here}} class class_redecl1 {} // expected-error {{invalid redeclaration}} class class_redecl2<T> {} // expected-note {{previously declared here}} class class_redecl2 {} // expected-error {{invalid redeclaration}} class class_redecl3 {} // expected-note {{previously declared here}} class class_redecl3<T> {} // expected-error {{invalid redeclaration}} struct struct_redecl1 {} // expected-note {{previously declared here}} struct struct_redecl1 {} // expected-error {{invalid redeclaration}} struct struct_redecl2<T> {} // expected-note {{previously declared here}} struct struct_redecl2 {} // expected-error {{invalid redeclaration}} struct struct_redecl3 {} // expected-note {{previously declared here}} struct struct_redecl3<T> {} // expected-error {{invalid redeclaration}} enum enum_redecl1 {} // expected-note {{previously declared here}} enum enum_redecl1 {} // expected-error {{invalid redeclaration}} enum enum_redecl2<T> {} // expected-note {{previously declared here}} enum enum_redecl2 {} // expected-error {{invalid redeclaration}} enum enum_redecl3 {} // expected-note {{previously declared here}} enum enum_redecl3<T> {} // expected-error {{invalid redeclaration}} protocol protocol_redecl1 {} // expected-note {{previously declared here}} protocol protocol_redecl1 {} // expected-error {{invalid redeclaration}} typealias typealias_redecl1 = Int // expected-note {{previously declared here}} typealias typealias_redecl1 = Int // expected-error {{invalid redeclaration}} typealias typealias_redecl2 = Int // expected-note {{previously declared here}} typealias typealias_redecl2 = UInt // expected-error {{invalid redeclaration}} var mixed_redecl1: Int // expected-note {{previously declared here}} class mixed_redecl1 {} // expected-error {{invalid redeclaration}} class mixed_redecl1a : mixed_redecl1 {} class mixed_redecl2 {} // expected-note {{previously declared here}} struct mixed_redecl2 {} // expected-error {{invalid redeclaration}} class mixed_redecl3 {} // expected-note {{previously declared here}} // expected-note @-1 2{{found this candidate}} enum mixed_redecl3 {} // expected-error {{invalid redeclaration}} // expected-note @-1 2{{found this candidate}} enum mixed_redecl3a : mixed_redecl3 {} // expected-error {{'mixed_redecl3' is ambiguous for type lookup in this context}} // expected-error @-1{{'mixed_redecl3a' does not conform}} class mixed_redecl3b : mixed_redecl3 {} // expected-error {{'mixed_redecl3' is ambiguous for type lookup in this context}} class mixed_redecl4 {} // expected-note {{previously declared here}} // expected-note@-1{{found this candidate}} protocol mixed_redecl4 {} // expected-error {{invalid redeclaration}} // expected-note@-1{{found this candidate}} protocol mixed_redecl4a : mixed_redecl4 {} // expected-error {{'mixed_redecl4' is ambiguous for type lookup in this context}} class mixed_redecl5 {} // expected-note {{previously declared here}} typealias mixed_redecl5 = Int // expected-error {{invalid redeclaration}} typealias mixed_redecl5a = mixed_redecl5 func mixed_redecl6() {} // expected-note {{'mixed_redecl6()' previously declared here}} var mixed_redecl6: Int // expected-error {{invalid redeclaration of 'mixed_redecl6'}} var mixed_redecl7: Int // expected-note {{'mixed_redecl7' previously declared here}} func mixed_redecl7() {} // expected-error {{invalid redeclaration of 'mixed_redecl7()'}} func mixed_redecl8() {} // expected-note {{previously declared here}} class mixed_redecl8 {} // expected-error {{invalid redeclaration}} class mixed_redecl8a : mixed_redecl8 {} class mixed_redecl9 {} // expected-note {{previously declared here}} func mixed_redecl9() {} // expected-error {{invalid redeclaration}} func mixed_redecl10() {} // expected-note {{previously declared here}} typealias mixed_redecl10 = Int // expected-error {{invalid redeclaration}} typealias mixed_redecl11 = Int // expected-note {{previously declared here}} func mixed_redecl11() {} // expected-error {{invalid redeclaration}} var mixed_redecl12: Int // expected-note {{previously declared here}} let mixed_redecl12: Int = 0 // expected-error {{invalid redeclaration}} let mixed_redecl13: Int = 0 // expected-note {{previously declared here}} var mixed_redecl13: Int // expected-error {{invalid redeclaration}} var mixed_redecl14 : Int func mixed_redecl14(_ i: Int) {} // okay func mixed_redecl15(_ i: Int) {} var mixed_redecl15 : Int // okay var mixed_redecl16: Int // expected-note {{'mixed_redecl16' previously declared here}} func mixed_redecl16() -> Int {} // expected-error {{invalid redeclaration of 'mixed_redecl16()'}} class OverloadStaticFromBase { class func create() {} } class OverloadStaticFromBase_Derived : OverloadStaticFromBase { class func create(_ x: Int) {} } // Overloading of functions based on argument names only. func ovl_argname1(x: Int, y: Int) { } func ovl_argname1(y: Int, x: Int) { } func ovl_argname1(a: Int, b: Int) { } // Overloading with generics protocol P1 { } protocol P2 { } func ovl_generic1<T: P1 & P2>(t: T) { } // expected-note{{previous}} func ovl_generic1<U: P1 & P2>(t: U) { } // expected-error{{invalid redeclaration of 'ovl_generic1(t:)'}} func ovl_generic2<T : P1>(_: T) {} // expected-note{{previously declared here}} func ovl_generic2<T : P1>(_: T) {} // expected-error{{invalid redeclaration of 'ovl_generic2'}} func ovl_generic3<T : P1>(_ x: T) {} // OK func ovl_generic3<T : P2>(_ x: T) {} // OK // Redeclarations within nominal types struct X { } struct Y { } struct Z { var a : X, // expected-note{{previously declared here}} a : Y // expected-error{{invalid redeclaration of 'a'}} var b: X // expected-note{{previously declared here}} } extension Z { var b: Int { return 0 } // expected-error{{invalid redeclaration of 'b'}} } struct X1 { func f(a : Int) {} // expected-note{{previously declared here}} func f(a : Int) {} // expected-error{{invalid redeclaration of 'f(a:)'}} } struct X2 { func f(a : Int) {} // expected-note{{previously declared here}} typealias IntAlias = Int func f(a : IntAlias) {} // expected-error{{invalid redeclaration of 'f(a:)'}} } struct X3 { func f(a : Int) {} // expected-note{{previously declared here}} func f(a : IntAlias) {} // expected-error{{invalid redeclaration of 'f(a:)'}} typealias IntAlias = Int } struct X4 { typealias i = Int // expected-note@-1 {{previously declared}} // expected-note@-2 {{previously declared}} static var i: String { return "" } // expected-error{{invalid redeclaration of 'i'}} static func i() {} // expected-error{{invalid redeclaration of 'i()'}} static var j: Int { return 0 } // expected-note{{previously declared here}} struct j {} // expected-error{{invalid redeclaration of 'j'}} var i: Int { return 0 } func i(x: String) {} } extension X4 { static var k: Int { return 0 } // expected-note{{previously declared here}} struct k {} // expected-error{{invalid redeclaration of 'k'}} } // Generic Placeholders struct X5<t, u, v> { static var t: Int { return 0 } static func u() {} typealias v = String func foo<t>(_ t: t) { let t = t _ = t } } struct X6<T> { var foo: T // expected-note{{previously declared here}} func foo() -> T {} // expected-error{{invalid redeclaration of 'foo()'}} func foo(_ x: T) {} static var j: Int { return 0 } // expected-note{{previously declared here}} struct j {} // expected-error{{invalid redeclaration of 'j'}} } extension X6 { var k: Int { return 0 } // expected-note{{previously declared here}} func k() // expected-error@-1{{invalid redeclaration of 'k()'}} // expected-error@-2{{expected '{' in body of function declaration}} } // Subscripting struct Subscript1 { subscript (a: Int) -> Int { get { return a } } subscript (a: Float) -> Int { get { return Int(a) } } subscript (a: Int) -> Float { get { return Float(a) } } } struct Subscript2 { subscript (a: Int) -> Int { // expected-note{{previously declared here}} get { return a } } subscript (a: Int) -> Int { // expected-error{{invalid redeclaration of 'subscript(_:)'}} get { return a } } var `subscript`: Int { return 0 } } struct Subscript3 { typealias `subscript` = Int // expected-note{{previously declared here}} static func `subscript`(x: Int) -> String { return "" } // expected-error{{invalid redeclaration of 'subscript(x:)'}} func `subscript`(x: Int) -> String { return "" } subscript(x x: Int) -> String { return "" } } struct GenericSubscripts { subscript<T>(x: T) -> Int { return 0 } // expected-note{{previously declared here}} } extension GenericSubscripts { subscript<U>(x: U) -> Int { return 0 } // expected-error{{invalid redeclaration of 'subscript(_:)'}} subscript<T, U>(x: T) -> U { fatalError() } subscript<T>(x: T) -> T { fatalError() } subscript(x: Int) -> Int { return 0 } } struct GenericSubscripts2<T> { subscript(x: T) -> Int { return 0 } // expected-note{{previously declared here}} } extension GenericSubscripts2 { subscript(x: T) -> Int { return 0 } // expected-error{{invalid redeclaration of 'subscript(_:)'}} subscript<U>(x: U) -> Int { return 0 } subscript(x: T) -> T { fatalError() } subscript<U>(x: T) -> U { fatalError() } subscript<U, V>(x: U) -> V { fatalError() } subscript(x: Int) -> Int { return 0 } } struct GenericSubscripts3<T> { subscript<U>(x: T) -> U { fatalError() } // expected-note{{previously declared here}} } extension GenericSubscripts3 { subscript<U>(x: T) -> U { fatalError() } // expected-error{{invalid redeclaration of 'subscript(_:)'}} subscript<U, V>(x: U) -> V { fatalError() } subscript<U>(x: U) -> U { fatalError() } subscript(x: Int) -> Int { return 0 } } // Initializers class Initializers { init(x: Int) { } // expected-note{{previously declared here}} convenience init(x: Int) { } // expected-error{{invalid redeclaration of 'init(x:)'}} static func `init`(x: Int) -> Initializers { fatalError() } func `init`(x: Int) -> Initializers { fatalError() } } // Default arguments // <rdar://problem/13338746> func sub(x:Int64, y:Int64) -> Int64 { return x - y } // expected-note 2{{'sub(x:y:)' previously declared here}} func sub(x:Int64, y:Int64 = 1) -> Int64 { return x - y } // expected-error{{invalid redeclaration of 'sub(x:y:)'}} func sub(x:Int64 = 0, y:Int64 = 1) -> Int64 { return x - y } // expected-error{{invalid redeclaration of 'sub(x:y:)'}} // <rdar://problem/13783231> struct NoneType { } func != <T>(lhs : T, rhs : NoneType) -> Bool { // expected-note{{'!=' previously declared here}} return true } func != <T>(lhs : T, rhs : NoneType) -> Bool { // expected-error{{invalid redeclaration of '!=}} return true } // throws func throwsFunc(code: Int) { } // expected-note{{previously declared}} func throwsFunc(code: Int) throws { } // expected-error{{invalid redeclaration of 'throwsFunc(code:)'}} // throws function parameter -- OK func throwsFuncParam(_ fn: () throws -> ()) { } func throwsFuncParam(_ fn: () -> ()) { } // @escaping func escaping(x: @escaping (Int) -> Int) { } // expected-note{{previously declared}} func escaping(x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping(x:)'}} func escaping(_ x: @escaping (Int) -> Int) { } // expected-note{{previously declared}} func escaping(_ x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping'}} func escaping(a: Int, _ x: @escaping (Int) -> Int) { } // expected-note{{previously declared}} func escaping(a: Int, _ x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping(a:_:)'}} func escaping(_ a: (Int) -> Int, _ x: (Int) -> Int) { } // expected-note@-1{{previously declared}} // expected-note@-2{{previously declared}} // expected-note@-3{{previously declared}} func escaping(_ a: (Int) -> Int, _ x: @escaping (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping'}} func escaping(_ a: @escaping (Int) -> Int, _ x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping'}} func escaping(_ a: @escaping (Int) -> Int, _ x: @escaping (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping'}} struct Escaping { func escaping(_ x: @escaping (Int) -> Int) { } // expected-note{{previously declared}} func escaping(_ x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping'}} func escaping(a: Int, _ x: @escaping (Int) -> Int) { } // expected-note{{previously declared}} func escaping(a: Int, _ x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping(a:_:)'}} } // @autoclosure func autoclosure(f: () -> Int) { } func autoclosure(f: @autoclosure () -> Int) { } // inout func inout2(x: Int) { } func inout2(x: inout Int) { } // optionals func optional(x: Int?) { } // expected-note{{previously declared}} func optional(x: Int!) { } // expected-error{{invalid redeclaration of 'optional(x:)'}} func optionalInOut(x: inout Int?) { } // expected-note{{previously declared}} func optionalInOut(x: inout Int!) { } // expected-error{{invalid redeclaration of 'optionalInOut(x:)}} class optionalOverloads { class func optionalInOut(x: inout Int?) { } // expected-note{{previously declared}} class func optionalInOut(x: inout Int!) { } // expected-error{{invalid redeclaration of 'optionalInOut(x:)'}} func optionalInOut(x: inout Int?) { } // expected-note{{previously declared}} func optionalInOut(x: inout Int!) { } // expected-error{{invalid redeclaration of 'optionalInOut(x:)}} } func optional_3() -> Int? { } // expected-note{{previously declared}} func optional_3() -> Int! { } // expected-error{{invalid redeclaration of 'optional_3()'}} // mutating / nonmutating protocol ProtocolWithMutating { mutating func test1() // expected-note {{previously declared}} func test1() // expected-error{{invalid redeclaration of 'test1()'}} mutating func test2(_ a: Int?) // expected-note {{previously declared}} func test2(_ a: Int!) // expected-error{{invalid redeclaration of 'test2'}} mutating static func classTest1() // expected-error {{static functions must not be declared mutating}} {{3-12=}} expected-note {{previously declared}} static func classTest1() // expected-error{{invalid redeclaration of 'classTest1()'}} } struct StructWithMutating { mutating func test1() { } // expected-note {{previously declared}} func test1() { } // expected-error{{invalid redeclaration of 'test1()'}} mutating func test2(_ a: Int?) { } // expected-note {{previously declared}} func test2(_ a: Int!) { } // expected-error{{invalid redeclaration of 'test2'}} } enum EnumWithMutating { mutating func test1() { } // expected-note {{previously declared}} func test1() { } // expected-error{{invalid redeclaration of 'test1()'}} } protocol ProtocolWithAssociatedTypes { associatedtype t // expected-note@-1 {{previously declared}} // expected-note@-2 {{previously declared}} static var t: Int { get } // expected-error{{invalid redeclaration of 't'}} static func t() // expected-error{{invalid redeclaration of 't()'}} associatedtype u associatedtype v // Instance requirements are fine. var t: Int { get } func u() mutating func v() associatedtype W func foo<W>(_ x: W) } // <rdar://problem/21783216> Ban members named Type and Protocol without backticks // https://twitter.com/jadengeller/status/619989059046240256 protocol r21783216a { // expected-error @+2 {{type member must not be named 'Type', since it would conflict with the 'foo.Type' expression}} // expected-note @+1 {{if this name is unavoidable, use backticks to escape it}} {{18-22=`Type`}} associatedtype Type // expected-error @+2 {{type member must not be named 'Protocol', since it would conflict with the 'foo.Protocol' expression}} // expected-note @+1 {{if this name is unavoidable, use backticks to escape it}} {{18-26=`Protocol`}} associatedtype Protocol } protocol r21783216b { associatedtype `Type` // ok associatedtype `Protocol` // ok } struct SR7249<T> { var x: T { fatalError() } // expected-note {{previously declared}} var y: Int // expected-note {{previously declared}} var z: Int // expected-note {{previously declared}} } extension SR7249 { var x: Int { fatalError() } // expected-warning{{redeclaration of 'x' is deprecated and will be an error in Swift 5}} var y: T { fatalError() } // expected-warning{{redeclaration of 'y' is deprecated and will be an error in Swift 5}} var z: Int { fatalError() } // expected-error{{invalid redeclaration of 'z'}} } // A constrained extension is okay. extension SR7249 where T : P1 { var x: Int { fatalError() } var y: T { fatalError() } var z: Int { fatalError() } } protocol P3 { var i: Int { get } subscript(i: Int) -> String { get } } extension P3 { var i: Int { return 0 } subscript(i: Int) -> String { return "" } } struct SR7250<T> : P3 {} extension SR7250 where T : P3 { var i: Int { return 0 } subscript(i: Int) -> String { return "" } }
apache-2.0
7e52a57723f21cd1000fdb12a1d03e5a
36.746362
152
0.676966
3.574719
false
false
false
false
Echx/GridOptic
GridOptic/GridOptic/GridOptic/OpticRepresentation/GOConcaveLensRep.swift
1
8979
// // GOConcaveLensRep.swift // GridOptic // // Created by Jiang Sheng on 1/4/15. // Copyright (c) 2015 Echx. All rights reserved. // import UIKit class GOConcaveLensRep: GOOpticRep { var thicknessCenter: CGFloat = ConcaveLensRepDefaults.defaultThicknessCenter var thicknessEdge: CGFloat = ConcaveLensRepDefaults.defaultThicknessEdge var curvatureRadius: CGFloat = ConcaveLensRepDefaults.defaultCurvatureRadius var thicknessDifference: CGFloat { get { return self.thicknessEdge - self.thicknessCenter } } var normalDirection: CGVector { get { return CGVectorMake(self.direction.dy, -self.direction.dx) } } var inverseNormalDirection: CGVector { get { return CGVectorMake(-self.normalDirection.dx, -self.normalDirection.dy) } } var length: CGFloat { get { return 2 * sqrt(self.curvatureRadius * self.curvatureRadius - (self.curvatureRadius - self.thicknessDifference / 2) * (self.curvatureRadius - self.thicknessDifference / 2)) } } override var bezierPath: UIBezierPath { get { var path1 = UIBezierPath() path1.appendPath(self.edges[ConcaveLensRepDefaults.rightArcTag].bezierPath) path1.addLineToPoint(self.edges[ConcaveLensRepDefaults.topEdgeTag].center) path1.addLineToPoint(self.edges[ConcaveLensRepDefaults.bottomEdgeTag].center) path1.closePath() var path2 = UIBezierPath() path2.appendPath(self.edges[ConcaveLensRepDefaults.leftArcTag].bezierPath) path2.addLineToPoint(self.edges[ConcaveLensRepDefaults.bottomEdgeTag].center) path2.addLineToPoint(self.edges[ConcaveLensRepDefaults.topEdgeTag].center) path2.closePath() path1.appendPath(path2) return path1 } } override var vertices: [CGPoint] { get { let angle = self.direction.angleFromXPlus let length = self.length let width = self.thicknessEdge let originalPoints = [ CGPointMake(-length/2, -width/2), CGPointMake(length/2, -width/2), CGPointMake(length/2, width/2), CGPointMake(-length/2, width/2) ] var finalPoints = [CGPoint]() for point in originalPoints { finalPoints.append(CGPoint.getPointAfterRotation(angle, from: point, translate: CGPointMake(CGFloat(self.center.x), CGFloat(self.center.y)))) } return finalPoints } } init(center: GOCoordinate, direction: CGVector, thicknessCenter: CGFloat, thicknessEdge: CGFloat, curvatureRadius: CGFloat, id: String, refractionIndex: CGFloat) { self.thicknessCenter = thicknessCenter self.thicknessEdge = thicknessEdge self.curvatureRadius = curvatureRadius super.init(id: id, center: center) self.refractionIndex = refractionIndex self.setUpEdges() self.setDirection(direction) self.setDeviceType(DeviceType.Lens) self.updateEdgesParent() } init(center: GOCoordinate, direction: CGVector, id: String, refractionIndex: CGFloat) { super.init(id: id, center: center) self.refractionIndex = refractionIndex self.setUpEdges() self.setDirection(direction) self.updateEdgesParent() } init(center: GOCoordinate, id: String, refractionIndex: CGFloat) { super.init(id: id, center: center) self.refractionIndex = refractionIndex self.setUpEdges() self.setDirection(self.direction) self.updateEdgesParent() } required convenience init(coder aDecoder: NSCoder) { let id = aDecoder.decodeObjectForKey(GOCodingKey.optic_id) as String let edges = aDecoder.decodeObjectForKey(GOCodingKey.optic_edges) as [GOSegment] let typeRaw = aDecoder.decodeObjectForKey(GOCodingKey.optic_type) as Int let type = DeviceType(rawValue: typeRaw) let thickCenter = aDecoder.decodeObjectForKey(GOCodingKey.optic_thickCenter) as CGFloat let thickEdge = aDecoder.decodeObjectForKey(GOCodingKey.optic_thickEdge) as CGFloat let curvatureRadius = aDecoder.decodeObjectForKey(GOCodingKey.optic_curvatureRadius) as CGFloat let length = aDecoder.decodeObjectForKey(GOCodingKey.optic_length) as CGFloat let center = aDecoder.decodeObjectForKey(GOCodingKey.optic_center) as GOCoordinate let direction = aDecoder.decodeCGVectorForKey(GOCodingKey.optic_direction) let refIndex = aDecoder.decodeObjectForKey(GOCodingKey.optic_refractionIndex) as CGFloat self.init(center: center, direction: direction, thicknessCenter: thickCenter, thicknessEdge: thickEdge, curvatureRadius: curvatureRadius, id: id, refractionIndex: refIndex) self.type = type! self.edges = edges } override func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(id, forKey: GOCodingKey.optic_id) aCoder.encodeObject(edges, forKey: GOCodingKey.optic_edges) aCoder.encodeObject(type.rawValue, forKey: GOCodingKey.optic_type) aCoder.encodeObject(thicknessCenter, forKey: GOCodingKey.optic_thickCenter) aCoder.encodeObject(thicknessEdge, forKey: GOCodingKey.optic_thickEdge) aCoder.encodeObject(curvatureRadius, forKey: GOCodingKey.optic_curvatureRadius) aCoder.encodeObject(length, forKey: GOCodingKey.optic_length) aCoder.encodeObject(center, forKey: GOCodingKey.optic_center) aCoder.encodeCGVector(direction, forKey: GOCodingKey.optic_direction) aCoder.encodeObject(refractionIndex, forKey: GOCodingKey.optic_refractionIndex) } override func setUpEdges() { self.edges = [GOSegment]() let radianSpan = acos((self.curvatureRadius - self.thicknessDifference / 2) / self.curvatureRadius) * 2 // set up top line segment let centerTopEdge = CGPointMake(CGFloat(self.center.x), CGFloat(self.center.y) + CGFloat(self.length)/2) let topEdge = GOLineSegment(center: centerTopEdge, length: self.thicknessEdge, direction: self.normalDirection) topEdge.tag = ConcaveLensRepDefaults.topEdgeTag self.edges.append(topEdge) // set up right arc let centerRightArc = CGPointMake(CGFloat(self.center.x) + CGFloat(self.thicknessCenter)/2 + self.curvatureRadius, CGFloat(self.center.y)) let rightArc = GOArcSegment(center: centerRightArc, radius: self.curvatureRadius, radian: radianSpan, normalDirection: self.inverseNormalDirection) rightArc.tag = ConcaveLensRepDefaults.rightArcTag self.edges.append(rightArc) // set up bottom line segment let centerBottomEdge = CGPointMake(CGFloat(self.center.x), CGFloat(self.center.y) - CGFloat(self.length)/2) let bottomEdge = GOLineSegment(center: centerBottomEdge, length: self.thicknessEdge, direction: self.normalDirection) bottomEdge.tag = ConcaveLensRepDefaults.bottomEdgeTag bottomEdge.revert() self.edges.append(bottomEdge) // set up left arc let centerLeftArc = CGPointMake(CGFloat(self.center.x) - CGFloat(self.thicknessCenter)/2 - self.curvatureRadius, CGFloat(self.center.y)) let leftArc = GOArcSegment(center: centerLeftArc, radius: self.curvatureRadius, radian: radianSpan, normalDirection: self.normalDirection) leftArc.tag = ConcaveLensRepDefaults.leftArcTag self.edges.append(leftArc) } override func setDirection(direction: CGVector) { let directionDifference = direction.angleFromXPlus - self.direction.angleFromXPlus self.direction = direction for edge in self.edges { if edge.tag == ConcaveLensRepDefaults.leftArcTag { edge.center = edge.center.getPointAfterRotation(about: self.center.point, byAngle: directionDifference) edge.normalDirection = self.normalDirection } else if edge.tag == ConcaveLensRepDefaults.rightArcTag { edge.center = edge.center.getPointAfterRotation(about: self.center.point, byAngle: directionDifference) edge.normalDirection = self.inverseNormalDirection } else { edge.center = edge.center.getPointAfterRotation(about: self.center.point, byAngle: directionDifference) edge.direction = self.normalDirection } } } }
mit
b87361ef0a6fa3e1ed8b2f505fa71e16
41.353774
119
0.655307
4.500752
false
false
false
false
elfketchup/SporkVN
SporkVN/VN Classes/VNSceneNode.swift
1
188491
// // VNSceneNode.swift // SporkVN // // Created by James on 1/14/18. // Copyright © 2018 James Briones. All rights reserved. // import UIKit import SpriteKit import AVFoundation /* VNScene VNScene is the main class for displaying and interacting with the Visual Novel system (or "VN system") I've coded. VNScene works by taking script data (interpreted from a Property List file using VNScript), and processes the script to handle audio and display graphics, text, and basic animation. It also handles user input for playing the scene and user choices, plus saving related data to SMRecord. Visual and audio elements are handled by VNScene; sprites and sounds are stored in a mutable dictionary and mutable array, respectively. A record of the dialogue scene / visual-novel elements is kept by VNScene, and can be copied over to SMRecord (and from SMRecord, into device memory) when necessary. During certain "volatile" periods (like when performing effects or presenting the player with a menu of choices), VNScene will store that record in a "safe save," which is created just before the effect/choice-menu is run, and holds the data from "the last time it was safe to save the game." Afterwards, when VNScene resumes "normal" activity, then the safe-save is removed and any attempts to save the game will just draw data from the "normal" record. When processing script data from VNScript, the script is divided into "conversations," which are really an NSArray of text/NSString objects that have been converted to string and number data to be more easily processed. Different "conversations" represent branching paths in the script. When VNScene begins processing script data, it always starts with a converation named "start". */ /* Coding/readability notes NOTE: What would become VNScene was originally written as part of a visual-novel game engine that I made in conjuction with a custom sprite-drawing kit written in OpenGL ES v1. At that time, it used the MVC (Model-View-Controller) model, where there were separate classes for each. Later, I ported the code over to Cocos2D (which worked MUCH better than my custom graphics kit), and the View and Controller classes were mixed together to form VNScene, while VNScript held the Model information. I've tried to clean up the code so it would make sense to reflect how things work now, but there are still some quirks and "leftovers" from the prior version of the code. Added January 2014: Also, upgrading to Cocos2D v3.0 caused some other changes to be made. VNScene used to be VNLayer, and inherited from CCLayer. Since that class has been removed, VNScene now inherits from CCScene. As some other Cocos2D classes have been renamed or had major changes, the classes in EKVN that relied on Cocos2D have had to change or be renamed alongside that. I've cleaned up the code somewhat, but it's possible that there are still some comments and other references to the "old" version of Cocos2D that I haven't spotted! Added September 2014: EKVN SpriteKit has been ported from cocos2d to -- as you might have guessed -- SpriteKit. The two are kind of similar, but there are enough differences to make seemingly normal things (like positioning nodes) act differently. To maintain compatibility with the "regular" EKVN that uses cocos2d, a lot of old code (and commments!) have been left in, but hacked/patched to work with SpriteKit. In short, some things are going to look a little confusing. */ /** Defintions and Constants **/ let VNSceneActivityType = "VNScene" // The type of activity this is (used in conjuction with SMRecord) let VNSceneToPlayKey = "scene to play" let VNSceneViewFontSize = 17 let VNSceneSpriteIsSafeToRemove = "sprite is safe to remove" // Used for sprite removal (to free up memory and remove unused sprite) let VNScenePopSceneWhenDoneKey = "pop scene when done" // Ask CCDirector to pop the scene when the script finishes? let VNSceneDiceRollResultFlag = "DICEROLL" // flag that stores results of dice rolls // Sprite alignment strings (used for commands) let VNSceneViewSpriteAlignmentLeftString = "left" // 25% of screen width let VNSceneViewSpriteAlignmentCenterString = "center" // 50% of screen width let VNSceneViewSpriteAlignmentRightString = "right" // 75% of screen width let VNSceneViewSpriteAlignemntFarLeftString = "far left" // 0% of screen width let VNSceneViewSpriteAlignmentExtremeLeftString = "extreme left" // -50% of screen width; offscreen to the left let VNSceneViewSpriteAlignmentFarRightString = "far right" // 100% of screen width let VNSceneViewSpriteAlignmentExtremeRightString = "extreme right" // 150% of screen width; offscreen to the right // View settings keys let VNSceneViewTalkboxName = "talkbox.png" let VNSceneViewSpeechBoxOffsetFromBottomKey = "speechbox offset from bottom" let VNSceneViewSpriteTransitionSpeedKey = "sprite transition speed" let VNSceneViewTextTransitionSpeedKey = "text transition speed" let VNSceneViewNameTransitionSpeedKey = "speaker name transition speed" let VNSceneViewSpeechBoxXKey = "speech box x" let VNSceneViewSpeechBoxYKey = "speech box y" let VNSceneViewNameXKey = "name x" let VNSceneViewNameYKey = "name y" let VNSceneViewSpeechXKey = "speech x" let VNSceneViewSpeechYKey = "speech y" let VNSceneViewSpriteXKey = "sprite x" let VNSceneViewSpriteYKey = "sprite y" let VNSceneViewButtonXKey = "button x" let VNSceneViewButtonYKey = "button y" let VNSceneViewSpeechHorizontalMarginsKey = "speech horizontal margins" let VNSceneViewSpeechVerticalMarginsKey = "speech vertical margins" let VNSceneViewSpeechBoxFilenameKey = "speech box filename" let VNSceneViewSpeechOffsetXKey = "speech offset x" let VNSceneViewSpeechOffsetYKey = "speech offset y" let VNSceneViewDefaultBackgroundOpacityKey = "default background opacity" let VNSceneViewMultiplyFontSizeForiPadKey = "multiply font size for iPad" let VNSceneViewButtonUntouchedColorsKey = "button untouched colors" let VNSceneViewButtonsTouchedColorsKey = "button touched colors" let VNSceneViewDoesUseHeightMarginForAdsKey = "does use height margin for ads" // currently does nothing let VNSceneViewButtonTextColorKey = "button text color" // color of the text in buttons let VNSceneViewSpeechboxColorKey = "speechbox color" // color speech box let VNSceneViewSpeechboxTextColorKey = "speechbox text color" // color of text in speech box (both dialogue and speaker name) let VNSceneViewChoiceButtonOffsetX = "choicebox offset x" let VNSceneViewChoiceButtonOffsetY = "choicebox offset y" // Resource dictionary keys let VNSceneViewSpeechTextKey = "speech text" let VNSceneViewSpeakerNameKey = "speaker name" let VNSceneViewShowSpeechKey = "show speech flag" let VNSceneViewBackgroundResourceKey = "background resource" let VNSceneViewAudioInfoKey = "audio info" let VNSceneViewSpriteResourcesKey = "sprite resources" let VNSceneViewSpriteNameKey = "sprite name" let VNSceneViewSpriteAlphaKey = "sprite alpha" let VNSceneViewSpeakerNameXOffsetKey = "speaker name offset x" let VNSceneViewSpeakerNameYOffsetKey = "speaker name offset y" let VNSceneViewButtonFilenameKey = "button filename" let VNSceneViewFontSizeKey = "font size" let VNSceneViewFontNameKey = "font name" let VNSceneViewOverrideSpeechFontKey = "override speech font from save" let VNSceneViewOverrideSpeechSizeKey = "override speech size from save" let VNSceneViewOverrideSpeakerFontKey = "override speaker font from save" let VNSceneViewOverrideSpeakerSizeKey = "override speaker size from save" let VNSceneViewNoSkipUntilTextShownKey = "no skipping until text is shown" // Prevents skipping until the text is fully shown // Dictionary keys let VNSceneSavedScriptInfoKey = "script info" let VNSceneSavedResourcesKey = "saved resources" let VNSceneMusicToPlayKey = "music to play" let VNSceneMusicShouldLoopKey = "music should loop" let VNSceneSpritesToShowKey = "sprites to show" let VNSceneSoundsToRemoveKey = "sounds to remove" let VNSceneMusicToRemoveKey = "music to remove" let VNSceneBackgroundToShowKey = "background to show" let VNSceneSpeakerNameToShowKey = "speaker name to show" let VNSceneSpeechToDisplayKey = "speech to display" let VNSceneShowSpeechKey = "show speech" let VNSceneBackgroundXKey = "background x" let VNSceneBackgroundYKey = "background y" let VNSceneTypewriterTextCanSkip = "typewriter text can skip" let VNSceneTypewriterTextSpeed = "typewriter text speed" let VNSceneSavedOverriddenSpeechboxKey = "overridden speechbox" // used to store speechbox sprites modified by .SETSPEECHBOX in saves let VNSceneChoiceSetsKey = "choice sets" // stores choice sets that can be modified on the fly and dislayed whenever // UI "override" keys (used when you change things like font size/font name in the middle of a scene). // By default, any changes will be restored when a saved game is loaded, though the "override X from save" // settings can change this. let VNSceneOverrideSpeechFontKey = "override speech font" let VNSceneOverrideSpeechSizeKey = "override speech size" let VNSceneOverrideSpeakerFontKey = "override speaker font" let VNSceneOverrideSpeakerSizeKey = "override speaker size" // Graphics/display stuff let VNSceneViewSettingsFileName = "vnscene view settings" let VNSceneSpriteXKey = "x position" let VNSceneSpriteYKey = "y position" // Sprite/node layers let VNSceneBackgroundLayer:CGFloat = 50.0 let VNSceneCharacterLayer:CGFloat = 60.0 let VNSceneUILayer:CGFloat = 100.0 let VNSceneTextLayer:CGFloat = 110.0 let VNSceneButtonsLayer:CGFloat = 120.0 let VNSceneButtonTextLayer:CGFloat = 130.0 // Node tags (NOTE: In Cocos2D v3.0, numeric tags were replaced with string-based names, similar to Sprite Kit) let VNSceneTagSpeechBox = "speech box" //600 let VNSceneTagSpeakerName = "speaker name" //601 let VNSceneTagSpeechText = "speech text" //602 let VNSceneTagBackground = "background" //603 // Scene modes let VNSceneModeLoading = 100 let VNSceneModeFinishedLoading = 101 let VNSceneModeNormal = 200 // Normal "playing," with dialogue and interaction let VNSceneModeEffectIsRunning = 201 // An Effect (fade-in/fade-out, sprite-movement, etc.) is currently running let VNSceneModeChoiceWithFlag = 202 let VNSceneModeChoiceWithJump = 203 let VNSceneModeEnded = 300 // There isn't any more script data to process // Transition types (currently unused, but can be used to transition to other types of SKScene subclasses) let VNSceneTransitionTypeNone = 00 // Other constants let VNSceneNodeChoiceButtonStartingPercentage = CGFloat(0.63) // A percentage of the screen height, is used for positioning buttons during choices private var VNSceneNodeSharedInstance:VNSceneNode? = nil class VNSceneNode : SKNode { var script:VNScript? class var sharedScene:VNSceneNode? { if( VNSceneNodeSharedInstance != nil ) { return VNSceneNodeSharedInstance } return nil } // A helper class that can be used to handle .systemcall commands. var systemCallHelper:VNSystemCall = VNSystemCall() var record:NSMutableDictionary = NSMutableDictionary() // Holds misc data (especially regarding the script) var flags:NSMutableDictionary = NSMutableDictionary() // Local flags data (later saved to SMRecord's flags, when the scene is saved) var mode:Int = VNSceneModeLoading // What the scene is doing (or should be doing) at the current moment // The "safe save" is an pseudo-autosave created right before performing a "dangerous" action like running an EKEffect. // Since saving the game in the middle of an effectt can cause unexpected results (like sprites being in the wrong // position), VNScene won't allow for anything to be saved until a "safe" point can be reached. Instead, VNScene saves // its data into this dictionary object beforehand, and if the user attempts to save the game in the middle of an effect, // they will only save the "safe" information instead of anything dangerous. Of course, when the "dangerous" part ends, // this dictionary is deleted, and things can be saved as normal. var safeSave:NSMutableDictionary = NSMutableDictionary() // View data var viewSettings:NSMutableDictionary = NSMutableDictionary() var viewSize = CGSize(width: 0, height: 0) var effectIsRunning = false var isPlayingMusic = false var noSkippingUntilTextIsShown = false var backgroundMusic:AVAudioPlayer? = nil var soundsLoaded = NSMutableArray() var buttons:NSMutableArray = NSMutableArray() var choices:NSMutableArray = NSMutableArray() // Holds values that will be used when making choices var choiceExtras:NSMutableArray = NSMutableArray() // Holds extra data that's used when making choices (usually, flag data) var buttonPicked:Int = -1 // Keeps track of the most recently touched button in the menu var sprites = NSMutableDictionary() var spritesToRemove = NSMutableArray() var localSpriteAliases = NSMutableDictionary() var speechBox:SKSpriteNode? // Dialogue box var speech:SMTextNode? // The text displayed as dialogue var speaker:SMTextNode? // Name of speaker var speechBoxColor = UIColor.white var speechBoxTextColor = UIColor.white /* NOTE: Currently heigh margins aren't used or haven't been incorporated */ /* (also note that support for ads hasn't really been added, and would probably be an experimental feature if it were) */ var heightMarginForAds = CGFloat(0) // affects sprite Y-position when ads are shown var doesUseHeightMarginForAds = false // determines whether or not ad-based height margins are used var speechFont = ""; // The name of the font used by the speech text var speakerFont = "Helvetica"; // The name of the font used by the speaker text var fontSizeForSpeech:CGFloat = 17.0 var fontSizeForSpeaker:CGFloat = 19.0 var spriteTransitionSpeed:Double = 0.5 var speechTransitionSpeed:Double = 0.5 var speakerTransitionSpeed:Double = 0.5 var buttonTouchedColors = UIColor.blue var buttonUntouchedColors = UIColor.black var buttonTextColor = UIColor.white var choiceButtonOffsetX = CGFloat(0) var choiceButtonOffsetY = CGFloat(0) var previousScene:SKScene? = nil var allSettings:NSDictionary? var isFinished = false var wasJustLoadedFromSave = true var popSceneWhenDone = false // Typewriter text var TWModeEnabled = false; // Off by default (standard EKVN text mode) var TWCanSkip = true; // Can the user skip ahead (and cut the text short) by tapping? var TWSpeedInCharacters = 0; // How many characters it should print per second var TWSpeedInFrames = 0 var TWTimer = 0; // Used to determine how many characters should be displayed (relative to the time/speed of displaying characters) var TWSpeedInSeconds = 0.0 var TWNumberOfCurrentCharacters = 0 var TWPreviousNumberOfCurrentChars = 0 var TWNumberOfTotalCharacters = 0 var TWCurrentText = " "; // What's currently on the screen var TWFullText = " "; // The entire line of text // Used to handle SpriteKit's weird text-display quirks var TWInvisibleText:SMTextNode? = nil // Choice sets, used to store dynamically added/removed choices var choiceSets = NSMutableDictionary() // MARK: - Initialization override init() { super.init() } init(settings:NSDictionary) { super.init() allSettings = NSDictionary(dictionary: settings) // copy all dictionary values } // Just something that Xcode wants me to put in required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) print("[VNSceneNode] ERROR: Initialization via NSCoder has not been implemented!") } // This is called OUTSIDE of this class by whatever function or class initializes VNSceneNode; this function is usually called // immediately afterwards, right before VNSceneNode gets added to a parent node func loadDataOnView(view:SKView) { SMSetScreenDataFromView(view); // Get view and screen size data; this is used to position UI elements let fooW = view.frame.size.width let fooH = view.frame.size.height /* let testImage = SKSpriteNode(imageNamed: "pond") testImage.position = CGPoint(x: fooW*0.5, y: fooH*0.5) testImage.zPosition = 1; testImage.colorBlendFactor = 1.0 testImage.color = UIColor.red self.addChild(testImage)*/ print("Width is \(fooW) and height is \(fooH)") isFinished = false isUserInteractionEnabled = true wasJustLoadedFromSave = true popSceneWhenDone = true // Set default values mode = VNSceneModeLoading; // Mode is "loading resources" effectIsRunning = false; isPlayingMusic = false; buttonPicked = -1; soundsLoaded = NSMutableArray() sprites = NSMutableDictionary() record = NSMutableDictionary(dictionary: allSettings!) flags = NSMutableDictionary(dictionary: SMRecord.sharedRecord.flags()) choiceSets = NSMutableDictionary(dictionary: SMRecord.sharedRecord.choiceSetsFromRecord()) // Also set the defaults for text-skipping behavior noSkippingUntilTextIsShown = false // Set default UI values fontSizeForSpeaker = 0.0; fontSizeForSpeech = 0.0; viewSize = view.frame.size // Try to load script info from any saved script data that might exist. Otherwise, just create a fresh script object let savedScriptInfo:NSDictionary? = allSettings!.object(forKey: VNSceneSavedScriptInfoKey) as? NSDictionary // Was there previous saved script / saved game data? if( savedScriptInfo != nil ) { // Load script data from a saved game //script = VNScript(info: savedScriptInfo!)! let loadedScript:VNScript? = VNScript(info: savedScriptInfo!) if( loadedScript == nil ) { print("[SMRecord] ERROR: Could not load VNScript object.") return } script = loadedScript! wasJustLoadedFromSave = true // Set flag; this is important since it's meant to prevent autosave errors script!.indexesDone = script!.currentIndex print("[VNScene] Settings were loaded from a saved game.") } else { // No previous saved data let scriptFileName:NSString? = allSettings!.object(forKey: VNSceneToPlayKey) as? NSString if( scriptFileName == nil ) { print("[VNScene] ERROR: Could not load script file for new scene.") return } else { print("[VNScene] The name of the script to be loaded is [\(scriptFileName!)]") } // Create the dictionary that will be used to load script data from a file let dictionaryForScriptLoading = NSMutableDictionary() dictionaryForScriptLoading.setValue(scriptFileName, forKey: VNScriptFilenameKey) dictionaryForScriptLoading.setValue(VNScriptStartingPoint, forKey: VNScriptConversationNameKey) // Create script data let loadedScript:VNScript? = VNScript(info: dictionaryForScriptLoading) if loadedScript == nil { print("[VNScene] ERROR: Could not load script named: \(String(describing: scriptFileName))") return } // Otherwise... print("[VNScene] Settings were loaded from a script file.") script = loadedScript } // Load default view settings //[self loadDefaultViewSettings) // The standard settings loadDefaultViewSettings() print("[VNScene] Default view settings loaded."); // Load any "extra" view settings that may exist in a certain Property List file ("VNScene View Settings.plist") //NSString* filePath = [[NSBundle mainBundle] pathForResource:VNSceneViewSettingsFileName ofType:@"plist") let filePath:NSString? = Bundle.main.path(forResource: VNSceneViewSettingsFileName, ofType: "plist") as NSString? if filePath != nil { let manualSettings:NSDictionary? = NSDictionary(contentsOfFile: filePath! as String) if manualSettings != nil { print("[VNScene] Manual settings found; will load into view settings dictionary.") viewSettings.addEntries(from: manualSettings! as! [AnyHashable: Any]) // Copy custom settings to UI dictionary; overwrite default values } } // This mimics cocos2d's ability to "pop" a scene when it's finished running... however, SpriteKit doesn't // have built-in push/pop support for SKScene, so it has to be done manually, and in some cases it might // not be a good idea (such as if there's no previous scene to pop to). This flag tracks whether or not // to attempt to "pop" the scene when it's finished. let shouldPopWhenDone:NSNumber? = record.object(forKey: VNScenePopSceneWhenDoneKey) as? NSNumber if( shouldPopWhenDone != nil ) { popSceneWhenDone = shouldPopWhenDone!.boolValue } loadUI() // Load the UI using settings dictionary print("[VNScene] This instance of VNScene will now become the primary VNScene instance."); VNSceneNodeSharedInstance = self; //self.allSettings = nil; // Free up space } // MARK: - Audio /** AUDIO **/ func stopBGMusic() { /*if( isPlayingMusic == true ) { //[[OALSimpleAudio sharedInstance] stopBg) OALSimpleAudio.sharedInstance().stopBg() }*/ //OALSimpleAudio.sharedInstance().stopBg() if backgroundMusic != nil { backgroundMusic!.stop() } isPlayingMusic = false; } //- (void)playBGMusic:(NSString*)filename willLoop:(BOOL)willLoopForever func playBGMusic(_ filename:String, willLoopForever:Bool) { //[self stopBGMusic) // Cancel any existing music stopBGMusic() //OALSimpleAudio.sharedInstance().playEffect(filename, loop: willLoopForever) //OALSimpleAudio.sharedInstance().playBg(filename, loop: willLoopForever) if SMStringLength(filename) < 1 { print("[VNScene] ERROR: Could not load background music because input filename is invalid.") return; } backgroundMusic = SMAudioSoundFromFile(filename) if backgroundMusic == nil { print("[VNScene] ERROR: Could not load background music from file named: \(filename)") return; } if willLoopForever == true { backgroundMusic!.numberOfLoops = -1 } backgroundMusic!.play() isPlayingMusic = true; } //- (void)playSoundEffect:(NSString*)filename func playSoundEffect(_ filename:String) { //[self runAction:[SKAction playSoundFileNamed:filename waitForCompletion:NO]) //[[OALSimpleAudio sharedInstance] playEffect:filename) //OALSimpleAudio.sharedInstance().playEffect(filename) if SMStringLength(filename) < 1 { print("[VNScene] ERROR: Could not play sound effect because input filename was invalid.") return; } let playSoundEffectAction = SKAction.playSoundFileNamed(filename, waitForCompletion: false) self.run(playSoundEffectAction) } // MARK: - Other setup or deletion functions /** Other setup or deletion functions **/ // The state of VNScene's UI is stored whenever the game is saved. That way, in case music is playing, or some text is // supposed to be on screen, VNScene will remember and SHOULD restore things to exactly the way they were when the game // was saved. The restoration of UI is what this function is for. func loadSavedResources() { // Load any saved resource information from the dictionary let savedSprites:NSArray? = record.object(forKey: VNSceneSpritesToShowKey) as? NSArray let loadedMusic:NSString? = record.object(forKey: VNSceneMusicToPlayKey) as? NSString let savedBackground:NSString? = record.object(forKey: VNSceneBackgroundToShowKey) as? NSString let savedSpeakerName:NSString? = record.object(forKey: VNSceneSpeakerNameToShowKey) as? NSString let savedSpeech:NSString? = record.object(forKey: VNSceneSpeechToDisplayKey) as? NSString let savedSpeechbox:NSString? = record.object(forKey: VNSceneSavedOverriddenSpeechboxKey) as? NSString let showSpeechKey:NSNumber? = record.object(forKey: VNSceneShowSpeechKey) as? NSNumber let musicShouldLoop:NSNumber? = record.object(forKey: VNSceneMusicShouldLoopKey) as? NSNumber let savedBackgroundX:NSNumber? = record.object(forKey: VNSceneBackgroundXKey) as? NSNumber let savedBackgroundY:NSNumber? = record.object(forKey: VNSceneBackgroundYKey) as? NSNumber //let screenSize:CGSize = viewSize; // Screensize is loaded to help position UI elements // This determines whether or not the speechbox will be shown. By default, the speechbox is hidden // until a point in the script manually tells it to be shown, but when loading from a saved game, // it's necessary to know whether or not the box should be shown already if( showSpeechKey != nil ) { if( showSpeechKey!.boolValue == false ) { speechBox!.alpha = 0.1 } else { speechBox!.alpha = 1.0 } } // Load speaker name (if any exists) if( savedSpeakerName != nil ) { //speaker!.text = savedSpeakerName; speaker!.text = savedSpeakerName! as String } // Load speech data (if any exists) if( savedSpeech != nil ) { //[speech setString:savedSpeech) speech!.text = savedSpeech! as String } //if( self.wasJustLoadedFromSave == YES ) if wasJustLoadedFromSave == true { //[speech setText:@" ") // Use empty text as the default speech!.text = " " } // Load background image (CCSprite) if( savedBackground != nil ) { // Create/load saved background coordinates var backgroundX = viewSize.width * 0.5; // By default, the background would be positioned in the middle of the screen var backgroundY = viewSize.height * 0.5; // Check for custom background coordinates if( savedBackgroundX != nil ) { backgroundX = CGFloat(savedBackgroundX!.doubleValue) } if( savedBackgroundY != nil ) { backgroundY = CGFloat(savedBackgroundY!.doubleValue) } // Create and add background image node let background:SKSpriteNode = SKSpriteNode(imageNamed:savedBackground! as String) background.position = CGPoint( x: backgroundX, y: backgroundY ) background.zPosition = VNSceneBackgroundLayer background.name = VNSceneTagBackground addChild( background ) } // Load any music that was saved if( loadedMusic != nil ) { var loopFlag = true // Default value provided in case the "should loop" flag doesn't couldn't be loaded if musicShouldLoop != nil { loopFlag = musicShouldLoop!.boolValue } isPlayingMusic = true; playBGMusic(loadedMusic! as String, willLoopForever: loopFlag) } // Check if any sprites need to be displayed if( savedSprites != nil ) { print("[VNScene] Sprite data was found in the saved game data.") // Check each entry of sprite data that was found, and start loading them into memory and displaying them onto the screen. // In theory, the process should be fast enough (and the number of sprites FEW enough) that the user shouldn't notice any delays. //for( NSDictionary* spriteData in savedSprites ) { for spriteData in savedSprites! { var doesHaveAlias = true // default assumption, used for loading sprite alias data // Grab sprite data from dictionary let nameOfSprite:NSString = (spriteData as AnyObject).object(forKey: "name") as! NSString print("[VNScene] Restoring saved sprite named: \(nameOfSprite)"); // check for filename var filenameOfSprite:NSString? = (spriteData as AnyObject).object(forKey: "filename") as? NSString if( filenameOfSprite == nil ) { doesHaveAlias = false filenameOfSprite = nameOfSprite } // Load sprite object and set its coordinates let spriteX:CGFloat = CGFloat(((spriteData as AnyObject).object(forKey: "x") as! NSNumber).doubleValue) let spriteY:CGFloat = CGFloat(((spriteData as AnyObject).object(forKey: "y") as! NSNumber).doubleValue) let scaleX:CGFloat = CGFloat(((spriteData as AnyObject).object(forKey: "scale x") as! NSNumber).doubleValue) let scaleY:CGFloat = CGFloat(((spriteData as AnyObject).object(forKey: "scale y") as! NSNumber).doubleValue) // check if this will incorporate height margin for ads if( doesUseHeightMarginForAds == true ) { //spriteY = spriteY - heightMarginForAds; } let sprite = SKSpriteNode(imageNamed: filenameOfSprite! as String) sprite.position = CGPoint(x: spriteX, y: spriteY) sprite.xScale = scaleX sprite.yScale = scaleY sprite.zPosition = VNSceneCharacterLayer addChild(sprite) // Finally, add the sprite to the 'sprites' dictionary2 sprites.setValue(sprite, forKey: nameOfSprite as String) // copy sprite alias data to local sprite aliases dictionary if doesHaveAlias == true { localSpriteAliases.setValue(filenameOfSprite, forKey:nameOfSprite as String) } } } if savedSpeechbox != nil { let widthOfScreen = viewSize.width;//SMScreenSizeInPoints().width var originalChildren:NSArray? = nil let boxToBottomMargin = CGFloat( (viewSettings.object(forKey: VNSceneViewSpeechBoxOffsetFromBottomKey) as! NSNumber).floatValue ) if speechBox != nil { originalChildren = speechBox!.children as NSArray? speechBox!.removeFromParent() } speechBox = SKSpriteNode(imageNamed: savedSpeechbox! as String) speechBox!.position = CGPoint( x: widthOfScreen * 0.5, y: (speechBox!.frame.size.height * 0.5) + boxToBottomMargin ); speechBox!.zPosition = VNSceneUILayer speechBox!.name = VNSceneTagSpeechBox self.addChild(speechBox!) // add children from "old" speech box if( originalChildren != nil && originalChildren!.count > 0 ) { for someChild in originalChildren! { speechBox!.addChild(someChild as! SKNode) } } } // make sure the speaker name appears properly if savedSpeakerName != nil && speaker != nil { speaker!.anchorPoint = CGPoint(x: 0, y: 1.0); speaker!.position = self.updatedSpeakerPosition() //[self updatedSpeakerPosition) // Fade in the speaker name label //let fadeIn = SKAction.fadeIn(withDuration: speechTransitionSpeed) //speaker!.run(fadeIn) } // Load typewriter text information if let TWValueForSpeed = record.object(forKey: VNSceneTypewriterTextSpeed) as? NSNumber { TWSpeedInCharacters = TWValueForSpeed.intValue } if let TWValueForSkip = record.object(forKey: VNSceneTypewriterTextCanSkip) as? NSNumber { TWCanSkip = TWValueForSkip.boolValue } self.updateTypewriterTextSettings() // choicebox effects if let valueForChoiceboxOffsetX = record.object(forKey: VNSceneViewChoiceButtonOffsetX) as? NSNumber { choiceButtonOffsetX = CGFloat(valueForChoiceboxOffsetX.doubleValue) } if let valueForChoiceboxOffsetY = record.object(forKey: VNSceneViewChoiceButtonOffsetY) as? NSNumber { choiceButtonOffsetY = CGFloat(valueForChoiceboxOffsetY.doubleValue) } } // Loads the default, hard-coded values for the view / UI settings dictionary. //- (void)loadDefaultViewSettings func loadDefaultViewSettings() { let fontSize = VNSceneViewFontSize; let iPadFontSizeMultiplier = 1.5; // Determines how much larger the "speech text" and speaker name will be on the iPad let dialogueBoxName:String = VNSceneViewTalkboxName; //if( viewSettings == nil ) { // viewSettings = NSMutableDictionary() //} // Manually enter the default data for the UI viewSettings.setValue(1.0, forKey: VNSceneViewDefaultBackgroundOpacityKey) viewSettings.setValue(0.0, forKey: VNSceneViewSpeechBoxOffsetFromBottomKey) viewSettings.setValue(0.5, forKey: VNSceneViewSpriteTransitionSpeedKey) viewSettings.setValue(0.5, forKey: VNSceneViewTextTransitionSpeedKey) viewSettings.setValue(0.5, forKey: VNSceneViewNameTransitionSpeedKey) viewSettings.setValue(10.0, forKey: VNSceneViewSpeechHorizontalMarginsKey) viewSettings.setValue(30.0, forKey: VNSceneViewSpeechVerticalMarginsKey) viewSettings.setValue(0.0, forKey: VNSceneViewSpeechOffsetXKey) viewSettings.setValue((fontSize * 2), forKey: VNSceneViewSpeechOffsetYKey) viewSettings.setValue(0.0, forKey: VNSceneViewSpeakerNameXOffsetKey) viewSettings.setValue(0.0, forKey: VNSceneViewSpeakerNameYOffsetKey) viewSettings.setValue((fontSize), forKey: VNSceneViewFontSizeKey) // Was 'fontSize'; changed due to iPad font multiplier viewSettings.setValue(dialogueBoxName, forKey: VNSceneViewSpeechBoxFilenameKey) viewSettings.setValue("choicebox.png", forKey: VNSceneViewButtonFilenameKey) viewSettings.setValue("Helvetica", forKey: VNSceneViewFontNameKey) viewSettings.setValue((iPadFontSizeMultiplier), forKey: VNSceneViewMultiplyFontSizeForiPadKey) // This is used for the iPad // Create default settings for whether or not the "override from save" values should take place. viewSettings.setValue(true, forKey:VNSceneViewOverrideSpeakerFontKey) viewSettings.setValue(true, forKey:VNSceneViewOverrideSpeakerSizeKey) viewSettings.setValue(true, forKey:VNSceneViewOverrideSpeechFontKey) viewSettings.setValue(true, forKey:VNSceneViewOverrideSpeechSizeKey) let buttonTouchedColorsDict = NSDictionary(dictionary: ["r":0, "g":0, "b":255]) // BLUE <- r0, g0, b255 let buttonUntouchedColorsDict = NSDictionary(dictionary: ["r":0, "g":0, "b":0]) // BLACK <- r0, g0, b0 viewSettings.setValue(buttonTouchedColorsDict, forKey:VNSceneViewButtonsTouchedColorsKey) viewSettings.setValue(buttonUntouchedColorsDict, forKey:VNSceneViewButtonUntouchedColorsKey) // Load other settings viewSettings.setValue(NSNumber(value: false), forKey:VNSceneViewNoSkipUntilTextShownKey) } // Actually loads images and text for the UI (as opposed to just loading information ABOUT the UI) func loadUI() { heightMarginForAds = 0 // Load the default settings if they don't exist yet. If there's custom data, the default settings will be overwritten. if( viewSettings.count < 1 ) { print("[VNScene] Loading default view settings."); loadDefaultViewSettings() } // Get screen size data; getting the size/coordiante data is very important for placing UI elements on the screen let widthOfScreen = viewSize.width//viewSize.width; // Check if this is on an iPad, and if the default font size should be adjusted to compensate for the larger screen size //if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) { if( UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad ) { let multiplyFontSizeForiPadFactor:NSNumber? = viewSettings.object(forKey: VNSceneViewMultiplyFontSizeForiPadKey) as? NSNumber // Default is 1.5x let standardFontSize:NSNumber? = viewSettings.object(forKey: VNSceneViewFontSizeKey) as? NSNumber // Default value is 17.0 if( multiplyFontSizeForiPadFactor != nil && standardFontSize != nil ) { let fontFactor = multiplyFontSizeForiPadFactor!.doubleValue //[multiplyFontSizeForiPadFactor floatValue) let fontSize = (standardFontSize!.doubleValue) * fontFactor; // Default is standardFontSize * 1.5 viewSettings.setObject(NSNumber(value: fontSize), forKey:VNSceneViewFontSizeKey as NSCopying) // The value for the offset key is reset because the font size may have changed, and offsets are affected by this. viewSettings.setValue(NSNumber(value: (fontSize * 2)), forKey:VNSceneViewSpeechOffsetYKey) } } // Part 1: Create speech box, and then position it at the bottom of the screen (with a small margin, if one exists). // The default setting is to have NO margin/space, meaning the bottom of the box touches the bottom of the screen. let speechBoxFile:NSString = viewSettings.object(forKey: VNSceneViewSpeechBoxFilenameKey) as! NSString let boxToBottomValue:NSNumber = viewSettings.object(forKey: VNSceneViewSpeechBoxOffsetFromBottomKey) as! NSNumber let boxToBottomMargin:Double = boxToBottomValue.doubleValue // Create speechbox sprite node and set its data speechBox = SKSpriteNode(imageNamed: speechBoxFile as String) let speechBoxX = CGFloat(widthOfScreen * 0.5 ) let speechBoxHalfHeight = speechBox!.size.height * 0.5; let speechBoxY = CGFloat( speechBoxHalfHeight + CGFloat(boxToBottomMargin) ) speechBox!.position = CGPoint(x: speechBoxX, y: speechBoxY) speechBox!.zPosition = VNSceneUILayer speechBox!.name = VNSceneTagSpeechBox addChild(speechBox!) // Save speech box position in the settings dictionary; this is useful in case you need to restore it to its default position later viewSettings.setValue( NSNumber(value: Double(speechBox!.position.x)), forKey:"speechbox x") viewSettings.setValue( NSNumber(value: Double(speechBox!.position.y)), forKey:"speechbox y") // Hide the speech-box by default. speechBox!.alpha = 0; // It's possible that the speechbox sprite may be wider than the width of the screen (this can happen if a // speechbox designed for the iPhone 5 is shown on an iPhone 4S or earlier). As the speech text's boundaries // are based (by default, at least) on the width and height of the speechbox sprite, it may be necessary to // pretend that the speechbox is smaller in order to fit it on a pre-iPhone5 screen. var widthOfSpeechBox = speechBox!.size.width; let heightOfSpeechBox = speechBox!.size.height; if( widthOfSpeechBox > widthOfScreen ) { widthOfSpeechBox = widthOfScreen; // Limit the width to whatever the screen's width is } // load speechbox color let speechBoxColorDictionary = viewSettings.object(forKey: VNSceneViewSpeechboxColorKey) as? NSDictionary if speechBoxColorDictionary != nil { let colorR = (speechBoxColorDictionary!.object(forKey: "r") as! NSNumber).intValue let colorG = (speechBoxColorDictionary!.object(forKey: "g") as! NSNumber).intValue let colorB = (speechBoxColorDictionary!.object(forKey: "b") as! NSNumber).intValue //let untouchedColor = SMColorFromRGB(untouchedR, g: untouchedG, b: untouchedB) let theColor = SMColorFromRGB(colorR, g: colorG, b: colorB) speechBoxColor = theColor print("[VNScene] Speech box color set to \(theColor)") speechBox!.colorBlendFactor = 1.0; speechBox!.color = theColor; } // Part 2: Create the speech label. // The "margins" part is tricky. When generating the size for the CCLabelTTF object, it's important to pretend // that the margins value is twice as large (as what's stored), since the label's position won't be in the // exact center of the speech box, but slightly to the right and down, to create "margins" between speech and // the box it's displayed in. let verticalMarginValue = viewSettings.object(forKey: VNSceneViewSpeechVerticalMarginsKey) as! NSNumber let horizontalMarginValue = viewSettings.object(forKey: VNSceneViewSpeechHorizontalMarginsKey) as! NSNumber let verticalMargins = CGFloat(verticalMarginValue.doubleValue) let horizontalMargins = CGFloat(horizontalMarginValue.doubleValue) // Width multiplier is used for creating margins (when displaying the speech text). Due to differences in size, // the exact value changes between the iPhone and the iPad. var widthMultiplierValue:CGFloat = 4.0; //if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) { if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { widthMultiplierValue = 6.0; } let speechSizeWidth = widthOfSpeechBox - (horizontalMargins * widthMultiplierValue) let speechSizeHeight = heightOfSpeechBox - (verticalMargins * 2.0) // Set dimensions let speechSize = CGSize( width: speechSizeWidth, height: speechSizeHeight ) let fontSizeValue = viewSettings.object(forKey: VNSceneViewFontSizeKey) as! NSNumber let fontSize = CGFloat( fontSizeValue.doubleValue ) // Now actually create the speech label. By default, it's just empty text (until a character/narrator speaks later on) //speech = [SMTextNode labelNodeWithFontNamed:[viewSettings.objectForKey(VNSceneViewFontNameKey]) let fontNameValue = viewSettings.object(forKey: VNSceneViewFontNameKey) as! NSString speech = SMTextNode(fontNamed: fontNameValue as String) speech!.text = " "; speech!.fontSize = fontSize; speech!.paragraphWidth = (speechSize.width * 0.92) - (horizontalMargins * widthMultiplierValue); // Adjust for iPad size differences //if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) if( UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad ) { speech!.paragraphWidth = (speechSize.width * 0.94) - (horizontalMargins * widthMultiplierValue); } // Make sure that the position is slightly off-center from where the textbox would be (plus any other offsets that may exist). let speechXOffset = (viewSettings.object(forKey: VNSceneViewSpeechOffsetXKey) as! NSNumber).doubleValue let speechYOffset = (viewSettings.object(forKey: VNSceneViewSpeechOffsetYKey) as! NSNumber).doubleValue let originalSpeechPosX = CGFloat(speechBox!.size.width * 0.5) + CGFloat(speechXOffset) let originalSpeechPosY = speechBox!.size.height * 0.5 + CGFloat(verticalMargins) - CGFloat(speechYOffset) //CGPoint originalSpeechPos = CGPointMake( speechBox!.size.width * 0.5 /* + horizontalMargins */ + speechXOffset, // speechBox!.size.height * 0.5 + verticalMargins - speechYOffset ); let originalSpeechPos = CGPoint(x: originalSpeechPosX, y: originalSpeechPosY) let bottomLeftCornerOfSpeechBox = SMPositionOfBottomLeftCornerOfSKNode(speechBox!); speech!.position = SMPositionAddTwoPositions(originalSpeechPos, second: bottomLeftCornerOfSpeechBox); speech!.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.left speech!.zPosition = VNSceneTextLayer; speech!.name = VNSceneTagSpeechText; //[speechBox addChild:speech) speechBox!.addChild(speech!) // load speech text colors let speechBoxTextColorDict = viewSettings.object(forKey: VNSceneViewSpeechboxTextColorKey) as? NSDictionary if speechBoxTextColorDict != nil { let colorR = (speechBoxTextColorDict!.object(forKey: "r") as! NSNumber).intValue let colorG = (speechBoxTextColorDict!.object(forKey: "g") as! NSNumber).intValue let colorB = (speechBoxTextColorDict!.object(forKey: "b") as! NSNumber).intValue //let untouchedColor = SMColorFromRGB(untouchedR, g: untouchedG, b: untouchedB) let theColor = SMColorFromRGB(colorR, g: colorG, b: colorB) speechBoxTextColor = theColor print("[VNScene] Speech box color set to \(theColor)") speech!.colorBlendFactor = 1.0 speech!.color = theColor } // determine if the UI will use height margin for ads let numberForDoesUseHeightMarginForAds:NSNumber? = viewSettings.object(forKey: VNSceneViewDoesUseHeightMarginForAdsKey) as? NSNumber if numberForDoesUseHeightMarginForAds != nil { doesUseHeightMarginForAds = numberForDoesUseHeightMarginForAds!.boolValue } /** COPY TO TWINVISIBLE TEXT **/ TWInvisibleText = SMTextNode(fontNamed: fontNameValue as String) TWInvisibleText!.text = " "; TWInvisibleText!.fontSize = speech!.fontSize TWInvisibleText!.paragraphWidth = speech!.paragraphWidth TWInvisibleText!.position = speech!.position TWInvisibleText!.horizontalAlignmentMode = speech!.horizontalAlignmentMode TWInvisibleText!.zPosition = speech!.zPosition TWInvisibleText!.alpha = 0.0; // make sure this really is invisible TWInvisibleText!.name = "TWInvisibleText" speechBox!.addChild(TWInvisibleText!) // Part 3: Create speaker label // But first, figure out all the offsets and sizes. var speakerNameOffsets = CGPoint( x: 0.0, y: 0.0 ); let speakerSize = CGSize( width: widthOfSpeechBox * 0.99, height: speechBox!.size.height * 0.95 ); let speakerNameOffsetXValue:NSNumber? = viewSettings.object(forKey: VNSceneViewSpeakerNameXOffsetKey) as? NSNumber let speakerNameOffsetYValue:NSNumber? = viewSettings.object(forKey: VNSceneViewSpeakerNameYOffsetKey) as? NSNumber if( speakerNameOffsetXValue != nil ) { speakerNameOffsets.x = CGFloat(speakerNameOffsetXValue!.doubleValue) } if( speakerNameOffsetYValue != nil ) { speakerNameOffsets.y = CGFloat(speakerNameOffsetYValue!.doubleValue) } // Add the speaker to the speech-box. The "name" is just empty text by default, until an actual name is provided later. //speaker = [SMTextNode labelNodeWithFontNamed:[viewSettings.objectForKey(VNSceneViewFontNameKey]) //speaker = SMTextNode(fontNamed:fontNameValue as String) speaker = SMTextNode(fontNamed: fontNameValue as String) speaker!.text = " "; speaker!.fontSize = CGFloat(fontSize * 1.1) // 1.1 is used as a "magic number" because it looks OK speaker!.paragraphWidth = speakerSize.width; speaker!.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.left; // Position the label and then add it to the display let speakerPosX = (speechBox!.frame.size.width * -0.5) + (speaker!.frame.size.width * 0.5) let speakerPosY = speechBox!.frame.size.height speaker!.position = CGPoint( x: speakerPosX, y: speakerPosY ); speaker!.zPosition = VNSceneTextLayer; speaker!.name = VNSceneTagSpeakerName; speechBox!.addChild(speaker!); // set speaker color value speaker!.color = speechBoxTextColor speaker!.colorBlendFactor = 1.0 // Part 4: Load the button colors // First load the default colors buttonUntouchedColors = UIColor(red: 0, green: 0, blue: 0, alpha: 1.0) // black buttonTouchedColors = UIColor(red: 0, green: 0, blue: 1.0, alpha: 1.0) // blue // Grab dictionaries from view settings let buttonUntouchedColorsDict:NSDictionary? = viewSettings.object(forKey: VNSceneViewButtonUntouchedColorsKey) as? NSDictionary let buttonTouchedColorsDict:NSDictionary? = viewSettings.object(forKey: VNSceneViewButtonsTouchedColorsKey) as? NSDictionary let buttonTextColorDict:NSDictionary? = viewSettings.object(forKey: VNSceneViewButtonTextColorKey) as? NSDictionary // Copy values from the dictionary if( buttonUntouchedColorsDict != nil ) { let untouchedR = (buttonUntouchedColorsDict!.object(forKey: "r") as! NSNumber).intValue let untouchedG = (buttonUntouchedColorsDict!.object(forKey: "g") as! NSNumber).intValue let untouchedB = (buttonUntouchedColorsDict!.object(forKey: "b") as! NSNumber).intValue let untouchedColor = SMColorFromRGB(untouchedR, g: untouchedG, b: untouchedB) buttonUntouchedColors = untouchedColor print("[VNScene] Button untouched colors set to \(buttonUntouchedColors)") } if( buttonTouchedColorsDict != nil ) { //println("[VNScene] Touched buttons colors settings = %@", buttonTouchedColorsDict); let touchedR = (buttonTouchedColorsDict!.object(forKey: "r") as! NSNumber).intValue let touchedG = (buttonTouchedColorsDict!.object(forKey: "g") as! NSNumber).intValue let touchedB = (buttonTouchedColorsDict!.object(forKey: "b") as! NSNumber).intValue let touchedColor = SMColorFromRGB(touchedR, g: touchedG, b: touchedB) buttonTouchedColors = touchedColor } if buttonTextColorDict != nil { let R = (buttonTextColorDict!.object(forKey: "r") as! NSNumber).intValue let G = (buttonTextColorDict!.object(forKey: "g") as! NSNumber).intValue let B = (buttonTextColorDict!.object(forKey: "b") as! NSNumber).intValue let theColor = SMColorFromRGB(R, g: G, b: B) buttonTextColor = theColor } // Part 5: Load transition speeds spriteTransitionSpeed = (viewSettings.object(forKey: VNSceneViewSpriteTransitionSpeedKey) as! NSNumber).doubleValue speechTransitionSpeed = (viewSettings.object(forKey: VNSceneViewTextTransitionSpeedKey) as! NSNumber).doubleValue speakerTransitionSpeed = (viewSettings.object(forKey: VNSceneViewNameTransitionSpeedKey) as! NSNumber).doubleValue // Part 6: Load overrides, if any are found let overrideSpeechFont:NSString? = record.object(forKey: VNSceneOverrideSpeechFontKey) as? NSString let overrideSpeakerFont:NSString? = record.object(forKey: VNSceneOverrideSpeakerFontKey) as? NSString let overrideSpeechSize:NSNumber? = record.object(forKey: VNSceneOverrideSpeechSizeKey) as? NSNumber let overrideSpeakerSize:NSNumber? = record.object(forKey: VNSceneOverrideSpeakerSizeKey) as? NSNumber let shouldOverrideSpeechFont = (viewSettings.object(forKey: VNSceneViewOverrideSpeechFontKey) as! NSNumber).boolValue let shouldOverrideSpeechSize = (viewSettings.object(forKey: VNSceneViewOverrideSpeechSizeKey) as! NSNumber).boolValue let shouldOverrideSpeakerFont = (viewSettings.object(forKey: VNSceneViewOverrideSpeakerFontKey) as! NSNumber).boolValue let shouldOverrideSpeakerSize = (viewSettings.object(forKey: VNSceneViewOverrideSpeakerSizeKey) as! NSNumber).boolValue if( shouldOverrideSpeakerFont && overrideSpeakerFont != nil ) { speaker!.fontName = overrideSpeakerFont! as String } if( shouldOverrideSpeakerSize && overrideSpeakerSize != nil ) { speaker!.fontSize = CGFloat(overrideSpeakerSize!.doubleValue) } if( shouldOverrideSpeechFont && overrideSpeechFont != nil ) { speech!.fontName = overrideSpeechFont! as String } if( shouldOverrideSpeechSize && overrideSpeechSize != nil ) { speech!.fontSize = CGFloat(overrideSpeechSize!.doubleValue) } // load choicebox/choice-button offsets if let valueForChoiceboxOffsetX = viewSettings.object(forKey: VNSceneViewChoiceButtonOffsetX) as? NSNumber { choiceButtonOffsetX = CGFloat(valueForChoiceboxOffsetX.doubleValue) } if let valueForChoiceboxOffsetY = viewSettings.object(forKey: VNSceneViewChoiceButtonOffsetY) as? NSNumber { choiceButtonOffsetY = CGFloat(valueForChoiceboxOffsetY.doubleValue) } // Part 7: Load extra features let blockSkippingUntilTextIsDone:NSNumber? = viewSettings.object(forKey: VNSceneViewNoSkipUntilTextShownKey) as? NSNumber if( blockSkippingUntilTextIsDone != nil ) { noSkippingUntilTextIsShown = blockSkippingUntilTextIsDone!.boolValue } } // Removes unused character sprites (CCSprite objects) from memory. //- (void)removeUnusedSprites func removeUnusedSprites() { // Check if there are no unused sprites to begin with if( spritesToRemove.count < 1 ) { return } print("[VNScene] Will now remove unused sprites - \(spritesToRemove.count) found.") //for var part = 1; part < command.count; part += 1 { //for part in 1 ..< command.count { // Get all the CCSprite objects in the array and then remove them, starting from the last item and ending with the first. //for( NSInteger i = (spritesToRemove.count - 1); i >= 0; i-- ) { //for var i = (spritesToRemove.count - 1); i >= 0; i -= 1 { //for i in (spritesToRemove.count - 1) ..>= 0 { while spritesToRemove.count > 0 { let sprite:SKSpriteNode = spritesToRemove.object(at: 0) as! SKSpriteNode // If the sprite has no parent node (and is marked as safe to remove), then it's time to get rid of it if( sprite.parent != nil && sprite.name!.caseInsensitiveCompare(VNSceneSpriteIsSafeToRemove) == ComparisonResult.orderedSame ) { // remove from array also, before removing from parent node spritesToRemove.remove(sprite) sprite.removeFromParent() } } } // This takes all the "active" sprites and moves them to the "inactive" list. If you really want to remove them from memory, you // should call 'removeUnusedSprites' soon afterwards; that will actually remove the CCSprite objects from RAM. //- (void)markActiveSpritesAsUnused func markActiveSpritesAsUnused() { if sprites.count < 1 { return } // Grab all the sprites (by name or "key") and relocate them to the "inactive sprites" list //for( NSString* spriteName in [sprites allKeys] ) { for spriteName in sprites.allKeys { let spriteToRelocate = sprites.object(forKey: spriteName) as! SKSpriteNode // Grab sprite from active sprites dictionary spriteToRelocate.alpha = 0.0; // Mark as invisble/inactive (inactive as far as VNScene is concerned) spriteToRelocate.name = VNSceneSpriteIsSafeToRemove; // Mark as definitely unused spritesToRemove.add(spriteToRelocate) // Push to inactive sprites array sprites.removeObject(forKey: spriteName) // Remove from "active sprites" dictionary } } // Currently, this removes "unused" character sprites, plus all audio. The name may be misleading, since it doesn't // remove "active" character sprites or the background. //- (void)purgeDataCreatedByScene func purgeDataCreatedByScene() { markActiveSpritesAsUnused() // Mark all sprites as being unused removeUnusedSprites() // Remove the "unused" sprites spritesToRemove.removeAllObjects() // Free from memory sprites.removeAllObjects() // Array now unnecessary; any remaining child nodes will be released from memory in this function // Check if any sounds were loaded; they should be removed by this function. if( soundsLoaded.count > 0 ) { soundsLoaded.removeAllObjects() } // Unload any music that may be playing. if( isPlayingMusic ) { stopBGMusic() isPlayingMusic = false; // Make sure this is set to NO, since the function might be called more than once! } // Now, forcibly get rid of anything that might have been missed if self.children.count > 0 { print("[VNScene] Will now forcibly remove all child nodes of this layer."); removeAllChildren() print("[VNScene] All child nodes have been removed."); } } // MARK: - Choice sets // Adds a destination:"choice text" string combination to a choice set that's been stored in the choice sets dictionary func addToChoiceSet(setName:String, destination:String, choiceText:String) { var choiceSetObject : NSMutableDictionary? = nil if let savedSet = choiceSets.object(forKey: setName) as? NSMutableDictionary { //choiceSetObject = NSMutableDictionary(dictionary: savedSet) choiceSetObject = savedSet } else { choiceSetObject = NSMutableDictionary() choiceSets.setValue(choiceSetObject, forKey: setName) } choiceSetObject!.setValue(choiceText, forKey: destination) //print("Choice sets currently are: \(choiceSets)") } // Removes an existing destination/choice combination from a Choice Set func removeFromChoiceSet(setName:String, destination:String) { if let savedSet = choiceSets.object(forKey: setName) as? NSMutableDictionary { savedSet.removeObject(forKey: destination) } } // Remove an entire Choice Set func wipeChoiceSet(setName:String) { choiceSets.removeObject(forKey: setName) } // Display a choice set func displayChoiceSet(setName:String) { if let savedSet = choiceSets.object(forKey: setName) as? NSMutableDictionary { if savedSet.count < 1 { print("[VNSceneNode] WARNING: There were no choices found in the Choice Set \(setName), so nothing was displayed.") return } self.createSafeSave() // Always create safe-save before doing something volatile let choiceTexts = NSMutableArray() let destinations = NSMutableArray() // Populate the arrays for currentDestination in savedSet.allKeys { let destinationText = currentDestination as! String let currentChoiceText = savedSet.object(forKey: destinationText) as! String destinations.add(destinationText) choiceTexts.add(currentChoiceText) //print("displayChoiceSet: Adding Destination [\(destinationText)] with Choice Text [\(currentChoiceText)]") } //let choiceTexts = command.object(at: 1) as! NSArray // Get the strings to display for individual choices //let destinations = command.object(at: 2) as! NSArray // Get the names of the conversations to "jump" to let numberOfChoices = choiceTexts.count // Calculate number of choices // Make sure the arrays that hold the data are prepared buttons.removeAllObjects() choices.removeAllObjects() // Come up with some position data let screenWidth = viewSize.width let screenHeight = viewSize.height for i in 0 ..< numberOfChoices { let buttonImageName = SMStringFromDictionary(viewSettings, nameOfObject: VNSceneViewButtonFilenameKey) //viewSettings.objectForKey(VNSceneViewButtonFilenameKey) as! NSString let button:SKSpriteNode = SKSpriteNode(imageNamed: buttonImageName) // Calculate the amount of space (including space between buttons) that each button will take up, and then // figure out where and how to position the buttons (factoring in margins / spaces between buttons). Generally, // the button in the middle of the menu of choices will show up in the middle of the screen with this formula. let spaceBetweenButtons:CGFloat = button.frame.size.height * 0.2; let buttonHeight:CGFloat = button.frame.size.height; let totalButtonSpace:CGFloat = buttonHeight + spaceBetweenButtons; //let heightPercentage = VNSceneNodeChoiceButtonStartingPercentage // usually 0.70 or 70% of the screen height let heightPercentage = choiceButtonStartingYFactor(numberOfChoices: numberOfChoices) let startingPosition:CGFloat = (screenHeight * heightPercentage) - ( ( CGFloat(numberOfChoices / 2) ) * totalButtonSpace ) + choiceButtonOffsetY let buttonY:CGFloat = startingPosition + ( CGFloat(i) * totalButtonSpace ); //print("displayChoiceSet: buttonY = \(buttonY) | startingPosition = \(startingPosition) | choiceButtonOffsetY = \(choiceButtonOffsetY)") // Set button position button.position = CGPoint( x: (screenWidth * 0.5) + choiceButtonOffsetX, y: buttonY ); button.zPosition = VNSceneButtonsLayer; button.name = "\(i)" //button.name = [NSString stringWithFormat:@"%d", i) self.addChild(button) // Set color and add to array button.color = buttonUntouchedColors buttons.add(button) // Determine where the text should be positioned inside the button var labelWithinButtonPos = CGPoint( x: button.frame.size.width * 0.5, y: button.frame.size.height * 0.35 ); if( UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad ) { // The position of the text inside the button has to be adjusted, since the actual font size on the iPad isn't exactly // twice as large, but modified with some custom code. This results in having to do some custom positioning as well! labelWithinButtonPos.y = CGFloat(button.frame.size.height * 0.31) } // Create the button label /*CCLabelTTF* buttonLabel = [CCLabelTTF labelWithString:[choiceTexts objectAtIndex:i] fontName:[viewSettings.objectForKey(VNSceneViewFontNameKey] fontSize:[[viewSettings.objectForKey(VNSceneViewFontSizeKey] floatValue] dimensions:button.boundingBox.size)*/ let labelFontName = SMStringFromDictionary(viewSettings, nameOfObject: VNSceneViewFontNameKey)//viewSettings.objectForKey(VNSceneViewFontNameKey) as NSString let labelFontSize = SMNumberFromDictionary(viewSettings, nameOfObject: VNSceneViewFontSizeKey)//viewSettings.objectForKey(VNSceneViewFontSizeKey) as NSNumber let buttonLabel = SKLabelNode(fontNamed: labelFontName) // Set label properties buttonLabel.text = choiceTexts.object(at: i) as! NSString as String buttonLabel.fontSize = CGFloat( labelFontSize.floatValue ) buttonLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center // Center the text in the button // Handle positioning for the text var buttonLabelYPos = 0 - (button.size.height * 0.20) if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { buttonLabelYPos = 0 - (button.size.height * 0.20) } buttonLabel.position = CGPoint(x: 0.0, y: buttonLabelYPos) buttonLabel.zPosition = VNSceneButtonTextLayer // set button text color buttonLabel.color = buttonTextColor; buttonLabel.colorBlendFactor = 1.0; buttonLabel.fontColor = buttonTextColor; button.addChild(buttonLabel) button.colorBlendFactor = 1.0 // Needed to "color" the sprite; it wouldn't have any color-blending otherwise choices.add( destinations.object(at: i) ) } mode = VNSceneModeChoiceWithJump } } // MARK: - Typewriter Text mode // Updates data regarding speed (and whether or not typewriter mode should be enabled). This should only get called occasionally, // such as when this speed values are changed. func updateTypewriterTextSettings() { if TWSpeedInCharacters <= 0 { TWModeEnabled = false TWTimer = 0 } else { TWModeEnabled = true // Calculate speed in seconds based on characters per second let charsPerSecond = Double(TWSpeedInCharacters) TWSpeedInSeconds = (60.0) / charsPerSecond; // at 60fps this is 60/characters-per-second let speedInFrames = (60.0) * TWSpeedInSeconds; TWSpeedInFrames = Int(speedInFrames) TWTimer = 0; // This gets reset print("[VNScene] DIAGNOSTIC: Typewriter Text - speed in seconds: \(TWSpeedInSeconds) | speed in frames: \(TWSpeedInFrames)"); } record.setValue(NSNumber(value: TWSpeedInCharacters), forKey: VNSceneTypewriterTextSpeed) record.setValue(NSNumber(value: TWCanSkip), forKey: VNSceneTypewriterTextCanSkip) } // This gets called every frame to determine how to display labels when typewriter text is enabled. func updateTypewriterTextDisplay() { if TWSpeedInCharacters < 1 { return; } var shouldRedrawText = false; // Determines whether or not to go through the trouble of recalculating text node positions // Used to calculate how many characters to display (in each frame) let currentChars = Double(TWNumberOfCurrentCharacters) let charsPerSecond = Double(TWSpeedInCharacters) let charsPerFrame = (charsPerSecond / 60.0) let c = currentChars + charsPerFrame // Convert back to integer (from the more precise Double) TWNumberOfCurrentCharacters = Int(c) // Clamp excessive min-max values if TWNumberOfCurrentCharacters < 0 { TWNumberOfCurrentCharacters = 0 } else if TWNumberOfCurrentCharacters > TWNumberOfTotalCharacters { TWNumberOfCurrentCharacters = TWNumberOfTotalCharacters } // The "previous number" counter is used to ensure that changes to the display are only made when it's necessary // (in this case, when the value changes for good) instead of possibly every single frame. if( TWNumberOfCurrentCharacters > TWPreviousNumberOfCurrentChars ) { // Actually commit new values to display let numberOfCharsToUse = TWNumberOfCurrentCharacters; let TWIndex: String.Index = TWFullText.index(TWFullText.startIndex, offsetBy: numberOfCharsToUse) //TWCurrentText = TWFullText.substring(to: TWIndex) //TWCurrentText = "\(TWFullText[..<TWIndex])" TWCurrentText = String(TWFullText[..<TWIndex]) if speech != nil { speech!.text = TWCurrentText } // Update "previous counter" with the new value TWPreviousNumberOfCurrentChars = TWNumberOfCurrentCharacters; shouldRedrawText = true } if shouldRedrawText == true { // Also change the text position so it doesn't get all weird; TWInvisibleText is used as a guide for positioning speech!.size = TWInvisibleText!.size speech!.paragraphWidth = TWInvisibleText!.paragraphWidth speech!.horizontalAlignmentMode = TWInvisibleText!.horizontalAlignmentMode speech!.position = TWInvisibleText!.position var someX = TWInvisibleText!.position.x var someY = TWInvisibleText!.position.y someX = someX + (speech!.size.width * 0.5) someY = someY - (speech!.size.height * 0.5) speech!.position = CGPoint(x: someX, y: someY) } } // MARK: - Misc and Utility // just a quick utility function designed to quickly tell if this is portrait mode or not` func viewIsPortrait() -> Bool { let width = viewSize.width let height = viewSize.height if( width > height ) { return false } return true } // Used to retrieve potential sprite alias names from the local sprite alias dictionary func filenameOfSpriteAlias(_ someName:String) -> String { let filenameOfSprite:String? = self.localSpriteAliases.object(forKey: someName) as? String // Check if the corresponding filename was NOT found in the alias list if filenameOfSprite == nil { // In this case, just return the original name, which can be assumed to be an actual filename already return String(someName) } // Otherwise, assume that the filename was found return String(filenameOfSprite!) } // The set/clear effect-running-flag functions exist so that Cocos2D can call them after certain actions // (or sequences of actions) have been run. The "effect is running" flag is important, since it lets VNScene // know when it's safe (or unsafe) to do certain things (which might interrupt the effect that's being run). func setEffectRunningFlag() { print("[VNScene] Effect will be running."); effectIsRunning = true; mode = VNSceneModeEffectIsRunning; } func clearEffectRunningFlag() { effectIsRunning = false; print("[VNScene] Effect is no longer running."); } // Update script info. This consists of index data, the script name, and which conversation/section is the current one // being displayed (or run) before the player. func updateScriptInfo() { if( script != nil ) { // Save existing script information (indexes, "current" conversation name, etc.) in the record. // This overwrites any script information which may already have been stored. record.setValue(script!.info(), forKey: VNSceneSavedScriptInfoKey) } } // MARK: - Saving/loading to record // This saves important information (script info, flags, which resources are being used, etc) to SMRecord. func saveToRecord() { print("[VNScene] Saving data to record."); // Create the default "dictionary to save" that will be passed into SMRecord's "activity dictionary." // Keep in mind that the activity dictionary holds the type of activity that the player was engaged in // when the game was saved (in this case, the activity is a VN scene), plus any specific details // of that activity (in this case, the script's data, which includes indexes, script name, etc.) let dictToSave = NSMutableDictionary() dictToSave.setValue(VNSceneActivityType, forKey: SMRecordActivityTypeKey) // Check if the "safe save" exists; if it does, then it should be used instead of whatever the current data is. //if( safeSave != nil ) { if safeSave.count > 1 { let localFlags = safeSave.object(forKey: "flags") as! NSDictionary let localRecord = safeSave.object(forKey: "record") as! NSMutableDictionary let aliasesFromSafeSave = safeSave.object(forKey: "aliases") as! NSDictionary let localChoiceSets = safeSave.object(forKey: "choicesets") as! NSDictionary //let recordedFlags = SMRecord.sharedRecord.flags() //recordedFlags.addEntriesFromDictionary(localFlags) //SMDictionaryAddEntriesFromAnotherDictionary(SMRecord.sprite) SMRecord.sharedRecord.addExistingFlags(fromDictionary: aliasesFromSafeSave) SMRecord.sharedRecord.addExistingFlags(fromDictionary: localFlags) SMRecord.sharedRecord.saveChoiceSetsToRecord(dictionary: localChoiceSets) dictToSave.setValue(localRecord, forKey: SMRecordActivityDataKey) //SMRecord.sharedRecord.setActivityDict(dictToSave) SMRecord.sharedRecord.setActivityDictionary(dictionary: dictToSave) if SMRecord.sharedRecord.saveToDevice() == true { print("[VNSceneNode] Saved to device.") } //[[[SMRecord sharedRecord] flags] addEntriesFromDictionary:[safeSave.objectForKey(@"flags"]) //[dictToSave setObject:[safeSave.objectForKey(@"record"] forKey:SMRecordActivityDataKey) //[[SMRecord sharedRecord] setActivityDict:dictToSave) print("[VNSceneNode] Saving 'safe save' data from scene.") return; } // Save all the names and coordinates of the sprites still active in the scene. This data will be enough // to recreate them later on, when the game is loaded from saved data. let spritesToSave:NSArray? = spriteDataFromScene() if( spritesToSave != nil ) { record.setValue(spritesToSave!, forKey: VNSceneSpritesToShowKey) } else { record.removeObject(forKey: VNSceneSpritesToShowKey) } // Load all flag data back to SMRecord. Remember that VNScene doesn't have a monopoly on flag data; // other classes and game systems can modify the flags as well! //[[SMRecord sharedRecord].flags addEntriesFromDictionary:flags) //SMRecord.sharedRecord.addExistingFlags(flags) SMRecord.sharedRecord.addExistingFlags(fromDictionary: flags) // Save the choice sets as well SMRecord.sharedRecord.saveChoiceSetsToRecord(dictionary: choiceSets) // Update script data and then load it into the activity dictionary. updateScriptInfo() // Update all index and conversation data dictToSave.setValue(record, forKey:SMRecordActivityDataKey) // Load into activity dictionary SMRecord.sharedRecord.setActivityDictionary(dictionary: dictToSave) // Save the activity dictionary into SMRecord if SMRecord.sharedRecord.saveToDevice() == true { // Save all record data to device memory print("[VNSceneNode] Saved to device.") } print("[VNScene] Data has been saved. Stored data is: \(dictToSave)"); } // Create the "safe save." This function usually gets called before VNScene does some sort of volatile/potentially-hazardous // operation, like performing effects or presenting the player with choices menus. In case the game needs to be saved during // times like this, the data stored in the "safe save" will be the data that's stored in the saved game. func createSafeSave() { if( script == nil ) { print("[VNScene] WARNING: Cannot create safe save, as no script information exists.") return; } print("[VNScene] Creating safe-save data."); updateScriptInfo() // Update index data, conversation name, script filename, etc. to the most recent information // Save sprite names and coordinates let spritesToSave:NSArray? = spriteDataFromScene() if( spritesToSave != nil ) { record.setValue(spritesToSave, forKey:VNSceneSpritesToShowKey) } // Create dictionary object //let flagsAsDictionary = flags.copy() as NSDictionary let flagsCopy = NSMutableDictionary(dictionary: flags) //let recordCopy = record let scriptInfo = script!.info() safeSave = NSMutableDictionary(dictionary: ["flags":flagsCopy, "aliases":self.localSpriteAliases.copy(), "record":record, "choicesets":choiceSets, VNSceneSavedScriptInfoKey:scriptInfo]) /*safeSave = NSMutableDictionary(dictionaryLiteral: flagsCopy, "flags", record, "record", scriptInfo, VNSceneSavedScriptInfoKey);*/ /* safeSave = NSMutableDictionary(objectsAndKeys: (flags.copy() as NSMutableDictionary), "flags", record, "record", script!.info(), VNSceneSavedScriptInfoKey); */ } func removeSafeSave() { print("[VNScene] Removing safe-save data."); safeSave.removeAllObjects() } // This creates an array that stores all the sprite filenames and coordinates. When the game is loaded from saved data, // the sprites can be easily reloaded and repositioned. func spriteDataFromScene() -> NSArray? { //if( sprites == nil || sprites.count < 1 ) { if sprites.count < 1 { print("[VNScene] No sprite data found in scene."); return nil; } print("[VNScene] Retrieving sprite data from scene!"); // Create the "sprites array." Each index in the array holds a dictionary, and each dictionary holds // certain data: sprite filename, sprite x coordinate, and sprite y coordinate. let spritesArray = NSMutableArray() //[NSMutableArray array) // Get every single sprite from the 'sprites' dictionary and extract the relevent data from it. //for( NSString* spriteName in [sprites allKeys] ) { for spriteName in sprites.allKeys { print("[VNScene] Saving sprite named: \(spriteName)") let actualSprite:SKSpriteNode = sprites.object(forKey: spriteName) as! SKSpriteNode //sprites[spriteName) let spriteX = NSNumber(value: Double(actualSprite.position.x) ) // Get coordinates; these will be saved to the dictionary. let spriteY = NSNumber(value: Double(actualSprite.position.y) ) // store scaling data as well (this is used mostly for inverted sprites) let scaleX = NSNumber(value: Double(actualSprite.xScale)) let scaleY = NSNumber(value: Double(actualSprite.yScale)) // Save relevant data (sprite name and coordinates) in a dictionary /*let savedSpriteData = NSDictionary(dictionary: ["name":spriteName, "x":spriteX, "y":spriteY]);*/ let tempSpriteDictionary = NSMutableDictionary() tempSpriteDictionary.setValue(spriteName, forKey:"name") tempSpriteDictionary.setValue(spriteX, forKey:"x") tempSpriteDictionary.setValue(spriteY, forKey:"y") tempSpriteDictionary.setValue(scaleX, forKey:"scale x") tempSpriteDictionary.setValue(scaleY, forKey:"scale y") // check if this has a different filename let filenameOfSprite = self.filenameOfSpriteAlias(spriteName as! String) // if the filenames are different, then it means that there is an alias value if filenameOfSprite.caseInsensitiveCompare(spriteName as! String) != ComparisonResult.orderedSame { tempSpriteDictionary.setValue(filenameOfSprite, forKey:"filename") } let savedSpriteData = NSDictionary(dictionary: tempSpriteDictionary) /*let savedSpriteData = NSDictionary(dictionaryLiteral: spriteName, "name", spriteX, "x", spriteY, "y")*/ //NSDictionary* savedSpriteData = @{ @"name" : spriteName, // @"x" : spriteX, // @"y" : spriteY }; // Save dictionary data into the array (which will later be saved to a file) //[spritesArray addObject:savedSpriteData) spritesArray.add(savedSpriteData) } //return [NSArray arrayWithArray:spritesArray) return NSArray(array: spritesArray) } // MARK: - Touch input //- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event //override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let touchPos = touch.location(in: self) // During the "choice" sections of the VN scene, any buttons that are touched in the menu will // change their background appearance (to blue, by default), while all the untouched buttons // will stay black by default. In both cases, the color of text ON the button remains unchanged. if( mode == VNSceneModeChoiceWithJump || mode == VNSceneModeChoiceWithFlag ) { //if( buttons ) { if buttons.count > 0 { //for( CCSprite* button in buttons ) { //for( SKSpriteNode* button in buttons ) { for button in buttons { let currentButton = button as! SKSpriteNode //if( CGRectContainsPoint(button.frame, touchPos) ) { if ((button as AnyObject).frame).contains(touchPos) == true { currentButton.color = buttonTouchedColors // Turn blue } else { currentButton.color = buttonUntouchedColors // Turn black } } } } } } // touchesBegan //- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event //override func touchesMoved(touches: NSSet, withEvent event: UIEvent) override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { //for( UITouch* touch in touches ) { for currentTouch in touches { let touch:UITouch = currentTouch //as! UITouch //CGPoint touchPos = [touch locationInNode:self) let touchPos = touch.location(in: self) if( mode == VNSceneModeChoiceWithJump || mode == VNSceneModeChoiceWithFlag ) { if( buttons.count > 0 ) { //for( CCSprite* button in buttons ) { //for( SKSpriteNode* button in buttons ) { for currentButton in buttons { let button:SKSpriteNode = currentButton as! SKSpriteNode if( button.frame.contains(touchPos) ) { //button.color = [[CCColor alloc] initWithCcColor3b:buttonTouchedColors) button.color = buttonTouchedColors; } else { //button.color = [[CCColor alloc] initWithCcColor3b:buttonUntouchedColors) button.color = buttonUntouchedColors; } } } } } } //- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event //override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { //for( UITouch* touch in touches ) { for currentTouch in touches { let touch:UITouch = currentTouch //as! UITouch let touchPos = touch.location(in: self) // Check if this is the "normal mode," in which there are no choices and dialogue is just displayed normally. // Every time the user does "Touches Ended" during Normal Mode, VNScene advances to the next command (or line // of dialogue). if( mode == VNSceneModeNormal ) { // Story mode // The "just loaded from save" flag is disabled once the user passes the first line of dialogue if( self.wasJustLoadedFromSave == true ) { self.wasJustLoadedFromSave = false; // Remove flag } if( noSkippingUntilTextIsShown == false ){ var canSkip = true if TWModeEnabled == true && TWCanSkip == false { let lengthOfTWCurrentText = SMStringLength(TWCurrentText) let lengthOfTWFullText = SMStringLength(TWFullText) if lengthOfTWCurrentText < lengthOfTWFullText { canSkip = false } } if canSkip == true { script!.advanceIndex() // Move the script forward } } else { // Only allow advancing/skipping if there's no text or if the opacity/alpha has reached 1.0 //if( speech == nil || speech!.text.length < 1 || speech!.alpha >= 1.0 ) { if SMStringLength(speech!.text) < 1 || speech!.alpha >= 1.0 { script!.advanceIndex() } } // If the current mode is some kind of choice menu, then Touches Ended actually picks a choice (assuming, // of course, that the touch landed on a button). } else if( mode == VNSceneModeChoiceWithJump || mode == VNSceneModeChoiceWithFlag ) { // Choice menu mode if( buttons.count > 0 ) { //for( int currentButton = 0; currentButton < buttons.count; currentButton++ ) { for currentButton in 0 ..< buttons.count { //SKSpriteNode* button = [buttons objectAtIndex:currentButton) let button:SKSpriteNode = buttons.object(at: currentButton) as! SKSpriteNode if( button.frame.contains(touchPos) ) { button.color = buttonTouchedColors; buttonPicked = currentButton; // Remember the button's index for later. 'buttonPicked' is normally set to -1, but // when a button is pressed, then the button's index number is copied over to 'buttonPicked' // so that VNScene will know which button was pressed. } else { button.color = buttonUntouchedColors; } } } } } } // MARK: - Updates //- (void)update:(NSTimeInterval)currentTime func update(_ currentTime: TimeInterval) { // Check if the scene is finished if( script!.isFinished == true ) { // Print the 'quitting time' message print("[VNScene] The 'Script Is Finished' flag is triggered. Now moving to 'end of script' mode."); mode = VNSceneModeEnded; // Set 'end' mode } //switch( mode ) { switch mode { // Resources need to be loaded? case VNSceneModeLoading: print("[VNScene] Now in 'loading mode'"); // Do any last-minute loading operations here //[self loadSavedResources) loadSavedResources() // Switch to 'clean-up loading' mode mode = VNSceneModeFinishedLoading; // Have all the resources and script data just finished loading? case VNSceneModeFinishedLoading: print("[VNScene] Finished loading."); // Switch to "Normal Mode" (which is where the dialogue and normal script processing happen) mode = VNSceneModeNormal; // Is everything just being processed as usual? case VNSceneModeNormal: // Check if there's any safe-save data. When the scene has switched over to Normal Mode, then the safe-save // becomes unnecessary, since the conditions that caused it (like certain effects being run) are no longer // active. In this case, the safe-save should just be removed so that the normal data can be saved. if( safeSave.count > 0 ) { //[self removeSafeSave) removeSafeSave() } // Take care of normal operations //[self runScript) // Process script data runScript() if TWModeEnabled == true { // Update typewriter text /* if( TWTimer <= TWSpeedInFrames ) { TWTimer++; self.updateTypewriterTextDisplay() }*/ if TWNumberOfCurrentCharacters < TWNumberOfTotalCharacters { TWTimer += 1 self.updateTypewriterTextDisplay() } } // Is an effect currently running? (this is normally when the "safe save" data comes into play) case VNSceneModeEffectIsRunning: // Ask the scene view object if the effect has finished. If it has, then it will delete the effect object automatically, // and then it will be time for VNScene to return to 'normal' mode. if( effectIsRunning == false ) { //[self removeSafeSave) removeSafeSave() // Change mode mode = VNSceneModeNormal; } // Is the player being presented with a choice menu? (the "choice with jump" means that when the user makes a choice, // VNScene "jumps" to a different array of dialogue immediately afterwards.) case VNSceneModeChoiceWithJump: // Check if there was any input. Normally, 'buttonPicked' is set to -1, but when a button is pressed, // the button's tag (which is always zero or higher) is copied over to 'buttonPicked', and so it's possible // to figure out which button was pressed just by seeing what value was stored in 'buttonPicked' if( buttonPicked >= 0 ) { let conversationToJumpTo = choices.object(at: buttonPicked) as! NSString // The conversation names are stored in the 'choices' array // Switch to the new "conversation" / dialogue array. if script!.changeConversationTo(conversationToJumpTo as String) == false { print("[VNScene] ERROR: Could not switch script to section named: \(conversationToJumpTo)") } mode = VNSceneModeNormal; // Go back to Normal Mode (after this has been processed, of course) // Get rid of any lingering objects in memory if( buttons.count > 0 ) { //for( SKSpriteNode* button in buttons ) { for currentButton in buttons { let button = currentButton as! SKSpriteNode button.removeAllChildren() //[button removeFromParent) button.removeFromParent() } } //[buttons removeAllObjects) buttons.removeAllObjects() //buttons = nil; buttonPicked = -1; // Reset "which button was pressed" to its default, untouched state } // Is the player being presented with another choice menu? (the "choice with flag" means that when a user makes a choice, // VNScene just changes the value of a "flag" or variable that it's keeping track of. Later, when the game is saved, the // value of that flag is copied over to SMRecord). case VNSceneModeChoiceWithFlag: if( buttonPicked >= 0 ) { // Get array elements let flagName:NSString? = choices.object(at: buttonPicked) as? NSString var flagValue:NSNumber? = choiceExtras.object(at: buttonPicked) as? NSNumber let oldFlag:NSNumber? = flags.object(forKey: flagName!) as? NSNumber //id flagName = [choices objectAtIndex:buttonPicked) //id flagValue = [choiceExtras objectAtIndex:buttonPicked) //id oldFlag = [flags.objectForKey(flagName) // Check if the flag had a previously existing value; if it did, then just add the old value to the new value if( oldFlag != nil ) { let oldFlagAsInteger = oldFlag!.int32Value let flagInteger = flagValue!.int32Value let combinedIntegers = oldFlagAsInteger + flagInteger let tempValue = NSNumber(value: combinedIntegers) flagValue = tempValue //id tempValue = [NSNumber numberWithInt:( [oldFlag intValue] + [flagValue intValue] )) //flagValue = tempValue; } // Set the new value of the flag. The change will be made to the "local" flag dictionary, not the // global one stored in SMRecord. This is to prevent any save-data conflicts (since it's certainly // possible that not all the data in the VNScene will be stored along with the updated flag data) //[flags.setValue:flagValue forKey:flagName) flags.setValue(flagValue!, forKey: flagName! as String) // Get rid of any unnecessary objects in memory if( buttons.count > 0 ) { //for( SKSpriteNode* button in buttons ) { for currentButton in buttons { let button:SKSpriteNode = currentButton as! SKSpriteNode button.removeAllChildren() button.removeFromParent() } } // Get rid of any lingering data buttons.removeAllObjects() choices.removeAllObjects() choiceExtras.removeAllObjects() buttonPicked = -1; // Reset this to the original, untouched value // Return to 'normal' mode mode = VNSceneModeNormal; } // In this case, the script has completely finished running, so there's nothing left to do but get rid of any // lingering resources, save data back to the global record in SMRecord, and then return to the previous CCScene. case VNSceneModeEnded: if( self.isFinished == false ) { print("[VNScene] The scene has ended. Flag data will be auto-saved."); print("[VNScene] Remaining scene and activity data will be deleted."); // Save all necessary data //SMRecord* theRecord = [SMRecord sharedRecord) let theRecord = SMRecord.sharedRecord //[theRecord addExistingFlags:flags) // Save flag data (this can overwrite existing flag values) //theRecord.addExistingFlags(flags) theRecord.addExistingFlags(fromDictionary: flags) //[theRecord resetActivityInformationInDict:theRecord.record) // Remove activity data from record //theRecord.resetActivityInformationInDict(theRecord.record) theRecord.resetActivityInformation(inDictionary: theRecord.record) self.isFinished = true; // Mark as finished //[self purgeDataCreatedByScene) // Get rid of all data stored by the scene purgeDataCreatedByScene() // Note that popping the scene results in a very sudden transition, so it might help if the script // ends with a fade-out, and if the previous scene somehow fades in. Otherwise, the sudden transition // might seem TOO sudden. if( popSceneWhenDone == true ) { print("[VNScene] VNScene will now ask Cocos2D to pop the current scene."); //[[CCDirector sharedDirector] popScene) if( previousScene != nil ) { //[self.view presentScene:self.previousScene) print("[VNScene] Previous scene was found; now attempting to switch to previous scene.") //self.view!.presentScene(self.previousScene!) } else { print("[VNScene] WARNING: There is no previous scene to return to."); } } } default: print("[VNScene] WARNING: Now in unknown state"); } } // MARK: - Positioning // Returns the position for where the speaker label should be (since the size changes every time the text changes, // it has to be repositioned each time). //- (CGPoint)updatedSpeakerPosition func updatedSpeakerPosition() -> CGPoint { var widthOfSpeechBox = speechBox!.frame.size.width; let heightOfSpeechBox = speechBox!.frame.size.height; var speakerNameOffsets = CGPoint.zero; // Load speaker offset values let speakerNameOffsetXValue:NSNumber? = viewSettings.object(forKey: VNSceneViewSpeakerNameXOffsetKey) as? NSNumber let speakerNameOffsetYValue:NSNumber? = viewSettings.object(forKey: VNSceneViewSpeakerNameYOffsetKey) as? NSNumber if( speakerNameOffsetXValue != nil ) { speakerNameOffsets.x = CGFloat(speakerNameOffsetXValue!.doubleValue) } if( speakerNameOffsetYValue != nil ) { speakerNameOffsets.y = CGFloat(speakerNameOffsetYValue!.doubleValue) } /* if( self.view == nil ) { print("[VNScene] ERROR: Cannot get updated speaker position, as this scene's view is invalid."); return CGPoint.zero }*/ let screenSize = viewSize let boxSize = speechBox!.frame.size; var workingArea = boxSize; // Check if the speech box is actually wider than the screen's width if( screenSize.width < boxSize.width ) { workingArea.width = screenSize.width; } widthOfSpeechBox = workingArea.width; // Find top-left corner of the speech box let topLeftCornerOfSpeechBox:CGPoint = CGPoint( x: 0.0 - (widthOfSpeechBox * 0.5), y: 0 + (heightOfSpeechBox * 0.5)); // Adjust slightly so that the label isn't jammed up against the upper-left corner; there should be a bit of margins let adjustment:CGPoint = CGPoint( x: widthOfSpeechBox * 0.02, y: heightOfSpeechBox * -0.05 ); // Store adjustments let cornerPlusAdjustments:CGPoint = SMPositionAddTwoPositions(topLeftCornerOfSpeechBox, second: adjustment); // Add custom offsets let adjustedPlusOffsets:CGPoint = SMPositionAddTwoPositions(cornerPlusAdjustments, second: speakerNameOffsets); return adjustedPlusOffsets; } // When calculating the heights for buttons during choice segments, this determines the starting Y value factor (represented // as a percentage of the screen height. For example, this usually defaults to 0.60 or 60%, but if there are more choices, this // might go as high as 70% of the screen height. func choiceButtonStartingYFactor(numberOfChoices:Int) -> CGFloat { var result = VNSceneNodeChoiceButtonStartingPercentage // this is usually 0.60 or 60% of the screen height let choiceNumberCutoff = 3 // above this value, the original starting point will need to be moved let heightCutoff = CGFloat(0.75) // can't use a value higher than this if numberOfChoices > choiceNumberCutoff { let numberOfChoicesAboveStandard = numberOfChoices - choiceNumberCutoff result = result + CGFloat(numberOfChoicesAboveStandard) * 0.03 } if result > heightCutoff { result = heightCutoff } return result } // Since the speech label's size changes every time the text changes, this also has to be repositioned each time // a new line of dialogue is shown. //- (CGPoint)updatedTextPosition func updatedTextPosition() -> CGPoint { //if( !speech || !speechBox ) //return CGPointZero; /* if( self.view == nil ) { print("[VNScene] ERROR: Cannot get updated text position, as this scene's view is invalid."); return CGPoint.zero }*/ var widthOfBox = speechBox!.frame.size.width; let heightOfBox = speechBox!.frame.size.height; let screenSize:CGSize = viewSize let boxSize:CGSize = speechBox!.frame.size; var workingArea:CGSize = boxSize; // Check if the speechbox is wider than the screen/view, in which case whichever one is smaller will be used if( screenSize.width < boxSize.width ) { workingArea.width = screenSize.width; } widthOfBox = workingArea.width; //float verticalMargins = [[viewSettings.objectForKey(VNSceneViewSpeechVerticalMarginsKey] floatValue) let horizontalMarginsNumber = viewSettings.object(forKey: VNSceneViewSpeechHorizontalMarginsKey) as! NSNumber let speechXOffsetNumber = viewSettings.object(forKey: VNSceneViewSpeechOffsetXKey) as! NSNumber let horizontalMargins = CGFloat(horizontalMarginsNumber.doubleValue) let speechXOffset = CGFloat(speechXOffsetNumber.doubleValue) //float speechYOffset = [[viewSettings.objectForKey(VNSceneViewSpeechOffsetYKey] floatValue) //println("verticalMargins = %f, speechYOffset = %f", verticalMargins, speechYOffset); // Find top-left corner of speechbox (child node will be centered right over the very corner) let topLeftCornerOfBox = CGPoint( x: 0.0 - (widthOfBox * 0.5), y: 0 + (heightOfBox * 0.5)); let textX:CGFloat = topLeftCornerOfBox.x + (widthOfBox * 0.04) + speechXOffset + horizontalMargins; // + speechXOffset + horizontalMargins; let textY:CGFloat = topLeftCornerOfBox.y - (heightOfBox * 0.1) - speaker!.frame.size.height;// - verticalMargins - speechYOffset; return CGPoint(x: textX, y: textY); } // MARK: - Script processing // Processes the script (during "Normal Mode"). This function determines whether it's safe to process the script (since there are // many times when it might be considered "unsafe," such as when effects are being run, or even if it's something mundane like // waiting for user input). func runScript() { if( script == nil ) { print("[VNScene] ERROR: Script cannot be run because it has no data.") return } var scriptShouldBeRun = true; // This flag is used to run the following loop... while( scriptShouldBeRun == true ) { // Check if there's anything that could change this flag if( script!.lineShouldBeProcessed() == false ) { // Have enough indexes been processed for now? scriptShouldBeRun = false; } if( mode == VNSceneModeEffectIsRunning ) { // When effects are running, it becomes impossible to reliably process the script scriptShouldBeRun = false; } if( mode == VNSceneModeChoiceWithJump || mode == VNSceneModeChoiceWithFlag ) { // Should a choice be made? scriptShouldBeRun = false; // Can't run script while waiting for player input! } // Check if any of the "stop running" conditions were met; in that case the function should just stop if( scriptShouldBeRun == false ) { return; } /* If the function has made it this far, then it's time to grab more script data and process that */ // Get the current line/command from the script //NSArray* currentCommand = [script currentCommand) let currentCommand:NSArray? = script!.currentCommand() // Check if there is no valid data (this might also mean that there are no more commands at all) if( currentCommand == nil ) { // Print warning message and finish the scene print("[VNScene] NOTICE: Script has run out of commands. Switching to 'Scene Ended' mode..."); mode = VNSceneModeEnded; return; } // Helpful output! This is just optional, but it's useful for development (especially for tracking // bugs and crashes... hopefully most of those have been ironed out at this point!) //println("[%ld] %@ - %@", (long)script.currentIndex, [currentCommand objectAtIndex:0], [currentCommand objectAtIndex:1]); //var logstr1:String = currentCommand!.objectAtIndex(0) as String //var logstr2:String = currentCommand!.objectAtIndex(1) as String //println("[\(script!.currentIndex)] \(logstr1) - \(logstr2)") //[self processCommand:currentCommand) // Handle whatever line was just taken from the script processCommand(currentCommand!) //script.indexesDone++; // Tell the script that it's handled yet another line script!.indexesDone += 1 } } // This is the most important function; it breaks down the data stored in each line of the script and actually // does something useful with it. //- (void)processCommand:(NSArray *)command func processCommand(_ command: NSArray) { if( command.count < 1 ) { print("[VNScene] Cannot process command as array has insufficient data.") return } // Extract some data from the command let commandTypeNumber = command.object(at: 0) as! NSNumber // Command type, always stored as 'int' let type:Int = commandTypeNumber.intValue let param1:AnyObject? = command.object(at: 1) as AnyObject? // Get the first parameter (which might be a string, number, etc) // Check for an invalid parameter if param1 == nil { print("[VNScene] ERROR: No parameter detected; all commands must have at least 1 parameter!"); return; } /* // Parameter 1 type var param1IsString = false //var param1IsNumber = false var String(command.object(at: 1)) = "" //if param1!.isKindOfClass(NSNumber) == true { // param1IsNumber = true //} if param1!.isKind(of: NSString) == true { param1IsString = true } // Convert to string if param1IsString == true { String(command.object(at: 1)) = param1! as! String }*/ // Check if the command is really just "display a regular line of text" if( type == VNScriptCommandSayLine ) { if TWModeEnabled == false { // Speech opacity is set to zero, making it invisible. Remember, speech is supposed to "fade in" // instead of instantly appearing, since an instant appearance can be visually jarring to players. speech!.alpha = 0.0; //[speech setText:parameter1) // Copy over the text (while the text label is "invisble") speech!.text = String(describing: command.object(at: 1)) //[record.setValue:parameter1 forKey:VNSceneSpeechToDisplayKey) // Copy text to save-game record record.setValue(param1, forKey: VNSceneSpeechToDisplayKey) // Copy text to save-game record // Now have the text fade into full visibility. let fadeIn:SKAction = SKAction.fadeIn(withDuration: speechTransitionSpeed) //[SKAction fadeInWithDuration:speechTransitionSpeed) speech!.run(fadeIn) // If the speech-box isn't visible (or at least not fully visible), then it should fade-in as well if( speechBox!.alpha < 0.9 ) { //CCActionFadeIn* fadeInSpeechBox = [CCActionFadeIn actionWithDuration:speechTransitionSpeed) //let fadeInSpeechBox = [SKAction fadeInWithDuration:speechTransitionSpeed) let fadeInSpeechBox = SKAction.fadeIn(withDuration: speechTransitionSpeed) //[speechBox runAction:fadeInSpeechBox) speechBox!.run(fadeInSpeechBox) } speech!.anchorPoint = CGPoint(x: 0, y: 1.0); //speech!.position = [self updatedTextPosition) speech!.position = updatedTextPosition() } else { let parameter1AsString = command.object(at: 1) as! NSString // Reset counter TWTimer = 0; TWFullText = String(describing: command.object(at: 1))//parameter1AsString as String TWCurrentText = ""; TWNumberOfCurrentCharacters = 0; TWNumberOfTotalCharacters = NSString(string: TWFullText).length//Int( parameter1AsString.length ) TWPreviousNumberOfCurrentChars = 0; //[record setValue:parameter1 forKey:VNSceneSpeechToDisplayKey]; record.setValue(parameter1AsString, forKey: VNSceneSpeechToDisplayKey) speech!.text = " "// parameter1AsString speechBox!.alpha = 1.0; speech!.anchorPoint = CGPoint(x: 0, y: 1.0) speech!.position = updatedTextPosition() TWInvisibleText!.text = String(describing: command.object(at: 1)) //parameter1AsString as String TWInvisibleText!.anchorPoint = CGPoint(x: 0, y: 1.0) TWInvisibleText!.position = updatedTextPosition() TWInvisibleText!.alpha = 0.0 } return; } // Advance the script's index to make sure that commands run one after the other. Otherwise, they will only run one at a time // and the user would have to keep touching the screen each time in order for the next command to be run. Except for the // "display a line of text" command, most of the commands are designed to run one after the other seamlessly. script!.currentIndex += 1; // Now, figure out what type of command this is! switch( type ) { // Adds a CCSprite object to the screen; the image is loaded from a file in the app bundle. Currently, VNScene doesn't // support texture atlases, so it can only load the WHOLE IMAGE as-is. case VNScriptCommandAddSprite: //NSString* spriteName = parameter1; let spriteName = String(describing: command.object(at: 1)) let filenameOfSprite = self.filenameOfSpriteAlias(spriteName) //BOOL appearAtOnce = [[command objectAtIndex:2] boolValue) // Should the sprite show up at once, or fade in (like text does) let parameter2 = command.object(at: 2) as! NSNumber let appearAtOnce = parameter2.boolValue // Check if this sprite already exists, and if it does, then stop the function since there's no point adding the sprite a second time. let spriteAlreadyExists:SKSpriteNode? = sprites.object(forKey: spriteName) as? SKSpriteNode if( spriteAlreadyExists != nil ) { return; } // Try to load the sprite from an image in the app bundle //CCSprite* createdSprite = [CCSprite spriteWithImageNamed:spriteName) // Loads from file; sprite-sheets not supported //SKSpriteNode* createdSprite = [SKSpriteNode spriteNodeWithImageNamed:spriteName) let createdSprite:SKSpriteNode? = SKSpriteNode(imageNamed: filenameOfSprite) if( createdSprite == nil ) { print("[VNScene] ERROR: Could not load sprite named: \(filenameOfSprite)"); return; } // Add the newly-created sprite to the sprite dictionary //[sprites.setValue:createdSprite forKey:spriteName) sprites.setValue(createdSprite!, forKey: spriteName) // Position the sprite at the center; the position can be changed later. Usually, the command to change sprite positions // is almost immediately right after the command to add the sprite; the commands are executed so quickly that the user // shouldn't see any delay. createdSprite!.position = SMPositionWithNormalizedCoordinates(0.5, normalizedY: 0.5); // Sprite positioned at screen center createdSprite!.zPosition = VNSceneCharacterLayer; //[self addChild:createdSprite z:VNSceneCharacterLayer) //[self addChild:createdSprite) addChild(createdSprite!) // Right now, the sprite is fully visible on the screen. If it's supposed to fade in, then the opacity is set to zero // (making the sprite "invisible") and then it fades in over a period of time (by default, that period is half a second). //if( appearAtOnce == NO ) { if appearAtOnce == false { // Make the sprite fade in gradually ("gradually" being a relative term!) createdSprite!.alpha = 0.0; let fadeIn = SKAction.fadeIn(withDuration: spriteTransitionSpeed) createdSprite!.run(fadeIn) } // appearAtOnce // This "aligns" a sprite so that it's either in the left, center, or right areas of the screen. (This is calculated as being // 25%, 50% or 75% of the screen width). case VNScriptCommandAlignSprite: //NSString* spriteName = parameter1; let spriteName = String(describing: command.object(at: 1)) let newAlignment = command.object(at: 2) as! String // "left", "center", "right" let duration = command.object(at: 3) as! NSNumber // Default duration is 0.5 seconds; this is stored as an NSNumber (double) let durationAsDouble = duration.doubleValue // For when an actual scalar value has to be passed (instead of NSNumber) var alignmentFactor = CGFloat(0.5) // 0.50 is the center of the screen, 0.25 is left-aligned, and 0.75 is right-aligned // STEP ONE: Find the sprite if it exists. If it doesn't, then just stop the function. let sprite:SKSpriteNode? = sprites.object(forKey: spriteName) as? SKSpriteNode if( sprite == nil ) { return; } // STEP TWO: Set the new sprite position // Check the string to find out if the sprite should be left-aligned or right-aligned instead if newAlignment.caseInsensitiveCompare(VNSceneViewSpriteAlignmentLeftString) == ComparisonResult.orderedSame { alignmentFactor = 0.25; // "left" } else if newAlignment.caseInsensitiveCompare(VNSceneViewSpriteAlignmentRightString) == ComparisonResult.orderedSame { alignmentFactor = 0.75; // "right" } else if( newAlignment.caseInsensitiveCompare(VNSceneViewSpriteAlignemntFarLeftString) == ComparisonResult.orderedSame ) { alignmentFactor = 0.0; // "far left" } else if( newAlignment.caseInsensitiveCompare(VNSceneViewSpriteAlignmentFarRightString) == ComparisonResult.orderedSame ) { alignmentFactor = 1.0; // "far right" } else if( newAlignment.caseInsensitiveCompare(VNSceneViewSpriteAlignmentExtremeLeftString) == ComparisonResult.orderedSame ) { alignmentFactor = -0.5; // "extreme left" } else if( newAlignment.caseInsensitiveCompare(VNSceneViewSpriteAlignmentExtremeRightString) == ComparisonResult.orderedSame ) { alignmentFactor = 1.5; // "extreme right" } // Tell the view to instantly re-position the sprite //float updatedX = [[CCDirector sharedDirector] viewSize].width * alignmentFactor; let updatedX = viewSize.width * alignmentFactor; let updatedY = sprite!.position.y; // Maintain the same height as before // If the duration is set to "instant" (meaning zero duration), then just move the sprite into position // and stop the function if( durationAsDouble <= 0.0 ) { sprite!.position = CGPoint( x: updatedX, y: updatedY ); // Set new position return; } createSafeSave() // Create safe-save before using a move effect on the sprite (safe-saves are always used before effects are run) // STEP THREE: Make preparations for the "move sprite" effect. Once the actual movement has been completed, then // the action sequence will call 'clearEffectRunningFlag' to let VNScene know that the effect's done. //CCActionMoveTo* moveSprite = [CCActionMoveTo actionWithDuration:durationAsDouble position:CGPointMake(updatedX, updatedY)) //CCActionCallFunc* clearFlagAction = [CCActionCallFunc actionWithTarget:self selector:@selector(clearEffectRunningFlag)) //CCActionSequence* spriteMoveSequence = [CCActionSequence actions:moveSprite, clearFlagAction, nil) let moveSprite = SKAction.move(to: CGPoint(x: updatedX, y: updatedY), duration:durationAsDouble) //let clearFlagAction = SKAction.performSelector(Selector("clearEffectRunningFlag"), onThread: <#NSThread!#>, withObject: <#AnyObject!#>, waitUntilDone: <#Bool#>) let clearFlagAction = SKAction.run(self.clearEffectRunningFlag) //let spriteMoveSequence = SKAction.sequence(moveSprite, clearFlagAction) let spriteMoveSequence = SKAction.sequence([moveSprite, clearFlagAction]) //let clearFlagAction = [SKAction performSelector:@selector(clearEffectRunningFlag) onTarget:self) //let spriteMoveSequence = [SKAction sequence:@[moveSprite, clearFlagAction]) // STEP FOUR: Set the "effect running" flag, and then actually perform the CCAction sequence. setEffectRunningFlag() sprite!.run(spriteMoveSequence) // This command just removes a sprite from the screen. It can be done immediately (though suddenly vanishing is kind of // jarring for players) or it can gradually fade from sight. case VNScriptCommandRemoveSprite: let spriteName = String(describing: command.object(at: 1)) let spriteVanishesImmediately = (command.object(at: 2) as! NSNumber).boolValue //[[command objectAtIndex:2] boolValue) // Check if the sprite even exists. If it doesn't, just stop the function let sprite:SKSpriteNode? = sprites.object(forKey: spriteName) as? SKSpriteNode if( sprite == nil ) { return; } // Remove the sprite from the sprites array. If the game needs be saved soon right after this command // is called, then the now-removed sprite won't be included in the save data. sprites.removeObject(forKey: spriteName) // Check if it should just vanish at once (this should probably be done offscreen because it looks weird // if it just happens while the player can still see the sprite). if( spriteVanishesImmediately == true ) { // Remove it from its parent node (if it has one) if( sprite!.parent != nil ) { sprite!.removeFromParent() } } else { // If the sprite shouldn't be removed immediately, then it should be moved to an array of "unused" (or soon-to-be-unused) // sprites, and then later deleted. spritesToRemove.add(sprite!) // Add to the sprite-removal array; sprite will be removed later by a function sprite!.name = VNSceneSpriteIsSafeToRemove; // Mark the sprite as safe-to-delete // This sequence of CCActions will cause the sprite to fade out, and then it'll be removed from memory. //CCActionFadeOut* fadeOutSprite = [CCActionFadeOut actionWithDuration:spriteTransitionSpeed) //CCActionCallFunc* removeSprite = [CCActionCallFunc actionWithTarget:self selector:@selector(removeUnusedSprites)) //CCActionSequence* spriteRemovalSequence = [CCActionSequence actions:fadeOutSprite, removeSprite, nil) let fadeOutSprite = SKAction.fadeOut(withDuration: spriteTransitionSpeed) let removeSprite = SKAction.run(self.removeUnusedSprites) let spriteRemovalSequence = SKAction.sequence([fadeOutSprite, removeSprite]) sprite!.run(spriteRemovalSequence) } // This command is used to move/pan the background around, using the "moveBy" action case VNScriptCommandEffectMoveBackground: // Check if the background even exists to begin with, because otherwise there's no point to any of this! //CCSprite* background = (CCSprite*) [self getChildByName:VNSceneTagBackground recursively:false) let backgroundSprite:SKSpriteNode? = self.childNode(withName: VNSceneTagBackground) as? SKSpriteNode if( backgroundSprite == nil ) { return } let background = backgroundSprite! createSafeSave() let moveByX = command.object(at: 1) as! NSNumber let moveByY = command.object(at: 2) as! NSNumber let duration = command.object(at: 3) as! NSNumber let parallaxing = command.object(at: 4) as! NSNumber let durationAsDouble = duration.doubleValue let parallaxFactor = CGFloat(parallaxing.doubleValue) self.setEffectRunningFlag() // Also update the background's position in the record, so that when the game is loaded from a saved game, // then the background will be where it should be (that is, where it will be once the CCAction has finished). let finishedX = background.position.x + CGFloat(moveByX.floatValue) let finishedY = background.position.y + CGFloat(moveByY.floatValue) record.setObject(NSNumber(value: Double(finishedX)), forKey: VNSceneBackgroundXKey as NSCopying) record.setObject(NSNumber(value: Double(finishedY)), forKey: VNSceneBackgroundYKey as NSCopying) // Updates sprites to move along with the background for currentName in sprites.allKeys { let spriteName = currentName as! String let currentSprite:SKSpriteNode? = sprites.object(forKey: spriteName) as? SKSpriteNode if( currentSprite!.parent != nil ) { let spriteMovementX = parallaxFactor * CGFloat( moveByX.doubleValue ) let spriteMovementY = parallaxFactor * CGFloat( moveByY.doubleValue ) let movementAction = SKAction.move(by: CGVector(dx: spriteMovementX, dy: spriteMovementY), duration: durationAsDouble) currentSprite!.run(movementAction) } } // Set up the movement sequence let movementAmount = CGVector( dx: CGFloat(moveByX.floatValue), dy: CGFloat(moveByY.floatValue) ); let moveByAction = SKAction.move(by: movementAmount, duration: durationAsDouble) let clearEffectFlag = SKAction.run(self.clearEffectRunningFlag) let movementSequence = SKAction.sequence([moveByAction, clearEffectFlag]) background.run(movementSequence) // This command moves a sprite by a certain number of points (since Cocos2D uses points instead of pixels). This // is really just a "wrapper" of sorts for the CCMoveBy action in Cocos2D. case VNScriptCommandEffectMoveSprite: let spriteName = String(describing: command.object(at: 1)) let moveByXNumber = command.object(at: 2) as! NSNumber let moveByYNumber = command.object(at: 3) as! NSNumber let durationNumber:NSNumber? = command.object(at: 4) as? NSNumber // Create scalar versions let moveByX = CGFloat( moveByXNumber.doubleValue ) let moveByY = CGFloat( moveByYNumber.doubleValue ) var duration = Double( 0 ) // Default duration length let tempSprite:SKSpriteNode? = sprites.object(forKey: spriteName) as? SKSpriteNode if( tempSprite == nil ) { return; } if durationNumber != nil { duration = durationNumber!.doubleValue } let sprite = tempSprite! createSafeSave() if duration < 0.0 { let updatedX = sprite.position.x + moveByX let updatedY = sprite.position.y + moveByY sprite.position = CGPoint(x: updatedX, y: updatedY) return; // Stop the function, since an "immediate movement" command doesn't need to go any further } self.setEffectRunningFlag() // Set up movement action, and then have the "effect is running" flag get cleared at the end of the sequence let movementAmount = CGVector(dx: moveByX, dy: moveByY) let moveByAction = SKAction.move(by: movementAmount, duration: duration) let clearEffectFlag = SKAction.run(self.clearEffectRunningFlag) let movementSequence = SKAction.sequence([moveByAction, clearEffectFlag]) sprite.run(movementSequence) // Instantly set a sprite's position (this is similar to the "move sprite" command, except this happens instantly). // While instant movement can look strange, there are some situations it can be useful. case VNScriptCommandSetSpritePosition: let spriteName = String(describing: command.object(at: 1)) let updatedXNumber = command.object(at: 2) as! NSNumber let updatedYNumber = command.object(at: 3) as! NSNumber let updatedX = CGFloat( updatedXNumber.doubleValue ) let updatedY = CGFloat( updatedYNumber.doubleValue ) let loadedSprite:SKSpriteNode? = sprites.object(forKey: spriteName) as? SKSpriteNode if( loadedSprite != nil ) { loadedSprite!.position = CGPoint(x: updatedX, y: updatedY) } // Change the background image. If the name parameter is set to "nil" then this command just removes the background image. case VNScriptCommandSetBackground: let backgroundName = String(describing: command.object(at: 1)); // Get rid of the old background let background:SKSpriteNode? = self.childNode(withName: VNSceneTagBackground) as? SKSpriteNode if( background != nil ) { background!.removeFromParent() } // Also remove background data from records record.removeObject(forKey: VNSceneBackgroundToShowKey) record.removeObject(forKey: VNSceneBackgroundXKey) record.removeObject(forKey: VNSceneBackgroundYKey) // Check the value of the string. If the string is "nil", then just get rid of any existing background // data. Otherwise, VNSceneView will try to use the string as a file name. if backgroundName.caseInsensitiveCompare(VNScriptNilValue) != ComparisonResult.orderedSame { let updatedBackground = SKSpriteNode(imageNamed: backgroundName) // Get some data needed to set the background var alphaValue = CGFloat( 1.0 ) let alphaNumber:NSNumber? = viewSettings.object(forKey: VNSceneViewDefaultBackgroundOpacityKey) as? NSNumber if( alphaNumber != nil ) { alphaValue = CGFloat( alphaNumber!.doubleValue ) } // Set properties //updatedBackground.position = CGPoint(x: viewSize.width * 0.5, y: viewSize.height * 0.5) // Position at the center of the frame updatedBackground.position = CGPoint(x: viewSize.width * 0.5, y: viewSize.height * 0.5) // Position at the center of the frame updatedBackground.alpha = alphaValue updatedBackground.zPosition = VNSceneBackgroundLayer updatedBackground.name = VNSceneTagBackground self.addChild(updatedBackground) // Convert coordinates to NSNumber format let backgroundXDouble = Double( updatedBackground.position.x ) let backgroundYDouble = Double( updatedBackground.position.y ) let bgXNumber = NSNumber( value: backgroundXDouble ) let bgYNumber = NSNumber( value: backgroundYDouble ) // Update record record.setObject(backgroundName, forKey: VNSceneBackgroundToShowKey as NSCopying) record.setObject(bgXNumber, forKey: VNSceneBackgroundXKey as NSCopying) record.setObject(bgYNumber, forKey: VNSceneBackgroundYKey as NSCopying) } // Sets the "speaker name," so that the player knows which character is speaking. The name usually appears above and to the // left of the actual dialogue text. The value of the speaker name can be set to "nil" to hide the label. case VNScriptCommandSetSpeaker: let updatedSpeakerName = String(describing: command.object(at: 1)) speaker!.alpha = 0; // Make the label invisible so that it can fade in speaker!.text = " "; // Default value is to not have any speaker name in the label's text string record.removeObject(forKey: VNSceneSpeakerNameToShowKey) // Check if this is a valid name (instead of the 'nil' value) if updatedSpeakerName.caseInsensitiveCompare(VNScriptNilValue) != ComparisonResult.orderedSame { // Set new name record.setValue(updatedSpeakerName, forKey: VNSceneSpeakerNameToShowKey) speaker!.alpha = 0; speaker!.text = updatedSpeakerName; speaker!.anchorPoint = CGPoint(x: 0, y: 1.0); speaker!.position = self.updatedSpeakerPosition() //[self updatedSpeakerPosition) // Fade in the speaker name label let fadeIn = SKAction.fadeIn(withDuration: speechTransitionSpeed) speaker!.run(fadeIn) } // This changes which "conversation" (or array of dialogue) in the script is currently being run. case VNScriptCommandChangeConversation: //NSString* updatedConversationName = parameter1; let updatedConversationName = String(describing: command.object(at: 1)) let convo:NSArray? = script!.data!.object(forKey: updatedConversationName) as? NSArray if convo == nil { print("[VNScene] ERROR: No section titled \(updatedConversationName) was found in script!") return; } // If the conversation actually exists, then just switch to it if script!.changeConversationTo(updatedConversationName) == false { print("[VNScene] WARNING: Could not switch script to section named: \(updatedConversationName)") } script!.indexesDone -= 1 // This command presents a choice menu to the player, and after the player chooses, then VNScene switches conversations. case VNScriptCommandJumpOnChoice: self.createSafeSave() // Always create safe-save before doing something volatile let choiceTexts = command.object(at: 1) as! NSArray // Get the strings to display for individual choices let destinations = command.object(at: 2) as! NSArray // Get the names of the conversations to "jump" to let numberOfChoices = choiceTexts.count // Calculate number of choices // Make sure the arrays that hold the data are prepared buttons.removeAllObjects() choices.removeAllObjects() // Come up with some position data let screenWidth = viewSize.width let screenHeight = viewSize.height for i in 0 ..< numberOfChoices { let buttonImageName = SMStringFromDictionary(viewSettings, nameOfObject: VNSceneViewButtonFilenameKey) //viewSettings.objectForKey(VNSceneViewButtonFilenameKey) as! NSString let button:SKSpriteNode = SKSpriteNode(imageNamed: buttonImageName) // Calculate the amount of space (including space between buttons) that each button will take up, and then // figure out where and how to position the buttons (factoring in margins / spaces between buttons). Generally, // the button in the middle of the menu of choices will show up in the middle of the screen with this formula. let spaceBetweenButtons:CGFloat = button.frame.size.height * 0.2; let buttonHeight:CGFloat = button.frame.size.height; let totalButtonSpace:CGFloat = buttonHeight + spaceBetweenButtons; //let startingPosition:CGFloat = (screenHeight * 0.5) + ( ( CGFloat(numberOfChoices / 2) ) * totalButtonSpace ) + choiceButtonOffsetY //let heightPercentage = VNSceneNodeChoiceButtonStartingPercentage // usually 0.70 or 70% of the screen height let heightPercentage = choiceButtonStartingYFactor(numberOfChoices: numberOfChoices) let startingPosition:CGFloat = (screenHeight * heightPercentage) - ( ( CGFloat(numberOfChoices / 2) ) * totalButtonSpace ) + choiceButtonOffsetY let buttonY:CGFloat = startingPosition + ( CGFloat(i) * totalButtonSpace ); // Set button position button.position = CGPoint( x: (screenWidth * 0.5) + choiceButtonOffsetX, y: buttonY ); button.zPosition = VNSceneButtonsLayer; button.name = "\(i)" //button.name = [NSString stringWithFormat:@"%d", i) self.addChild(button) // Set color and add to array button.color = buttonUntouchedColors buttons.add(button) // Determine where the text should be positioned inside the button var labelWithinButtonPos = CGPoint( x: button.frame.size.width * 0.5, y: button.frame.size.height * 0.35 ); if( UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad ) { // The position of the text inside the button has to be adjusted, since the actual font size on the iPad isn't exactly // twice as large, but modified with some custom code. This results in having to do some custom positioning as well! labelWithinButtonPos.y = CGFloat(button.frame.size.height * 0.31) } // Create the button label /*CCLabelTTF* buttonLabel = [CCLabelTTF labelWithString:[choiceTexts objectAtIndex:i] fontName:[viewSettings.objectForKey(VNSceneViewFontNameKey] fontSize:[[viewSettings.objectForKey(VNSceneViewFontSizeKey] floatValue] dimensions:button.boundingBox.size)*/ let labelFontName = SMStringFromDictionary(viewSettings, nameOfObject: VNSceneViewFontNameKey)//viewSettings.objectForKey(VNSceneViewFontNameKey) as NSString let labelFontSize = SMNumberFromDictionary(viewSettings, nameOfObject: VNSceneViewFontSizeKey)//viewSettings.objectForKey(VNSceneViewFontSizeKey) as NSNumber let buttonLabel = SKLabelNode(fontNamed: labelFontName) // Set label properties buttonLabel.text = choiceTexts.object(at: i) as! NSString as String buttonLabel.fontSize = CGFloat( labelFontSize.floatValue ) buttonLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center // Center the text in the button // Handle positioning for the text var buttonLabelYPos = 0 - (button.size.height * 0.20) if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { buttonLabelYPos = 0 - (button.size.height * 0.20) } buttonLabel.position = CGPoint(x: 0.0, y: buttonLabelYPos) buttonLabel.zPosition = VNSceneButtonTextLayer // set button text color buttonLabel.color = buttonTextColor; buttonLabel.colorBlendFactor = 1.0; buttonLabel.fontColor = buttonTextColor; button.addChild(buttonLabel) button.colorBlendFactor = 1.0 // Needed to "color" the sprite; it wouldn't have any color-blending otherwise choices.add( destinations.object(at: i) ) } mode = VNSceneModeChoiceWithJump // This command will show (or hide) the speech box (the little box where all the speech/dialogue text is shown). // Hiding it is useful in case you want the player to just enjoy the background art. case VNScriptCommandShowSpeechOrNot: let showSpeechNumber = param1! as! NSNumber let showSpeechOrNot = showSpeechNumber.boolValue record.setValue(showSpeechNumber, forKey: VNSceneShowSpeechKey) // Case 1: DO show the speech box if( showSpeechOrNot == true ) { //[speechBox stopAllActions) //[speech stopAllActions) speechBox!.removeAllActions() speech!.removeAllActions() //CCActionFadeIn* fadeInSpeechBox = [CCActionFadeIn actionWithDuration:speechTransitionSpeed) let fadeInSpeechBox = SKAction.fadeIn(withDuration: speechTransitionSpeed) speechBox!.run(fadeInSpeechBox) let fadeInText = SKAction.fadeIn(withDuration: speechTransitionSpeed) speech!.run(fadeInText) // Case 2: DON'T show the speech box. } else { speech!.removeAllActions() speechBox!.removeAllActions() let fadeOutBox = SKAction.fadeOut(withDuration: speechTransitionSpeed) let fadeOutText = SKAction.fadeOut(withDuration: speechTransitionSpeed) speechBox!.run(fadeOutBox) speech!.run(fadeOutText) } // This command causes the background image and character sprites to "fade in" (go from being fully transparent to being // opaque). // // Note that if you want a fade-to-black (or rather, fade-FROM-black) effect, it helps if this CCLayer is being run in // its own CCScene. If the layer has just been added on to an existing CCScene/CCLayer, then hopefully there's a big // black image behind it or something. case VNScriptCommandEffectFadeIn: let durationNumber = param1 as! NSNumber let duration = durationNumber.doubleValue self.createSafeSave() self.setEffectRunningFlag() // Check if there's any character sprites in existence. If there are, they all need to have a CCFadeIn action // applied to each and every one. if sprites.count > 0 { for tempSprite in sprites.allValues { let currentSprite:SKSpriteNode = tempSprite as! SKSpriteNode let fadeIn = SKAction.fadeIn(withDuration: duration) currentSprite.run(fadeIn) } } // Fade in the background sprite, if it exists let backgroundSprite:SKSpriteNode? = self.childNode(withName: VNSceneTagBackground) as? SKSpriteNode if( backgroundSprite != nil ) { let fadeIn = SKAction.fadeIn(withDuration: duration) backgroundSprite!.run(fadeIn) } // Since the upcoming CCSequence runs at the same time that the prior CCFadeIn actions are run, the first thing // put into the sequence is a delay action, so that the "function call" action gets run immediately after the // fade-in actions finish. let delay = SKAction.wait(forDuration: duration) let callFunc = SKAction.run(self.clearEffectRunningFlag) //let callFunc = SKAction performSelector:@selector(clearEffectRunningFlag) onTarget:self) let delayedClearSequence = SKAction.sequence([delay, callFunc]) //[self runAction:delayedClearSequence) self.run(delayedClearSequence) // Finally, update the view settings with the "fully faded-in" value for the background's opacity //[viewSettings.setValue(1.0f forKey:VNSceneViewDefaultBackgroundOpacityKey) viewSettings.setValue(NSNumber(value: 1.0), forKey: VNSceneViewDefaultBackgroundOpacityKey) // This is similar to the above command, except that it causes the character sprites and background to go from being // fully opaque to fully transparent (or "fade out"). case VNScriptCommandEffectFadeOut: let durationNumber = param1 as! NSNumber let duration = durationNumber.doubleValue self.createSafeSave() self.setEffectRunningFlag() if sprites.count > 0 { for tempSprite in sprites.allValues { let fadeOut = SKAction.fadeOut(withDuration: duration) let currentSprite = tempSprite as! SKSpriteNode currentSprite.run(fadeOut) } let backgroundSprite:SKSpriteNode? = self.childNode(withName: VNSceneTagBackground) as? SKSpriteNode if( backgroundSprite != nil ) { let fadeOut = SKAction.fadeOut(withDuration: duration) backgroundSprite!.run(fadeOut) } } let delay = SKAction.wait(forDuration: duration) let callFunc = SKAction.run(self.clearEffectRunningFlag) let delayedClearSequence = SKAction.sequence([delay, callFunc]) self.run(delayedClearSequence) viewSettings.setValue(NSNumber(value: 0.0), forKey: VNSceneViewDefaultBackgroundOpacityKey) // This just plays a sound. I had actually thought about creating some kind of system to keep track of all // the sounds loaded, and then to manually remove them from memory once they were no longer being used, // but I've never gotten around to implementing it. case VNScriptCommandPlaySound: let soundName = String(describing: command.object(at: 1)) self.playSoundEffect(soundName) // This plays music (an MP3 file is good, though AAC might be better since iOS devices supposedly have built-in // hardware-decoding for them, or CAF since they have small filesizes and small memory footprints). You can only // play one music file at a time. You can choose whether it loops infinitely, or if it just plays once. // // If you want to STOP music from playing, you can also pass "nil" as the filename (parameter #1) to cause // VNScene to stop all music. case VNScriptCommandPlayMusic: let musicName = String(describing: command.object(at: 1)) let musicShouldLoop = (command.object(at: 2) as! NSNumber) print("[VNScene] Should now stop background music.") self.stopBGMusic() if musicName.caseInsensitiveCompare(VNScriptNilValue) == ComparisonResult.orderedSame { // Remove all the existing music data from the saved game information record.removeObject(forKey: VNSceneMusicToPlayKey) record.removeObject(forKey: VNSceneMusicShouldLoopKey) } else { record.setValue(musicName, forKey: VNSceneMusicToPlayKey) record.setValue(musicShouldLoop, forKey: VNSceneMusicShouldLoopKey) // Play the new background music self.playBGMusic(musicName, willLoopForever: musicShouldLoop.boolValue) } // This command sets a variable (or "flag"), which is usually an "int" value stored in an NSNumber object by a dictionary. // VNScene stores a local dictionary, and whenever the game is saved, the contents of that dictionary are copied over to // SMRecord's own flags dictionary (and stored in device memory). case VNScriptCommandSetFlag: let flagName = String(describing: command.object(at: 1)) let flagValue:AnyObject = command.object(at: 2) as AnyObject //NSLog("[VNScene] Setting flag named [%@] to a value of [%@]", flagName, flagValue); // Store the new value in the local dictionary //[flags.setValue:flagValue forKey:flagName) flags.setValue(flagValue, forKey: flagName) // This modifies an existing flag's integer value by a certain amount (you might have guessed: a positive value "adds", // while a negative "subtracts). If no flag actually exists, then a new flag is created with whatever value was passed in. case VNScriptCommandModifyFlagValue: let flagName = String(describing: command.object(at: 1)) let modifyWithValue = (command.object(at: 2) as! NSNumber).intValue let originalObject:AnyObject? = flags.object(forKey: flagName) as AnyObject? if originalObject == nil { // Set a new value based on the parameter flags.setValue( NSNumber(value: modifyWithValue), forKey: flagName) return; // And that's the end of it } // Handle modification operation let originalNumber:NSNumber = originalObject! as! NSNumber let originalValue = originalNumber.intValue let modifiedValue = originalValue + modifyWithValue let finalNumber = NSNumber(value: modifiedValue) flags.setValue(finalNumber, forKey: flagName) // This checks if a particular flag has a certain value. If it does, then it executes ANOTHER command (which starts // at the third parameter and continues to whatever comes afterwards). case VNScriptCommandIfFlagHasValue: let flagName = String(describing: command.object(at: 1)) let expectedValue = (command.object(at: 2) as! NSNumber).intValue let secondaryCommand:NSArray = command.object(at: 3) as! NSArray // Secondary command, which runs if the actual and expected values are the same let theFlag:NSNumber? = flags.object(forKey: flagName) as? NSNumber if theFlag == nil { return; } let actualValue = Int(theFlag!.int32Value) if( actualValue != expectedValue ) { return; } // If the function reaches this point, it's safe to move on to the next phase self.processCommand(secondaryCommand) let secondaryCommandType = (secondaryCommand.object(at: 0) as! NSNumber).intValue // Make sure that things don't get knocked out of order by the secondary command (if it involves switching conversations) if secondaryCommandType != VNScriptCommandChangeConversation { script!.currentIndex -= 1 } // This checks if a particular flag is GREATER THAN a certain value. If it does, then it executes ANOTHER command (which starts // at the third parameter and continues to whatever comes afterwards). case VNScriptCommandIsFlagMoreThan: let flagName = String(describing: command.object(at: 1)) let expectedValue = (command.object(at: 2) as! NSNumber).intValue let secondaryCommand = command.object(at: 3) as! NSArray let theFlag:NSNumber? = flags.object(forKey: flagName) as? NSNumber if theFlag == nil { return; } let actualValue = Int(theFlag!.int32Value) if( actualValue <= expectedValue ) { return; } self.processCommand(secondaryCommand) let secondaryCommandType = (secondaryCommand.object(at: 0) as! NSNumber).intValue if( secondaryCommandType != VNScriptCommandChangeConversation ) { script!.currentIndex -= 1 } // This checks if a particular flag LESS THAN certain value. If it does, then it executes ANOTHER command (which starts // at the third parameter and continues to whatever comes afterwards). case VNScriptCommandIsFlagLessThan: let flagName = String(describing: command.object(at: 1)) let expectedValue = (command.object(at: 2) as! NSNumber).intValue let secondaryCommand = command.object(at: 3) as! NSArray let theFlag:NSNumber? = flags.object(forKey: flagName) as? NSNumber if( theFlag == nil ) { return; } let actualValue = Int(theFlag!.int32Value) if( actualValue >= expectedValue ) { return; } self.processCommand(secondaryCommand) let secondaryCommandType = (secondaryCommand.object(at: 0) as! NSNumber).intValue if( secondaryCommandType != VNScriptCommandChangeConversation ) { script!.currentIndex -= 1; } // This checks if a particular flag is between two values (a lesser value and a greater value). If thie is the case, // then a secondary command is run. case VNScriptCommandIsFlagBetween: let flagName = String(describing: command.object(at: 1)) let lesserValue = (command.object(at: 2) as! NSNumber).intValue let greaterValue = (command.object(at: 3) as! NSNumber).intValue let secondaryCommand = command.object(at: 4) as! NSArray let theFlag:NSNumber? = flags.object(forKey: flagName) as? NSNumber if( theFlag == nil ) { return; } let actualValue = Int(theFlag!.int32Value) if( actualValue <= lesserValue || actualValue >= greaterValue ) { return; } self.processCommand(secondaryCommand) let secondaryCommandType = (secondaryCommand.object(at: 0) as! NSNumber).intValue if( secondaryCommandType != VNScriptCommandChangeConversation ) { script!.currentIndex -= 1; } // This command presents the user with a choice menu. When the user makes a choice, it results in the value of a flag // being modified by a certain amount (just like if the .MODIFYFLAG command had been used). case VNScriptCommandModifyFlagOnChoice: // Create "safe" autosave before doing something as volatile as presenting a choice menu self.createSafeSave() let choiceTexts = param1! as! NSArray let variableNames = command.object(at: 2) as! NSArray let variableValues = command.object(at: 3) as! NSArray let numberOfChoices = choiceTexts.count // Prepare the arrays buttons.removeAllObjects() choices.removeAllObjects() choiceExtras.removeAllObjects() let screenWidth = viewSize.width let screenHeight = viewSize.height // The following loop creates the buttons (and their label "child nodes") and adds them to an array. It also // loads the flag modification data into their own arrays. for i in 0 ..< numberOfChoices { let loopIndex = CGFloat( i ) //let choiceCount = CGFloat( numberOfChoices ) let buttonFilename = viewSettings.object(forKey: VNSceneViewButtonFilenameKey) as! NSString let button = SKSpriteNode(imageNamed: buttonFilename as String) // Calculate the amount of space (including space between buttons) that each button will take up, and then // figure out the position of the button that's being made. Ideally, the middle of the choice menu will also be the middle // of the screen. Of course, if you have a LOT of choices, there may be more buttons than there is space to put them! let spaceBetweenButtons = button.frame.size.height * 0.2; // 20% of button sprite height let buttonHeight = button.frame.size.height; let totalButtonSpace = buttonHeight + spaceBetweenButtons; // total used-up space = 120% of button height //let startingPosition = (screenHeight * 0.70) - ( ( choiceCount * 0.5 ) * totalButtonSpace ) + choiceButtonOffsetY //let heightPercentage = VNSceneNodeChoiceButtonStartingPercentage // usually 0.70 or 70% of the screen height let heightPercentage = choiceButtonStartingYFactor(numberOfChoices: numberOfChoices) let startingPosition:CGFloat = (screenHeight * heightPercentage) - ( ( CGFloat(numberOfChoices / 2) ) * totalButtonSpace ) + choiceButtonOffsetY let buttonY = startingPosition + ( loopIndex * totalButtonSpace ); // This button's position // Set button position and other attributes button.position = CGPoint( x: (screenWidth * 0.5) + choiceButtonOffsetX, y: buttonY ); //button.color = [[CCColor alloc] initWithCcColor3b:buttonUntouchedColors) button.color = buttonUntouchedColors; button.zPosition = VNSceneButtonsLayer; self.addChild(button) buttons.add(button) // Determine where the text should be positioned inside the button var labelWithinButtonPos = CGPoint( x: button.frame.size.width * 0.5, y: button.frame.size.height * 0.35 ); if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { labelWithinButtonPos.y = button.frame.size.height * 0.31; } // Create button label, set the position of the text, and add this label to the main 'button' sprite let labelFontName = SMStringFromDictionary(viewSettings, nameOfObject: VNSceneViewFontNameKey) let labelFontSizeNumber = SMNumberFromDictionary(viewSettings, nameOfObject: VNSceneViewFontSizeKey) let labelFontSize = CGFloat( labelFontSizeNumber.doubleValue ) let buttonLabel = SKLabelNode(fontNamed: labelFontName) buttonLabel.fontSize = labelFontSize buttonLabel.text = choiceTexts.object(at: i) as! NSString as String buttonLabel.zPosition = VNSceneButtonsLayer buttonLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center // set button text color buttonLabel.color = buttonTextColor; buttonLabel.colorBlendFactor = 1.0; buttonLabel.fontColor = buttonTextColor; // Position Y coordinate var buttonLabelY:CGFloat = 0 - (button.size.height * 0.20) if( UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad ) { buttonLabelY = 0 - (button.size.height * 0.20) } buttonLabel.position = CGPoint(x: 0, y: buttonLabelY) button.addChild(buttonLabel) button.colorBlendFactor = 1.0; // Set up choices choices.add(variableNames.object(at: i)) choiceExtras.add(variableValues.object(at: i)) } mode = VNSceneModeChoiceWithFlag print("CHOICES array is \(choices)") print("CHOICE EXTRAS array is \(choiceExtras)") // This command will cause VNScene to switch conversations if a certain flag holds a particular value. case VNScriptCommandJumpOnFlag: let flagName = String(describing: command.object(at: 1)) let expectedValue = (command.object(at: 2) as! NSNumber).intValue let targetedConversation = command.object(at: 3) as! NSString let theFlag:NSNumber? = flags.object(forKey: flagName) as? NSNumber if theFlag == nil { return; } let actualValue = Int(theFlag!.int32Value) if( actualValue != expectedValue ) { return; } let convo:NSArray? = script!.data!.object(forKey: targetedConversation) as? NSArray if convo == nil { print("[VNScene] ERROR: No section titled \(targetedConversation) was found in script!") return; } //script!.changeConversationTo(targetedConversation as String) if script!.changeConversationTo(targetedConversation as String) == false { print("[VNScene] WARNING: Could not switch script to section named: \(targetedConversation)") } script!.indexesDone -= 1; // This command is used in conjuction with the VNSystemCall class, and is used to create certain game-specific effects. case VNScriptCommandSystemCall: let systemCallArray = NSMutableArray(array: command) systemCallArray.removeObject(at: 0) // Remove the ".systemcall" part of the command systemCallHelper.sendCall(systemCallArray) // This command replaces the scene's script with a script loaded from another .PLIST file. This is useful in case // your script is actually broken up into multiple .PLIST files. case VNScriptCommandSwitchScript: let scriptName = command.object(at: 1) as! NSString let startingPoint = command.object(at: 2) as! NSString print("[VNScene] Switching to script named \(scriptName) with starting point [\(startingPoint)]"); //let loadingDictionary = NSDictionary(objectsAndKeys: scriptName, VNScriptFilenameKey, // startingPoint, VNScriptConversationNameKey); let loadingDictionary = NSDictionary(dictionary: [VNScriptFilenameKey:scriptName, VNScriptConversationNameKey:startingPoint]) script = VNScript(info: loadingDictionary); if script == nil { print("[VNScene] ERROR: Cannot load script named: \(scriptName)") return; } script!.indexesDone -= 1; print("[VNScene] Script object replaced."); case VNScriptCommandSetSpeechFont: speechFont = String(describing: command.object(at: 1)) // This will only change the font if the font name is of a "proper" length; no supported font on iOS // is shorter than 4 characters (as far as I know). //if countElements(speechFont) > 3 { if SMStringLength(speechFont) > 3 { speech!.fontName = String(describing: command.object(at: 1)) // Update record with override record.setObject(speechFont, forKey: VNSceneOverrideSpeechFontKey as NSCopying) } case VNScriptCommandSetSpeechFontSize: let foundationString = String(describing: command.object(at: 1)) as NSString let convertedSize = CGFloat( foundationString.floatValue ) fontSizeForSpeech = convertedSize // Check for a font size that's too small; if this is the case, then just switch to a "normal" font size if( fontSizeForSpeech < 1.0 ) { fontSizeForSpeech = 13.0; } speech!.fontSize = fontSizeForSpeech; // Store override data let storedFontSize = NSNumber( value: Double(fontSizeForSpeaker) ) // Conver to NSNumber record.setValue(storedFontSize, forKey: VNSceneOverrideSpeechSizeKey) case VNScriptCommandSetSpeakerFont: speakerFont = String(describing: command.object(at: 1)) if SMStringLength(speakerFont) > 3 { speaker!.fontName = speakerFont // Update records with override record.setValue(speakerFont, forKey: VNSceneOverrideSpeakerFontKey) // Set position speaker!.anchorPoint = CGPoint(x: 0, y: 1.0) speaker!.position = self.updatedSpeakerPosition() } case VNScriptCommandSetSpeakerFontSize: let convertedString = String(describing: command.object(at: 1)) as NSString fontSizeForSpeaker = CGFloat( convertedString.floatValue ) if fontSizeForSpeaker < 1.0 { fontSizeForSpeaker = 13.0 } speaker!.fontSize = fontSizeForSpeaker // Store override data let storedNumber = NSNumber(value: Double( fontSizeForSpeaker )) record.setValue(storedNumber, forKey: VNSceneOverrideSpeakerSizeKey) // Set the position speaker!.anchorPoint = CGPoint(x: 0, y: 1.0); speaker!.position = self.updatedSpeakerPosition() case VNScriptCommandSetTypewriterText: if let first = command.object(at: 1) as? NSNumber { TWSpeedInCharacters = first.intValue; } if let second = command.object(at: 2) as? NSNumber { TWCanSkip = second.boolValue } self.updateTypewriterTextSettings() case VNScriptCommandSetSpeechbox: let duration = (command.object(at: 2) as! NSNumber).doubleValue let speechboxFilename = String(describing: command.object(at: 1)) setSpeechBox(speechboxFilename, duration: duration) case VNScriptCommandSetSpriteAlias: let aliasParameter = command.object(at: 1) as! NSString let filenameParameter = command.object(at: 2) as! NSString setSpriteAlias(aliasParameter as String, filename: filenameParameter as String) case VNScriptCommandFlipSprite: let spriteName = String(describing: command.object(at: 1)) let durationAsDouble = (command.object(at: 2) as! NSNumber).doubleValue let flipHorizontal = (command.object(at: 3) as! NSNumber).boolValue flipSpriteNamed(spriteName, duration: durationAsDouble, horizontally: flipHorizontal) case VNScriptCommandRollDice: let maximumNumber = command.object(at: 1) as! NSNumber let numberOfDice = command.object(at: 2) as! NSNumber let flagName = command.object(at: 3) as! NSString rollDice(numberOfDice.intValue, maximumSidesOfDice: maximumNumber.intValue, plusFlagModifier: flagName as String) case VNScriptCommandModifyChoiceboxOffset: let xOffset = command.object(at: 1) as! NSNumber; let yOffset = command.object(at: 2) as! NSNumber; modifyChoiceboxOffset(xOffset.doubleValue, yOffset: yOffset.doubleValue) case VNScriptCommandScaleBackground: // get the background sprite let backgroundSprite:SKSpriteNode? = self.childNode(withName: VNSceneTagBackground) as? SKSpriteNode if( backgroundSprite == nil ) { return } let scaleNumber = command.object(at: 1) as! NSNumber let durationNumber = command.object(at: 2) as! NSNumber //scaleBackground(scaleFactor: scaleNumber.doubleValue, duration: durationNumber.doubleValue) scaleBackground(backgroundSprite!, scaleFactor: scaleNumber.doubleValue, duration: durationNumber.doubleValue) case VNScriptCommandScaleSprite: let spriteName = command.object(at: 1) as! NSString let scaleNumber = command.object(at: 2) as! NSNumber let durationNumber = command.object(at: 3) as! NSNumber scaleSprite(spriteName as String, scalingAmount: scaleNumber.doubleValue, duration: durationNumber.doubleValue) case VNScriptCommandAddToChoiceSet: let setName = command.object(at: 1) as! String let destination = command.object(at: 2) as! String let choiceText = command.object(at: 3) as! String addToChoiceSet(setName: setName, destination: destination, choiceText: choiceText) case VNScriptCommandRemoveFromChoiceSet: let setName = command.object(at: 1) as! String let destination = command.object(at: 2) as! String removeFromChoiceSet(setName: setName, destination: destination) case VNScriptCommandWipeChoiceSet: //print("stuff happens") let setName = command.object(at: 1) as! String wipeChoiceSet(setName: setName) case VNScriptCommandShowChoiceSet: let setName = command.object(at: 1) as! String displayChoiceSet(setName: setName) default: print("[VNScene] WARNING: Unknown command found in script. The command's NSArray is: %@", command); } // switch } // function // MARK: - Script commands /* NOTE: Originally, all this functionality was in the "processCommand" function. However, while the code didn't have any errors, attempting to compile on Xcode 8 would cause linker errors. The only way to avoid linker errors was to either completely comment out the last switch/case cases, or to just move the code to its own seperate functions; the latter is what's being done now. */ // scales background to (scaleFactor) amount func scaleBackground(_ sprite:SKSpriteNode, scaleFactor:Double, duration:Double) { if duration <= 0.0 { sprite.setScale(CGFloat(scaleFactor)) } else { self.createSafeSave() self.setEffectRunningFlag() let scaleAction = SKAction.scale(to: CGFloat(scaleFactor), duration: duration); let callClearFlag = SKAction.run(self.clearEffectRunningFlag); let sequence = SKAction.sequence([scaleAction, callClearFlag]); sprite.run(sequence); } } // scales an existing sprite by a certain amount over a particular duration func scaleSprite(_ spriteName:String, scalingAmount:Double, duration:Double) { let sprite:SKSpriteNode? = sprites.object(forKey: spriteName) as? SKSpriteNode if sprite == nil { return; } var xScale = CGFloat(scalingAmount) var yScale = CGFloat(scalingAmount) // invert x/y-scale values when dealing with flipped sprites if sprite!.xScale < 0.0 { xScale = xScale * (-1) } if sprite!.yScale < 0.0 { yScale = yScale * (-1) } if duration <= 0.0 { sprite!.xScale = xScale sprite!.yScale = yScale } else { self.createSafeSave() self.setEffectRunningFlag() let scaleAction = SKAction.scaleX(to: xScale, y: yScale, duration: duration) let callClearFlag = SKAction.run(self.clearEffectRunningFlag) let sequence = SKAction.sequence([scaleAction, callClearFlag]) sprite!.run(sequence) } } // swaps the current speechbox sprite for another sprite func setSpeechBox(_ spriteName:String, duration:Double) { // prepare positioning data var boxToBottomMargin = CGFloat(0) let widthOfScreen = viewSize.width//SMScreenSizeInPoints().width boxToBottomMargin = CGFloat((viewSettings.object(forKey: VNSceneViewSpeechBoxOffsetFromBottomKey) as! NSNumber).floatValue) if speechBox == nil { print("[VNScene] ERROR: .SETSPEECHBOX failed as speechbox node was invalid.") return; } if( duration <= 0.0 ) { let originalChildren = speechBox!.children speechBox?.removeFromParent() speechBox = SKSpriteNode(imageNamed: spriteName); speechBox!.position = CGPoint( x: widthOfScreen * 0.5, y: (speechBox!.frame.size.height * 0.5) + boxToBottomMargin ) speechBox!.alpha = 1.0; speechBox!.zPosition = VNSceneUILayer; speechBox!.name = VNSceneTagSpeechBox; self.addChild( speechBox! ) /*for( SKNode* aChild in originalChildren ) { [speechBox addChild:aChild]; //NSLog(@"d: child z is %f and name is %@", aChild.zPosition, aChild.name); }*/ if originalChildren.count > 0 { for aChild in originalChildren { speechBox!.addChild(aChild) } } // set speechbox color speechBox!.colorBlendFactor = 1.0; speechBox!.color = speechBoxColor; } else { // switch gradually self.createSafeSave() self.setEffectRunningFlag() let speechBoxChildren = speechBox!.children // create fake placeholder speechbox that looks like the original //CCSprite* fakeSpeechbox = [CCSprite spriteWithTexture:speechBox.texture]; let fakeSpeechbox = SKSpriteNode(texture: speechBox!.texture) fakeSpeechbox.position = speechBox!.position; fakeSpeechbox.zPosition = speechBox!.zPosition; //[self addChild:fakeSpeechbox]; self.addChild(fakeSpeechbox) // get rid of the original speechbox and replace it with a new and invisible speechbox //[speechBox removeFromParent]; speechBox!.removeFromParent() speechBox = SKSpriteNode(imageNamed: spriteName) //speechBox = [SKSpriteNode spriteNodeWithImageNamed:parameter1]; speechBox!.position = CGPoint( x: widthOfScreen * 0.5, y: (speechBox!.frame.size.height * 0.5) + boxToBottomMargin ); speechBox!.alpha = 0.0; speechBox!.zPosition = VNSceneUILayer; speechBox!.name = VNSceneTagSpeechBox; //[self addChild:speechBox]; self.addChild(speechBox!) // set speechbox color speechBox!.colorBlendFactor = 1.0; speechBox!.color = speechBoxColor; //for( SKNode* aChild in speechBoxChildren ) { for aChild in speechBoxChildren { speechBox!.addChild(aChild) // cause each child node to gradually fade out and fade back in so it looks like it's doing it in time with the speechboxes. let fadeOutChild = SKAction.fadeOut(withDuration: duration * 0.5) let fadeInChild = SKAction.fadeIn(withDuration: duration * 0.5) let sequenceForChild = SKAction.sequence([fadeOutChild, fadeInChild]) aChild.run(sequenceForChild) } // fade out the fake speechbox let fadeOut = SKAction.fadeOut(withDuration: duration * 0.5) fakeSpeechbox.run(fadeOut) // fade in the new "real" speechbox let fadeIn = SKAction.fadeOut(withDuration: duration * 0.5) let delay = SKAction.wait(forDuration: duration * 0.5) //let callFunc = SKAction.performSelector(@selec) let callFunc = SKAction.run(self.clearEffectRunningFlag) let delayedFadeInSequence = SKAction.sequence([delay, fadeIn, callFunc]) speechBox!.run(delayedFadeInSequence) /* SKAction* fadeIn = [SKAction fadeOutWithDuration:(duration * 0.5)]; SKAction* delay = [SKAction waitForDuration:(duration * 0.5)]; SKAction* callFunc = [SKAction performSelector:@selector(clearEffectRunningFlag) onTarget:self]; SKAction* delayedFadeInSequence = [SKAction sequence:@[delay, fadeIn, callFunc]]; [speechBox runAction:delayedFadeInSequence];*/ } //[record setValue:parameter1 forKey:VNSceneSavedOverriddenSpeechboxKey]; record.setValue(spriteName, forKey:VNSceneSavedOverriddenSpeechboxKey) } // adjusts sprite alias func setSpriteAlias(_ alias:String, filename:String) { //NSString* aliasParameter = [command objectAtIndex:1]; //NSString* filenameParameter = [command objectAtIndex:2]; let filenameParameter = filename as NSString if filenameParameter.caseInsensitiveCompare(VNScriptNilValue) == ComparisonResult.orderedSame { localSpriteAliases.removeObject(forKey: alias) // remove data for this alias } else { localSpriteAliases.setValue(filename, forKey: alias) } } // moves choice box offsets around (instead of having the choicebox buttons appearing near the middle of the screen) func modifyChoiceboxOffset(_ xOffset:Double, yOffset:Double) { choiceButtonOffsetX = CGFloat(xOffset) choiceButtonOffsetY = CGFloat(yOffset) // save offset data to record let xSave = NSNumber(value: xOffset) let ySave = NSNumber(value: yOffset) record.setValue(xSave, forKey: VNSceneViewChoiceButtonOffsetX); record.setValue(ySave, forKey: VNSceneViewChoiceButtonOffsetY); } // rolls dice; stores value in a predetermined flag func rollDice(_ numberOfDice:Int, maximumSidesOfDice:Int, plusFlagModifier:String) { var flagModifier = 0 let theFlag:NSNumber? = flags.object(forKey: plusFlagModifier) as? NSNumber if( theFlag != nil ) { flagModifier = theFlag!.intValue } let roll = SMRollDice(numberOfDice, maximumRollValue: maximumSidesOfDice, plusModifier: flagModifier) // Store results of roll in DICEROLL flag let diceRollResult = NSNumber(integerLiteral: roll) flags.setValue(diceRollResult, forKey: VNSceneDiceRollResultFlag) //print("[VNScene] Dice roll results of \(roll) stored in flag named: DICEROLL"); } // flips sprite around, can flip sprite vertically or horizontally func flipSpriteNamed(_ spriteName:String, duration:Double, horizontally:Bool) { // get sprite using name let sprite:SKSpriteNode? = sprites.object(forKey: spriteName) as? SKSpriteNode if sprite == nil { return; } self.createSafeSave() // If this has a duration of zero, the action will take place instantly and then the function will return if( duration <= 0.0 ) { // determine flip style if( horizontally == true ) { sprite!.xScale = sprite!.xScale * (-1); } else { sprite!.yScale = sprite!.yScale * (-1); } return; } //[self setEffectRunningFlag]; setEffectRunningFlag() var scaleToX = sprite!.xScale; var scaleToY = sprite!.yScale; var scalingAction:SKAction? = nil // determine what kind of action to take (this will determine scaling values) if( horizontally == true ) { scaleToX = scaleToX * (-1); //scalingAction = [SKAction scaleXTo:scaleToX duration:durationAsDouble]; scalingAction = SKAction.scaleX(to: scaleToX, duration:duration) } else { scaleToY = scaleToY * (-1); //scalingAction = [SKAction scaleYTo:scaleToY duration:durationAsDouble]; scalingAction = SKAction.scaleY(to: scaleToY, duration:duration) } let clearEffectFlag = SKAction.run(self.clearEffectRunningFlag) let theSequence = SKAction.sequence([scalingAction!, clearEffectFlag]) sprite!.run(theSequence) } }
mit
aa87eb854aac6068e580226f7e68959f
50.997241
193
0.60852
5.047803
false
false
false
false
WeltN24/SwiftFilePath
SwiftFilePath/Path.swift
1
3638
// // Path.swift // SwiftFilePath // // Created by nori0620 on 2015/01/08. // Copyright (c) 2015年 Norihiro Sakamoto. All rights reserved. // open class Path { // MARK: - Class methods open class func isDir(_ path:String) -> Bool { var isDirectory: ObjCBool = false _ = FileManager.default.fileExists(atPath: path, isDirectory:&isDirectory) return isDirectory.boolValue ? true : false } // MARK: - Instance properties and initializer lazy var fileManager = FileManager.default public let path_string:String public init(_ p: String) { self.path_string = p } // MARK: - Instance val open var attributes:NSDictionary?{ get { return self.loadAttributes() } } open var asString: String { return path_string } open var exists: Bool { return fileManager.fileExists(atPath: path_string) } open var isDir: Bool { return Path.isDir(path_string) } open var basename:String { return (path_string as NSString).lastPathComponent } open var parent: Path{ return Path((path_string as NSString).deletingLastPathComponent ) } // MARK: - Instance methods open func toString() -> String { return path_string } open func remove() -> Result<Path,NSError> { assert(self.exists,"To remove file, file MUST be exists") var error: NSError? let result: Bool do { try fileManager.removeItem(atPath: path_string) result = true } catch let error1 as NSError { error = error1 result = false } return result ? Result(success: self) : Result(failure: error!); } open func copyTo(_ toPath:Path) -> Result<Path,Error> { assert(self.exists,"To copy file, file MUST be exists") var error: Error? let result: Bool do { try fileManager.copyItem(atPath: path_string, toPath: toPath.toString()) result = true } catch let error1 { error = error1 result = false } return result ? Result(success: self) : Result(failure: error!) } open func moveTo(_ toPath:Path) -> Result<Path,Error> { assert(self.exists,"To move file, file MUST be exists") var error: Error? let result: Bool do { try fileManager.moveItem(atPath: path_string, toPath: toPath.toString()) result = true } catch let error1 { error = error1 result = false } return result ? Result(success: self) : Result(failure: error!) } private func loadAttributes() -> NSDictionary? { assert(self.exists,"File must be exists to load file.< \(path_string) >") var loadError: Error? let result: [AnyHashable: Any]? do { result = try self.fileManager.attributesOfItem(atPath: path_string) } catch let error { loadError = error result = nil } if let error = loadError { print("Error< \(error.localizedDescription) >") } return result as NSDictionary? } } // MARK: - extension Path: CustomStringConvertible { public var description: String { return "\(NSStringFromClass(type(of: self)))<path:\(path_string)>" } }
mit
e87d50a53be74283a24a25fe6da0db52
24.971429
82
0.548405
4.691613
false
false
false
false
sgoodwin/IRC
IRC/IRCServerInputParser.swift
1
4493
// // IRCServerInputParser.swift // IRC // // Created by Samuel Ryan Goodwin on 7/22/17. // Copyright © 2017 Roundwall Software. All rights reserved. // import Foundation struct IRCServerInputParser { static func parseServerMessage(_ message: String) -> IRCServerInput { if message.hasPrefix("PING") { return .ping } if message.hasPrefix(":") { let firstSpaceIndex = message.index(of: " ")! let source = message[..<firstSpaceIndex] let rest = message[firstSpaceIndex...].trimmingCharacters(in: .whitespacesAndNewlines) print(source) if rest.hasPrefix("PRIVMSG") { let remaining = rest[rest.index(message.startIndex, offsetBy: 8)...] if remaining.hasPrefix("#") { let split = remaining.components(separatedBy: ":") let channel = split[0].trimmingCharacters(in: CharacterSet(charactersIn: " #")) let user = source.components(separatedBy: "!")[0].trimmingCharacters(in: CharacterSet(charactersIn: ":")) let message = split[1] return .channelMessage(channel: channel, user: user, message: message) } } else if rest.hasPrefix("JOIN") { let user = source.components(separatedBy: "!")[0].trimmingCharacters(in: CharacterSet(charactersIn: ":")) let channel = rest[rest.index(message.startIndex, offsetBy: 5)...].trimmingCharacters(in: CharacterSet(charactersIn: "# ")) return .joinMessage(user: user, channel: channel) } else{ let server = source.trimmingCharacters(in: CharacterSet(charactersIn: ": ")) // :development.irc.roundwallsoftware.com 353 mukman = #clearlyafakechannel :mukman @sgoodwin\r\n:development.irc.roundwallsoftware.com 366 mukman #clearlyafakechannel :End of /NAMES list. if rest.hasSuffix(":End of /NAMES list.") { let scanner = Scanner(string: rest) scanner.scanUpTo("#", into: nil) var channel: NSString? scanner.scanUpTo(" ", into: &channel) let channelName = (channel as String?)!.trimmingCharacters(in: CharacterSet(charactersIn: "#")) var users = [String]() var user: NSString? scanner.scanUpTo(" ", into: &user) users.append((user as String?)!.trimmingCharacters(in: CharacterSet(charactersIn: ":"))) return .userList(channel: channelName, users: users) } if rest.contains(":") { let serverMessage = rest.components(separatedBy: ":")[1] return .serverMessage(server: server, message: serverMessage) } else { return .serverMessage(server: server, message: rest) } } } return .unknown(raw: message) } } enum IRCServerInput: Equatable { case unknown(raw: String) case ping case serverMessage(server: String, message: String) case channelMessage(channel: String, user: String, message: String) case joinMessage(user: String, channel: String) case userList(channel: String, users: [String]) } func ==(lhs: IRCServerInput, rhs: IRCServerInput) -> Bool{ switch (lhs, rhs) { case (.ping, .ping): return true case (.channelMessage(let lhsChannel, let lhsUser, let lhsMessage), .channelMessage(let rhsChannel, let rhsUser, let rhsMessage)): return lhsChannel == rhsChannel && lhsMessage == rhsMessage && lhsUser == rhsUser case (.serverMessage(let lhsServer, let lhsMessage), .serverMessage(let rhsServer, let rhsMessage)): return lhsServer == rhsServer && lhsMessage == rhsMessage case (.joinMessage(let lhsUser, let lhsChannel), .joinMessage(let rhsUser, let rhsChannel)): return lhsUser == rhsUser && lhsChannel == rhsChannel case (.userList(let lhsChannel, let lhsUsers), .userList(let rhsChannel, let rhsUsers)): return lhsChannel == rhsChannel && lhsUsers == rhsUsers default: return false } }
bsd-3-clause
be1455bb787560188e89216241fe7369
43.92
204
0.568566
4.930845
false
false
false
false
honghaoz/UW-Quest-iOS
UW Quest/ThirdParty/ZHDynamicTableView.swift
1
1855
// // ZHDynamicTableView.swift // UW Quest // // Created by Honghao Zhang on 1/21/15. // Copyright (c) 2015 Honghao. All rights reserved. // import UIKit class ZHDynamicTableView: UITableView { // A dictionary of offscreen cells that are used within the heightForIndexPath method to handle the size calculations. These are never drawn onscreen. The dictionary is in the format: // { NSString *reuseIdentifier : UITableViewCell *offscreenCell, ... } private var offscreenCells = Dictionary<String, UITableViewCell>() private var registeredCellNibs = Dictionary<String, UINib>() private var registeredCellClasses = Dictionary<String, UITableViewCell.Type>() override func registerClass(cellClass: AnyClass, forCellReuseIdentifier identifier: String) { super.registerClass(cellClass, forCellReuseIdentifier: identifier) registeredCellClasses[identifier] = (cellClass as? UITableViewCell.Type)! } override func registerNib(nib: UINib, forCellReuseIdentifier identifier: String) { super.registerNib(nib, forCellReuseIdentifier: identifier) registeredCellNibs[identifier] = nib } /** Returns a reusable table view cell object located by its identifier. This cell is not showing on screen, it's useful for calculating dynamic cell height :param: identifier identifier A string identifying the cell object to be reused. This parameter must not be nil. :returns: UITableViewCell? */ func dequeueReusableOffScreenCellWithIdentifier(identifier: String) -> UITableViewCell? { var cell: UITableViewCell? = offscreenCells[identifier] if cell == nil { cell = self.dequeueReusableCellWithIdentifier(identifier) as? UITableViewCell offscreenCells[identifier] = cell! } return cell } }
apache-2.0
5966ef1d20483e90e640d9ddc6cebdf1
41.159091
187
0.721833
5.196078
false
false
false
false
atl009/WordPress-iOS
WordPress/Classes/ViewRelated/Views/WPRichText/WPTextAttachmentManager.swift
1
7031
import Foundation import UIKit /// Wrangles attachment layout and exclusion paths for the specified UITextView. /// @objc open class WPTextAttachmentManager: NSObject { open var attachments = [WPTextAttachment]() var attachmentViews = [String: WPTextAttachmentView]() open weak var delegate: WPTextAttachmentManagerDelegate? fileprivate(set) open weak var textView: UITextView? let layoutManager: NSLayoutManager let infiniteFrame = CGRect(x: CGFloat.infinity, y: CGFloat.infinity, width: 0.0, height: 0.0) /// Designaged initializer. /// /// - Parameters: /// - textView: The UITextView to manage attachment layout. /// - delegate: The delegate who will provide the UIViews used as content represented by WPTextAttachments in the UITextView's NSAttributedString. /// public init(textView: UITextView, delegate: WPTextAttachmentManagerDelegate) { self.textView = textView self.delegate = delegate self.layoutManager = textView.layoutManager super.init() layoutManager.delegate = self enumerateAttachments() } /// Returns the custom view for the specified WPTextAttachment or nil if not found. /// /// - Parameters: /// - attachment: The WPTextAttachment /// /// - Returns: A UIView optional /// open func viewForAttachment(_ attachment: WPTextAttachment) -> UIView? { return attachmentViews[attachment.identifier]?.view } /// Updates the layout of any custom attachment views. Call this method after /// making changes to the alignment or size of an attachment's custom view, /// or after updating an attachment's `image` property. /// open func layoutAttachmentViews() { // Guard for paranoia guard let textStorage = layoutManager.textStorage else { print("Unable to layout attachment views. No NSTextStorage.") return } // Now do the update. textStorage.enumerateAttribute(NSAttachmentAttributeName, in: NSMakeRange(0, textStorage.length), options: [], using: { (object: Any?, range: NSRange, stop: UnsafeMutablePointer<ObjCBool>) in guard let attachment = object as? WPTextAttachment else { return } self.layoutAttachmentViewForAttachment(attachment, atRange: range) }) } /// Updates the layout of the attachment view for the specified attachment by /// creating a new exclusion path for the view based on the location of the /// specified attachment, and the frame and alignmnent of the view. /// /// - Parameters: /// - attachment: The WPTextAttachment /// - range: The range of the WPTextAttachment in the textView's NSTextStorage /// fileprivate func layoutAttachmentViewForAttachment(_ attachment: WPTextAttachment, atRange range: NSRange) { guard let textView = textView, let attachmentView = attachmentViews[attachment.identifier] else { return } // Make sure attachments are correctly laid out. layoutManager.invalidateLayout(forCharacterRange: range, actualCharacterRange: nil) layoutManager.ensureLayout(for: textView.textContainer) let frame = textView.frameForTextInRange(range) if frame == infiniteFrame { return } attachmentView.view.frame = frame } /// Called initially during the initial set up of the manager. // Should be called whenever the UITextView's attributedText property changes. /// After resetting the attachment manager, this method loops over any /// WPTextAttachments found in textStorage and asks the delegate for a /// custom view for the attachment. /// func enumerateAttachments() { resetAttachmentManager() // Safety new guard let textStorage = layoutManager.textStorage else { return } layoutManager.textStorage?.enumerateAttribute(NSAttachmentAttributeName, in: NSMakeRange(0, textStorage.length), options: [], using: { (object: Any?, range: NSRange, stop: UnsafeMutablePointer<ObjCBool>) in guard let attachment = object as? WPTextAttachment else { return } self.attachments.append(attachment) if let view = self.delegate?.attachmentManager(self, viewForAttachment: attachment) { self.attachmentViews[attachment.identifier] = WPTextAttachmentView(view: view, identifier: attachment.identifier, exclusionPath: nil) self.textView?.addSubview(view) } }) layoutAttachmentViews() } /// Resets the attachment manager. Any custom views for WPTextAttachments are /// removed from the UITextView, their exclusion paths are removed from /// textStorage. /// fileprivate func resetAttachmentManager() { for (_, attachmentView) in attachmentViews { attachmentView.view.removeFromSuperview() } attachmentViews.removeAll() attachments.removeAll() } } /// A UITextView does not register as delegate to its NSLayoutManager so the /// WPTextAttachmentManager does in order to be notified of any changes to the size /// of the UITextView's textContainer. /// extension WPTextAttachmentManager: NSLayoutManagerDelegate { /// When the size of an NSTextContainer managed by the NSLayoutManager changes /// this method updates the size of any custom views for WPTextAttachments, /// then lays out the attachment views. /// public func layoutManager(_ layoutManager: NSLayoutManager, textContainer: NSTextContainer, didChangeGeometryFrom oldSize: CGSize) { layoutAttachmentViews() } } /// A WPTextAttachmentManagerDelegate provides custom views for WPTextAttachments to /// its WPTextAttachmentManager. /// @objc public protocol WPTextAttachmentManagerDelegate: NSObjectProtocol { /// Delegates must implement this method and return either a UIView or nil for /// the specified WPTextAttachment. /// /// - Parameters: /// - attachmentManager: The WPTextAttachmentManager. /// - attachment: The WPTextAttachment /// /// - Returns: A UIView to represent the specified WPTextAttachment or nil. /// func attachmentManager(_ attachmentManager: WPTextAttachmentManager, viewForAttachment attachment: WPTextAttachment) -> UIView? } /// A convenience class for grouping a custom view with its attachment and /// exclusion path. /// class WPTextAttachmentView { var view: UIView var identifier: String var exclusionPath: UIBezierPath? init(view: UIView, identifier: String, exclusionPath: UIBezierPath?) { self.view = view self.identifier = identifier self.exclusionPath = exclusionPath } }
gpl-2.0
d21a4d229a33f29319560fce981c8e6f
35.811518
154
0.671739
5.354912
false
false
false
false
almazrafi/Metatron
Sources/ID3v2/FrameStuffs/ID3v2FeatureRegistration.swift
1
3914
// // ID3v2FeatureRegistration.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public class ID3v2FeatureRegistration: ID3v2FrameStuff { // MARK: Instance Properties var identifier: String = "" var supplement: [UInt8] = [] var slotSymbol: UInt8 = 0 // MARK: public var isEmpty: Bool { return self.identifier.isEmpty } // MARK: Initializers public init() { } public init(fromData data: [UInt8], version: ID3v2Version) { guard (data.count > 2) && (data[0] != 0) else { return } guard let identifier = ID3v2TextEncoding.latin1.decode(data) else { return } guard identifier.endIndex < data.count else { return } self.identifier = identifier.text self.slotSymbol = data[identifier.endIndex] self.supplement = [UInt8](data.suffix(from: identifier.endIndex + 1)) } // MARK: Instance Methods public func toData(version: ID3v2Version) -> [UInt8]? { guard !self.isEmpty else { return nil } switch version { case ID3v2Version.v2: return nil case ID3v2Version.v3: guard self.slotSymbol >= 128 else { return nil } case ID3v2Version.v4: guard self.slotSymbol >= 128 else { return nil } guard self.slotSymbol <= 240 else { return nil } } var data = ID3v2TextEncoding.latin1.encode(self.identifier, termination: true) data.append(self.slotSymbol) data.append(contentsOf: self.supplement) return data } public func toData() -> (data: [UInt8], version: ID3v2Version)? { guard let data = self.toData(version: ID3v2Version.v3) else { return nil } return (data: data, version: ID3v2Version.v3) } } public class ID3v2FeatureRegistrationFormat: ID3v2FrameStuffSubclassFormat { // MARK: Type Properties public static let regular = ID3v2FeatureRegistrationFormat() // MARK: Instance Methods public func createStuffSubclass(fromData data: [UInt8], version: ID3v2Version) -> ID3v2FeatureRegistration { return ID3v2FeatureRegistration(fromData: data, version: version) } public func createStuffSubclass(fromOther other: ID3v2FeatureRegistration) -> ID3v2FeatureRegistration { let stuff = ID3v2FeatureRegistration() stuff.identifier = other.identifier stuff.supplement = other.supplement stuff.slotSymbol = other.slotSymbol return stuff } public func createStuffSubclass() -> ID3v2FeatureRegistration { return ID3v2FeatureRegistration() } }
mit
7f646e4da6585d48d5147bc711cefcb1
27.992593
112
0.65304
4.235931
false
false
false
false
cookpad/Phakchi
Sources/Phakchi/ControlServer.swift
1
1546
import Foundation public class ControlServer { public static let `default` = ControlServer() public typealias StartSessionCompletionBlock = (Session?) -> Void // To have an internal setter private var _sessions: [Session] = [] public var sessions: [Session] { return _sessions } private let mockServiceClient = ControlServiceClient() @available(*, renamed: "startSession(consumerName:providerName:completion:)") public func startSession(withConsumerName consumerName: String, providerName: String, completionBlock: StartSessionCompletionBlock? = nil) { fatalError() } public func startSession(consumerName: String, providerName: String, completion completionBlock: StartSessionCompletionBlock? = nil) { mockServiceClient.start(session: consumerName, providerName: providerName) { session in if let session = session { self._sessions.append(session) } completionBlock?(session) } } public func session(forConsumerName consumerName: String, providerName: String) -> Session? { return sessions.filter { session in session.consumerName == consumerName && session.providerName == providerName }.first } }
mit
14d468384be33a1b63ca566f588241a3
38.641026
87
0.565977
6.184
false
false
false
false
hooman/swift
test/Constraints/bridging.swift
2
18824
// RUN: %target-typecheck-verify-swift // REQUIRES: objc_interop import Foundation public class BridgedClass : NSObject, NSCopying { @objc(copyWithZone:) public func copy(with zone: NSZone?) -> Any { return self } } public class BridgedClassSub : BridgedClass { } // Attempt to bridge to a type from another module. We only allow this for a // few specific types, like String. extension LazyFilterSequence.Iterator : _ObjectiveCBridgeable { // expected-error{{conformance of 'Iterator' to '_ObjectiveCBridgeable' can only be written in module 'Swift'}} public typealias _ObjectiveCType = BridgedClassSub public func _bridgeToObjectiveC() -> _ObjectiveCType { return BridgedClassSub() } public static func _forceBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterSequence.Iterator? ) { } public static func _conditionallyBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterSequence.Iterator? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> LazyFilterSequence.Iterator { let result: LazyFilterSequence.Iterator? return result! } } struct BridgedStruct : Hashable, _ObjectiveCBridgeable { func hash(into hasher: inout Hasher) {} func _bridgeToObjectiveC() -> BridgedClass { return BridgedClass() } static func _forceBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct?) { } static func _conditionallyBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct? ) -> Bool { return true } static func _unconditionallyBridgeFromObjectiveC(_ source: BridgedClass?) -> BridgedStruct { var result: BridgedStruct? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } func ==(x: BridgedStruct, y: BridgedStruct) -> Bool { return true } struct NotBridgedStruct : Hashable { func hash(into hasher: inout Hasher) {} } func ==(x: NotBridgedStruct, y: NotBridgedStruct) -> Bool { return true } class OtherClass : Hashable { func hash(into hasher: inout Hasher) {} } func ==(x: OtherClass, y: OtherClass) -> Bool { return true } // Basic bridging func bridgeToObjC(_ s: BridgedStruct) -> BridgedClass { return s // expected-error{{cannot convert return expression of type 'BridgedStruct' to return type 'BridgedClass'}} return s as BridgedClass } func bridgeToAnyObject(_ s: BridgedStruct) -> AnyObject { return s // expected-error{{return expression of type 'BridgedStruct' expected to be an instance of a class or class-constrained type}} return s as AnyObject } func bridgeFromObjC(_ c: BridgedClass) -> BridgedStruct { return c // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return c as BridgedStruct } func bridgeFromObjCDerived(_ s: BridgedClassSub) -> BridgedStruct { return s // expected-error{{'BridgedClassSub' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return s as BridgedStruct } // Array -> NSArray func arrayToNSArray() { var nsa: NSArray nsa = [AnyObject]() // expected-error {{cannot assign value of type '[AnyObject]' to type 'NSArray'}} nsa = [BridgedClass]() // expected-error {{cannot assign value of type '[BridgedClass]' to type 'NSArray'}} nsa = [OtherClass]() // expected-error {{cannot assign value of type '[OtherClass]' to type 'NSArray'}} nsa = [BridgedStruct]() // expected-error {{cannot assign value of type '[BridgedStruct]' to type 'NSArray'}} nsa = [NotBridgedStruct]() // expected-error{{cannot assign value of type '[NotBridgedStruct]' to type 'NSArray'}} nsa = [AnyObject]() as NSArray nsa = [BridgedClass]() as NSArray nsa = [OtherClass]() as NSArray nsa = [BridgedStruct]() as NSArray nsa = [NotBridgedStruct]() as NSArray _ = nsa } // NSArray -> Array func nsArrayToArray(_ nsa: NSArray) { var arr1: [AnyObject] = nsa // expected-error{{'NSArray' is not implicitly convertible to '[AnyObject]'; did you mean to use 'as' to explicitly convert?}} {{30-30= as [AnyObject]}} var _: [BridgedClass] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{30-30= as! [BridgedClass]}} var _: [OtherClass] = nsa // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{28-28= as! [OtherClass]}} var _: [BridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{31-31= as! [BridgedStruct]}} var _: [NotBridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[NotBridgedStruct]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{34-34= as! [NotBridgedStruct]}} var _: [AnyObject] = nsa as [AnyObject] var _: [BridgedClass] = nsa as [BridgedClass] // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{31-33=as!}} var _: [OtherClass] = nsa as [OtherClass] // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{29-31=as!}} var _: [BridgedStruct] = nsa as [BridgedStruct] // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{32-34=as!}} var _: [NotBridgedStruct] = nsa as [NotBridgedStruct] // expected-error{{'NSArray' is not convertible to '[NotBridgedStruct]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{35-37=as!}} var arr6: Array = nsa as Array arr6 = arr1 arr1 = arr6 } func dictionaryToNSDictionary() { // FIXME: These diagnostics are awful. var nsd: NSDictionary nsd = [NSObject : AnyObject]() // expected-error {{cannot assign value of type '[NSObject : AnyObject]' to type 'NSDictionary'}} nsd = [NSObject : AnyObject]() as NSDictionary nsd = [NSObject : BridgedClass]() // expected-error {{cannot assign value of type '[NSObject : BridgedClass]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass]() as NSDictionary nsd = [NSObject : OtherClass]() // expected-error {{cannot assign value of type '[NSObject : OtherClass]' to type 'NSDictionary'}} nsd = [NSObject : OtherClass]() as NSDictionary nsd = [NSObject : BridgedStruct]() // expected-error {{cannot assign value of type '[NSObject : BridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct]() as NSDictionary nsd = [NSObject : NotBridgedStruct]() // expected-error{{cannot assign value of type '[NSObject : NotBridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : NotBridgedStruct]() as NSDictionary nsd = [NSObject : BridgedClass?]() // expected-error{{cannot assign value of type '[NSObject : BridgedClass?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass?]() as NSDictionary nsd = [NSObject : BridgedStruct?]() // expected-error{{cannot assign value of type '[NSObject : BridgedStruct?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct?]() as NSDictionary nsd = [BridgedClass : AnyObject]() // expected-error {{cannot assign value of type '[BridgedClass : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedClass : AnyObject]() as NSDictionary nsd = [OtherClass : AnyObject]() // expected-error {{cannot assign value of type '[OtherClass : AnyObject]' to type 'NSDictionary'}} nsd = [OtherClass : AnyObject]() as NSDictionary nsd = [BridgedStruct : AnyObject]() // expected-error {{cannot assign value of type '[BridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedStruct : AnyObject]() as NSDictionary nsd = [NotBridgedStruct : AnyObject]() // expected-error{{cannot assign value of type '[NotBridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [NotBridgedStruct : AnyObject]() as NSDictionary // <rdar://problem/17134986> var bcOpt: BridgedClass? nsd = [BridgedStruct() : bcOpt as Any] bcOpt = nil _ = nsd } // In this case, we should not implicitly convert Dictionary to NSDictionary. struct NotEquatable {} func notEquatableError(_ d: Dictionary<Int, NotEquatable>) -> Bool { // There is a note attached to a requirement `requirement from conditional conformance of 'Dictionary<Int, NotEquatable>' to 'Equatable'` return d == d // expected-error{{operator function '==' requires that 'NotEquatable' conform to 'Equatable'}} } // NSString -> String var nss1 = "Some great text" as NSString var nss2: NSString = ((nss1 as String) + ", Some more text") as NSString // <rdar://problem/17943223> var inferDouble = 1.0/10 let d: Double = 3.14159 inferDouble = d // rdar://problem/17962491 _ = 1 % 3 / 3.0 // expected-error{{'%' is unavailable: For floating point numbers use truncatingRemainder instead}} var inferDouble2 = 1 / 3 / 3.0 let d2: Double = 3.14159 inferDouble2 = d2 // rdar://problem/18269449 var i1: Int = 1.5 * 3.5 // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}} // rdar://problem/18330319 func rdar18330319(_ s: String, d: [String : AnyObject]) { _ = d[s] as! String? } // rdar://problem/19551164 func rdar19551164a(_ s: String, _ a: [String]) {} func rdar19551164b(_ s: NSString, _ a: NSArray) { rdar19551164a(s, a) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{18-18= as String}} // expected-error@-1{{'NSArray' is not convertible to '[String]'}} // expected-note@-2 {{did you mean to use 'as!' to force downcast?}}{{21-21= as! [String]}} } // rdar://problem/19695671 func takesSet<T>(_ p: Set<T>) {} // expected-note {{in call to function 'takesSet'}} func takesDictionary<K, V>(_ p: Dictionary<K, V>) {} // expected-note {{in call to function 'takesDictionary'}} func takesArray<T>(_ t: Array<T>) {} // expected-note {{in call to function 'takesArray'}} func rdar19695671() { takesSet(NSSet() as! Set) // expected-error{{generic parameter 'T' could not be inferred}} takesDictionary(NSDictionary() as! Dictionary) // expected-error@-1 {{generic parameter 'K' could not be inferred}} // expected-error@-2 {{generic parameter 'V' could not be inferred}} takesArray(NSArray() as! Array) // expected-error{{generic parameter 'T' could not be inferred}} } // This failed at one point while fixing rdar://problem/19600325. func getArrayOfAnyObject(_: AnyObject) -> [AnyObject] { return [] } func testCallback(_ f: (AnyObject) -> AnyObject?) {} testCallback { return getArrayOfAnyObject($0) } // expected-error {{cannot convert value of type '[AnyObject]' to closure result type 'AnyObject?'}} // <rdar://problem/19724719> Type checker thinks "(optionalNSString ?? nonoptionalNSString) as String" is a forced cast func rdar19724719(_ f: (String) -> (), s1: NSString?, s2: NSString) { f((s1 ?? s2) as String) } // <rdar://problem/19770981> func rdar19770981(_ s: String, ns: NSString) { func f(_ s: String) {} f(ns) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7= as String}} f(ns as String) // 'as' has higher precedence than '>' so no parens are necessary with the fixit: s > ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{9-9= as String}} _ = s > ns as String ns > s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{5-5= as String}} _ = ns as String > s // 'as' has lower precedence than '+' so add parens with the fixit: s + ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{7-7=(}} {{9-9= as String)}} _ = s + (ns as String) ns + s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{3-3=(}} {{5-5= as String)}} _ = (ns as String) + s } // <rdar://problem/19831919> Fixit offers as! conversions that are known to always fail func rdar19831919() { var s1 = 1 + "str"; // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note{{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } // <rdar://problem/19831698> Incorrect 'as' fixits offered for invalid literal expressions func rdar19831698() { var v70 = true + 1 // expected-error@:13 {{cannot convert value of type 'Bool' to expected argument type 'Int'}} var v71 = true + 1.0 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Double'}} // expected-note@-1{{overloads for '+'}} var v72 = true + true // expected-error{{binary operator '+' cannot be applied to two 'Bool' operands}} // expected-note@-1{{overloads for '+'}} var v73 = true + [] // expected-error@:13 {{cannot convert value of type 'Bool' to expected argument type 'Array<Bool>'}} var v75 = true + "str" // expected-error@:13 {{cannot convert value of type 'Bool' to expected argument type 'String'}} } // <rdar://problem/19836341> Incorrect fixit for NSString? to String? conversions func rdar19836341(_ ns: NSString?, vns: NSString?) { var vns = vns let _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{22-22= as String?}} var _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{22-22= as String?}} // Important part about below diagnostic is that from-type is described as // 'NSString?' and not '@lvalue NSString?': let _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{23-23= as String?}} var _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{23-23= as String?}} vns = ns } // <rdar://problem/20029786> Swift compiler sometimes suggests changing "as!" to "as?!" func rdar20029786(_ ns: NSString?) { var s: String = ns ?? "str" as String as String // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{19-19=(}} {{50-50=) as String}} // expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'NSString'}} {{50-50= as NSString}} var s2 = ns ?? "str" as String as String // expected-error {{cannot convert value of type 'String' to expected argument type 'NSString'}}{{43-43= as NSString}} let s3: NSString? = "str" as String? // expected-error {{cannot convert value of type 'String?' to specified type 'NSString?'}}{{39-39= as NSString?}} var s4: String = ns ?? "str" // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{20-20=(}} {{31-31=) as String}} var s5: String = (ns ?? "str") as String // fixed version } // Make sure more complicated cast has correct parenthesization func castMoreComplicated(anInt: Int?) { let _: (NSObject & NSCopying)? = anInt // expected-error{{cannot convert value of type 'Int?' to specified type '(NSObject & NSCopying)?'}}{{41-41= as (NSObject & NSCopying)?}} } // <rdar://problem/19813772> QoI: Using as! instead of as in this case produces really bad diagnostic func rdar19813772(_ nsma: NSMutableArray) { var a1 = nsma as! Array // expected-error{{generic parameter 'Element' could not be inferred in cast to 'Array'}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{26-26=<Any>}} var a2 = nsma as! Array<AnyObject> // expected-warning{{forced cast from 'NSMutableArray' to 'Array<AnyObject>' always succeeds; did you mean to use 'as'?}} {{17-20=as}} var a3 = nsma as Array<AnyObject> } func rdar28856049(_ nsma: NSMutableArray) { _ = nsma as? [BridgedClass] _ = nsma as? [BridgedStruct] _ = nsma as? [BridgedClassSub] } // <rdar://problem/20336036> QoI: Add cast-removing fixit for "Forced cast from 'T' to 'T' always succeeds" func force_cast_fixit(_ a : [NSString]) -> [NSString] { return a as! [NSString] // expected-warning {{forced cast of '[NSString]' to same type has no effect}} {{12-27=}} } // <rdar://problem/21244068> QoI: IUO prevents specific diagnostic + fixit about non-implicitly converted bridge types func rdar21244068(_ n: NSString!) -> String { return n // expected-error {{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} } func forceBridgeDiag(_ obj: BridgedClass!) -> BridgedStruct { return obj // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} } struct KnownUnbridged {} class KnownClass {} protocol KnownClassProtocol: class {} func forceUniversalBridgeToAnyObject<T, U: KnownClassProtocol>(a: T, b: U, c: Any, d: KnownUnbridged, e: KnownClass, f: KnownClassProtocol, g: AnyObject, h: String) { var z: AnyObject z = a as AnyObject z = b as AnyObject z = c as AnyObject z = d as AnyObject z = e as AnyObject z = f as AnyObject z = g as AnyObject z = h as AnyObject z = a // expected-error{{value of type 'T' expected to be an instance of a class or class-constrained type in assignment}} z = b z = c // expected-error{{value of type 'Any' expected to be an instance of a class or class-constrained type in assignment}} expected-note {{cast 'Any' to 'AnyObject'}} {{8-8= as AnyObject}} z = d // expected-error{{value of type 'KnownUnbridged' expected to be an instance of a class or class-constrained type in assignment}} z = e z = f z = g z = h // expected-error{{value of type 'String' expected to be an instance of a class or class-constrained type in assignment}} _ = z } func bridgeAnyContainerToAnyObject(x: [Any], y: [NSObject: Any]) { var z: AnyObject z = x as AnyObject z = y as AnyObject _ = z } func bridgeTupleToAnyObject() { let x = (1, "two") let y = x as AnyObject _ = y } // Array defaulting and bridging type checking error per rdar://problem/54274245 func rdar54274245(_ arr: [Any]?) { _ = (arr ?? []) as [NSObject] // expected-warning {{coercion from '[Any]' to '[NSObject]' may fail; use 'as?' or 'as!' instead}} } // rdar://problem/60501780 - failed to infer NSString as a value type of a dictionary func rdar60501780() { func foo(_: [String: NSObject]) {} func bar(_ v: String) { foo(["": "", "": v as NSString]) } }
apache-2.0
240b6819a9dc30d3968e3ea025d31b07
46.535354
236
0.691351
4.017072
false
false
false
false
srosskopf/DMpruefungen
DMpruefer/AppDelegate.swift
1
7021
// // AppDelegate.swift // DMpruefer // // Created by Sebastian Roßkopf on 04.02.16. // Copyright © 2016 ross. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { let APP_ID = "DEB7A760-4830-D11E-FFC3-3AD86ED44B00" let SECRET_KEY = "7D999854-9B62-ACC9-FFCE-6530A0872F00" let VERSION_NUM = "v1" var backendless = Backendless.sharedInstance() var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. backendless.initApp(APP_ID, secret:SECRET_KEY, version:VERSION_NUM) if Reachability.isConnectedToNetwork() { //has internet connection, can delete coreData and get all new tests // SRCoreDataHelper.deleteAllTests() // // let parser = SRParseHelper() // parser.startParsing() } print(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)) // NSLog(@"Documents Directory: %@", [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]); return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "de.sebastian-rosskopf.DMpruefer" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("SRDataModel", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added 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. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() 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. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() 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 NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
fb7ae2cbac72b8de96741edaa16e528a
50.610294
291
0.706083
5.637751
false
false
false
false
diversario/bitfountain-ios-foundations
iOS/AnimalTrivia/AnimalTrivia/ThirdViewController.swift
1
1816
// // ThirdViewController.swift // AnimalTrivia // // Created by Ilya Shaisultanov on 1/1/16. // Copyright © 2016 Ilya Shaisultanov. All rights reserved. // import UIKit class ThirdViewController: UIViewController { @IBOutlet weak var aLabel: UILabel! @IBOutlet weak var bLabel: UILabel! @IBOutlet weak var cLabel: UILabel! @IBOutlet weak var aButton: UIButton! @IBOutlet weak var bButton: UIButton! @IBOutlet weak var cButton: UIButton! @IBOutlet weak var incorrectAImageView: UIImageView! @IBOutlet weak var incorrectBImageView: UIImageView! @IBOutlet weak var correctCImageView: UIImageView! @IBOutlet weak var startOverButton: UIButton! override func viewDidLoad() { super.viewDidLoad() startOverButton.layer.cornerRadius = 7 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func disableButtons () { let buttons = [aButton, bButton, cButton] for button in buttons { button.enabled = false } } @IBAction func aButtonPressed(sender: UIButton) { incorrectAImageView.hidden = false aButton.hidden = true aLabel.textColor = UIColor.redColor() disableButtons() } @IBAction func bButtonPressed(sender: UIButton) { incorrectBImageView.hidden = false bButton.hidden = true bLabel.textColor = UIColor.redColor() disableButtons() } @IBAction func cButtonPressed(sender: UIButton) { correctCImageView.hidden = false cButton.hidden = true cLabel.textColor = UIColor.greenColor() disableButtons() } }
mit
2fb69418ac70e3fc885fa31c2bf183c7
25.691176
60
0.639669
4.865952
false
false
false
false
phuc0302/swift-data
FwiData/org/monstergroup/lib/Services/Request/FwiMultipartParam.swift
1
2404
// Project name: FwiData // File name : FwiMultipartParam.swift // // Author : Phuc, Tran Huu // Created date: 12/3/14 // Version : 1.00 // -------------------------------------------------------------- // Copyright (c) 2014 Monster Group. All rights reserved. // -------------------------------------------------------------- import Foundation public class FwiMultipartParam : NSObject { // MARK: Class's constructors public override init() { super.init() } // MARK: Class's properties public var name: String! = nil public var fileName: String! = nil public var contentData: NSData! = nil public var contentType: String! = nil public override var hash: Int { var hash = (name != nil ? name.hash : 0) hash ^= (fileName != nil ? fileName.hash : 0) hash ^= (contentData != nil ? contentData.hash : 0) hash ^= (contentType != nil ? contentType.hash : 0) return hash } // MARK: Class's public methods public override func isEqual(object: AnyObject?) -> Bool { if let other = object as? FwiMultipartParam { return (self.hash == other.hash) } return false } public func compare(param: FwiMultipartParam) -> NSComparisonResult { if name == nil { return NSComparisonResult.OrderedAscending } else if param.name == nil { return NSComparisonResult.OrderedDescending } return name.compare(param.name) } } // Creation extension FwiMultipartParam { // MARK: Class's constructors public convenience init(name: String?, fileName file: String?, contentData data: NSData?, contentType type: String?) { self.init() // Validate name if let n = name { self.name = n } else { self.name = "" } // Validate file if let f = file { self.fileName = f } else { self.fileName = "" } // Validate data if let d = data { self.contentData = d } else { self.contentData = NSData() } // Validate type if let t = type { self.contentType = t } else { self.contentType = "" } } }
lgpl-3.0
57ac2daad3beb427a115b3281d2ee493
23.540816
122
0.503328
4.677043
false
false
false
false
benlangmuir/swift
test/Interop/SwiftToCxx/core/swift-impl-defs-in-cxx.swift
2
11810
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend %s -typecheck -module-name Core -clang-header-expose-public-decls -emit-clang-header-path %t/core.h // RUN: %FileCheck %s < %t/core.h // RUN: %check-interop-cxx-header-in-clang(%t/core.h) // CHECK: #ifndef SWIFT_PRINTED_CORE // CHECK-NEXT: #define SWIFT_PRINTED_CORE // CHECK-NEXT: namespace swift { // CHECK-EMPTY: // CHECK-NEXT: namespace _impl { // CHECK-EMPTY: // CHECK-NEXT: #ifdef __cplusplus // CHECK-NEXT: extern "C" { // CHECK-NEXT: #endif // CHECK-EMPTY: // CHECK-NEXT: // Swift type metadata response type. // CHECK-NEXT: struct MetadataResponseTy { // CHECK-NEXT: void * _Null_unspecified _0; // CHECK-NEXT: uint{{.*}}_t _1; // CHECK-NEXT: }; // CHECK-NEXT: // Swift type metadata request type. // CHECK-NEXT: typedef uint{{.*}}_t MetadataRequestTy; // CHECK-EMPTY: // CHECK-NEXT: #if __cplusplus > 201402L // CHECK-NEXT: # define SWIFT_NOEXCEPT_FUNCTION_PTR noexcept // CHECK-NEXT: #else // CHECK-NEXT: # define SWIFT_NOEXCEPT_FUNCTION_PTR // CHECK-NEXT: #endif // CHECK-EMPTY: // CHECK-NEXT: using ValueWitnessInitializeBufferWithCopyOfBufferTy = void * _Nonnull(* __ptrauth_swift_value_witness_function_pointer(55882))(void * _Nonnull, void * _Nonnull, void * _Nonnull) SWIFT_NOEXCEPT_FUNCTION_PTR; // CHECK-NEXT: using ValueWitnessDestroyTy = void(* __ptrauth_swift_value_witness_function_pointer(1272))(void * _Nonnull, void * _Nonnull) SWIFT_NOEXCEPT_FUNCTION_PTR; // CHECK-NEXT: using ValueWitnessInitializeWithCopyTy = void * _Nonnull(* __ptrauth_swift_value_witness_function_pointer(58298))(void * _Nonnull, void * _Nonnull, void * _Nonnull) SWIFT_NOEXCEPT_FUNCTION_PTR; // CHECK-NEXT: using ValueWitnessAssignWithCopyTy = void * _Nonnull(* __ptrauth_swift_value_witness_function_pointer(34641))(void * _Nonnull, void * _Nonnull, void * _Nonnull) SWIFT_NOEXCEPT_FUNCTION_PTR; // CHECK-NEXT: using ValueWitnessInitializeWithTakeTy = void * _Nonnull(* __ptrauth_swift_value_witness_function_pointer(18648))(void * _Nonnull, void * _Nonnull, void * _Nonnull) SWIFT_NOEXCEPT_FUNCTION_PTR; // CHECK-NEXT: using ValueWitnessAssignWithTakeTy = void * _Nonnull(* __ptrauth_swift_value_witness_function_pointer(61402))(void * _Nonnull, void * _Nonnull, void * _Nonnull) SWIFT_NOEXCEPT_FUNCTION_PTR; // CHECK-NEXT: using ValueWitnessGetEnumTagSinglePayloadTy = unsigned(* __ptrauth_swift_value_witness_function_pointer(24816))(const void * _Nonnull, unsigned, void * _Nonnull) SWIFT_NOEXCEPT_FUNCTION_PTR; // CHECK-NEXT: using ValueWitnessStoreEnumTagSinglePayloadTy = void(* __ptrauth_swift_value_witness_function_pointer(41169))(void * _Nonnull, unsigned, unsigned, void * _Nonnull) SWIFT_NOEXCEPT_FUNCTION_PTR; // CHECK-EMPTY: // CHECK-NEXT: struct ValueWitnessTable { // CHECK-NEXT: ValueWitnessInitializeBufferWithCopyOfBufferTy _Nonnull initializeBufferWithCopyOfBuffer; // CHECK-NEXT: ValueWitnessDestroyTy _Nonnull destroy; // CHECK-NEXT: ValueWitnessInitializeWithCopyTy _Nonnull initializeWithCopy; // CHECK-NEXT: ValueWitnessAssignWithCopyTy _Nonnull assignWithCopy; // CHECK-NEXT: ValueWitnessInitializeWithTakeTy _Nonnull initializeWithTake; // CHECK-NEXT: ValueWitnessAssignWithTakeTy _Nonnull assignWithTake; // CHECK-NEXT: ValueWitnessGetEnumTagSinglePayloadTy _Nonnull getEnumTagSinglePayload; // CHECK-NEXT: ValueWitnessStoreEnumTagSinglePayloadTy _Nonnull storeEnumTagSinglePayload; // CHECK-NEXT: size_t size; // CHECK-NEXT: size_t stride; // CHECK-NEXT: unsigned flags; // CHECK-NEXT: unsigned extraInhabitantCount; // CHECK-EMPTY: // CHECK-NEXT: constexpr size_t getAlignment() const { return (flags & 255) + 1; } // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: using EnumValueWitnessGetEnumTagTy = unsigned(* __ptrauth_swift_value_witness_function_pointer(41909))(const void * _Nonnull, void * _Nonnull) SWIFT_NOEXCEPT_FUNCTION_PTR; // CHECK-NEXT: using EnumValueWitnessDestructiveProjectEnumDataTy = void(* __ptrauth_swift_value_witness_function_pointer(1053))(void * _Nonnull, void * _Nonnull) SWIFT_NOEXCEPT_FUNCTION_PTR; // CHECK-NEXT: using EnumValueWitnessDestructiveInjectEnumTagTy = void(* __ptrauth_swift_value_witness_function_pointer(45796))(void * _Nonnull, unsigned, void * _Nonnull) SWIFT_NOEXCEPT_FUNCTION_PTR; // CHECK-EMPTY: // CHECK-NEXT: struct EnumValueWitnessTable { // CHECK-NEXT: ValueWitnessTable vwTable; // CHECK-NEXT: EnumValueWitnessGetEnumTagTy _Nonnull getEnumTag; // CHECK-NEXT: EnumValueWitnessDestructiveProjectEnumDataTy _Nonnull destructiveProjectEnumData; // CHECK-NEXT: EnumValueWitnessDestructiveInjectEnumTagTy _Nonnull destructiveInjectEnumTag; // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: #undef SWIFT_NOEXCEPT_FUNCTION_PTR // CHECK-EMPTY: // CHECK-EMPTY: // CHECK-NEXT: // type metadata address for Bool. // CHECK-NEXT: SWIFT_IMPORT_STDLIB_SYMBOL extern size_t $sSbN; // CHECK-NEXT: // type metadata address for Int8. // CHECK-NEXT: SWIFT_IMPORT_STDLIB_SYMBOL extern size_t $ss4Int8VN; // CHECK-NEXT: // type metadata address for UInt8. // CHECK-NEXT: SWIFT_IMPORT_STDLIB_SYMBOL extern size_t $ss5UInt8VN; // CHECK-NEXT: // type metadata address for Int16. // CHECK-NEXT: SWIFT_IMPORT_STDLIB_SYMBOL extern size_t $ss5Int16VN; // CHECK-NEXT: // type metadata address for UInt16. // CHECK-NEXT: SWIFT_IMPORT_STDLIB_SYMBOL extern size_t $ss6UInt16VN; // CHECK-NEXT: // type metadata address for Int32. // CHECK-NEXT: SWIFT_IMPORT_STDLIB_SYMBOL extern size_t $ss5Int32VN; // CHECK-NEXT: // type metadata address for UInt32. // CHECK-NEXT: SWIFT_IMPORT_STDLIB_SYMBOL extern size_t $ss6UInt32VN; // CHECK-NEXT: // type metadata address for Int64. // CHECK-NEXT: SWIFT_IMPORT_STDLIB_SYMBOL extern size_t $ss5Int64VN; // CHECK-NEXT: // type metadata address for UInt64. // CHECK-NEXT: SWIFT_IMPORT_STDLIB_SYMBOL extern size_t $ss6UInt64VN; // CHECK-NEXT: // type metadata address for Float. // CHECK-NEXT: SWIFT_IMPORT_STDLIB_SYMBOL extern size_t $sSfN; // CHECK-NEXT: // type metadata address for Double. // CHECK-NEXT: SWIFT_IMPORT_STDLIB_SYMBOL extern size_t $sSdN; // CHECK-NEXT: // type metadata address for OpaquePointer. // CHECK-NEXT: SWIFT_IMPORT_STDLIB_SYMBOL extern size_t $ss13OpaquePointerVN; // CHECK-EMPTY: // CHECK-NEXT: #ifdef __cplusplus // CHECK-NEXT: } // CHECK-NEXT: #endif // CHECK-EMPTY: // CHECK-NEXT: /// Naive exception class that should be thrown // CHECK-NEXT: class NaiveException : public swift::Error { // CHECK-NEXT: public: // CHECK-NEXT: inline NaiveException(const char * _Nonnull msg) noexcept : msg_(msg) { } // CHECK-NEXT: inline NaiveException(NaiveException&& other) noexcept : msg_(other.msg_) { other.msg_ = nullptr; } // CHECK-NEXT: inline ~NaiveException() noexcept { } // CHECK-NEXT: void operator =(NaiveException&& other) noexcept { auto temp = msg_; msg_ = other.msg_; other.msg_ = temp; } // CHECK-NEXT: void operator =(const NaiveException&) noexcept = delete; // CHECK-NEXT: inline const char * _Nonnull getMessage() const noexcept { return(msg_); } // CHECK-NEXT: private: // CHECK-NEXT: const char * _Nonnull msg_; // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: } // namespace _impl // CHECK-EMPTY: // CHECK-EMPTY: // CHECK-NEXT: #if __cplusplus > 201402L // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<bool> = true; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: struct TypeMetadataTrait<bool> { // CHECK-NEXT: static inline void * _Nonnull getTypeMetadata() { // CHECK-NEXT: return &_impl::$sSbN; // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<int8_t> = true; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: struct TypeMetadataTrait<int8_t> { // CHECK-NEXT: static inline void * _Nonnull getTypeMetadata() { // CHECK-NEXT: return &_impl::$ss4Int8VN; // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<uint8_t> = true; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: struct TypeMetadataTrait<uint8_t> { // CHECK-NEXT: static inline void * _Nonnull getTypeMetadata() { // CHECK-NEXT: return &_impl::$ss5UInt8VN; // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<int16_t> = true; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: struct TypeMetadataTrait<int16_t> { // CHECK-NEXT: static inline void * _Nonnull getTypeMetadata() { // CHECK-NEXT: return &_impl::$ss5Int16VN; // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<uint16_t> = true; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: struct TypeMetadataTrait<uint16_t> { // CHECK-NEXT: static inline void * _Nonnull getTypeMetadata() { // CHECK-NEXT: return &_impl::$ss6UInt16VN; // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<int32_t> = true; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: struct TypeMetadataTrait<int32_t> { // CHECK-NEXT: static inline void * _Nonnull getTypeMetadata() { // CHECK-NEXT: return &_impl::$ss5Int32VN; // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<uint32_t> = true; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: struct TypeMetadataTrait<uint32_t> { // CHECK-NEXT: static inline void * _Nonnull getTypeMetadata() { // CHECK-NEXT: return &_impl::$ss6UInt32VN; // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<int64_t> = true; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: struct TypeMetadataTrait<int64_t> { // CHECK-NEXT: static inline void * _Nonnull getTypeMetadata() { // CHECK-NEXT: return &_impl::$ss5Int64VN; // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<uint64_t> = true; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: struct TypeMetadataTrait<uint64_t> { // CHECK-NEXT: static inline void * _Nonnull getTypeMetadata() { // CHECK-NEXT: return &_impl::$ss6UInt64VN; // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<float> = true; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: struct TypeMetadataTrait<float> { // CHECK-NEXT: static inline void * _Nonnull getTypeMetadata() { // CHECK-NEXT: return &_impl::$sSfN; // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<double> = true; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: struct TypeMetadataTrait<double> { // CHECK-NEXT: static inline void * _Nonnull getTypeMetadata() { // CHECK-NEXT: return &_impl::$sSdN; // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<void *> = true; // CHECK-EMPTY: // CHECK-NEXT: template<> // CHECK-NEXT: struct TypeMetadataTrait<void *> { // CHECK-NEXT: static inline void * _Nonnull getTypeMetadata() { // CHECK-NEXT: return &_impl::$ss13OpaquePointerVN; // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: #endif // CHECK-EMPTY: // CHECK-NEXT: } // namespace swift // CHECK-EMPTY: // CHECK-NEXT: #endif
apache-2.0
9345b9444a2631b569f52a645f0114f1
47.801653
222
0.718374
3.386866
false
false
false
false
primetimer/PrimeFactors
Example/PrimeFactors/Extensions.swift
1
1938
// // Extensions.swift // PFactors_Example // // Created by Stephan Jancar on 20.10.17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import BigInt extension Int { func toUint() -> UInt64 { if self >= 0 { return UInt64(self) } let u = UInt64(self - Int.min) + UInt64(Int.max) + 1 return u } } extension BigUInt { func Build3Blocks() -> [String] { var arr : [String] = [] let valstr = String(self) var (str3,pos) = ("",0) for c in valstr.reversed() { (str3,pos) = (String(c) + str3,pos+1) if pos % 3 == 0 { arr.append(str3) (str3,pos) = ("",0) } } if str3 != "" { arr.append(str3) } return arr } func FormatStr(maxrows : Int, rowlen : Int = 18) -> (String,rows: Int) { if self == 0 { return ("0.",rows :1) } let blocks = self.Build3Blocks() var (outstr,len) = ("",0) let blocksperrow = rowlen / 3 var rows = 1 + (blocks.count-1) / blocksperrow var maxindex = maxrows * blocksperrow if rows > maxrows { rows = maxrows maxindex = maxindex - 3 //Get place for ### Info } for i in 0..<rows { for j in 0..<blocksperrow { let index = i * blocksperrow + j if index >= blocks.count { break } if index >= maxindex { var startstr = blocks[blocks.count-1] if index < blocks.count - 2 { startstr = startstr + "." + blocks[blocks.count-2] } outstr = startstr + ".###." + outstr return (outstr,i) } let blockstr = blocks[index] (outstr,len) = ( blockstr + "." + outstr,len+blockstr.count) } if i<rows-1 { outstr = "\n" + outstr } } return (outstr,rows) } } extension String { func asBigUInt() -> BigUInt { var ret = BigUInt(0) let chars = Array(self) for c in chars { switch c { case "0", "1", "2", "3", "4" , "5", "6", "7", "8", "9": let digit = BigUInt(String(c)) ?? 0 ret = ret * 10 + BigUInt(digit) default: break } } return ret } }
mit
cad90d31190c101b46291c9844a462b9
21.788235
73
0.57047
2.686546
false
false
false
false
khizkhiz/swift
benchmark/single-source/DictionaryBridge.swift
2
1575
//===--- DictionaryBridge.swift -------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // benchmark to test the performance of bridging an NSDictionary to a // Swift.Dictionary. import Foundation import TestsUtils class Thing : NSObject { required override init() { let c = self.dynamicType.col() CheckResults(c!.count == 10, "The rules of the universe apply") } private class func col() -> [String : AnyObject]? { let dict = NSMutableDictionary() dict.setValue(1, forKey: "one") dict.setValue(2, forKey: "two") dict.setValue(3, forKey: "three") dict.setValue(4, forKey: "four") dict.setValue(5, forKey: "five") dict.setValue(6, forKey: "six") dict.setValue(7, forKey: "seven") dict.setValue(8, forKey: "eight") dict.setValue(9, forKey: "nine") dict.setValue(10, forKey: "ten") return NSDictionary(dictionary: dict) as? [String: AnyObject] } class func mk() -> Thing { return self.init() } } class Stuff { var c : Thing = Thing.mk() init() { } } @inline(never) public func run_DictionaryBridge(N: Int) { for _ in 1...100*N { _ = Stuff() } }
apache-2.0
473fad663fb318dbdfa7429df74fd432
25.694915
80
0.604444
3.927681
false
false
false
false
josherick/DailySpend
DailySpend/UILabel+Size.swift
1
1028
// // Date+Convenience.swift // DailySpend // // Created by Josh Sherick on 3/16/17. // Copyright © 2017 Josh Sherick. All rights reserved. // import Foundation extension UILabel { func intrinsicHeightForWidth(_ width: CGFloat) -> CGFloat { // Set number of lines for this calculation to work properly. let oldLines = numberOfLines numberOfLines = 0 let height = sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)).height numberOfLines = oldLines return height } func resizeFontToFit(desiredFontSize: CGFloat? = nil, minFontSize: CGFloat? = nil) { guard let text = self.text, let font = self.font else { return } let sizedFont = desiredFontSize == nil ? font : font.withSize(desiredFontSize!) let newFontSize = text.maximumFontSize(sizedFont, maxWidth: bounds.size.width, maxHeight: bounds.size.height) self.font = font.withSize(max(newFontSize, minFontSize ?? 1)) } }
mit
3b893cc68ecd153201d9292ab5caf2b4
33.233333
117
0.65628
4.351695
false
false
false
false
vector-im/riot-ios
Riot/Modules/Settings/KeyBackup/SettingsKeyBackupTableViewSection.swift
1
15735
/* Copyright 2019 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 UIKit @objc protocol SettingsKeyBackupTableViewSectionDelegate: class { func settingsKeyBackupTableViewSectionDidUpdate(_ settingsKeyBackupTableViewSection: SettingsKeyBackupTableViewSection) func settingsKeyBackupTableViewSection(_ settingsKeyBackupTableViewSection: SettingsKeyBackupTableViewSection, textCellForRow: Int) -> MXKTableViewCellWithTextView func settingsKeyBackupTableViewSection(_ settingsKeyBackupTableViewSection: SettingsKeyBackupTableViewSection, buttonCellForRow: Int) -> MXKTableViewCellWithButton func settingsKeyBackupTableViewSectionShowKeyBackupSetup(_ settingsKeyBackupTableViewSection: SettingsKeyBackupTableViewSection) func settingsKeyBackup(_ settingsKeyBackupTableViewSection: SettingsKeyBackupTableViewSection, showKeyBackupRecover keyBackupVersion: MXKeyBackupVersion) func settingsKeyBackup(_ settingsKeyBackupTableViewSection: SettingsKeyBackupTableViewSection, showKeyBackupDeleteConfirm keyBackupVersion: MXKeyBackupVersion) func settingsKeyBackup(_ settingsKeyBackupTableViewSection: SettingsKeyBackupTableViewSection, showActivityIndicator show: Bool) func settingsKeyBackup(_ settingsKeyBackupTableViewSection: SettingsKeyBackupTableViewSection, showError error: Error) } private enum BackupRows { case info(text: String) case createAction case restoreAction(keyBackupVersion: MXKeyBackupVersion, title: String) case deleteAction(keyBackupVersion: MXKeyBackupVersion) } @objc final class SettingsKeyBackupTableViewSection: NSObject { // MARK: - Properties @objc weak var delegate: SettingsKeyBackupTableViewSectionDelegate? // MARK: Private // This view class holds the model because the model is in pure Swift // whereas this class can be used from objC private var viewModel: SettingsKeyBackupViewModelType! // Need to know the state to make `cellForRow` deliver cells accordingly private var viewState: SettingsKeyBackupViewState = .checkingBackup { didSet { self.updateBackupRows() } } private var userDevice: MXDeviceInfo private var backupRows: [BackupRows] = [] // MARK: - Public @objc init(withKeyBackup keyBackup: MXKeyBackup, userDevice: MXDeviceInfo) { self.viewModel = SettingsKeyBackupViewModel(keyBackup: keyBackup) self.userDevice = userDevice super.init() self.viewModel.viewDelegate = self self.viewModel.process(viewAction: .load) } @objc func numberOfRows() -> Int { return self.backupRows.count } @objc func cellForRow(atRow row: Int) -> UITableViewCell { guard let delegate = self.delegate else { return UITableViewCell() } let backupRow = self.backupRows[row] var cell: UITableViewCell switch backupRow { case .info(let infoText): let infoCell: MXKTableViewCellWithTextView = delegate.settingsKeyBackupTableViewSection(self, textCellForRow: row) infoCell.mxkTextView.text = infoText cell = infoCell case .createAction: cell = self.buttonCellForCreate(atRow: row) case .restoreAction(keyBackupVersion: let keyBackupVersion, let title): cell = self.buttonCellForRestore(keyBackupVersion: keyBackupVersion, title: title, atRow: row) case .deleteAction(keyBackupVersion: let keyBackupVersion): cell = self.buttonCellForDelete(keyBackupVersion: keyBackupVersion, atRow: row) } return cell } @objc func reload() { self.viewModel.process(viewAction: .load) } @objc func delete(keyBackupVersion: MXKeyBackupVersion) { self.viewModel.process(viewAction: .delete(keyBackupVersion)) } // MARK: - Data Computing private func updateBackupRows() { let backupRows: [BackupRows] switch self.viewState { case .checkingBackup: let info = VectorL10n.settingsKeyBackupInfo let checking = VectorL10n.settingsKeyBackupInfoChecking let strings = [info, "", checking] let text = strings.joined(separator: "\n") backupRows = [ .info(text: text) ] case .noBackup: let noBackup = VectorL10n.settingsKeyBackupInfoNone let info = VectorL10n.settingsKeyBackupInfo let signoutWarning = VectorL10n.settingsKeyBackupInfoSignoutWarning let strings = [noBackup, "", info, "", signoutWarning] let backupInfoText = strings.joined(separator: "\n") backupRows = [ .info(text: backupInfoText), .createAction ] case .backup(let keyBackupVersion, let keyBackupVersionTrust): let info = VectorL10n.settingsKeyBackupInfo let backupStatus = VectorL10n.settingsKeyBackupInfoValid let backupStrings = [info, "", backupStatus] let backupInfoText = backupStrings.joined(separator: "\n") let version = VectorL10n.settingsKeyBackupInfoVersion(keyBackupVersion.version ?? "") let algorithm = VectorL10n.settingsKeyBackupInfoAlgorithm(keyBackupVersion.algorithm) let uploadStatus = VectorL10n.settingsKeyBackupInfoProgressDone let additionalStrings = [version, algorithm, uploadStatus] let additionalInfoText = additionalStrings.joined(separator: "\n") let backupTrust = self.stringForKeyBackupTrust(keyBackupVersionTrust) let backupTrustInfoText = backupTrust.joined(separator: "\n") var backupViewStateRows: [BackupRows] = [ .info(text: backupInfoText), .info(text: additionalInfoText), .info(text: backupTrustInfoText) ] // TODO: Do not display restore button if all keys are stored on the device if true { backupViewStateRows.append(.restoreAction(keyBackupVersion: keyBackupVersion, title: VectorL10n.settingsKeyBackupButtonRestore)) } backupViewStateRows.append(.deleteAction(keyBackupVersion: keyBackupVersion)) backupRows = backupViewStateRows case .backupAndRunning(let keyBackupVersion, let keyBackupVersionTrust, let backupProgress): let info = VectorL10n.settingsKeyBackupInfo let backupStatus = VectorL10n.settingsKeyBackupInfoValid let backupStrings = [info, "", backupStatus] let backupInfoText = backupStrings.joined(separator: "\n") let remaining = backupProgress.totalUnitCount - backupProgress.completedUnitCount let version = VectorL10n.settingsKeyBackupInfoVersion(keyBackupVersion.version ?? "") let algorithm = VectorL10n.settingsKeyBackupInfoAlgorithm(keyBackupVersion.algorithm) let uploadStatus = VectorL10n.settingsKeyBackupInfoProgress(String(remaining)) let additionalStrings = [version, algorithm, uploadStatus] let additionalInfoText = additionalStrings.joined(separator: "\n") let backupTrust = self.stringForKeyBackupTrust(keyBackupVersionTrust) let backupTrustInfoText = backupTrust.joined(separator: "\n") var backupAndRunningViewStateRows: [BackupRows] = [ .info(text: backupInfoText), .info(text: additionalInfoText), .info(text: backupTrustInfoText) ] // TODO: Do not display restore button if all keys are stored on the device if true { backupAndRunningViewStateRows.append(.restoreAction(keyBackupVersion: keyBackupVersion, title: VectorL10n.settingsKeyBackupButtonRestore)) } backupAndRunningViewStateRows.append(.deleteAction(keyBackupVersion: keyBackupVersion)) backupRows = backupAndRunningViewStateRows case .backupNotTrusted(let keyBackupVersion, let keyBackupVersionTrust): let info = VectorL10n.settingsKeyBackupInfo let backupStatus = VectorL10n.settingsKeyBackupInfoNotValid let signoutWarning = VectorL10n.settingsKeyBackupInfoSignoutWarning let backupStrings = [info, "", backupStatus, "", signoutWarning] let backupInfoText = backupStrings.joined(separator: "\n") let version = VectorL10n.settingsKeyBackupInfoVersion(keyBackupVersion.version ?? "") let algorithm = VectorL10n.settingsKeyBackupInfoAlgorithm(keyBackupVersion.algorithm) let additionalStrings = [version, algorithm] let additionalInfoText = additionalStrings.joined(separator: "\n") let backupTrust = self.stringForKeyBackupTrust(keyBackupVersionTrust) let backupTrustInfoText = backupTrust.joined(separator: "\n") var backupNotTrustedViewStateRows: [BackupRows] = [ .info(text: backupInfoText), .info(text: additionalInfoText), .info(text: backupTrustInfoText) ] // TODO: Do not display restore button if all keys are stored on the device if true { backupNotTrustedViewStateRows.append(.restoreAction(keyBackupVersion: keyBackupVersion, title: VectorL10n.settingsKeyBackupButtonConnect)) } backupNotTrustedViewStateRows.append(.deleteAction(keyBackupVersion: keyBackupVersion)) backupRows = backupNotTrustedViewStateRows } self.backupRows = backupRows } private func stringForKeyBackupTrust(_ keyBackupVersionTrust: MXKeyBackupVersionTrust) -> [String] { return keyBackupVersionTrust.signatures.map { (signature) -> String in guard let device = signature.device else { return VectorL10n.settingsKeyBackupInfoTrustSignatureUnknown(signature.deviceId) } let displayName = device.displayName ?? device.deviceId ?? "" if device.fingerprint == self.userDevice.fingerprint { return VectorL10n.settingsKeyBackupInfoTrustSignatureValid } else if signature.valid && (device.trustLevel.localVerificationStatus == .verified) { return VectorL10n.settingsKeyBackupInfoTrustSignatureValidDeviceVerified(displayName) } else if signature.valid && (device.trustLevel.localVerificationStatus != .verified) { return VectorL10n.settingsKeyBackupInfoTrustSignatureValidDeviceUnverified(displayName) } else if !signature.valid && (device.trustLevel.localVerificationStatus == .verified) { return VectorL10n.settingsKeyBackupInfoTrustSignatureInvalidDeviceVerified(displayName) } else if !signature.valid && (device.trustLevel.localVerificationStatus != .verified) { return VectorL10n.settingsKeyBackupInfoTrustSignatureInvalidDeviceUnverified(displayName) } return "" } } // MARK: - Button cells private func buttonCellForCreate(atRow row: Int) -> UITableViewCell { guard let delegate = self.delegate else { return UITableViewCell() } let cell: MXKTableViewCellWithButton = delegate.settingsKeyBackupTableViewSection(self, buttonCellForRow: row) let btnTitle = VectorL10n.settingsKeyBackupButtonCreate cell.mxkButton.setTitle(btnTitle, for: .normal) cell.mxkButton.setTitle(btnTitle, for: .highlighted) cell.mxkButton.vc_addAction { self.viewModel.process(viewAction: .create) } return cell } private func buttonCellForRestore(keyBackupVersion: MXKeyBackupVersion, title: String, atRow row: Int) -> UITableViewCell { guard let delegate = self.delegate else { return UITableViewCell() } let cell: MXKTableViewCellWithButton = delegate.settingsKeyBackupTableViewSection(self, buttonCellForRow: row) cell.mxkButton.setTitle(title, for: .normal) cell.mxkButton.setTitle(title, for: .highlighted) cell.mxkButton.vc_addAction { self.viewModel.process(viewAction: .restore(keyBackupVersion)) } return cell } private func buttonCellForDelete(keyBackupVersion: MXKeyBackupVersion, atRow row: Int) -> UITableViewCell { guard let delegate = self.delegate else { return UITableViewCell() } let cell: MXKTableViewCellWithButton = delegate.settingsKeyBackupTableViewSection(self, buttonCellForRow: row) let btnTitle = VectorL10n.settingsKeyBackupButtonDelete cell.mxkButton.setTitle(btnTitle, for: .normal) cell.mxkButton.setTitle(btnTitle, for: .highlighted) cell.mxkButton.tintColor = ThemeService.shared().theme.warningColor cell.mxkButton.vc_addAction { self.viewModel.process(viewAction: .confirmDelete(keyBackupVersion)) } return cell } } // MARK: - KeyBackupSetupRecoveryKeyViewModelViewDelegate extension SettingsKeyBackupTableViewSection: SettingsKeyBackupViewModelViewDelegate { func settingsKeyBackupViewModel(_ viewModel: SettingsKeyBackupViewModelType, didUpdateViewState viewState: SettingsKeyBackupViewState) { self.viewState = viewState // The tableview datasource will call `self.cellForRow()` self.delegate?.settingsKeyBackupTableViewSectionDidUpdate(self) } func settingsKeyBackupViewModel(_ viewModel: SettingsKeyBackupViewModelType, didUpdateNetworkRequestViewState networkRequestViewSate: SettingsKeyBackupNetworkRequestViewState) { switch networkRequestViewSate { case .loading: self.delegate?.settingsKeyBackup(self, showActivityIndicator: true) case .loaded: self.delegate?.settingsKeyBackup(self, showActivityIndicator: false) case .error(let error): self.delegate?.settingsKeyBackup(self, showError: error) } } func settingsKeyBackupViewModelShowKeyBackupSetup(_ viewModel: SettingsKeyBackupViewModelType) { self.delegate?.settingsKeyBackupTableViewSectionShowKeyBackupSetup(self) } func settingsKeyBackup(_ viewModel: SettingsKeyBackupViewModelType, showKeyBackupRecover keyBackupVersion: MXKeyBackupVersion) { self.delegate?.settingsKeyBackup(self, showKeyBackupRecover: keyBackupVersion) } func settingsKeyBackup(_ viewModel: SettingsKeyBackupViewModelType, showKeyBackupDeleteConfirm keyBackupVersion: MXKeyBackupVersion) { self.delegate?.settingsKeyBackup(self, showKeyBackupDeleteConfirm: keyBackupVersion) } }
apache-2.0
ce4a7c01e1141b8f227be7d9b41ac014
43.449153
181
0.684144
5.499825
false
false
false
false
Mioke/SwiftArchitectureWithPOP
SwiftyArchitecture/Base/Assistance/Extensions/Double+Extension.swift
1
796
// // Double+Extension.swift // FileMail // // Created by jiangkelan on 22/05/2017. // Copyright © 2017 xlvip. All rights reserved. // import Foundation extension Double { /// Rounds the double to decimal places value func roundTo(places:Int) -> Double { let divisor = pow(10.0, Double(places)) return (self * divisor).rounded() / divisor } /* // Formate to file size string with KB, MB, GB func fileSizeFormate() -> String { var totalBytes = self / 1024.0 var multiplyFactor = 0 let tokens = ["KB","MB","GB","TB"] while totalBytes > 1024 { totalBytes /= 1024.0 multiplyFactor += 1 } return "\(String(format:"%.2f",totalBytes))\(tokens[multiplyFactor])" } */ }
mit
7b0ee4810daa5b1e68f21a9942841368
23.84375
77
0.574843
3.975
false
false
false
false
brokenhandsio/vapor-oauth
Sources/VaporOAuth/RouteHandlers/TokenIntrospectionHandler.swift
1
2840
import HTTP import JSON import Foundation struct TokenIntrospectionHandler { let clientValidator: ClientValidator let tokenManager: TokenManager let userManager: UserManager func handleRequest(_ req: Request) throws -> ResponseRepresentable { guard let tokenString = req.data[OAuthRequestParameters.token]?.string else { return try createErrorResponse(status: .badRequest, errorMessage: OAuthResponseParameters.ErrorType.missingToken, errorDescription: "The token parameter is required") } guard let token = tokenManager.getAccessToken(tokenString) else { return try createTokenResponse(active: false, expiryDate: nil, clientID: nil) } guard token.expiryTime >= Date() else { return try createTokenResponse(active: false, expiryDate: nil, clientID: nil) } let scopes = token.scopes?.joined(separator: " ") var user: OAuthUser? = nil if let userID = token.userID { if let tokenUser = userManager.getUser(userID: userID) { user = tokenUser } } return try createTokenResponse(active: true, expiryDate: token.expiryTime, clientID: token.clientID, scopes: scopes, user: user) } func createTokenResponse(active: Bool, expiryDate: Date?, clientID: String?, scopes: String? = nil, user: OAuthUser? = nil) throws -> Response { var json = JSON() try json.set(OAuthResponseParameters.active, active) if let clientID = clientID { try json.set(OAuthResponseParameters.clientID, clientID) } if let scopes = scopes { try json.set(OAuthResponseParameters.scope, scopes) } if let user = user { try json.set(OAuthResponseParameters.userID, user.id) try json.set(OAuthResponseParameters.username, user.username) if let email = user.emailAddress { try json.set(OAuthResponseParameters.email, email) } } if let expiryDate = expiryDate { try json.set(OAuthResponseParameters.expiry, Int(expiryDate.timeIntervalSince1970)) } let response = Response(status: .ok) response.json = json return response } func createErrorResponse(status: Status, errorMessage: String, errorDescription: String) throws -> Response { var json = JSON() try json.set(OAuthResponseParameters.error, errorMessage) try json.set(OAuthResponseParameters.errorDescription, errorDescription) let response = Response(status: status) response.json = json return response } }
mit
ae939059c222ba99ed46bb0eb0f69ccd
35.410256
113
0.62007
5.220588
false
false
false
false
ReactiveSprint/ReactiveSprint-Swift
Example/Tests/UIKit/UIAlertControllerSpec.swift
1
1132
// // UIAlertControllerSpec.swift // ReactiveSprint // // Created by Ahmad Baraka on 3/16/16. // Copyright © 2016 ReactiveSprint. All rights reserved. // import Foundation import Quick import Nimble import ReactiveSprint class UIAlertControllerSpec: QuickSpec { override func spec() { it("should init UIAlertController from error") { let title = "Error Title" let message = "Error message" let cancel = "Cancel" let userInfo: [NSObject: AnyObject] = [NSLocalizedDescriptionKey : title , NSLocalizedRecoverySuggestionErrorKey: message , NSLocalizedRecoveryOptionsErrorKey: [cancel]] let error = NSError(domain: "TestDomain", code: 0, userInfo: userInfo) let alert = UIAlertController(error: error) expect(alert.title) == title expect(alert.message) == message expect(alert.actions.count) == 1 expect(alert.actions[0].title) == cancel } } }
mit
b735a56a49f2c99dae55e8b05065f779
26.585366
84
0.568523
5.211982
false
false
false
false
alexander-ray/StudyOutlet
Sources/App/Models/Question.swift
1
2202
import Vapor import Fluent import Foundation // Model for a question final class Question: Model { // Fields from database to fully represent question var id: Node? // Identifier to comform to model // Question and solution contain base64 png to deal with Blob type let question: String let solution: String let answer: String let subject: String let topic: String var exists: Bool = false // Initialize values init(question: String, solution: String, answer: String, subject: String, topic: String) { self.question = question self.solution = solution self.answer = answer self.subject = subject self.topic = topic } // Getting data from database init(node: Node, in context: Context) throws { id = try node.extract("id") question = try node.extract("question") //question = try node.extract("question", transform: Question.stringToData) //solution = try node.extract("solution", transform: Question.stringToData) solution = try node.extract("solution") answer = try node.extract("answer") subject = try node.extract("subject") topic = try node.extract("topic") } // Insert info into database // Probably unused func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, // Node data type can only use strings, ints, etc "question": question, //"question": question, "solution": solution, "answer": answer, "subject": subject, "topic": topic ]) } // Needed to conform to model // Creates table if needed static func prepare(_ database: Database) throws { try database.create("questions") { questions in questions.id() questions.data("question") questions.data("solution") questions.string("answer") questions.string("subject") questions.string("topic") } } static func revert(_ database: Database) throws { try database.delete("questions") } }
mit
bf91bac1f1f20065fca782d57923e4b0
30.913043
94
0.599455
4.797386
false
false
false
false
insidegui/WWDC
Packages/ConfCore/ConfCore/Error+CloudKit.swift
1
2667
// // Error+CloudKit.swift // ConfCore // // Created by Guilherme Rambo on 25/05/18. // Copyright © 2018 Guilherme Rambo. All rights reserved. // import Foundation import CloudKit import os.log extension Error { var isCloudKitConflict: Bool { guard let effectiveError = self as? CKError else { return false } return effectiveError.code == .serverRecordChanged } func resolveConflict(with resolver: (CKRecord, CKRecord) -> CKRecord?) -> CKRecord? { guard let effectiveError = self as? CKError else { os_log("resolveConflict called on an error that was not a CKError. The error was %{public}@", log: .default, type: .fault, String(describing: self)) return nil } guard effectiveError.code == .serverRecordChanged else { os_log("resolveConflict called on a CKError that was not a serverRecordChanged error. The error was %{public}@", log: .default, type: .fault, String(describing: effectiveError)) return nil } guard let clientRecord = effectiveError.userInfo[CKRecordChangedErrorClientRecordKey] as? CKRecord else { os_log("Failed to obtain client record from serverRecordChanged error. The error was %{public}@", log: .default, type: .fault, String(describing: effectiveError)) return nil } guard let serverRecord = effectiveError.userInfo[CKRecordChangedErrorServerRecordKey] as? CKRecord else { os_log("Failed to obtain server record from serverRecordChanged error. The error was %{public}@", log: .default, type: .fault, String(describing: effectiveError)) return nil } return resolver(clientRecord, serverRecord) } @discardableResult func retryCloudKitOperationIfPossible(_ log: OSLog? = nil, in queue: DispatchQueue = .main, with block: @escaping () -> Void) -> Bool { let effectiveLog = log ?? .default guard let effectiveError = self as? CKError else { return false } guard let retryDelay = effectiveError.retryAfterSeconds else { os_log("Error is not recoverable", log: effectiveLog, type: .error) return false } os_log("Error is recoverable. Will retry after %{public}f seconds", log: effectiveLog, type: .error, retryDelay) queue.asyncAfter(deadline: .now() + retryDelay) { block() } return true } }
bsd-2-clause
881c29582088e32c4162119e85944f75
34.078947
158
0.604651
4.918819
false
false
false
false
kareman/FootlessParser
Tests/FootlessParserTests/PerformanceTests.swift
1
4050
// // PerformanceTests.swift // FootlessParser // // Created by Bouke Haarsma on 16-05-16. // // import FootlessParser import XCTest class PerformanceTests: XCTestCase { func testZeroOrMoreGeneric () { let parser = zeroOrMore(token(1)) let input = Array(repeating: 1, count: 1000) measure { self.assertParseSucceeds(parser, input, consumed: 1000) } } func testZeroOrMoreString () { let parser = zeroOrMore(char("a")) let input = String(repeating: "a", count: 1000) measure { self.assertParseSucceeds(parser, input, consumed: 1000) } } func testOneOrMoreGeneric() { let parser = oneOrMore(token(1)) assertParseSucceeds(parser, [1], result: [1], consumed: 1) assertParseSucceeds(parser, [1,1,1], result: [1,1,1], consumed: 3) assertParseSucceeds(parser, [1,1,1,9], result: [1,1,1], consumed: 3) let input = Array(repeating: 1, count: 1000) measure { self.assertParseSucceeds(parser, input, consumed: 1000) } } func testOneOrMoreString () { let parser = oneOrMore(char("a")) assertParseSucceeds(parser, "a", result: "a") assertParseSucceeds(parser, "aaa", result: "aaa") assertParseSucceeds(parser, "aaab", result: "aaa", consumed: 3) let input = String(repeating: "a", count: 1000) measure { self.assertParseSucceeds(parser, input, consumed: 1000) } } func testCount1000Generic () { let parser = count(1000, token(1)) let input = Array(repeating: 1, count: 1000) measure { self.assertParseSucceeds(parser, input, consumed: 1000) } } func testCount1000String () { let parser = count(1000, char("a")) let input = String(repeating: "a", count: 1000) measure { self.assertParseSucceeds(parser, input, consumed: 1000) } } func testRange0To1000Generic () { let parser = count(0...1000, token(1)) let input = Array(repeating: 1, count: 1000) measure { self.assertParseSucceeds(parser, input, consumed: 1000) } } func testRange0To1000String () { let parser = count(0...1000, char("a")) let input = String(repeating: "a", count: 1000) measure { self.assertParseSucceeds(parser, input, consumed: 1000) } } func testBacktrackingLeftString() { let parser = string("food") <|> string("foot") measure { for _ in 0..<1000 { self.assertParseSucceeds(parser, "food") } } } func testBacktrackingRightString() { let parser = string("food") <|> string("foot") measure { for _ in 0..<1000 { self.assertParseSucceeds(parser, "foot") } } } func testBacktrackingFailString() { let parser = string("food") <|> string("foot") measure { for _ in 0..<1000 { self.assertParseFails(parser, "fool") } } } func testCSVRow() { measure { for _ in 0..<1000 { _ = try! parse(row, "Hello,\"Dear World\",\"Hello\",Again\n") } } } } extension PerformanceTests { public static var allTests = [ ("testZeroOrMoreGeneric", testZeroOrMoreGeneric), ("testZeroOrMoreString", testZeroOrMoreString), ("testOneOrMoreGeneric", testOneOrMoreGeneric), ("testOneOrMoreString", testOneOrMoreString), ("testCount1000Generic", testCount1000Generic), ("testCount1000String", testCount1000String), ("testRange0To1000Generic", testRange0To1000Generic), ("testRange0To1000String", testRange0To1000String), ("testBacktrackingLeftString", testBacktrackingLeftString), ("testBacktrackingRightString", testBacktrackingRightString), ("testBacktrackingFailString", testBacktrackingFailString), ("testCSVRow", testCSVRow), ] }
mit
f4537540f66b3e8c8b52e43653c13612
28.347826
77
0.591852
4.041916
false
true
false
false
Nana-Muthuswamy/TwitterLite
TwitterLite/TweetsViewController.swift
1
6997
// // TweetsViewController.swift // TwitterLite // // Created by Nana on 4/15/17. // Copyright © 2017 Nana. All rights reserved. // import UIKit class TweetsViewController: UITableViewController { var tweets = Array<Tweet>() { didSet { emptyTweetsView = (tweets.count == 0) DispatchQueue.main.async {[weak self] in self?.tableView.reloadData() } } } private var emptyTweetsView = false override func viewDidLoad() { super.viewDidLoad() // Setup Navigation items navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named:"Compose")!, style: .plain, target: self, action: #selector(composeTweet(_:))) if (navigationController?.viewControllers.first == self) { // Include Sign Out button only for rootviewcontroller navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(signOut(_:))) } // Setup table view attributes tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 94 let tweetCellViewNib = UINib(nibName: "TweetTableViewCell", bundle: nil) tableView.register(tweetCellViewNib, forCellReuseIdentifier: "TweetTableViewCell") let emptyTweetsCellViewNib = UINib(nibName: "EmptyTweetsTableViewCell", bundle: nil) tableView.register(emptyTweetsCellViewNib, forCellReuseIdentifier: "EmptyTweetsTableViewCell") // Setup UIRefresh refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged) // Load twitter home time line of tweets... loadData() } // MARK: - Data func loadData() { // default implementation does nothing, need to be overriden by sub classes } // MARK: - Action Methods @IBAction func signOut(_ sender: Any) { NetworkManager.shared.logout() performSegue(withIdentifier: "unwindToLoginView", sender: self) } @IBAction func composeTweet(_ sender: Any) { performSegue(withIdentifier: "PresentComposeTweetView", sender: self) } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (emptyTweetsView ? 1 : tweets.count) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if emptyTweetsView { let cell = tableView.dequeueReusableCell(withIdentifier: "EmptyTweetsTableViewCell") as! EmptyTweetsTableViewCell cell.message = Message(title: "Nothing to see here. Yet.", body: "From Retweets to likes and a whole lot more, this is where all the action happens about your Tweets and followers. You'll like it here.") return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "TweetTableViewCell") as! TweetTableViewCell cell.delegate = self cell.model = tweets[indexPath.row] return cell } } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let cell = tableView.cellForRow(at: indexPath) as? TweetTableViewCell performSegue(withIdentifier: "ShowTweetDetailsView", sender: cell) } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if emptyTweetsView { return 600 } else { return UITableViewAutomaticDimension } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ShowTweetDetailsView" { let tweetDetailsVC = segue.destination as! TweetDetailsViewController let indexPath = tableView.indexPath(for: sender as! UITableViewCell)! tweetDetailsVC.tweet = tweets[indexPath.row] } else if segue.identifier == "PresentComposeTweetView" { let composeTweetVC = (segue.destination as! UINavigationController).viewControllers.first as! ComposeTweetViewController composeTweetVC.delegate = self } } func showProfileView(for user: User) { let storyboard = UIStoryboard.init(name: "Main", bundle: nil) let destination = storyboard.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController destination.user = user show(destination, sender: self) } // MARK: - Utils func displayAlert(title: String, message: String, completion: (() -> Void)?) { executeOnMain { let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert) alertVC.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in completion?() })) self.present(alertVC, animated: true, completion: nil) } } func executeOnMain(_ block: (() -> Void)?) { DispatchQueue.main.async { block?() } } } extension TweetsViewController: ComposeTweetViewControllerDelegate { func updateTimeline(with newTweet: Tweet) { tweets.insert(newTweet, at: 0) executeOnMain({self.tableView.reloadData()}) } } extension TweetsViewController: TweetTableViewCellDelegate { func tableViewCell(_ cell: TweetTableViewCell, didRetweet: Bool) { let tweet = cell.model! NetworkManager.shared.retweet(tweetID: tweet.idStr, retweet: didRetweet) {[weak self] (_, error) in if error == nil { tweet.retweeted = didRetweet self?.executeOnMain({self?.tableView.reloadData()}) } else { self?.displayAlert(title: "Unable to Perform Operation", message: error?.localizedDescription ?? "Remote API failed due to unknown reason.", completion: nil) } } } func tableViewCell(_ cell: TweetTableViewCell, didFavorite: Bool) { let tweet = cell.model! NetworkManager.shared.favorite(tweetID: tweet.idStr, favorite: didFavorite) { [weak self] (_, error) in if error == nil { tweet.favorited = didFavorite self?.executeOnMain({self?.tableView.reloadData()}) } else { self?.displayAlert(title: "Unable to Perform Operation", message: error?.localizedDescription ?? "Remote API failed due to unknown reason.", completion: nil) } } } func tableViewCell(_ cell: TweetTableViewCell, displayProfileView: Bool) { if displayProfileView { if let user = cell.model.tweetOwner { showProfileView(for: user) } } } }
mit
5326257ed7978332176fdff0048447ce
33.633663
215
0.647513
5.117776
false
false
false
false
loanburger/TaxCalc
TaxCalc/AppDelegate.swift
1
3343
// // AppDelegate.swift // TaxCalc // // Created by Loan Burger on 20/11/14. // Copyright (c) 2014 Loan Burger. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as UINavigationController navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController { if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } } } return false } }
mit
8f8a6afc934ceae4e9fa5b41332a06ca
52.063492
285
0.750823
6.213755
false
false
false
false
willlarche/material-components-ios
components/ButtonBar/examples/ButtonBarTypicalUseExample.swift
2
3242
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import MaterialComponents class ButtonBarTypicalUseSwiftExample: UIViewController { override func viewDidLoad() { super.viewDidLoad() let buttonBar = MDCButtonBar() buttonBar.backgroundColor = self.buttonBarBackgroundColor() // MDCButtonBar ignores the style of UIBarButtonItem. let ignored: UIBarButtonItemStyle = .done let actionItem = UIBarButtonItem( title: "Action", style: ignored, target: self, action: #selector(didTapActionButton) ) let secondActionItem = UIBarButtonItem( title: "Second action", style: ignored, target: self, action: #selector(didTapActionButton) ) let items = [actionItem, secondActionItem] // Set the title text attributes before assigning to buttonBar.items // because of https://github.com/material-components/material-components-ios/issues/277 for item in items { item.setTitleTextAttributes(self.itemTitleTextAttributes(), for: UIControlState()) } buttonBar.items = items // MDCButtonBar's sizeThatFits gives a "best-fit" size of the provided items. let size = buttonBar.sizeThatFits(self.view.bounds.size) let x = (self.view.bounds.size.width - size.width) / 2 let y = self.view.bounds.size.height / 2 - size.height buttonBar.frame = CGRect(x: x, y: y, width: size.width, height: size.height) buttonBar.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin] self.view.addSubview(buttonBar) // Ensure that the controller's view isn't transparent. view.backgroundColor = UIColor(white: 0.9, alpha:1.0) } @objc func didTapActionButton(_ sender: Any) { print("Did tap action item: \(sender)") } // MARK: Typical application code (not Material-specific) init() { super.init(nibName: nil, bundle: nil) self.title = "Button Bar" } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } // MARK: Catalog by convention extension ButtonBarTypicalUseSwiftExample { @objc class func catalogBreadcrumbs() -> [String] { return ["Button Bar", "Button Bar (Swift)"] } @objc class func catalogIsPrimaryDemo() -> Bool { return false } } // MARK: - Typical application code (not Material-specific) extension ButtonBarTypicalUseSwiftExample { func buttonBarBackgroundColor() -> UIColor { return UIColor(white: 0.1, alpha: 1.0) } func itemTitleTextAttributes () -> [String: Any] { let textColor = UIColor(white: 1, alpha: 0.8) return [NSForegroundColorAttributeName: textColor] } }
apache-2.0
cb31ad3e2b68549aac34fab8eb270576
29.584906
92
0.717767
4.398915
false
false
false
false
meetup-mobile/meetup-ios
Meetup/Meetup/Controllers/HomeViewController.swift
1
4268
import UIKit import RxSwift class HomeViewController: UIViewController, LocationServiceDelegate { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subtitleLabel: UILabel! @IBOutlet weak var signOutButton: UIBarButtonItem! @IBOutlet weak var recentlyViewedView: RecentlyViewedView! internal var locationService: LocationServiceProtocol! internal var userData: UserDataProtocol! private let disposeBag = DisposeBag() private var currentLocation: LocationProtocol? override func viewDidLoad() { super.viewDidLoad() self.locationService.delegate = self self.setRightBarButtonItem() } override func viewWillAppear(_ animated: Bool) { self.recentlyViewedView.reloadData() } @IBAction func onNavigationMenuItemClick(_ sender: UIButton) { let nearbyPlacesVC = UIStoryboard(name: "Main", bundle: nil) .instantiateViewController(withIdentifier: Constants.ViewControllerIdentifiers.NearbyViewController) as! NearbyViewController nearbyPlacesVC.placeType = PlaceType(rawValue: sender.tag) nearbyPlacesVC.currentLocation = self.currentLocation self.navigationController?.show(nearbyPlacesVC, sender: self) } func onSignOutButtonClick() { self.startLoading() self.userData.signOut() self.changeInitialViewController(identifier: "homeVC") self.showSuccess(withStatus: "You have signed out successfully") } func locationService(_ service: LocationServiceProtocol, didUpdateLocation location: LocationProtocol) { self.currentLocation = location self.setTitle(location: location) } func locationService(_ service: LocationServiceProtocol, didFailWithError error: Error) { self.clearTitle() } private func setTitle(location: LocationProtocol) { var title: String? var subtitle: String? func createSecondaryTitle(_ location: LocationProtocol) -> String? { var subtitle: String? let locationLocality = location.locality ?? "" let locationThoroughfare = location.thoroughfare ?? "" let locationSubThoroughfare = location.subThoroughfare ?? "" if !locationLocality.isEmpty { subtitle = locationLocality } if !locationThoroughfare.isEmpty && (subtitle ?? "").isEmpty { subtitle = "\(locationThoroughfare) \(locationSubThoroughfare)" } else if !locationThoroughfare.isEmpty && (subtitle ?? "").isEmpty { subtitle! += ", \(locationThoroughfare) \(locationSubThoroughfare)" } return subtitle } let locationName = location.name ?? "" if locationName.isEmpty { title = createSecondaryTitle(location) } else { title = locationName subtitle = createSecondaryTitle(location) } self.titleLabel.text = title self.subtitleLabel.text = subtitle } private func clearTitle() { self.titleLabel.text = "Unknown location" self.subtitleLabel.text = nil } private func setRightBarButtonItem() { if self.userData.isLoggedIn() { let signOutButton = UIBarButtonItem( title: "Sign Out", style: .plain, target: self, action: #selector(HomeViewController.onSignOutButtonClick)) self.navigationItem.rightBarButtonItem = signOutButton } else { self.navigationItem.rightBarButtonItem = nil } } private func changeInitialViewController(identifier: String) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let initialViewController = storyboard .instantiateViewController(withIdentifier: identifier) UIApplication.shared.keyWindow?.rootViewController = initialViewController } }
apache-2.0
9acc1fadd58d7d2934560fdec67535ee
30.614815
112
0.615511
5.94429
false
false
false
false
sharath-cliqz/browser-ios
Client/Frontend/Reader/ReaderModeUtils.swift
2
4046
/* 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 struct ReaderModeUtils { static let DomainPrefixesToSimplify = ["www.", "mobile.", "m.", "blog."] static func simplifyDomain(_ domain: String) -> String { for prefix in DomainPrefixesToSimplify { if domain.hasPrefix(prefix) { return domain.substring(from: domain.characters.index(domain.startIndex, offsetBy: prefix.characters.count)) } } return domain } static func generateReaderContent(_ readabilityResult: ReadabilityResult, initialStyle: ReaderModeStyle) -> String? { if let stylePath = Bundle.main.path(forResource: "Reader", ofType: "css") { do { let css = try NSString(contentsOfFile: stylePath, encoding: String.Encoding.utf8.rawValue) if let tmplPath = Bundle.main.path(forResource: "Reader", ofType: "html") { do { let tmpl = try NSMutableString(contentsOfFile: tmplPath, encoding: String.Encoding.utf8.rawValue) tmpl.replaceOccurrences(of: "%READER-CSS%", with: css as String, options: NSString.CompareOptions(), range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrences(of: "%READER-STYLE%", with: initialStyle.encode(), options: NSString.CompareOptions(), range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrences(of: "%READER-DOMAIN%", with: simplifyDomain(readabilityResult.domain), options: NSString.CompareOptions(), range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrences(of: "%READER-URL%", with: readabilityResult.url, options: NSString.CompareOptions(), range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrences(of: "%READER-TITLE%", with: readabilityResult.title, options: NSString.CompareOptions(), range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrences(of: "%READER-CREDITS%", with: readabilityResult.credits, options: NSString.CompareOptions(), range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrences(of: "%READER-CONTENT%", with: readabilityResult.content, options: NSString.CompareOptions(), range: NSMakeRange(0, tmpl.length)) return tmpl as String } catch _ { } } } catch _ { } } return nil } static func isReaderModeURL(_ url: URL) -> Bool { let scheme = url.scheme, host = url.host, path = url.path return scheme == "http" && host == "localhost" && path == "/reader-mode/page" } static func decodeURL(_ url: URL) -> URL? { if ReaderModeUtils.isReaderModeURL(url) { if let components = URLComponents(url: url, resolvingAgainstBaseURL: false), let queryItems = components.queryItems, queryItems.count == 1 { if let queryItem = queryItems.first, let value = queryItem.value { return URL(string: value) } } } return nil } static func encodeURL(_ url: URL?) -> URL? { let baseReaderModeURL: String = WebServer.sharedInstance.URLForResource("page", module: "reader-mode") if let absoluteString = url?.absoluteString { if let encodedURL = absoluteString.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics) { if let aboutReaderURL = URL(string: "\(baseReaderModeURL)?url=\(encodedURL)") { return aboutReaderURL } } } return nil } }
mpl-2.0
4879e8c59e5ba3563c5d19308b35497f
46.6
152
0.583786
5.213918
false
false
false
false
milseman/swift
stdlib/public/SDK/AppKit/AppKit_FoundationExtensions.swift
20
3123
//===----------------------------------------------------------------------===// // // 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 Foundation @_exported import AppKit // NSCollectionView extensions public extension IndexPath { /// Initialize for use with `NSCollectionView`. public init(item: Int, section: Int) { self.init(indexes: [section, item]) } /// The item of this index path, when used with `NSCollectionView`. /// /// - precondition: The index path must have exactly two elements. public var item : Int { get { precondition(count == 2, "Invalid index path for use with NSCollectionView. This index path must contain exactly two indices specifying the section and item.") return self[1] } set { precondition(count == 2, "Invalid index path for use with NSCollectionView. This index path must contain exactly two indices specifying the section and item.") self[1] = newValue } } /// The section of this index path, when used with `NSCollectionView`. /// /// - precondition: The index path must have exactly two elements. public var section : Int { get { precondition(count == 2, "Invalid index path for use with NSCollectionView. This index path must contain exactly two indices specifying the section and item.") return self[0] } set { precondition(count == 2, "Invalid index path for use with NSCollectionView. This index path must contain exactly two indices specifying the section and item.") self[0] = newValue } } } public extension URLResourceValues { /// Returns all thumbnails as a single NSImage. @available(OSX 10.10, *) public var thumbnail : NSImage? { return allValues[URLResourceKey.thumbnailKey] as? NSImage } /// The color of the assigned label. public var labelColor: NSColor? { return allValues[URLResourceKey.labelColorKey] as? NSColor } /// The icon normally displayed for the resource public var effectiveIcon: AnyObject? { return allValues[URLResourceKey.effectiveIconKey] as? NSImage } /// The custom icon assigned to the resource, if any (Currently not implemented) public var customIcon: NSImage? { return allValues[URLResourceKey.customIconKey] as? NSImage } /// Returns a dictionary of NSImage objects keyed by size. @available(OSX 10.10, *) public var thumbnailDictionary : [URLThumbnailDictionaryItem : NSImage]? { return allValues[URLResourceKey.thumbnailDictionaryKey] as? [URLThumbnailDictionaryItem : NSImage] } }
apache-2.0
95863f7c32f196bb21b3f6178c2fcacc
37.085366
171
0.634966
5.111293
false
false
false
false
PomTTcat/SourceCodeGuideRead_JEFF
RxSwiftGuideRead/RxDemoSelf/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift
2
5065
// // ObservableType+Extensions.swift // RxSwift // // Created by Krunoslav Zaher on 2/21/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if DEBUG import Foundation #endif extension ObservableType { /** Subscribes an event handler to an observable sequence. - parameter on: Action to invoke for each event in the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ public func subscribe(_ on: @escaping (Event<Element>) -> Void) -> Disposable { let observer = AnonymousObserver { e in on(e) } return self.asObservable().subscribe(observer) } /** Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence. - parameter onNext: Action to invoke for each element in the observable sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has gracefully completed, errored, or if the generation is canceled by disposing subscription). - returns: Subscription object used to unsubscribe from the observable sequence. */ public func subscribe(onNext: ((Element) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable { let disposable: Disposable // create Disposables if let disposed = onDisposed { disposable = Disposables.create(with: disposed) } else { disposable = Disposables.create() } // #if DEBUG // let synchronizationTracker = SynchronizationTracker() // #endif // 自定义Error。暂时可以忽略。 let callStack = Hooks.recordCallStackOnError ? Hooks.customCaptureSubscriptionCallstack() : [] // 创建匿名observer。把需要处理的事件都传递给它。 let observer = AnonymousObserver<Element> { event in // #if DEBUG // synchronizationTracker.register(synchronizationErrorMessage: .default) // defer { synchronizationTracker.unregister() } // #endif switch event { case .next(let value): onNext?(value) case .error(let error): if let onError = onError { onError(error) } else { Hooks.defaultErrorHandler(callStack, error) } disposable.dispose() case .completed: onCompleted?() disposable.dispose() } } // 合并两个disposable return Disposables.create( self.asObservable().subscribe(observer), disposable ) } } import class Foundation.NSRecursiveLock extension Hooks { public typealias DefaultErrorHandler = (_ subscriptionCallStack: [String], _ error: Error) -> Void public typealias CustomCaptureSubscriptionCallstack = () -> [String] fileprivate static let _lock = RecursiveLock() fileprivate static var _defaultErrorHandler: DefaultErrorHandler = { subscriptionCallStack, error in #if DEBUG let serializedCallStack = subscriptionCallStack.joined(separator: "\n") print("Unhandled error happened: \(error)\n subscription called from:\n\(serializedCallStack)") #endif } fileprivate static var _customCaptureSubscriptionCallstack: CustomCaptureSubscriptionCallstack = { #if DEBUG return Thread.callStackSymbols #else return [] #endif } /// Error handler called in case onError handler wasn't provided. public static var defaultErrorHandler: DefaultErrorHandler { get { _lock.lock(); defer { _lock.unlock() } return _defaultErrorHandler } set { _lock.lock(); defer { _lock.unlock() } _defaultErrorHandler = newValue } } /// Subscription callstack block to fetch custom callstack information. public static var customCaptureSubscriptionCallstack: CustomCaptureSubscriptionCallstack { get { _lock.lock(); defer { _lock.unlock() } return _customCaptureSubscriptionCallstack } set { _lock.lock(); defer { _lock.unlock() } _customCaptureSubscriptionCallstack = newValue } } }
mit
9739ffa52c473180fe29e5a010d4e464
35.735294
169
0.583667
5.729358
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/People/InvitePersonViewController.swift
1
31783
import Foundation import UIKit import WordPressShared import SVProgressHUD /// Allows the user to Invite Followers / Users /// class InvitePersonViewController: UITableViewController { // MARK: - Public Properties /// Target Blog /// @objc var blog: Blog! /// Core Data Context /// @objc let context = ContextManager.sharedInstance().mainContext // MARK: - Private Properties /// Invitation Username / Email /// fileprivate var usernameOrEmail: String? { didSet { refreshUsernameCell() validateInvitation() } } /// Invitation Role /// fileprivate var role: RemoteRole? { didSet { refreshRoleCell() validateInvitation() } } /// Invitation Message /// fileprivate var message: String? { didSet { refreshMessageTextView() // Note: This is a workaround. For some reason, the textView's properties are getting reset setupMessageTextView() } } /// Roles available for the current site /// fileprivate var availableRoles: [RemoteRole] { let blogRoles = blog?.sortedRoles ?? [] var roles = [RemoteRole]() let inviteRole: RemoteRole if blog.isPrivateAtWPCom() { inviteRole = RemoteRole.viewer } else { inviteRole = RemoteRole.follower } roles += blogRoles.map({ $0.toUnmanaged() }) roles.append(inviteRole) return roles } private lazy var inviteActivityView: UIActivityIndicatorView = { let activityView = UIActivityIndicatorView(style: .medium) activityView.startAnimating() return activityView }() private var updatingInviteLinks = false { didSet { guard updatingInviteLinks != oldValue else { return } if updatingInviteLinks == false { generateShareCell.accessoryView = nil disableLinksCell.accessoryView = nil return } if blog.inviteLinks?.count == 0 { generateShareCell.accessoryView = inviteActivityView } else { disableLinksCell.accessoryView = inviteActivityView } } } private var sortedInviteLinks: [InviteLinks] { guard let links = blog.inviteLinks?.array as? [InviteLinks] else { return [] } return availableRoles.compactMap { role -> InviteLinks? in return links.first { link -> Bool in link.role == role.slug } } } private var selectedInviteLinkIndex = 0 { didSet { tableView.reloadData() } } private var currentInviteLink: InviteLinks? { let links = sortedInviteLinks guard links.count > 0 && selectedInviteLinkIndex < links.count else { return nil } return links[selectedInviteLinkIndex] } private let rolesDefinitionUrl = "https://wordpress.com/support/user-roles/" private let messageCharacterLimit = 500 // MARK: - Outlets /// Username Cell /// @IBOutlet fileprivate var usernameCell: UITableViewCell! { didSet { setupUsernameCell() refreshUsernameCell() } } /// Role Cell /// @IBOutlet fileprivate var roleCell: UITableViewCell! { didSet { setupRoleCell() refreshRoleCell() } } /// Message Placeholder Label /// @IBOutlet private var placeholderLabel: UILabel! { didSet { setupPlaceholderLabel() } } /// Message Cell /// @IBOutlet private var messageTextView: UITextView! { didSet { setupMessageTextView() refreshMessageTextView() } } @IBOutlet private var generateShareCell: UITableViewCell! { didSet { refreshGenerateShareCell() } } @IBOutlet private var currentInviteCell: UITableViewCell! { didSet { refreshCurrentInviteCell() } } @IBOutlet private var expirationCell: UITableViewCell! { didSet { refreshExpirationCell() } } @IBOutlet private var disableLinksCell: UITableViewCell! { didSet { refreshDisableLinkCell() } } // MARK: - View Lifecyle Methods override func viewDidLoad() { super.viewDidLoad() setupNavigationBar() setupDefaultRole() WPStyleGuide.configureColors(view: view, tableView: tableView) WPStyleGuide.configureAutomaticHeightRows(for: tableView) // Use the system separator color rather than the one defined by WPStyleGuide // so cell separators stand out in darkmode. tableView.separatorColor = .separator if blog.isWPForTeams() { syncInviteLinks() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.deselectSelectedRowWithAnimation(true) } // MARK: - UITableView Methods override func numberOfSections(in tableView: UITableView) -> Int { // Hide the last section if the site is not a p2. let count = super.numberOfSections(in: tableView) return blog.isWPForTeams() ? count : count - 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard blog.isWPForTeams(), section == numberOfSections(in: tableView) - 1 else { // If not a P2 or not the last section, just call super. return super.tableView(tableView, numberOfRowsInSection: section) } // One cell for no cached inviteLinks. Otherwise 4. return blog.inviteLinks?.count == 0 ? 1 : 4 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard Section.inviteLink == Section(rawValue: section) else { return nil } return NSLocalizedString("Invite Link", comment: "Title for the Invite Link section of the Invite Person screen.") } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { let sectionType = Section(rawValue: section) var footerText = sectionType?.footerText if sectionType == .message, let footerFormat = footerText { footerText = String(format: footerFormat, messageCharacterLimit) } return footerText } override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { addTapGesture(toView: view, inSection: section) WPStyleGuide.configureTableViewSectionFooter(view) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Workaround for UIKit issue where labels text are set to nil // when user changes system font size in static tables (dynamic type) switch Section(rawValue: indexPath.section) { case .username: refreshUsernameCell() case .role: setupRoleCell() refreshRoleCell() case .message: refreshMessageTextView() case .inviteLink: refreshInviteLinkCell(indexPath: indexPath) case .none: break } return super.tableView(tableView, cellForRowAt: indexPath) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard indexPath.section == Section.inviteLink.rawValue else { // There is no valid `super` implementation so do not call it. return } tableView.deselectRow(at: indexPath, animated: true) handleInviteLinkRowTapped(indexPath: indexPath) } // MARK: - Storyboard Methods override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let rawIdentifier = segue.identifier, let identifier = SegueIdentifier(rawValue: rawIdentifier) else { return } switch identifier { case .Username: setupUsernameSegue(segue) case .Role: setupRoleSegue(segue) case .Message: setupMessageSegue(segue) case .InviteRole: setupInviteRoleSegue(segue) } } fileprivate func setupUsernameSegue(_ segue: UIStoryboardSegue) { guard let textViewController = segue.destination as? SettingsTextViewController else { return } let title = NSLocalizedString("Recipient", comment: "Invite Person: Email or Username Edition Title") let placeholder = NSLocalizedString("Email or Username…", comment: "A placeholder for the username textfield.") let hint = NSLocalizedString("Email or Username of the person that should receive your invitation.", comment: "Username Placeholder") textViewController.title = title textViewController.text = usernameOrEmail textViewController.placeholder = placeholder textViewController.hint = hint textViewController.onValueChanged = { [unowned self] value in self.usernameOrEmail = value.nonEmptyString() } // Note: Let's disable validation, since we need to allow Username OR Email textViewController.validatesInput = false textViewController.autocorrectionType = .no textViewController.mode = .email } fileprivate func setupRoleSegue(_ segue: UIStoryboardSegue) { guard let roleViewController = segue.destination as? RoleViewController else { return } roleViewController.roles = availableRoles roleViewController.selectedRole = role?.slug roleViewController.onChange = { [unowned self] newRole in self.role = self.availableRoles.first(where: { $0.slug == newRole }) } } fileprivate func setupMessageSegue(_ segue: UIStoryboardSegue) { guard let textViewController = segue.destination as? SettingsMultiTextViewController else { return } let title = NSLocalizedString("Message", comment: "Invite Message Editor's Title") let hintFormat = NSLocalizedString("Optional message up to %1$d characters to be included in the invitation.", comment: "Invite: Message Hint. %1$d is the maximum number of characters allowed.") let hint = String(format: hintFormat, messageCharacterLimit) textViewController.title = title textViewController.text = message textViewController.hint = hint textViewController.isPassword = false textViewController.maxCharacterCount = messageCharacterLimit textViewController.onValueChanged = { [unowned self] value in self.message = value } } private func setupInviteRoleSegue(_ segue: UIStoryboardSegue) { guard let roleViewController = segue.destination as? RoleViewController else { return } roleViewController.roles = availableRoles roleViewController.selectedRole = currentInviteLink?.role roleViewController.onChange = { [unowned self] newRole in self.selectedInviteLinkIndex = self.availableRoles.firstIndex(where: { $0.slug == newRole }) ?? 0 } } // MARK: - Private Enums private enum SegueIdentifier: String { case Username = "username" case Role = "role" case Message = "message" case InviteRole = "inviteRole" } // The case order matches the custom sections order in People.storyboard. private enum Section: Int { case username case role case message case inviteLink var footerText: String? { switch self { case .role: return NSLocalizedString("Learn more about roles", comment: "Footer text for Invite People role field.") case .message: // messageCharacterLimit cannot be accessed here, so the caller will insert it in the string. return NSLocalizedString("Optional: Enter a custom message up to %1$d characters to be sent with your invitation.", comment: "Footer text for Invite People message field. %1$d is the maximum number of characters allowed.") case .inviteLink: return NSLocalizedString("Use this link to onboard your team members without having to invite them one by one. Anybody visiting this URL will be able to sign up to your organization, even if they received the link from somebody else, so make sure that you share it with trusted people.", comment: "Footer text for Invite Links section of the Invite People screen.") default: return nil } } } // These represent the rows of the invite links section, in the order the rows appear. private enum InviteLinkRow: Int { case generateShare case role case expires case disable } } // MARK: - Helpers: Actions // extension InvitePersonViewController { @IBAction func cancelWasPressed() { dismiss(animated: true) } @IBAction func sendWasPressed() { guard let recipient = usernameOrEmail else { return } // Notes: // - We'll hit the actual send call once the dismiss is wrapped up. // - If, for networking reasons, the call fails instantly, UIAlertViewController presentation will // fail, because it'll get attached to a VC that's getting dismissed. // // Thank you Apple . I love you too. // dismiss(animated: true) { guard let role = self.role else { return } self.sendInvitation(self.blog, recipient: recipient, role: role.slug, message: self.message ?? "") } } @objc func sendInvitation(_ blog: Blog, recipient: String, role: String, message: String) { guard let service = PeopleService(blog: blog, context: context) else { return } service.sendInvitation(recipient, role: role, message: message, success: { let success = NSLocalizedString("Invitation Sent!", comment: "The app successfully sent an invitation") SVProgressHUD.showDismissibleSuccess(withStatus: success) }, failure: { error in self.handleSendError() { self.sendInvitation(blog, recipient: recipient, role: role, message: message) } }) } @objc func handleSendError(_ onRetry: @escaping (() -> Void)) { let message = NSLocalizedString("There has been an unexpected error while sending your Invitation", comment: "Invite Failed Message") let cancelText = NSLocalizedString("Cancel", comment: "Cancels an Action") let retryText = NSLocalizedString("Try Again", comment: "Retries an Action") let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert) alertController.addCancelActionWithTitle(cancelText) alertController.addDefaultActionWithTitle(retryText) { action in onRetry() } // Note: This viewController might not be visible anymore alertController.presentFromRootViewController() } private func addTapGesture(toView footerView: UIView, inSection section: Int) { guard let footer = footerView as? UITableViewHeaderFooterView else { return } guard Section(rawValue: section) == .role else { footer.textLabel?.isUserInteractionEnabled = false footer.accessibilityTraits = .staticText footer.gestureRecognizers?.removeAll() return } footer.textLabel?.isUserInteractionEnabled = true footer.accessibilityTraits = .link let tap = UITapGestureRecognizer(target: self, action: #selector(handleRoleFooterTap(_:))) footer.addGestureRecognizer(tap) } @objc private func handleRoleFooterTap(_ sender: UITapGestureRecognizer) { guard let url = URL(string: rolesDefinitionUrl) else { return } let webViewController = WebViewControllerFactory.controller(url: url) let navController = UINavigationController(rootViewController: webViewController) present(navController, animated: true) } } // MARK: - Helpers: Validation // private extension InvitePersonViewController { func validateInvitation() { guard let usernameOrEmail = usernameOrEmail, let service = PeopleService(blog: blog, context: context) else { sendActionEnabled = false return } guard let role = role else { return } service.validateInvitation(usernameOrEmail, role: role.slug, success: { [weak self] in guard self?.shouldHandleValidationResponse(usernameOrEmail) == true else { return } self?.sendActionEnabled = true }, failure: { [weak self] error in guard self?.shouldHandleValidationResponse(usernameOrEmail) == true else { return } self?.sendActionEnabled = false self?.handleValidationError(error) }) } func shouldHandleValidationResponse(_ requestUsernameOrEmail: String) -> Bool { // Handle only whenever the recipient didn't change let recipient = usernameOrEmail ?? String() return recipient == requestUsernameOrEmail } func handleValidationError(_ error: Error) { guard let error = error as? PeopleServiceRemote.ResponseError else { return } let messageMap: [PeopleServiceRemote.ResponseError: String] = [ .invalidInputError: NSLocalizedString("The specified user cannot be found. Please, verify if it's correctly spelt.", comment: "People: Invitation Error"), .userAlreadyHasRoleError: NSLocalizedString("The user already has the specified role. Please, try assigning a different role.", comment: "People: Invitation Error"), .unknownError: NSLocalizedString("Unknown error has occurred", comment: "People: Invitation Error") ] let message = messageMap[error] ?? messageMap[.unknownError]! let title = NSLocalizedString("Sorry!", comment: "Invite Validation Alert") let okTitle = NSLocalizedString("OK", comment: "Alert dismissal title") let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addDefaultActionWithTitle(okTitle) present(alert, animated: true) } var sendActionEnabled: Bool { get { return navigationItem.rightBarButtonItem?.isEnabled ?? false } set { navigationItem.rightBarButtonItem?.isEnabled = newValue } } } // MARK: - Invite Links related. // private extension InvitePersonViewController { func refreshInviteLinkCell(indexPath: IndexPath) { guard let row = InviteLinkRow(rawValue: indexPath.row) else { return } switch row { case .generateShare: refreshGenerateShareCell() case .role: refreshCurrentInviteCell() case .expires: refreshExpirationCell() case .disable: refreshDisableLinkCell() } } func refreshGenerateShareCell() { if blog.inviteLinks?.count == 0 { generateShareCell.textLabel?.text = NSLocalizedString("Generate new link", comment: "Title. A call to action to generate a new invite link.") generateShareCell.textLabel?.font = WPStyleGuide.tableviewTextFont() } else { generateShareCell.textLabel?.attributedText = createAttributedShareInviteText() } generateShareCell.textLabel?.font = WPStyleGuide.tableviewTextFont() generateShareCell.textLabel?.textAlignment = .center generateShareCell.textLabel?.textColor = .primary } func createAttributedShareInviteText() -> NSAttributedString { let pStyle = NSMutableParagraphStyle() pStyle.alignment = .center let font = WPStyleGuide.tableviewTextFont() let textAttributes: [NSAttributedString.Key: Any] = [ .font: font, .paragraphStyle: pStyle ] let image = UIImage.gridicon(.shareiOS) let attachment = NSTextAttachment(image: image) attachment.bounds = CGRect(x: 0, y: (font.capHeight - image.size.height)/2, width: image.size.width, height: image.size.height) let textStr = NSAttributedString(string: NSLocalizedString("Share invite link", comment: "Title. A call to action to share an invite link."), attributes: textAttributes) let attrStr = NSMutableAttributedString(attachment: attachment) attrStr.append(NSAttributedString(string: " ")) attrStr.append(textStr) return attrStr } func refreshCurrentInviteCell() { guard selectedInviteLinkIndex < availableRoles.count else { return } currentInviteCell.textLabel?.text = NSLocalizedString("Role", comment: "Title. Indicates the user role an invite link is for.") currentInviteCell.textLabel?.textColor = .text // sortedInviteLinks and availableRoles should be complimentary. We can cheat a little and // get the localized "display name" to use from availableRoles rather than // trying to capitalize the role slug from the current invite link. let role = availableRoles[selectedInviteLinkIndex] currentInviteCell.detailTextLabel?.text = role.name WPStyleGuide.configureTableViewCell(currentInviteCell) } func refreshExpirationCell() { guard let invite = currentInviteLink, invite.expiry > 0 else { return } expirationCell.textLabel?.text = NSLocalizedString("Expires on", comment: "Title. Indicates an expiration date.") expirationCell.textLabel?.textColor = .text let formatter = DateFormatter() formatter.dateStyle = .medium let date = Date(timeIntervalSince1970: Double(invite.expiry)) expirationCell.detailTextLabel?.text = formatter.string(from: date) WPStyleGuide.configureTableViewCell(expirationCell) } func refreshDisableLinkCell() { disableLinksCell.textLabel?.text = NSLocalizedString("Disable invite link", comment: "Title. A call to action to disable invite links.") disableLinksCell.textLabel?.font = WPStyleGuide.tableviewTextFont() disableLinksCell.textLabel?.textColor = .error disableLinksCell.textLabel?.textAlignment = .center } func syncInviteLinks() { guard let siteID = blog.dotComID?.intValue else { return } let service = PeopleService(blog: blog, context: context) service?.fetchInviteLinks(siteID, success: { [weak self] _ in self?.bumpStat(event: .inviteLinksGetStatus, error: nil) self?.updatingInviteLinks = false self?.tableView.reloadData() }, failure: { [weak self] error in // Fail silently. self?.bumpStat(event: .inviteLinksGetStatus, error: error) self?.updatingInviteLinks = false DDLogError("Error syncing invite links. \(error)") }) } func generateInviteLinks() { guard updatingInviteLinks == false, let siteID = blog.dotComID?.intValue else { return } updatingInviteLinks = true let service = PeopleService(blog: blog, context: context) service?.generateInviteLinks(siteID, success: { [weak self] _ in self?.bumpStat(event: .inviteLinksGenerate, error: nil) self?.updatingInviteLinks = false self?.tableView.reloadData() }, failure: { [weak self] error in self?.bumpStat(event: .inviteLinksGenerate, error: error) self?.updatingInviteLinks = false self?.displayNotice(title: NSLocalizedString("Unable to create new invite links.", comment: "An error message shown when there is an issue creating new invite links.")) DDLogError("Error generating invite links. \(error)") }) } func shareInviteLink() { guard let link = currentInviteLink?.link, let url = URL(string: link) as NSURL? else { return } let controller = PostSharingController() controller.shareURL(url: url, fromRect: generateShareCell.frame, inView: view, inViewController: self) bumpStat(event: .inviteLinksShare, error: nil) } func handleDisableTapped() { guard updatingInviteLinks == false else { return } let title = NSLocalizedString("Disable invite link", comment: "Title. Title of a prompt to disable group invite links.") let message = NSLocalizedString("Once this invite link is disabled, nobody will be able to use it to join your team. Are you sure?", comment: "Warning message about disabling group invite links.") let controller = UIAlertController(title: title, message: message, preferredStyle: .alert) controller.addCancelActionWithTitle(NSLocalizedString("Cancel", comment: "Title. Title of a cancel button. Tapping disnisses an alert.")) let action = UIAlertAction(title: NSLocalizedString("Disable", comment: "Title. Title of a button that will disable group invite links when tapped."), style: .destructive) { [weak self] _ in self?.disableInviteLinks() } controller.addAction(action) controller.preferredAction = action present(controller, animated: true, completion: nil) } func disableInviteLinks() { guard let siteID = blog.dotComID?.intValue else { return } updatingInviteLinks = true let service = PeopleService(blog: blog, context: context) service?.disableInviteLinks(siteID, success: { [weak self] in self?.bumpStat(event: .inviteLinksDisable, error: nil) self?.updatingInviteLinks = false self?.tableView.reloadData() }, failure: { [weak self] error in self?.bumpStat(event: .inviteLinksDisable, error: error) self?.updatingInviteLinks = false self?.displayNotice(title: NSLocalizedString("Unable to disable invite links.", comment: "An error message shown when there is an issue creating new invite links.")) DDLogError("Error disabling invite links. \(error)") }) } func handleInviteLinkRowTapped(indexPath: IndexPath) { guard let row = InviteLinkRow(rawValue: indexPath.row) else { return } switch row { case .generateShare: if blog.inviteLinks?.count == 0 { generateInviteLinks() } else { shareInviteLink() } case .disable: handleDisableTapped() default: // .role is handled by a segue. // .expires is a no op break } } func bumpStat(event: WPAnalyticsEvent, error: Error?) { let resultKey = "invite_links_action_result" let errorKey = "invite_links_action_error_message" var props = [AnyHashable: Any]() if let err = error { props = [ resultKey: "error", errorKey: "\(err)" ] } else { props = [ resultKey: "success" ] } WPAnalytics.track(event, properties: props, blog: blog) } } // MARK: - Private Helpers: Initializing Interface // private extension InvitePersonViewController { func setupUsernameCell() { usernameCell.accessoryType = .disclosureIndicator WPStyleGuide.configureTableViewCell(usernameCell) } func setupRoleCell() { roleCell.textLabel?.text = NSLocalizedString("Role", comment: "User's Role") roleCell.textLabel?.textColor = .text roleCell.accessoryType = .disclosureIndicator WPStyleGuide.configureTableViewCell(roleCell) } func setupMessageTextView() { messageTextView.font = WPStyleGuide.tableviewTextFont() messageTextView.textColor = .text messageTextView.backgroundColor = .listForeground messageTextView.delegate = self } func setupPlaceholderLabel() { placeholderLabel.text = NSLocalizedString("Custom message…", comment: "Placeholder for Invite People message field.") placeholderLabel.font = WPStyleGuide.tableviewTextFont() placeholderLabel.textColor = UIColor.textPlaceholder } func setupNavigationBar() { title = NSLocalizedString("Invite People", comment: "Invite People Title") navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelWasPressed)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Invite", comment: "Send Person Invite"), style: .plain, target: self, action: #selector(sendWasPressed)) // By default, Send is disabled navigationItem.rightBarButtonItem?.isEnabled = false } func setupDefaultRole() { guard let lastRole = availableRoles.last else { return } role = lastRole } } // MARK: - Private Helpers: Refreshing Interface // private extension InvitePersonViewController { func refreshUsernameCell() { guard let usernameOrEmail = usernameOrEmail?.nonEmptyString() else { usernameCell.textLabel?.text = NSLocalizedString("Email or Username…", comment: "Invite Username Placeholder") usernameCell.textLabel?.textColor = .textPlaceholder return } usernameCell.textLabel?.text = usernameOrEmail usernameCell.textLabel?.textColor = .text } func refreshRoleCell() { roleCell.detailTextLabel?.text = role?.name } func refreshMessageTextView() { messageTextView.text = message refreshPlaceholderLabel() } func refreshPlaceholderLabel() { placeholderLabel?.isHidden = !messageTextView.text.isEmpty } } // MARK: - UITextViewDelegate extension InvitePersonViewController: UITextViewDelegate { func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { // This calls the segue in People.storyboard // that shows the SettingsMultiTextViewController. performSegue(withIdentifier: "message", sender: nil) return false } }
gpl-2.0
e3c08cb0b4511e5e4450879f8361ae5c
34.94457
381
0.626027
5.402074
false
false
false
false
steryokhin/AsciiArtPlayer
src/AsciiArtPlayer/Pods/SwiftyUtils/Sources/Extensions/UIKit/UITextFieldExtension.swift
2
1119
// // Created by Tom Baranes on 18/01/2017. // Copyright © 2017 Tom Baranes. All rights reserved. // import UIKit // MARK: - Clear button extension UITextField { public func setClearButton(with image: UIImage) { let clearButton = UIButton(type: .custom) clearButton.setImage(image, for: .normal) clearButton.frame = CGRect(origin: .zero, size: image.size) clearButton.contentMode = .left clearButton.addTarget(self, action: #selector(clear), for: .touchUpInside) clearButtonMode = .never rightView = clearButton rightViewMode = .whileEditing } func clear() { text = "" sendActions(for: .editingChanged) } } // MARK: - Placeholder public extension UITextField { public func setPlaceHolderTextColor(_ color: UIColor) { guard let placeholder = placeholder, placeholder.isNotEmpty else { return } attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: color]) } }
mit
35eec1c7ffc74b16fe1083c61459f6ff
25
103
0.629696
4.903509
false
false
false
false
witekbobrowski/Stanford-CS193p-Winter-2017
Faceit/Faceit/EmotionsViewController.swift
1
2787
// // EmotionsViewController.swift // Faceit // // Created by Witek on 24/04/2017. // Copyright © 2017 Witek Bobrowski. All rights reserved. // import UIKit class EmotionsViewController: UITableViewController { fileprivate var emotionalFaces: [(name: String, expression: FacialExpression)] = [ ("sad", FacialExpression(eyes: .closed, mouth: .frown)), ("happy", FacialExpression(eyes: .open, mouth: .smile)), ("worried", FacialExpression(eyes: .open, mouth: .smirk)) ] @IBAction func addEmotionalFace(from segue: UIStoryboardSegue) { if let editor = segue.source as? ExpressionEditorViewController { emotionalFaces.append((editor.name, editor.expression)) tableView.reloadData() } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { var destinationViewController = segue.destination if let navigationController = destinationViewController as? UINavigationController { destinationViewController = navigationController.visibleViewController ?? destinationViewController } if let faceViewController = destinationViewController as? FaceViewController, let cell = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) { faceViewController.expression = emotionalFaces[indexPath.row].expression faceViewController.navigationItem.title = (sender as? UIButton)?.currentTitle } else if destinationViewController is ExpressionEditorViewController { if let popoverPresentationController = segue.destination.popoverPresentationController { popoverPresentationController.delegate = self } } } } extension EmotionsViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return emotionalFaces.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Emotion Cell", for: indexPath) cell.textLabel?.text = emotionalFaces[indexPath.row].name return cell } } extension EmotionsViewController: UIPopoverPresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { if traitCollection.verticalSizeClass == .compact { return .none } else if traitCollection.horizontalSizeClass == .compact { return .overFullScreen } else { return .none } } }
mit
12536200dcc4c04300bedaee49e75657
37.164384
142
0.685212
5.560878
false
false
false
false
joshuapinter/react-native-unified-contacts
RNUnifiedContacts/RNUnifiedContacts.swift
1
29923
// // RNUnifiedContacts.swift // RNUnifiedContacts // // Copyright © 2016 Joshua Pinter. All rights reserved. // import Contacts import ContactsUI import Foundation @available(iOS 9.0, *) @objc(RNUnifiedContacts) class RNUnifiedContacts: NSObject { // iOS Reference: https://developer.apple.com/library/ios/documentation/Contacts/Reference/CNContact_Class/#//apple_ref/doc/constant_group/Metadata_Keys let keysToFetch = [ CNContactBirthdayKey, CNContactDatesKey, CNContactDepartmentNameKey, CNContactEmailAddressesKey, CNContactFamilyNameKey, CNContactGivenNameKey, CNContactIdentifierKey, CNContactImageDataAvailableKey, // CNContactImageDataKey, CNContactInstantMessageAddressesKey, CNContactJobTitleKey, CNContactMiddleNameKey, CNContactNamePrefixKey, CNContactNameSuffixKey, CNContactNicknameKey, CNContactNonGregorianBirthdayKey, // CNContactNoteKey, // NOTE: iOS 13 does not allow fetching of notes without the com.apple.developer.contacts.notes entitlement, which requires special permission from Apple. CNContactOrganizationNameKey, CNContactPhoneNumbersKey, CNContactPhoneticFamilyNameKey, CNContactPhoneticGivenNameKey, CNContactPhoneticMiddleNameKey, // CNContactPhoneticOrganizationNameKey, CNContactPostalAddressesKey, CNContactPreviousFamilyNameKey, CNContactRelationsKey, CNContactSocialProfilesKey, CNContactThumbnailImageDataKey, CNContactTypeKey, CNContactUrlAddressesKey, ] @objc func userCanAccessContacts(_ callback: (Array<Bool>) -> ()) -> Void { let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts) switch authorizationStatus{ case .notDetermined, .restricted, .denied: callback([false]) case .authorized: callback([true]) } } @objc func requestAccessToContacts(_ callback: @escaping (Array<Bool>) -> ()) -> Void { userCanAccessContacts() { (userCanAccessContacts) in if (userCanAccessContacts == [true]) { callback([true]) return } CNContactStore().requestAccess(for: CNEntityType.contacts) { (userCanAccessContacts, error) in if (userCanAccessContacts) { callback([true]) return } else { callback([false]) return } } } } @objc func alreadyRequestedAccessToContacts(_ callback: (Array<Bool>) -> ()) -> Void { let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts) switch authorizationStatus{ case .notDetermined: callback([false]) case .authorized, .restricted, .denied: callback([true]) } } @objc func getContact(_ identifier: String, callback: (NSArray) -> () ) -> Void { let cNContact = getCNContact( identifier, keysToFetch: keysToFetch as [CNKeyDescriptor] ) if ( cNContact == nil ) { callback( ["Could not find a contact with the identifier ".appending(identifier), NSNull()] ) return } let contactAsDictionary = convertCNContactToDictionary( cNContact! ) callback( [NSNull(), contactAsDictionary] ) } @objc func getGroup(_ identifier: String, callback: (NSArray) -> () ) -> Void { let cNGroup = getCNGroup( identifier ) if ( cNGroup == nil ) { callback( ["Could not find a group with the identifier ".appending(identifier), NSNull()] ) return } let groupAsDictionary = convertCNGroupToDictionary( cNGroup! ) callback( [NSNull(), groupAsDictionary] ) } // Pseudo overloads getContacts but with no searchText. // Makes it easy to get all the Contacts with not passing anything. // NOTE: I tried calling the two methods the same but it barfed. It should be // allowed but perhaps how React Native is handling it, it won't work. PR // possibility. // @objc func getContacts(_ callback: (NSObject) -> ()) -> Void { searchContacts(nil) { (result: NSObject) in callback(result) } } @objc func getGroups(_ callback: (NSArray) -> ()) -> Void { let contactStore = CNContactStore() do { var cNGroups = [CNGroup]() try cNGroups = contactStore.groups(matching: nil) var groups = [NSDictionary](); for cNGroup in cNGroups { groups.append( convertCNGroupToDictionary(cNGroup) ) } callback([NSNull(), groups]) } catch let error as NSError { NSLog("Problem getting groups.") NSLog(error.localizedDescription) callback([error.localizedDescription, NSNull()]) } } @objc func contactsInGroup(_ identifier: String, callback: (NSArray) -> ()) -> Void { let contactStore = CNContactStore() do { var cNContacts = [CNContact]() let predicate = CNContact.predicateForContactsInGroup(withIdentifier: identifier) let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch as [CNKeyDescriptor]) fetchRequest.predicate = predicate fetchRequest.sortOrder = CNContactSortOrder.userDefault try contactStore.enumerateContacts(with: fetchRequest) { (cNContact, pointer) -> Void in cNContacts.append(cNContact) } var contacts = [NSDictionary](); for cNContact in cNContacts { contacts.append( convertCNContactToDictionary(cNContact) ) } callback([NSNull(), contacts]) } catch let error as NSError { NSLog("Problem getting contacts.") NSLog(error.localizedDescription) callback([error.localizedDescription, NSNull()]) } } @objc func searchContacts(_ searchText: String?, callback: (NSArray) -> ()) -> Void { let contactStore = CNContactStore() do { var cNContacts = [CNContact]() let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch as [CNKeyDescriptor]) fetchRequest.sortOrder = CNContactSortOrder.givenName try contactStore.enumerateContacts(with: fetchRequest) { (cNContact, pointer) -> Void in if searchText == nil { // Add all Contacts if no searchText is provided. cNContacts.append(cNContact) } else { // If the Contact contains the search string then add it. if self.contactContainsText( cNContact, searchText: searchText! ) { cNContacts.append(cNContact) } } } var contacts = [NSDictionary](); for cNContact in cNContacts { contacts.append( convertCNContactToDictionary(cNContact) ) } callback([NSNull(), contacts]) } catch let error as NSError { NSLog("Problem getting contacts.") NSLog(error.localizedDescription) callback([error.localizedDescription, NSNull()]) } } @objc func addContact(_ contactData: NSDictionary, callback: (NSArray) -> () ) -> Void { let contactStore = CNContactStore() let mutableContact = CNMutableContact() let saveRequest = CNSaveRequest() // TODO: Extend method to handle more fields. // if (contactData["givenName"] != nil) { mutableContact.givenName = contactData["givenName"] as! String } if (contactData["familyName"] != nil) { mutableContact.familyName = contactData["familyName"] as! String } if (contactData["organizationName"] != nil) { mutableContact.organizationName = contactData["organizationName"] as! String } for phoneNumber in contactData["phoneNumbers"] as! NSArray { let phoneNumberAsCNLabeledValue = convertPhoneNumberToCNLabeledValue( phoneNumber as! NSDictionary ) mutableContact.phoneNumbers.append( phoneNumberAsCNLabeledValue ) } for emailAddress in contactData["emailAddresses"] as! NSArray { let emailAddressAsCNLabeledValue = convertEmailAddressToCNLabeledValue ( emailAddress as! NSDictionary ) mutableContact.emailAddresses.append( emailAddressAsCNLabeledValue ) } for postalAddress in contactData["postalAddresses"] as! NSArray { let postalAddressAsCNLabeledValue = convertPostalAddressToCNLabeledValue ( postalAddress as! NSDictionary ) mutableContact.postalAddresses.append( postalAddressAsCNLabeledValue ) } do { saveRequest.add(mutableContact, toContainerWithIdentifier:nil) try contactStore.execute(saveRequest) callback( [NSNull(), true] ) } catch let error as NSError { NSLog("Problem creating contact.") NSLog(error.localizedDescription) callback( [error.localizedDescription, false] ) } } @objc func addGroup(_ groupData: NSDictionary, callback: (NSArray) -> () ) -> Void { let contactStore = CNContactStore() let mutableGroup = CNMutableGroup() let saveRequest = CNSaveRequest() if (groupData["name"] != nil) { mutableGroup.name = groupData["name"] as! String } do { saveRequest.add(mutableGroup, toContainerWithIdentifier:nil) try contactStore.execute(saveRequest) callback( [NSNull(), true] ) } catch let error as NSError { NSLog("Problem creating group.") NSLog(error.localizedDescription) callback( [error.localizedDescription, false] ) } } @objc func updateContact(_ identifier: String, contactData: NSDictionary, callback: (NSArray) -> () ) -> Void { let contactStore = CNContactStore() let saveRequest = CNSaveRequest() let cNContact = getCNContact(identifier, keysToFetch: keysToFetch as [CNKeyDescriptor]) let mutableContact = cNContact!.mutableCopy() as! CNMutableContact if ( contactData["givenName"] != nil ) { mutableContact.givenName = contactData["givenName"] as! String } if ( contactData["familyName"] != nil ) { mutableContact.familyName = contactData["familyName"] as! String } if ( contactData["organizationName"] != nil ) { mutableContact.organizationName = contactData["organizationName"] as! String } if ( contactData["phoneNumbers"] != nil ) { mutableContact.phoneNumbers.removeAll() for phoneNumber in contactData["phoneNumbers"] as! NSArray { let phoneNumberAsCNLabeledValue = convertPhoneNumberToCNLabeledValue( phoneNumber as! NSDictionary ) mutableContact.phoneNumbers.append( phoneNumberAsCNLabeledValue ) } } if ( contactData["emailAddresses"] != nil ) { mutableContact.emailAddresses.removeAll() for emailAddress in contactData["emailAddresses"] as! NSArray { let emailAddressAsCNLabeledValue = convertEmailAddressToCNLabeledValue ( emailAddress as! NSDictionary ) mutableContact.emailAddresses.append( emailAddressAsCNLabeledValue ) } } if ( contactData["postalAddresses"] != nil ) { mutableContact.postalAddresses.removeAll() for postalAddress in contactData["postalAddresses"] as! NSArray { let postalAddressAsCNLabeledValue = convertPostalAddressToCNLabeledValue ( postalAddress as! NSDictionary ) mutableContact.postalAddresses.append( postalAddressAsCNLabeledValue ) } } do { saveRequest.update(mutableContact) try contactStore.execute(saveRequest) callback( [NSNull(), true] ) } catch let error as NSError { NSLog("Problem updating Contact with identifier: " + identifier) NSLog(error.localizedDescription) callback( [error.localizedDescription, false] ) } } @objc func updateGroup(_ identifier: String, groupData: NSDictionary, callback: (NSArray) -> () ) -> Void { let contactStore = CNContactStore() let saveRequest = CNSaveRequest() let cNGroup = getCNGroup(identifier) let mutableGroup = cNGroup!.mutableCopy() as! CNMutableGroup if ( groupData["name"] != nil ) { mutableGroup.name = groupData["name"] as! String } do { saveRequest.update(mutableGroup) try contactStore.execute(saveRequest) callback( [NSNull(), true] ) } catch let error as NSError { NSLog("Problem updating group with identifier: " + identifier) NSLog(error.localizedDescription) callback( [error.localizedDescription, false] ) } } @objc func deleteContact(_ identifier: String, callback: (NSArray) -> () ) -> Void { let contactStore = CNContactStore() let cNContact = getCNContact( identifier, keysToFetch: keysToFetch as [CNKeyDescriptor] ) let saveRequest = CNSaveRequest() let mutableContact = cNContact!.mutableCopy() as! CNMutableContact saveRequest.delete(mutableContact) do { try contactStore.execute(saveRequest) callback( [NSNull(), true] ) } catch let error as NSError { NSLog("Problem deleting unified contact with identifier: " + identifier) NSLog(error.localizedDescription) callback( [error.localizedDescription, false] ) } } @objc func deleteGroup(_ identifier: String, callback: (NSArray) -> () ) -> Void { let contactStore = CNContactStore() let cNGroup = getCNGroup(identifier) let saveRequest = CNSaveRequest() let mutableGroup = cNGroup!.mutableCopy() as! CNMutableGroup saveRequest.delete(mutableGroup) do { try contactStore.execute(saveRequest) callback( [NSNull(), true] ) } catch let error as NSError { NSLog("Problem deleting group with identifier: " + identifier) NSLog(error.localizedDescription) callback( [error.localizedDescription, false] ) } } @objc func addContactsToGroup(_ identifier: String, contactIdentifiers: [NSString], callback: (NSArray) -> () ) -> Void { let contactStore = CNContactStore() let cNGroup = getCNGroup(identifier) let saveRequest = CNSaveRequest() let mutableGroup = cNGroup!.mutableCopy() as! CNMutableGroup do { for contactIdentifier in contactIdentifiers { let cNContact = getCNContact(contactIdentifier as String, keysToFetch: keysToFetch as [CNKeyDescriptor]) let mutableContact = cNContact!.mutableCopy() as! CNMutableContact saveRequest.addMember(mutableContact, to: mutableGroup) } try contactStore.execute(saveRequest) callback( [NSNull(), true] ) } catch let error as NSError { NSLog("Problem adding contacts to group with identifier: " + identifier) NSLog(error.localizedDescription) callback( [error.localizedDescription, false] ) } } @objc func removeContactsFromGroup(_ identifier: String, contactIdentifiers: [NSString], callback: (NSArray) -> () ) -> Void { let contactStore = CNContactStore() let cNGroup = getCNGroup(identifier) let saveRequest = CNSaveRequest() let mutableGroup = cNGroup!.mutableCopy() as! CNMutableGroup do { for contactIdentifier in contactIdentifiers { let cNContact = getCNContact(contactIdentifier as String, keysToFetch: keysToFetch as [CNKeyDescriptor]) let mutableContact = cNContact!.mutableCopy() as! CNMutableContact saveRequest.removeMember(mutableContact, from: mutableGroup) } try contactStore.execute(saveRequest) callback( [NSNull(), true] ) } catch let error as NSError { NSLog("Problem removing contacts from group with identifier: " + identifier) NSLog(error.localizedDescription) callback( [error.localizedDescription, false] ) } } ///////////// // PRIVATE // func getCNContact( _ identifier: String, keysToFetch: [CNKeyDescriptor] ) -> CNContact? { let contactStore = CNContactStore() do { let cNContact = try contactStore.unifiedContact( withIdentifier: identifier, keysToFetch: keysToFetch ) return cNContact } catch let error as NSError { NSLog("Problem getting unified contact with identifier: " + identifier) NSLog(error.localizedDescription) return nil } } func getCNGroup( _ identifier: String ) -> CNGroup? { let contactStore = CNContactStore() do { let predicate = CNGroup.predicateForGroups(withIdentifiers: [identifier]) let cNGroup = try contactStore.groups(matching: predicate).first return cNGroup } catch let error as NSError { NSLog("Problem getting group with identifier: " + identifier) NSLog(error.localizedDescription) return nil } } func contactContainsText( _ cNContact: CNContact, searchText: String ) -> Bool { let searchText = searchText.lowercased(); let textToSearch = cNContact.givenName.lowercased() + " " + cNContact.familyName.lowercased() + " " + cNContact.nickname.lowercased() if searchText.isEmpty || textToSearch.contains(searchText) { return true } else { return false } } func getLabeledDict<T>(_ item: CNLabeledValue<T>) -> [String: Any] { var dict = [String: Any]() dict["identifier"] = item.identifier if let label = item.label { if label.hasPrefix("_$!<") && label.hasSuffix(">!$_") { addString(&dict, key: "label", value: label.substring(with: label.index(label.startIndex, offsetBy: 4)..<label.index(label.endIndex, offsetBy: -4))) } else { addString(&dict, key: "label", value: item.label) } } addString(&dict, key: "localizedLabel", value: item.label == nil ? nil : CNLabeledValue<T>.localizedString(forLabel: item.label!)) return dict } func addString(_ dict: inout [String: Any], key: String, value: String?) { if let value = value, !value.isEmpty { let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) if (!trimmed.isEmpty) { dict[key] = value } } } func convertCNGroupToDictionary(_ cNGroup: CNGroup) -> NSDictionary { var group = [String: Any]() addString(&group, key: "identifier", value: cNGroup.identifier) addString(&group, key: "name", value: cNGroup.name) return group as NSDictionary } func convertCNContactToDictionary(_ cNContact: CNContact) -> NSDictionary { var contact = [String: Any]() if let birthday = cNContact.birthday { var date = [String: Int]() date["year"] = birthday.year == NSDateComponentUndefined ? nil : birthday.year date["month"] = birthday.month == NSDateComponentUndefined ? nil : birthday.month date["day"] = birthday.day == NSDateComponentUndefined ? nil : birthday.day contact["birthday"] = date } if cNContact.contactRelations.count > 0 { contact["contactRelations"] = cNContact.contactRelations.map { (item) -> [String: Any] in var dict = getLabeledDict(item) addString(&dict, key: "name", value: item.value.name) return dict } } addString(&contact, key: "contactType", value: cNContact.contactType == CNContactType.person ? "person" : "organization") if cNContact.dates.count > 0 { contact["dates"] = cNContact.dates.map { (item) -> [String: Any] in var dict = getLabeledDict(item) dict["year"] = item.value.year == NSDateComponentUndefined ? nil : item.value.year dict["month"] = item.value.month == NSDateComponentUndefined ? nil : item.value.month dict["day"] = item.value.day == NSDateComponentUndefined ? nil : item.value.day return dict } } addString(&contact, key: "departmentName", value: cNContact.departmentName) if cNContact.emailAddresses.count > 0 { contact["emailAddresses"] = cNContact.emailAddresses.map { (item) -> [String: Any] in var dict = getLabeledDict(item) addString(&dict, key: "value", value: item.value as String) return dict } } addString(&contact, key: "familyName", value: cNContact.familyName) addString(&contact, key: "givenName", value: cNContact.givenName) addString(&contact, key: "identifier", value: cNContact.identifier) contact["imageDataAvailable"] = cNContact.imageDataAvailable if cNContact.instantMessageAddresses.count > 0 { contact["instantMessageAddresses"] = cNContact.instantMessageAddresses.map { (item) -> [String: Any] in var dict = getLabeledDict(item) addString(&dict, key: "service", value: item.value.service) addString(&dict, key: "localizedService", value: CNInstantMessageAddress.localizedString(forService: item.value.service)) addString(&dict, key: "username", value: item.value.username) return dict } } addString(&contact, key: "jobTitle", value: cNContact.jobTitle) addString(&contact, key: "middleName", value: cNContact.middleName) addString(&contact, key: "namePrefix", value: cNContact.namePrefix) addString(&contact, key: "nameSuffix", value: cNContact.nameSuffix) addString(&contact, key: "nickname", value: cNContact.nickname) if let nonGregorianBirthday = cNContact.nonGregorianBirthday { var date = [String: Int]() date["year"] = nonGregorianBirthday.year == NSDateComponentUndefined ? nil : nonGregorianBirthday.year date["month"] = nonGregorianBirthday.month == NSDateComponentUndefined ? nil : nonGregorianBirthday.month date["day"] = nonGregorianBirthday.day == NSDateComponentUndefined ? nil : nonGregorianBirthday.day contact["nonGregorianBirthday"] = date } // addString(&contact, key: "note", value: cNContact.note) // NOTE: iOS 13 does not allow fetching of notes without the com.apple.developer.contacts.notes entitlement, which requires special permission from Apple. addString(&contact, key: "organizationName", value: cNContact.organizationName) if cNContact.phoneNumbers.count > 0 { contact["phoneNumbers"] = cNContact.phoneNumbers.map { (item) -> [String: Any] in var dict = getLabeledDict(item) addString(&dict, key: "stringValue", value: item.value.stringValue) addString(&dict, key: "countryCode", value: item.value.value(forKey: "countryCode") as? String) addString(&dict, key: "digits", value: item.value.value(forKey: "digits") as? String) return dict } } addString(&contact, key: "phoneticFamilyName", value: cNContact.phoneticFamilyName) addString(&contact, key: "phoneticGivenName", value: cNContact.phoneticGivenName) addString(&contact, key: "phoneticMiddleName", value: cNContact.phoneticMiddleName) // if #available(iOS 10.0, *) { // contact["phoneticOrganizationName"] = cNContact.phoneticOrganizationName // } else { // // Fallback on earlier versions // } if cNContact.postalAddresses.count > 0 { contact["postalAddresses"] = cNContact.postalAddresses.map { (item) -> [String: Any] in var dict = getLabeledDict(item) addString(&dict, key: "street", value: item.value.street) addString(&dict, key: "city", value: item.value.city) addString(&dict, key: "state", value: item.value.state) addString(&dict, key: "postalCode", value: item.value.postalCode) addString(&dict, key: "country", value: item.value.country) addString(&dict, key: "isoCountryCode", value: item.value.isoCountryCode) addString(&dict, key: "mailingAddress", value: CNPostalAddressFormatter.string(from: item.value, style: .mailingAddress)) return dict } } addString(&contact, key: "previousFamilyName", value: cNContact.previousFamilyName) if cNContact.socialProfiles.count > 0 { contact["socialProfiles"] = cNContact.socialProfiles.map { (item) -> [String: Any] in var dict = getLabeledDict(item) addString(&dict, key: "urlString", value: item.value.urlString) addString(&dict, key: "username", value: item.value.username) addString(&dict, key: "userIdentifier", value: item.value.userIdentifier) addString(&dict, key: "service", value: item.value.service) addString(&dict, key: "localizedService", value: CNSocialProfile.localizedString(forService: item.value.service)) return dict } } if let thumbnailImageData = cNContact.thumbnailImageData { addString(&contact, key: "thumbnailImageData", value: thumbnailImageData.base64EncodedString(options: [])) } if cNContact.urlAddresses.count > 0 { contact["urlAddresses"] = cNContact.urlAddresses.map { (item) -> [String: Any] in var dict = getLabeledDict(item) addString(&dict, key: "value", value: item.value as String) return dict } } addString(&contact, key: "fullName", value: CNContactFormatter.string( from: cNContact, style: .fullName )) return contact as NSDictionary } func convertPhoneNumberToCNLabeledValue(_ phoneNumber: NSDictionary) -> CNLabeledValue<CNPhoneNumber> { var formattedLabel = String() let userProvidedLabel = phoneNumber["label"] as! String let lowercaseUserProvidedLabel = userProvidedLabel.lowercased() switch (lowercaseUserProvidedLabel) { case "home": formattedLabel = CNLabelHome case "work": formattedLabel = CNLabelWork case "mobile": formattedLabel = CNLabelPhoneNumberMobile case "iphone": formattedLabel = CNLabelPhoneNumberiPhone case "main": formattedLabel = CNLabelPhoneNumberMain case "home fax": formattedLabel = CNLabelPhoneNumberHomeFax case "work fax": formattedLabel = CNLabelPhoneNumberWorkFax case "pager": formattedLabel = CNLabelPhoneNumberPager case "other": formattedLabel = CNLabelOther default: formattedLabel = userProvidedLabel } return CNLabeledValue( label:formattedLabel, value:CNPhoneNumber(stringValue: phoneNumber["stringValue"] as! String) ) } func convertEmailAddressToCNLabeledValue(_ emailAddress: NSDictionary) -> CNLabeledValue<NSString> { var formattedLabel = String() let userProvidedLabel = emailAddress["label"] as! String let lowercaseUserProvidedLabel = userProvidedLabel.lowercased() switch (lowercaseUserProvidedLabel) { case "home": formattedLabel = CNLabelHome case "work": formattedLabel = CNLabelWork case "icloud": formattedLabel = CNLabelEmailiCloud case "other": formattedLabel = CNLabelOther default: formattedLabel = userProvidedLabel } return CNLabeledValue( label:formattedLabel, value: emailAddress["value"] as! NSString ) } func convertPostalAddressToCNLabeledValue(_ postalAddress: NSDictionary) -> CNLabeledValue<CNPostalAddress> { var formattedLabel = String() let userProvidedLabel = postalAddress["label"] as! String let lowercaseUserProvidedLabel = userProvidedLabel.lowercased() switch (lowercaseUserProvidedLabel) { case "home": formattedLabel = CNLabelHome case "work": formattedLabel = CNLabelWork case "other": formattedLabel = CNLabelOther default: formattedLabel = userProvidedLabel } let mutableAddress = CNMutablePostalAddress() mutableAddress.street = postalAddress["street"] as! String mutableAddress.city = postalAddress["city"] as! String mutableAddress.state = postalAddress["state"] as! String mutableAddress.postalCode = postalAddress["postalCode"] as! String mutableAddress.country = postalAddress["country"] as! String return CNLabeledValue( label: formattedLabel, value: mutableAddress as CNPostalAddress ) } }
mit
57009e610dcd1fbbed434d53d76177ae
36.637736
221
0.623989
4.887618
false
false
false
false
codestergit/swift
test/SILGen/cf_members.swift
2
11648
// RUN: %target-swift-frontend -emit-silgen -I %S/../IDE/Inputs/custom-modules %s | %FileCheck %s // REQUIRES: objc_interop import ImportAsMember func makeMetatype() -> Struct1.Type { return Struct1.self } // CHECK-LABEL: sil @_T010cf_members17importAsUnaryInityyF public func importAsUnaryInit() { // CHECK: function_ref @CCPowerSupplyCreateDangerous : $@convention(c) () -> @owned CCPowerSupply var a = CCPowerSupply(dangerous: ()) let f: () -> CCPowerSupply = CCPowerSupply.init(dangerous:) a = f() } // CHECK-LABEL: sil @_T010cf_members3foo{{[_0-9a-zA-Z]*}}F public func foo(_ x: Double) { // CHECK: bb0([[X:%.*]] : $Double): // CHECK: [[GLOBALVAR:%.*]] = global_addr @IAMStruct1GlobalVar // CHECK: [[ZZ:%.*]] = load [trivial] [[GLOBALVAR]] let zz = Struct1.globalVar // CHECK: assign [[ZZ]] to [[GLOBALVAR]] Struct1.globalVar = zz // CHECK: [[Z:%.*]] = project_box // CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple // CHECK: apply [[FN]]([[X]]) var z = Struct1(value: x) // The metatype expression should still be evaluated even if it isn't // used. // CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @_T010cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: apply [[FN]]([[X]]) z = makeMetatype().init(value: x) // CHECK: [[THUNK:%.*]] = function_ref @_T0SC7Struct1VABSd5value_tcfCTcTO // CHECK: [[SELF_META:%.*]] = metatype $@thin Struct1.Type // CHECK: [[A:%.*]] = apply [[THUNK]]([[SELF_META]]) // CHECK: [[BORROWED_A:%.*]] = begin_borrow [[A]] // CHECK: [[A_COPY:%.*]] = copy_value [[BORROWED_A]] let a: (Double) -> Struct1 = Struct1.init(value:) // CHECK: apply [[A_COPY]]([[X]]) // CHECK: end_borrow [[BORROWED_A]] from [[A]] z = a(x) // TODO: Support @convention(c) references that only capture thin metatype // let b: @convention(c) (Double) -> Struct1 = Struct1.init(value:) // z = b(x) // CHECK: [[FN:%.*]] = function_ref @IAMStruct1InvertInPlace // CHECK: apply [[FN]]([[Z]]) z.invert() // CHECK: [[FN:%.*]] = function_ref @IAMStruct1Rotate : $@convention(c) (@in Struct1, Double) -> Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[Z]] // CHECK: store [[ZVAL]] to [trivial] [[ZTMP:%.*]] : // CHECK: apply [[FN]]([[ZTMP]], [[X]]) z = z.translate(radians: x) // CHECK: [[THUNK:%.*]] = function_ref [[THUNK_NAME:@_T0SC7Struct1V9translateABSd7radians_tFTcTO]] // CHECK: [[ZVAL:%.*]] = load [trivial] [[Z]] // CHECK: [[C:%.*]] = apply [[THUNK]]([[ZVAL]]) // CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]] // CHECK: [[C_COPY:%.*]] = copy_value [[BORROWED_C]] let c: (Double) -> Struct1 = z.translate(radians:) // CHECK: apply [[C_COPY]]([[X]]) // CHECK: end_borrow [[BORROWED_C]] from [[C]] z = c(x) // CHECK: [[THUNK:%.*]] = function_ref [[THUNK_NAME]] // CHECK: thin_to_thick_function [[THUNK]] let d: (Struct1) -> (Double) -> Struct1 = Struct1.translate(radians:) z = d(z)(x) // TODO: If we implement SE-0042, this should thunk the value Struct1 param // to a const* param to the underlying C symbol. // // let e: @convention(c) (Struct1, Double) -> Struct1 // = Struct1.translate(radians:) // z = e(z, x) // CHECK: [[FN:%.*]] = function_ref @IAMStruct1Scale // CHECK: [[ZVAL:%.*]] = load [trivial] [[Z]] // CHECK: apply [[FN]]([[ZVAL]], [[X]]) z = z.scale(x) // CHECK: [[THUNK:%.*]] = function_ref @_T0SC7Struct1V5scaleABSdFTcTO // CHECK: [[ZVAL:%.*]] = load [trivial] [[Z]] // CHECK: [[F:%.*]] = apply [[THUNK]]([[ZVAL]]) // CHECK: [[BORROWED_F:%.*]] = begin_borrow [[F]] // CHECK: [[F_COPY:%.*]] = copy_value [[BORROWED_F]] let f = z.scale // CHECK: apply [[F_COPY]]([[X]]) // CHECK: end_borrow [[BORROWED_F]] from [[F]] z = f(x) // CHECK: [[THUNK:%.*]] = function_ref @_T0SC7Struct1V5scaleABSdFTcTO // CHECK: thin_to_thick_function [[THUNK]] let g = Struct1.scale // CHECK: [[ZVAL:%.*]] = load [trivial] [[Z]] z = g(z)(x) // TODO: If we implement SE-0042, this should directly reference the // underlying C function. // let h: @convention(c) (Struct1, Double) -> Struct1 = Struct1.scale // z = h(z, x) // CHECK: [[ZVAL:%.*]] = load [trivial] [[Z]] // CHECK: store [[ZVAL]] to [trivial] [[ZTMP:%.*]] : // CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetRadius : $@convention(c) (@in Struct1) -> Double // CHECK: apply [[GET]]([[ZTMP]]) _ = z.radius // CHECK: [[ZVAL:%.*]] = load [trivial] [[Z]] // CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetRadius : $@convention(c) (Struct1, Double) -> () // CHECK: apply [[SET]]([[ZVAL]], [[X]]) z.radius = x // CHECK: [[ZVAL:%.*]] = load [trivial] [[Z]] // CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetAltitude : $@convention(c) (Struct1) -> Double // CHECK: apply [[GET]]([[ZVAL]]) _ = z.altitude // CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetAltitude : $@convention(c) (@inout Struct1, Double) -> () // CHECK: apply [[SET]]([[Z]], [[X]]) z.altitude = x // CHECK: [[ZVAL:%.*]] = load [trivial] [[Z]] // CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetMagnitude : $@convention(c) (Struct1) -> Double // CHECK: apply [[GET]]([[ZVAL]]) _ = z.magnitude // CHECK: [[FN:%.*]] = function_ref @IAMStruct1StaticMethod // CHECK: apply [[FN]]() var y = Struct1.staticMethod() // CHECK: [[THUNK:%.*]] = function_ref @_T0SC7Struct1V12staticMethods5Int32VyFZTcTO // CHECK: [[SELF:%.*]] = metatype // CHECK: [[I:%.*]] = apply [[THUNK]]([[SELF]]) // CHECK: [[BORROWED_I:%.*]] = begin_borrow [[I]] // CHECK: [[I_COPY:%.*]] = copy_value [[BORROWED_I]] let i = Struct1.staticMethod // CHECK: apply [[I_COPY]]() // CHECK: end_borrow [[BORROWED_I]] from [[I]] y = i() // TODO: Support @convention(c) references that only capture thin metatype // let j: @convention(c) () -> Int32 = Struct1.staticMethod // y = j() // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty // CHECK: apply [[GET]]() _ = Struct1.property // CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty // CHECK: apply [[SET]](%{{[0-9]+}}) Struct1.property = y // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty // CHECK: apply [[GET]]() _ = Struct1.getOnlyProperty // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @_T010cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty // CHECK: apply [[GET]]() _ = makeMetatype().property // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @_T010cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty // CHECK: apply [[SET]](%{{[0-9]+}}) makeMetatype().property = y // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @_T010cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty // CHECK: apply [[GET]]() _ = makeMetatype().getOnlyProperty // CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesLast : $@convention(c) (Double, Struct1) -> () // CHECK: [[ZVAL:%.*]] = load [trivial] [[Z]] // CHECK: apply [[FN]]([[X]], [[ZVAL]]) z.selfComesLast(x: x) let k: (Double) -> () = z.selfComesLast(x:) k(x) let l: (Struct1) -> (Double) -> () = Struct1.selfComesLast(x:) l(z)(x) // TODO: If we implement SE-0042, this should thunk to reorder the arguments. // let m: @convention(c) (Struct1, Double) -> () = Struct1.selfComesLast(x:) // m(z, x) // CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesThird : $@convention(c) (Int32, Float, Struct1, Double) -> () // CHECK: [[ZVAL:%.*]] = load [trivial] [[Z]] // CHECK: apply [[FN]]({{.*}}, {{.*}}, [[ZVAL]], [[X]]) z.selfComesThird(a: y, b: 0, x: x) let n: (Int32, Float, Double) -> () = z.selfComesThird(a:b:x:) n(y, 0, x) let o: (Struct1) -> (Int32, Float, Double) -> () = Struct1.selfComesThird(a:b:x:) o(z)(y, 0, x) // TODO: If we implement SE-0042, this should thunk to reorder the arguments. // let p: @convention(c) (Struct1, Int, Float, Double) -> () // = Struct1.selfComesThird(a:b:x:) // p(z, y, 0, x) } // CHECK: } // end sil function '_T010cf_members3foo{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1VABSd5value_tcfCTO // CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $@thin Struct1.Type): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1CreateSimple // CHECK: [[RET:%.*]] = apply [[CFUNC]]([[X]]) // CHECK: return [[RET]] // CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1V9translateABSd7radians_tFTO // CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1): // CHECK: store [[SELF]] to [trivial] [[TMP:%.*]] : // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Rotate // CHECK: [[RET:%.*]] = apply [[CFUNC]]([[TMP]], [[X]]) // CHECK: return [[RET]] // CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1V5scaleABSdFTO // CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Scale // CHECK: [[RET:%.*]] = apply [[CFUNC]]([[SELF]], [[X]]) // CHECK: return [[RET]] // CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1V12staticMethods5Int32VyFZTO // CHECK: bb0([[SELF:%.*]] : $@thin Struct1.Type): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1StaticMethod // CHECK: [[RET:%.*]] = apply [[CFUNC]]() // CHECK: return [[RET]] // CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1V13selfComesLastySd1x_tFTO // CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesLast // CHECK: apply [[CFUNC]]([[X]], [[SELF]]) // CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1V14selfComesThirdys5Int32V1a_Sf1bSd1xtFTO // CHECK: bb0([[X:%.*]] : $Int32, [[Y:%.*]] : $Float, [[Z:%.*]] : $Double, [[SELF:%.*]] : $Struct1): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesThird // CHECK: apply [[CFUNC]]([[X]], [[Y]], [[SELF]], [[Z]]) // CHECK-LABEL: sil @_T010cf_members3bar{{[_0-9a-zA-Z]*}}F public func bar(_ x: Double) { // CHECK: function_ref @CCPowerSupplyCreate : $@convention(c) (Double) -> @owned CCPowerSupply let ps = CCPowerSupply(watts: x) // CHECK: function_ref @CCRefrigeratorCreate : $@convention(c) (CCPowerSupply) -> @owned CCRefrigerator let fridge = CCRefrigerator(powerSupply: ps) // CHECK: function_ref @CCRefrigeratorOpen : $@convention(c) (CCRefrigerator) -> () fridge.open() // CHECK: function_ref @CCRefrigeratorGetPowerSupply : $@convention(c) (CCRefrigerator) -> @autoreleased CCPowerSupply let ps2 = fridge.powerSupply // CHECK: function_ref @CCRefrigeratorSetPowerSupply : $@convention(c) (CCRefrigerator, CCPowerSupply) -> () fridge.powerSupply = ps2 let a: (Double) -> CCPowerSupply = CCPowerSupply.init(watts:) let _ = a(x) let b: (CCRefrigerator) -> () -> () = CCRefrigerator.open b(fridge)() let c = fridge.open c() } // CHECK-LABEL: sil @_T010cf_members28importGlobalVarsAsProperties{{[_0-9a-zA-Z]*}}F public func importGlobalVarsAsProperties() -> (Double, CCPowerSupply, CCPowerSupply?) { // CHECK: global_addr @kCCPowerSupplyDC // CHECK: global_addr @kCCPowerSupplyAC // CHECK: global_addr @kCCPowerSupplyDefaultPower return (CCPowerSupply.defaultPower, CCPowerSupply.AC, CCPowerSupply.DC) }
apache-2.0
4fddd563e63a520291743b1948df6666
42.462687
120
0.592634
3.335624
false
false
false
false
hoolrory/VideoInfoViewer-iOS
VideoInfoViewer/VideoManager.swift
1
7744
/** Copyright (c) 2016 Rory Hool 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 AVFoundation import CoreData import Foundation import Photos class VideoManager { lazy var managedContext: NSManagedObjectContext? = { if let appDelegate = UIApplication.shared.delegate as? AppDelegate { return appDelegate.managedObjectContext } return nil }() let backgroundQueue = DispatchQueue(label: "backgroundQueue") func getVideos() -> [Video] { var videos = [Video]() let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Video") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "openDate", ascending: false)] do { let results = try managedContext?.fetch(fetchRequest) if let objects = results as? [NSManagedObject] { for object in objects { videos.append(Video(fromObject: object)) } } } catch _ { } return videos } func getVideoByAssetId(_ assetId: String) -> Video? { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Video") fetchRequest.predicate = NSPredicate(format: "assetId == %@", assetId) do { let results = try managedContext?.fetch(fetchRequest) if let objects = results as? [NSManagedObject] { if objects.count == 1 { return Video(fromObject: objects[0]) } } } catch _ { } return nil } func updateOpenDate(_ video: Video) { video.coreDataObject.setValue(Date(), forKey: "openDate") do { try managedContext?.save() } catch _ { } } typealias CompletionHandler = (_ result:Video?) -> Void func addVideoFromAVURLAsset(_ asset: AVURLAsset, phAsset: PHAsset, completionHandler: @escaping CompletionHandler) { backgroundQueue.async { let videoName = asset.url.lastPathComponent let videoURL = self.getDocumentUrl(videoName) let creationDate = phAsset.creationDate let assetId = phAsset.localIdentifier do { try FileManager.default.copyItem(at: asset.url, to: videoURL) } catch _ { print("Failed to copy") completionHandler(nil) } let thumbURL = self.getDocumentUrl("\(videoName).png") let thumbSize: CGSize = CGSize(width: CGFloat(phAsset.pixelWidth), height: CGFloat(phAsset.pixelHeight)) let options = PHImageRequestOptions() options.isSynchronous = true let cachingImageManager = PHCachingImageManager() cachingImageManager.requestImage(for: phAsset, targetSize: thumbSize, contentMode: PHImageContentMode.aspectFill, options: options, resultHandler: { (image: UIImage?, info: [AnyHashable: Any]?) -> Void in if let image = image { try? UIImagePNGRepresentation(image)?.write(to: thumbURL, options: [.atomic]) } else { let duration = MediaUtils.getVideoDuration(videoURL) let thumbTime = CMTime(seconds: duration.seconds / 2.0, preferredTimescale: duration.timescale) _ = MediaUtils.renderThumbnailFromVideo(videoURL, thumbURL: thumbURL, time: thumbTime) } }) let video = self.addVideo(assetId, videoURL: videoURL, thumbURL: thumbURL, creationDate: creationDate) completionHandler(video) } } func addVideoFromURL(_ url: URL, completionHandler: @escaping CompletionHandler) { backgroundQueue.async { let videoName = url.lastPathComponent let videoURL = self.getDocumentUrl(videoName) let creationDate = Date() let assetId = "" do { try FileManager.default.copyItem(at: url, to: videoURL) } catch _ { print("Failed to copy") completionHandler(nil) } let thumbURL = self.getDocumentUrl("\(videoName).png") let duration = MediaUtils.getVideoDuration(videoURL) let thumbTime = CMTime(seconds: duration.seconds / 2.0, preferredTimescale: duration.timescale) _ = MediaUtils.renderThumbnailFromVideo(videoURL, thumbURL: thumbURL, time: thumbTime) let video = self.addVideo(assetId, videoURL: videoURL, thumbURL: thumbURL, creationDate: creationDate) completionHandler(video) } } func addVideo(_ assetId: String, videoURL: URL, thumbURL: URL, creationDate: Date?) -> Video? { guard let managedContext = managedContext else { return nil } let entity = NSEntityDescription.entity(forEntityName: "Video", in:managedContext) let object = NSManagedObject(entity: entity!, insertInto: managedContext) object.setValue(assetId, forKey: "assetId") object.setValue(videoURL.lastPathComponent, forKey: "videoFile") object.setValue(thumbURL.lastPathComponent, forKey: "thumbFile") object.setValue(Date(), forKey: "openDate") object.setValue(creationDate, forKey: "creationDate") do { try managedContext.save() removeOldVideos() return Video(fromObject: object) } catch let error { print("Could not save \(error))") } return nil } func removeOldVideos() { let videos = getVideos() if videos.count > 5 { let videosToDelete = videos[5 ..< videos.count ] for video in videosToDelete { removeVideo(video: video) } } } func removeVideo(video: Video) { managedContext?.delete(video.coreDataObject) do { try managedContext?.save() let filemgr = FileManager.default if filemgr.fileExists(atPath: video.videoURL.path) { try filemgr.removeItem(at: video.videoURL as URL) } if filemgr.fileExists(atPath: video.thumbURL.path) { try filemgr.removeItem(at: video.thumbURL as URL) } } catch let error { print("Could not save \(error))") } } func getDocumentUrl(_ pathComponent: String) -> URL { let fileManager = FileManager.default let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask) guard let documentDirectory: URL = urls.first else { fatalError("documentDir Error") } return documentDirectory.appendingPathComponent(pathComponent) } }
apache-2.0
7acdf9a59768f9543510f9abec42d323
34.522936
216
0.57593
5.539342
false
false
false
false
darthpelo/TimerH2O
TimerH2O/TimerH2O/Views/TH2OWaterPickerView.swift
1
2733
// // TH2OWaterPickerView.swift // TimerH2O // // Created by Alessio Roberto on 29/10/16. // Copyright © 2016 Alessio Roberto. All rights reserved. // import UIKit class TH2OWaterPickerView: UIView { @IBOutlet weak var pickerTitleLabel: UILabel! @IBOutlet weak var doneButton: UIButton! @IBOutlet weak var pickerView: UIPickerView! fileprivate let numbers = (0...9).map {"\($0)"} fileprivate var amount = ["0", "0", "0", "0"] typealias DoneAmount = (Int) -> Void fileprivate var doneAmount: DoneAmount? private var parentView: UIView? @IBAction func doneButtonPressed(_ sender: AnyObject) { guard let amount = Converter.convert(amount: amount) else { return } doneAmount?(amount) } func loadPickerView() -> TH2OWaterPickerView? { guard let view = R.nib.th2OWaterPickerView.firstView(owner: self) else { return nil } view.frame.origin.y = UIScreen.main.bounds.height view.frame.size.width = UIScreen.main.bounds.width return view } func configure(onView: UIView, withCallback: @escaping DoneAmount) { doneAmount = withCallback parentView = onView self.frame.origin.y = onView.frame.size.height pickerTitleLabel.text = R.string.localizable.setsessionWaterpickerTitle() doneButton.setTitle(R.string.localizable.done(), for: .normal) pickerView.selectRow(2, inComponent: 0, animated: false) amount[0] = "2" UIApplication.shared.keyWindow?.addSubview(self) } func isTo(show: Bool) { guard let height = parentView?.frame.size.height else { return } UIView.animate(withDuration: 0.3, animations: { if show { self.frame.origin.y = height - self.frame.size.height } else { self.frame.origin.y = height } }, completion: nil) } } extension TH2OWaterPickerView: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 4 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return numbers.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return numbers[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { amount[component] = numbers[row] } }
mit
c4c88e25a27bcbbe4d8ee1e9b7965540
30.045455
111
0.601757
4.630508
false
false
false
false
vector-im/vector-ios
RiotSwiftUI/Modules/Room/RoomAccess/RoomAccessTypeChooser/Service/Mock/MockRoomAccessTypeChooserService.swift
1
2653
// // 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) { } }
apache-2.0
0f1b11c69484966cccd73d348aa252af
41.790323
245
0.753487
4.78018
false
false
false
false
PedroTrujilloV/TIY-Assignments
24--Iron-Tips/IronTips/IronTips/AppDelegate.swift
1
3121
// // AppDelegate.swift // IronTips // // Created by Ben Gohlke on 11/4/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. Parse.setApplicationId("appIdGoesHere", clientKey: "clientKeyGoesHere") // let player = PFObject(className: "Player") // player["name"] = "Ben" // player["score"] = 450 // player.saveInBackgroundWithBlock { // (success: Bool, error: NSError?) -> Void in // if success // { // print("great!") // } // else // { // print(error?.localizedDescription) // } // } // let query = PFQuery(className: "Player") // query.whereKey("score", greaterThan: 500) // query.findObjectsInBackgroundWithBlock { // (results: [PFObject]?, error: NSError?) -> Void in // if error == nil // { // print(results) // } // else // { // print(error?.localizedDescription) // } // } return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
cc0-1.0
06443d3680444e9ddfe7432e141177f7
38.493671
285
0.651923
5.148515
false
false
false
false
LeonZong/throb
Throb/Throb/ViewController.swift
1
6934
// // ViewController.swift // Throb // // Created by 宗健平 on 2017/4/8. // Copyright © 2017年 Leon Zong. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController,AVCaptureVideoDataOutputSampleBufferDelegate { // 会话,用于传递输出信号至输出信号 let session = AVCaptureSession() // 输入设备,这是是用后置摄像头 let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) // 输出设备,等待后续数字图像处理 let videoDataOutput = AVCaptureVideoDataOutput() // 心电图绘制 var lineView:LineView? = nil var step:Int = 0 // 显示心率 var lable = UILabel(frame: CGRect(x: 10, y: 10, width: 100, height: 100)) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // 设置输入 let input = try! AVCaptureDeviceInput(device: self.device) // 开启闪光灯 try! self.device?.lockForConfiguration() self.device?.torchMode=AVCaptureTorchMode.on self.device?.unlockForConfiguration() // 设置预览 let captureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.session) captureVideoPreviewLayer?.frame = self.view.bounds captureVideoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill self.view.layer.addSublayer(captureVideoPreviewLayer!) // 设置输出视频的格式 self.videoDataOutput.videoSettings=[kCVPixelBufferPixelFormatTypeKey as AnyHashable:kCVPixelFormatType_32BGRA] // 设置缓存区 let queue = DispatchQueue(label: "videoQueue") self.videoDataOutput.setSampleBufferDelegate(self, queue: queue) // 设置好session的输入输出,并启动session self.session.addInput(input) self.session.addOutput(self.videoDataOutput) self.session.beginConfiguration() self.session.sessionPreset = AVCaptureSessionPreset352x288 self.session.commitConfiguration() self.session.startRunning() // 绘制心电图的LineView self.lineView = LineView(frame: self.view.bounds) self.lineView?.initPoints() self.lineView?.backgroundColor = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0) self.view.addSubview(self.lineView!) // 显示心率带label self.lable.text = "0" self.lable.textColor = UIColor.white self.lable.textAlignment = .center self.lineView?.addSubview(self.lable) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) { let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) // 处理缓存区指针 CVPixelBufferLockBaseAddress(imageBuffer!, CVPixelBufferLockFlags.readOnly) let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer!) let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer!) let height = CVPixelBufferGetHeight(imageBuffer!) let width = CVPixelBufferGetWidth(imageBuffer!) CVPixelBufferUnlockBaseAddress(imageBuffer!, CVPixelBufferLockFlags.readOnly) // 计算特征值 let bytesPerPixel = bytesPerRow / width let up = height / 5 let down = height - up let left = width / 5 let right = width - left var avgB = 0 var avgG = 0 var avgR = 0 var counter = 0 for row in 0..<height { for col in 0..<width { if (row < up || row > down) && (col < left || col > right) { let p = row * col * bytesPerPixel counter += 1 avgB += Int((baseAddress?.load(fromByteOffset: p+0, as: UInt8.self))!) avgG += Int((baseAddress?.load(fromByteOffset: p+1, as: UInt8.self))!) avgR += Int((baseAddress?.load(fromByteOffset: p+2, as: UInt8.self))!) } } } avgB /= counter avgG /= counter avgR /= counter var BGR:[Double]=[] BGR.append(Double(avgB)/255.0) BGR.append(Double(avgG)/255.0) BGR.append(Double(avgR)/255.0) // 计算HSV中的H let H = (1.0 / 6.0) * Double(Double(avgG) / 255.0 - Double(avgB) / 255.0) / (BGR.max()! - BGR.min()!) // 寻找波峰,CG循环 if self.step < Int(self.view.frame.width) - 1 { if self.step < Int(self.view.frame.width) - 60 - 1 { var temp:[Double] = [] for index in self.step..<self.step + 60 { temp.append(Double((self.lineView?.points[index].y)!)) } var firstSummit = -1 var secondSummit = -1 var flag = true var finish = false for index in 0..<51 { var beats = 0 for j in 0..<9 { if j == 4 { continue } if temp[index + 4] > temp[index + j] { beats += 1 continue } break } if beats == 10 { if flag { firstSummit = index flag = false } else { secondSummit = index flag = true finish = true } } if finish { finish = false flag = true break } } if firstSummit != secondSummit && firstSummit != -1 && secondSummit != -1 { let distance = secondSummit - firstSummit let cyc = Double(distance) * 1.0 / 29.0 let conclusion = 60 * 1.0 / cyc self.lable.text = String(Int(conclusion)) } } self.step += 1 } else { self.step = 0 } self.lineView?.points[self.step]=CGPoint(x: CGFloat(self.step), y: (self.lineView?.yMid)!+CGFloat(H)*10000.0) DispatchQueue.main.async { self.lineView?.setNeedsDisplay() // self.lable.text = String(H) } // NSLog("B: %d, G: %d, R: %d", avgB,avgG,avgR) } }
mit
beb6429b243a5c154810f1df751a865e
36.689266
151
0.536651
4.678121
false
false
false
false
ggu/2D-RPG-Template
Borba/backend/AssetManager.swift
2
2016
// // AssetManager.swift // Borba // // Created by Gabriel Uribe on 8/10/15. // Copyright (c) 2015 Team Five Three. All rights reserved. // import SpriteKit enum Particle { static let fireball = "Fireball" static let arcaneBolt = "Slimebolt" static let lightningStorm = "LightningBall" static let rain = "Rain" static let fire = "Fire" static let dissipate = "Dissipate" static let levelUp = "LevelUp" static let enemyDeath = "Death" } final class AssetManager { private enum ImagePath { static let mainMap = "ice.png" static let enemy = "enemy.png" static let hero = "hero.png" } static let heroTexture = SKTexture(imageNamed: ImagePath.hero) static let enemyTexture = SKTexture(imageNamed: ImagePath.enemy) static let mapTexture = SKTexture(imageNamed: ImagePath.mainMap) private static var arcaneBoltParticles = AssetManager.loadParticles(Particle.arcaneBolt) private static var fireballParticles = AssetManager.loadParticles(Particle.fireball) private static var lightningStormParticles = AssetManager.loadParticles(Particle.lightningStorm) static func getEmitter(particle: String) -> SKEmitterNode? { return loadParticles(particle) } // MARK: Spell Assets static func getSpellEmitter(spell: Spell.Name) -> SKEmitterNode? { var emitter: SKEmitterNode? = nil switch spell { case .fireball: emitter = fireballParticles?.copy() as? SKEmitterNode case .arcaneBolt: emitter = arcaneBoltParticles?.copy() as? SKEmitterNode case .lightning: emitter = lightningStormParticles?.copy() as? SKEmitterNode } return emitter } // MARK: Utilities private static func loadParticles(resource: String) -> SKEmitterNode? { var particles: SKEmitterNode? = nil if let myParticlePath = NSBundle.mainBundle().pathForResource(resource, ofType: "sks") { particles = NSKeyedUnarchiver.unarchiveObjectWithFile(myParticlePath) as! SKEmitterNode? } return particles } }
mit
1fec1d5120826eb64cd59dc1dbbb9e56
28.647059
98
0.71875
4.097561
false
false
false
false
djwbrown/swift
test/Constraints/generics.swift
2
20448
// RUN: %target-typecheck-verify-swift infix operator +++ protocol ConcatToAnything { static func +++ <T>(lhs: Self, other: T) } func min<T : Comparable>(_ x: T, y: T) -> T { if y < x { return y } return x } func weirdConcat<T : ConcatToAnything, U>(_ t: T, u: U) { t +++ u t +++ 1 u +++ t // expected-error{{argument type 'U' does not conform to expected type 'ConcatToAnything'}} } // Make sure that the protocol operators don't get in the way. var b1, b2 : Bool _ = b1 != b2 extension UnicodeScalar { func isAlpha2() -> Bool { return (self >= "A" && self <= "Z") || (self >= "a" && self <= "z") } } protocol P { static func foo(_ arg: Self) -> Self } struct S : P { static func foo(_ arg: S) -> S { return arg } } func foo<T : P>(_ arg: T) -> T { return T.foo(arg) } // Associated types and metatypes protocol SomeProtocol { associatedtype SomeAssociated } func generic_metatypes<T : SomeProtocol>(_ x: T) -> (T.Type, T.SomeAssociated.Type) { return (type(of: x), type(of: x).SomeAssociated.self) } // Inferring a variable's type from a call to a generic. struct Pair<T, U> { } // expected-note 4 {{'T' declared as parameter to type 'Pair'}} expected-note {{'U' declared as parameter to type 'Pair'}} func pair<T, U>(_ x: T, _ y: U) -> Pair<T, U> { } var i : Int, f : Float var p = pair(i, f) // Conformance constraints on static variables. func f1<S1 : Sequence>(_ s1: S1) {} var x : Array<Int> = [1] f1(x) // Inheritance involving generics and non-generics. class X { func f() {} } class Foo<T> : X { func g() { } } class Y<U> : Foo<Int> { } func genericAndNongenericBases(_ x: Foo<Int>, y: Y<()>) { x.f() y.f() y.g() } func genericAndNongenericBasesTypeParameter<T : Y<()>>(_ t: T) { t.f() t.g() } protocol P1 {} protocol P2 {} func foo<T : P1>(_ t: T) -> P2 { return t // expected-error{{return expression of type 'T' does not conform to 'P2'}} } func foo2(_ p1: P1) -> P2 { return p1 // expected-error{{return expression of type 'P1' does not conform to 'P2'}} } // <rdar://problem/14005696> protocol BinaryMethodWorkaround { associatedtype MySelf } protocol Squigglable : BinaryMethodWorkaround { } infix operator ~~~ func ~~~ <T : Squigglable>(lhs: T, rhs: T) -> Bool where T.MySelf == T { return true } extension UInt8 : Squigglable { typealias MySelf = UInt8 } var rdar14005696 : UInt8 _ = rdar14005696 ~~~ 5 // <rdar://problem/15168483> public struct SomeIterator<C: Collection, Indices: Sequence> : IteratorProtocol, Sequence where C.Index == Indices.Iterator.Element { var seq : C var indices : Indices.Iterator public typealias Element = C.Iterator.Element public mutating func next() -> Element? { fatalError() } public init(elements: C, indices: Indices) { fatalError() } } func f1<T>(seq: Array<T>) { let x = (seq.indices).lazy.reversed() SomeIterator(elements: seq, indices: x) // expected-warning{{unused}} SomeIterator(elements: seq, indices: seq.indices.reversed()) // expected-warning{{unused}} } // <rdar://problem/16078944> func count16078944<T>(_ x: Range<T>) -> Int { return 0 } func test16078944 <T: Comparable>(lhs: T, args: T) -> Int { return count16078944(lhs..<args) // don't crash } // <rdar://problem/22409190> QoI: Passing unsigned integer to ManagedBuffer elements.destroy() class r22409190ManagedBuffer<Value, Element> { final var value: Value { get {} set {}} func withUnsafeMutablePointerToElements<R>( _ body: (UnsafeMutablePointer<Element>) -> R) -> R { } } class MyArrayBuffer<Element>: r22409190ManagedBuffer<UInt, Element> { deinit { self.withUnsafeMutablePointerToElements { elems -> Void in elems.deinitialize(count: self.value) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} } } } // <rdar://problem/22459135> error: 'print' is unavailable: Please wrap your tuple argument in parentheses: 'print((...))' func r22459135() { func h<S : Sequence>(_ sequence: S) -> S.Iterator.Element where S.Iterator.Element : FixedWidthInteger { return 0 } func g(_ x: Any) {} func f(_ x: Int) { g(h([3])) } func f2<TargetType: AnyObject>(_ target: TargetType, handler: @escaping (TargetType) -> ()) { let _: (AnyObject) -> () = { internalTarget in handler(internalTarget as! TargetType) } } } // <rdar://problem/19710848> QoI: Friendlier error message for "[] as Set" // <rdar://problem/22326930> QoI: "argument for generic parameter 'Element' could not be inferred" lacks context _ = [] as Set // expected-error {{generic parameter 'Element' could not be inferred in cast to 'Set<_>}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{14-14=<<#Element: Hashable#>>}} //<rdar://problem/22509125> QoI: Error when unable to infer generic archetype lacks greatness func r22509125<T>(_ a : T?) { // expected-note {{in call to function 'r22509125'}} r22509125(nil) // expected-error {{generic parameter 'T' could not be inferred}} } // <rdar://problem/24267414> QoI: error: cannot convert value of type 'Int' to specified type 'Int' struct R24267414<T> { // expected-note {{'T' declared as parameter to type 'R24267414'}} static func foo() -> Int {} } var _ : Int = R24267414.foo() // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{24-24=<Any>}} // https://bugs.swift.org/browse/SR-599 func SR599<T: FixedWidthInteger>() -> T.Type { return T.self } // expected-note {{in call to function 'SR599()'}} _ = SR599() // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/19215114> QoI: Poor diagnostic when we are unable to infer type protocol Q19215114 {} protocol P19215114 {} // expected-note @+1 {{in call to function 'body9215114'}} func body9215114<T: P19215114, U: Q19215114>(_ t: T) -> (_ u: U) -> () {} func test9215114<T: P19215114, U: Q19215114>(_ t: T) -> (U) -> () { //Should complain about not being able to infer type of U. let f = body9215114(t) // expected-error {{generic parameter 'T' could not be inferred}} return f } // <rdar://problem/21718970> QoI: [uninferred generic param] cannot invoke 'foo' with an argument list of type '(Int)' class Whatever<A: Numeric, B: Numeric> { // expected-note 2 {{'A' declared as parameter to type 'Whatever'}} static func foo(a: B) {} static func bar() {} } Whatever.foo(a: 23) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{9-9=<<#A: Numeric#>, <#B: Numeric#>>}} // <rdar://problem/21718955> Swift useless error: cannot invoke 'foo' with no arguments Whatever.bar() // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{9-9=<<#A: Numeric#>, <#B: Numeric#>>}} // <rdar://problem/27515965> Type checker doesn't enforce same-type constraint if associated type is Any protocol P27515965 { associatedtype R func f() -> R } struct S27515965 : P27515965 { func f() -> Any { return self } } struct V27515965 { init<T : P27515965>(_ tp: T) where T.R == Float {} } func test(x: S27515965) -> V27515965 { return V27515965(x) // expected-error {{generic parameter 'T' could not be inferred}} } protocol BaseProto {} protocol SubProto: BaseProto {} @objc protocol NSCopyish { func copy() -> Any } struct FullyGeneric<Foo> {} // expected-note 11 {{'Foo' declared as parameter to type 'FullyGeneric'}} expected-note 1 {{generic type 'FullyGeneric' declared here}} struct AnyClassBound<Foo: AnyObject> {} // expected-note {{'Foo' declared as parameter to type 'AnyClassBound'}} expected-note {{generic type 'AnyClassBound' declared here}} struct AnyClassBound2<Foo> where Foo: AnyObject {} // expected-note {{'Foo' declared as parameter to type 'AnyClassBound2'}} struct ProtoBound<Foo: SubProto> {} // expected-note {{'Foo' declared as parameter to type 'ProtoBound'}} expected-note {{generic type 'ProtoBound' declared here}} struct ProtoBound2<Foo> where Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'ProtoBound2'}} struct ObjCProtoBound<Foo: NSCopyish> {} // expected-note {{'Foo' declared as parameter to type 'ObjCProtoBound'}} expected-note {{generic type 'ObjCProtoBound' declared here}} struct ObjCProtoBound2<Foo> where Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ObjCProtoBound2'}} struct ClassBound<Foo: X> {} // expected-note {{generic type 'ClassBound' declared here}} struct ClassBound2<Foo> where Foo: X {} // expected-note {{generic type 'ClassBound2' declared here}} struct ProtosBound<Foo> where Foo: SubProto & NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound'}} expected-note {{generic type 'ProtosBound' declared here}} struct ProtosBound2<Foo: SubProto & NSCopyish> {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound2'}} struct ProtosBound3<Foo: SubProto> where Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound3'}} struct AnyClassAndProtoBound<Foo> where Foo: AnyObject, Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'AnyClassAndProtoBound'}} struct AnyClassAndProtoBound2<Foo> where Foo: SubProto, Foo: AnyObject {} // expected-note {{'Foo' declared as parameter to type 'AnyClassAndProtoBound2'}} struct ClassAndProtoBound<Foo> where Foo: X, Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'ClassAndProtoBound'}} struct ClassAndProtosBound<Foo> where Foo: X, Foo: SubProto, Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ClassAndProtosBound'}} struct ClassAndProtosBound2<Foo> where Foo: X, Foo: SubProto & NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ClassAndProtosBound2'}} extension Pair { init(first: T) {} init(second: U) {} var first: T { fatalError() } var second: U { fatalError() } } func testFixIts() { _ = FullyGeneric() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<Any>}} _ = FullyGeneric<Any>() _ = AnyClassBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<AnyObject>}} _ = AnyClassBound<Any>() // expected-error {{'Any' is not convertible to 'AnyObject'}} _ = AnyClassBound<AnyObject>() _ = AnyClassBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{21-21=<AnyObject>}} _ = AnyClassBound2<Any>() // expected-error {{'Any' is not convertible to 'AnyObject'}} _ = AnyClassBound2<AnyObject>() _ = ProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{17-17=<<#Foo: SubProto#>>}} _ = ProtoBound<Any>() // expected-error {{type 'Any' does not conform to protocol 'SubProto'}} _ = ProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{18-18=<<#Foo: SubProto#>>}} _ = ProtoBound2<Any>() // expected-error {{type 'Any' does not conform to protocol 'SubProto'}} _ = ObjCProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{21-21=<NSCopyish>}} _ = ObjCProtoBound<AnyObject>() // expected-error {{type 'AnyObject' does not conform to protocol 'NSCopyish'}} _ = ObjCProtoBound<NSCopyish>() _ = ObjCProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{22-22=<NSCopyish>}} _ = ObjCProtoBound2<AnyObject>() // expected-error {{type 'AnyObject' does not conform to protocol 'NSCopyish'}} _ = ObjCProtoBound2<NSCopyish>() _ = ProtosBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{18-18=<<#Foo: NSCopyish & SubProto#>>}} _ = ProtosBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<<#Foo: NSCopyish & SubProto#>>}} _ = ProtosBound3() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<<#Foo: NSCopyish & SubProto#>>}} _ = AnyClassAndProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{28-28=<<#Foo: SubProto & AnyObject#>>}} _ = AnyClassAndProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{29-29=<<#Foo: SubProto & AnyObject#>>}} _ = ClassAndProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{25-25=<<#Foo: X & SubProto#>>}} _ = ClassAndProtosBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{26-26=<<#Foo: X & NSCopyish & SubProto#>>}} _ = ClassAndProtosBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{27-27=<<#Foo: X & NSCopyish & SubProto#>>}} _ = Pair() // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<Any, Any>}} _ = Pair(first: S()) // expected-error {{generic parameter 'U' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<S, Any>}} _ = Pair(second: S()) // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<Any, S>}} } func testFixItClassBound() { // We infer a single class bound for simple cases in expressions... let x = ClassBound() let x1: String = x // expected-error {{cannot convert value of type 'ClassBound<X>' to specified type 'String'}} let y = ClassBound2() let y1: String = y // expected-error {{cannot convert value of type 'ClassBound2<X>' to specified type 'String'}} // ...but not in types. let z1: ClassBound // expected-error {{reference to generic type 'ClassBound' requires arguments in <...>}} {{21-21=<X>}} let z2: ClassBound2 // expected-error {{reference to generic type 'ClassBound2' requires arguments in <...>}} {{22-22=<X>}} } func testFixItCasting(x: Any) { _ = x as! FullyGeneric // expected-error {{generic parameter 'Foo' could not be inferred in cast to 'FullyGeneric<_>'}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{25-25=<Any>}} } func testFixItContextualKnowledge() { // FIXME: These could propagate backwards. let _: Int = Pair().first // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any, Any>}} let _: Int = Pair().second // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any, Any>}} } func testFixItTypePosition() { let _: FullyGeneric // expected-error {{reference to generic type 'FullyGeneric' requires arguments in <...>}} {{22-22=<Any>}} let _: ProtoBound // expected-error {{reference to generic type 'ProtoBound' requires arguments in <...>}} {{20-20=<<#Foo: SubProto#>>}} let _: ObjCProtoBound // expected-error {{reference to generic type 'ObjCProtoBound' requires arguments in <...>}} {{24-24=<NSCopyish>}} let _: AnyClassBound // expected-error {{reference to generic type 'AnyClassBound' requires arguments in <...>}} {{23-23=<AnyObject>}} let _: ProtosBound // expected-error {{reference to generic type 'ProtosBound' requires arguments in <...>}} {{21-21=<<#Foo: NSCopyish & SubProto#>>}} } func testFixItNested() { _ = Array<FullyGeneric>() // expected-error {{generic parameter 'Foo' could not be inferred}} // expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{25-25=<Any>}} _ = [FullyGeneric]() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any>}} _ = FullyGeneric<FullyGeneric>() // expected-error {{generic parameter 'Foo' could not be inferred}} _ = Pair< // expected-error {{generic parameter 'Foo' could not be inferred}} FullyGeneric, // expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}} FullyGeneric // FIXME: We could diagnose both of these, but we don't. >() _ = Pair< // expected-error {{generic parameter 'Foo' could not be inferred}} FullyGeneric<Any>, FullyGeneric >() _ = Pair< // expected-error {{generic parameter 'Foo' could not be inferred}} FullyGeneric, // expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}} FullyGeneric<Any> >() _ = pair( // expected-error {{generic parameter 'Foo' could not be inferred}} {{none}} FullyGeneric(), // expected-note {{explicitly specify the generic arguments to fix this issue}} FullyGeneric() ) _ = pair( // expected-error {{generic parameter 'Foo' could not be inferred}} {{none}} FullyGeneric<Any>(), FullyGeneric() // expected-note {{explicitly specify the generic arguments to fix this issue}} ) _ = pair( // expected-error {{generic parameter 'Foo' could not be inferred}} {{none}} FullyGeneric(), // expected-note {{explicitly specify the generic arguments to fix this issue}} FullyGeneric<Any>() ) } // rdar://problem/26845038 func occursCheck26845038(a: [Int]) { _ = Array(a)[0] } // rdar://problem/29633747 extension Array where Element: Hashable { public func trimmed(_ elements: [Element]) -> SubSequence { return [] } } func rdar29633747(characters: String.CharacterView) { let _ = Array(characters).trimmed(["("]) } // Null pointer dereference in noteArchetypeSource() class GenericClass<A> {} // expected-note@-1 {{'A' declared as parameter to type 'GenericClass'}} func genericFunc<T>(t: T) { _ = [T: GenericClass] // expected-error {{generic parameter 'A' could not be inferred}} // expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} // expected-error@-2 2 {{type 'T' does not conform to protocol 'Hashable'}} } struct SR_3525<T> {} func sr3525_arg_int(_: inout SR_3525<Int>) {} func sr3525_arg_gen<T>(_: inout SR_3525<T>) {} func sr3525_1(t: SR_3525<Int>) { let _ = sr3525_arg_int(&t) // expected-error {{cannot pass immutable value as inout argument: 't' is a 'let' constant}} } func sr3525_2(t: SR_3525<Int>) { let _ = sr3525_arg_gen(&t) // expected-error {{cannot pass immutable value as inout argument: 't' is a 'let' constant}} } func sr3525_3<T>(t: SR_3525<T>) { let _ = sr3525_arg_gen(&t) // expected-error {{cannot pass immutable value as inout argument: 't' is a 'let' constant}} } class testStdlibType { let _: Array // expected-error {{reference to generic type 'Array' requires arguments in <...>}} {{15-15=<Any>}} } // rdar://problem/32697033 protocol P3 { associatedtype InnerAssoc } protocol P4 { associatedtype OuterAssoc: P3 } struct S3 : P3 { typealias InnerAssoc = S4 } struct S4: P4 { typealias OuterAssoc = S3 } public struct S5 { func f<Model: P4, MO> (models: [Model]) where Model.OuterAssoc == MO, MO.InnerAssoc == Model { } func g<MO, Model: P4> (models: [Model]) where Model.OuterAssoc == MO, MO.InnerAssoc == Model { } func f(arr: [S4]) { f(models: arr) g(models: arr) } }
apache-2.0
7a13285eb0a344ff3329620fa57e7ac3
41.6
219
0.684321
3.819914
false
false
false
false
pkadams67/PKA-Project---Advent-16
Controllers/NSDate Extension.swift
1
2870
// // NSDateAdditions.swift // Advent '16 // // Created by Paul Kirk Adams on 11/15/16. // Copyright © 2016 Paul Kirk Adams. All rights reserved. // import Foundation extension NSDate { var startOfDay: NSDate { let components = self.components components.hour = 0 components.minute = 0 components.second = 0 return NSCalendar.currentCalendar().dateFromComponents(components)! } var endOfTheDay: NSDate { let components = self.components components.hour = 23 components.minute = 59 components.second = 59 return NSCalendar.currentCalendar().dateFromComponents(components)! } var firstDayOfTheMonth: NSDate { var date: NSDate? NSCalendar.currentCalendar().rangeOfUnit(.Month, startDate:&date , interval: nil, forDate: self) return date! } var firstDayOfPreviousMonth: NSDate { return firstDay(false) } var firstDayOfFollowingMonth: NSDate { return firstDay(true) } var monthDayAndYearComponents: NSDateComponents { let components: NSCalendarUnit = [.Year, .Month, .Day] return NSCalendar.currentCalendar().components(components, fromDate: self) } var weekDay: Int { return components.weekday } var numberOfDaysInMonth: Int { return NSCalendar.currentCalendar().rangeOfUnit(.Day, inUnit: .Month, forDate: self).length } var day: Int { return components.day } var month: Int { return components.month } var year: Int { return components.year } var minute: Int { return components.minute } var second: Int { return components.second } var hour: Int { return components.hour } private var components: NSDateComponents { let calendarUnit = NSCalendarUnit(rawValue: UInt.max) let components = NSCalendar.currentCalendar().components(calendarUnit, fromDate: self) return components } private func firstDay(followingMonth: Bool) -> NSDate { let dateComponent = NSDateComponents() dateComponent.month = followingMonth ? 1: -1 let date = NSCalendar.currentCalendar().dateByAddingComponents(dateComponent, toDate: self, options: NSCalendarOptions(rawValue: 0)) return date!.firstDayOfTheMonth } class func date(day: Int, month: Int, year: Int) -> NSDate { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy" let dayString = String(format: "%02d", day) let monthString = String(format: "%02d", month) let yearString = String(format: "%04d", year) return dateFormatter.dateFromString(dayString + "/" + monthString + "/" + yearString)! } }
mit
d8cd922c661417f21b8299c68130164b
27.405941
140
0.632973
4.870968
false
false
false
false
402v/swiftdemo
SwiftDemo/SwiftDemo/ModelController.swift
1
3137
// // ModelController.swift // SwiftDemo // // Created by kimimaro on 15/11/27. // Copyright © 2015年 OneBox Design. All rights reserved. // import UIKit /* A controller object that manages a simple model -- a collection of month names. The controller serves as the data source for the page view controller; it therefore implements pageViewController:viewControllerBeforeViewController: and pageViewController:viewControllerAfterViewController:. It also implements a custom method, viewControllerAtIndex: which is useful in the implementation of the data source methods, and in the initial configuration of the application. There is no need to actually create view controllers for each page in advance -- indeed doing so incurs unnecessary overhead. Given the data model, these methods create, configure, and return a new view controller on demand. */ class ModelController: NSObject, UIPageViewControllerDataSource { var pageData: [String] = [] override init() { super.init() // Create the data model. let dateFormatter = NSDateFormatter() pageData = dateFormatter.monthSymbols } func viewControllerAtIndex(index: Int, storyboard: UIStoryboard) -> DataViewController? { // Return the data view controller for the given index. if (self.pageData.count == 0) || (index >= self.pageData.count) { return nil } // Create a new view controller and pass suitable data. let dataViewController = storyboard.instantiateViewControllerWithIdentifier("DataViewController") as! DataViewController dataViewController.dataObject = self.pageData[index] return dataViewController } func indexOfViewController(viewController: DataViewController) -> Int { // Return the index of the given data view controller. // For simplicity, this implementation uses a static array of model objects and the view controller stores the model object; you can therefore use the model object to identify the index. return pageData.indexOf(viewController.dataObject) ?? NSNotFound } // MARK: - Page View Controller Data Source func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { var index = self.indexOfViewController(viewController as! DataViewController) if (index == 0) || (index == NSNotFound) { return nil } index-- return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!) } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { var index = self.indexOfViewController(viewController as! DataViewController) if index == NSNotFound { return nil } index++ if index == self.pageData.count { return nil } return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!) } }
mit
4c580a1d56ce513c1a2ab1172b4c24f5
39.701299
225
0.716018
5.616487
false
false
false
false
Hidebush/McBlog
McBlog/McBlog/Classes/Module/Discover/DiscoverTableViewController.swift
1
3424
// // DiscoverTableViewController.swift // McBlog // // Created by Theshy on 16/4/15. // Copyright © 2016年 郭月辉. All rights reserved. // import UIKit class DiscoverTableViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() visitorView?.setUpVisitView(false, imageName: "visitordiscover_image_message", message: "登录后,最新、最热微博尽在掌握,不再会与实事潮流擦肩而过") // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... 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 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?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
9a68076ef2f829ebd0c75f024c5802f1
34.357895
157
0.691575
5.391653
false
false
false
false
BennyHarv3/habitica-ios
HabiticaTests/TestObserver.swift
2
6925
import XCTest import ReactiveCocoa import ReactiveSwift import Result /** A `TestObserver` is a wrapper around an `Observer` that saves all events to an internal array so that assertions can be made on a signal's behavior. To use, just create an instance of `TestObserver` that matches the type of signal/producer you are testing, and observer/start your signal by feeding it the wrapped observer. For example, ``` let test = TestObserver<Int, NoError>() mySignal.observer(test.observer) // ... later ... test.assertValues([1, 2, 3]) ``` */ internal final class TestObserver <Value, E: Error> { internal private(set) var events: [Event<Value, E>] = [] internal private(set) var observer: Observer<Value, E>! internal init() { self.observer = Observer<Value, E>(action) } private func action(event: Event<Value, E>) -> () { self.events.append(event) } /// Get all of the next values emitted by the signal. internal var values: [Value] { return self.events.filter { $0.isNext }.map { $0.value! } } /// Get the last value emitted by the signal. internal var lastValue: Value? { return self.values.last } /// `true` if at least one `.Next` value has been emitted. internal var didEmitValue: Bool { return self.values.count > 0 } /// The failed error if the signal has failed. internal var failedError: Error? { return self.events.filter { $0.isFailed }.map { $0.error! }.first } /// `true` if a `.Failed` event has been emitted. internal var didFail: Bool { return self.failedError != nil } /// `true` if a `.Completed` event has been emitted. internal var didComplete: Bool { return self.events.filter { $0.isCompleted }.count > 0 } /// `true` if a .Interrupt` event has been emitted. internal var didInterrupt: Bool { return self.events.filter { $0.isInterrupted }.count > 0 } internal func assertDidComplete(message: String = "Should have completed.", file: StaticString = #file, line: UInt = #line) { XCTAssertTrue(self.didComplete, message, file: file, line: line) } internal func assertDidFail(message: String = "Should have failed.", file: StaticString = #file, line: UInt = #line) { XCTAssertTrue(self.didFail, message, file: file, line: line) } internal func assertDidNotFail(message: String = "Should not have failed.", file: StaticString = #file, line: UInt = #line) { XCTAssertFalse(self.didFail, message, file: file, line: line) } internal func assertDidInterrupt(message: String = "Should have failed.", file: StaticString = #file, line: UInt = #line) { XCTAssertTrue(self.didInterrupt, message, file: file, line: line) } internal func assertDidNotInterrupt(message: String = "Should not have failed.", file: StaticString = #file, line: UInt = #line) { XCTAssertFalse(self.didInterrupt, message, file: file, line: line) } internal func assertDidNotComplete(message: String = "Should not have completed", file: StaticString = #file, line: UInt = #line) { XCTAssertFalse(self.didComplete, message, file: file, line: line) } internal func assertDidEmitValue(message: String = "Should have emitted at least one value.", file: StaticString = #file, line: UInt = #line) { XCTAssert(self.values.count > 0, message, file: file, line: line) } internal func assertDidNotEmitValue(message: String = "Should not have emitted any values.", file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(0, self.values.count, message, file: file, line: line) } internal func assertDidTerminate( message: String = "Should have terminated, i.e. completed/failed/interrupted.", file: StaticString = #file, line: UInt = #line) { XCTAssertTrue(self.didFail || self.didComplete || self.didInterrupt, message, file: file, line: line) } internal func assertDidNotTerminate( message: String = "Should not have terminated, i.e. completed/failed/interrupted.", file: StaticString = #file, line: UInt = #line) { XCTAssertTrue(!self.didFail && !self.didComplete && !self.didInterrupt, message, file: file, line: line) } internal func assertValueCount(count: Int, _ message: String? = nil, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(count, self.values.count, message ?? "Should have emitted \(count) values", file: file, line: line) } } extension TestObserver where Value: Equatable { internal func assertValue(value: Value, _ message: String? = nil, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(1, self.values.count, "A single item should have been emitted.", file: file, line: line) XCTAssertEqual(value, self.lastValue, message ?? "A single value of \(value) should have been emitted", file: file, line: line) } internal func assertLastValue(value: Value, _ message: String? = nil, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(value, self.lastValue, message ?? "Last emitted value is equal to \(value).", file: file, line: line) } internal func assertValues(values: [Value], _ message: String = "", file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(values, self.values, message, file: file, line: line) } } extension TestObserver where Value: Sequence, Value.Iterator.Element: Equatable { internal func assertValue(value: Value, _ message: String? = nil, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(1, self.values.count, "A single item should have been emitted.", file: file, line: line) XCTAssertEqual(Array(value), self.lastValue.map(Array.init) ?? [], message ?? "A single value of \(value) should have been emitted", file: file, line: line) } internal func assertLastValue(value: Value, _ message: String? = nil, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(Array(value), self.lastValue.map(Array.init) ?? [], message ?? "Last emitted value is equal to \(value).", file: file, line: line) } }
gpl-3.0
e548c61b27abb6c5927aac9e02c6a3bf
42.012422
112
0.600866
4.416454
false
true
false
false
taichisocks/taichiOSX
taichiOSX/SettingViewController.swift
1
3319
// // SettingViewController.swift // taichiOSX // // Created by taichi on 15/4/20. // Copyright (c) 2015 taichi. All rights reserved. // import Cocoa class SettingViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() remoteHostTextField.stringValue = SettingsModel.sharedInstance.remoteHost remotePortTextField.stringValue = SettingsModel.sharedInstance.remotePort passwordTextField.stringValue = SettingsModel.sharedInstance.password localHostTextField.stringValue = SettingsModel.sharedInstance.localHost localPortTextField.stringValue = SettingsModel.sharedInstance.localPort for i in 0..<methodSelector.numberOfItems { if methodSelector.itemTitleAtIndex(i) == SettingsModel.sharedInstance.method { methodSelector.selectItemAtIndex(i) break } } } @IBOutlet weak var remoteHostTextField: NSTextField! @IBOutlet weak var remotePortTextField: NSTextField! @IBOutlet weak var methodSelector: NSPopUpButton! @IBOutlet weak var passwordTextField: NSTextField! @IBOutlet weak var localHostTextField: NSTextField! @IBOutlet weak var localPortTextField: NSTextField! @IBAction func importConfig(sender: AnyObject) { alertMsg("Not implement") } @IBAction func export(sender: AnyObject) { alertMsg("Not implement") } func alertMsg(msg: String) { let alert = NSAlert() alert.messageText = msg alert.runModal() } @IBAction func restartProxy(sender: AnyObject) { let remoteHost = remoteHostTextField.stringValue SettingsModel.sharedInstance.remoteHost = remoteHost var c_remote_host = remoteHost.cStringUsingEncoding(NSUTF8StringEncoding)! let remotePort = remotePortTextField.integerValue SettingsModel.sharedInstance.remotePort = remotePortTextField.stringValue var c_remote_port = CInt(remotePort) // var c_remote_port = remotePort.cStringUsingEncoding(NSUTF8StringEncoding)! let method = methodSelector.titleOfSelectedItem! SettingsModel.sharedInstance.method = method var c_method = method.cStringUsingEncoding(NSUTF8StringEncoding)! let password = passwordTextField.stringValue SettingsModel.sharedInstance.password = password var c_password = password.cStringUsingEncoding(NSUTF8StringEncoding)! let localHost = localHostTextField.stringValue SettingsModel.sharedInstance.localHost = localHost var c_local_host = localHost.cStringUsingEncoding(NSUTF8StringEncoding)! let localPort = localPortTextField.integerValue PacServer.sharedInstance.socks5Port = localPort SettingsModel.sharedInstance.localPort = localPortTextField.stringValue var c_local_port = CInt(localPort) // var c_local_port = localPort.cStringUsingEncoding(NSUTF8StringEncoding)! SettingsModel.sharedInstance.saveData() startProxyWithConfig(c_remote_host, c_remote_port, c_method, c_password, c_local_host, c_local_port) PacServer.sharedInstance.start(listenPort: 8100, error: nil) } }
apache-2.0
95edc51966870da3cce672f1c3a94d08
34.308511
108
0.697801
5.013595
false
false
false
false
JakeLin/IBAnimatable
Sources/ActivityIndicators/Animations/ActivityIndicatorAnimationBallScaleMultiple.swift
2
1981
// // Created by Tom Baranes on 23/08/16. // Copyright (c) 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationBallScaleMultiple: ActivityIndicatorAnimating { // MARK: Properties fileprivate let duration: CFTimeInterval = 1 // MARK: ActivityIndicatorAnimating public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let beginTime = layer.currentMediaTime let beginTimes = [0, 0.2, 0.4] let animation = defaultAnimation for i in 0 ..< 3 { let circle = ActivityIndicatorShape.circle.makeLayer(size: size, color: color) let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height) animation.beginTime = beginTime + beginTimes[i] circle.frame = frame circle.opacity = 0 circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } } // MARK: - Setup private extension ActivityIndicatorAnimationBallScaleMultiple { var defaultAnimation: CAAnimationGroup { let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimation] animation.timingFunctionType = .linear animation.duration = duration animation.repeatCount = .infinity animation.isRemovedOnCompletion = false return animation } var scaleAnimation: CABasicAnimation { let scaleAnimation = CABasicAnimation(keyPath: .scale) scaleAnimation.duration = duration scaleAnimation.fromValue = 0 scaleAnimation.toValue = 1 return scaleAnimation } var opacityAnimation: CAKeyframeAnimation { let opacityAnimation = CAKeyframeAnimation(keyPath: .opacity) opacityAnimation.duration = duration opacityAnimation.keyTimes = [0, 0.05, 1] opacityAnimation.values = [0, 1, 0] return opacityAnimation } }
mit
01e61390c2b5c3a75d712f0b8eeb8838
28.567164
86
0.694599
4.855392
false
false
false
false
caobo56/Juyou
JuYou/JuYou/ThirdParty/CyclePictureView/AuxiliaryModels.swift
1
5125
// // AuxiliaryModels.swift // CyclePictureView // // Created by wl on 15/11/8. // Copyright © 2015年 wl. All rights reserved. // /*************************************************** * 如果您发现任何BUG,或者有更好的建议或者意见,欢迎您的指出。 *邮箱:[email protected].感谢您的支持 ***************************************************/ import UIKit //======================================================== // MARK: - 图片类型处理 //======================================================== enum ImageSource { case Local(name: String) case Network(urlStr: String) } enum ImageType { case Local case Network } struct ImageBox { var imageType: ImageType var imageArray: [ImageSource] init(imageType: ImageType, imageArray: [String]) { self.imageType = imageType self.imageArray = [] switch imageType { case .Local: for str in imageArray { self.imageArray.append(ImageSource.Local(name: str)) } case .Network: for str in imageArray { self.imageArray.append(ImageSource.Network(urlStr: str)) } } } subscript (index: Int) -> ImageSource { get { return self.imageArray[index] } } } //======================================================== // MARK: - PageControl对齐协议 //======================================================== enum PageControlAliment { case CenterBottom case LeftBottom case RightBottom } protocol PageControlAlimentProtocol: class{ var pageControlAliment: PageControlAliment {get set} func AdjustPageControlPlace(pageControl: UIPageControl) } extension PageControlAlimentProtocol where Self : UIView { func AdjustPageControlPlace(pageControl: UIPageControl) { if !pageControl.hidden { switch self.pageControlAliment { case .CenterBottom: let pageW:CGFloat = CGFloat(pageControl.numberOfPages * 15) let pageH:CGFloat = 20 let pageX = self.center.x - 0.5 * pageW let pageY = self.bounds.height - pageH pageControl.frame = CGRectMake(pageX, pageY, pageW, pageH) case .LeftBottom: let pageW:CGFloat = CGFloat(pageControl.numberOfPages * 15) let pageH:CGFloat = 20 let pageX = self.bounds.origin.x let pageY = self.bounds.height - pageH pageControl.frame = CGRectMake(pageX, pageY, pageW, pageH) case .RightBottom: let pageW:CGFloat = CGFloat(pageControl.numberOfPages * 15) let pageH:CGFloat = 20 let pageX = self.bounds.width - pageW let pageY = self.bounds.height - pageH pageControl.frame = CGRectMake(pageX, pageY, pageW, pageH) } } } } //======================================================== // MARK: - 无限滚动协议 //======================================================== protocol EndlessCycleProtocol: class{ /// 是否开启自动滚动 var autoScroll: Bool {get set} /// 开启自动滚动后,自动翻页的时间 var timeInterval: Double {get set} /// 用于控制自动滚动的定时器 var timer: NSTimer? {get set} /// 是否开启无限滚动模式 var needEndlessScroll: Bool {get set} /// 开启无限滚动模式后,cell需要增加的倍数 var imageTimes: Int {get} /// 开启无限滚动模式后,真实的cell数量 var actualItemCount: Int {get set} /** 设置定时器,用于控制自动翻页 */ func setupTimer(userInfo: AnyObject?) /** 在无限滚动模式中,显示的第一页其实是最中间的那一个cell */ func showFirstImagePageInCollectionView(collectionView: UICollectionView) } extension EndlessCycleProtocol where Self : UIView { func autoChangePicture(collectionView: UICollectionView) { guard actualItemCount != 0 else { return } let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout let currentIndex = Int(collectionView.contentOffset.x / flowLayout.itemSize.width) let nextIndex = currentIndex + 1 if nextIndex >= actualItemCount { showFirstImagePageInCollectionView(collectionView) }else { collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: nextIndex, inSection: 0), atScrollPosition: .None, animated: true) } } func showFirstImagePageInCollectionView(collectionView: UICollectionView) { guard actualItemCount != 0 else { return } var newIndex = 0 if needEndlessScroll { newIndex = actualItemCount / 2 } collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: newIndex, inSection: 0), atScrollPosition: .None, animated: false) } }
apache-2.0
52d96ba448a83ed27bca871a4bb5ec5b
28.95
138
0.555718
4.716535
false
false
false
false
gernotstarke/pdfstamper
mac-stamper/pdfstamper/pdfstamper/RootViewController.swift
1
7541
// // RootViewController.swift // pdfstamper // // Created by Dr. Gernot Starke, June-Sept 2015. // Copyright (c) 2015 Dr. Gernot Starke. All rights reserved. // import Cocoa class RootViewController: NSViewController { // application name and version, to be shown in footer of view // (in versionLabel) let appName: String = "org.arc42.PdfStamper" var appVersionInfo: String = "-.-.-" var myModel: PdfStamperModel = PdfStamperModel.init() // MARK labels and textfields @IBOutlet weak var sourceDirectoryButton: NSButton! @IBOutlet weak var sourceDirTextField: NSTextField! @IBOutlet weak var sourceDirStatusLabel: NSTextField! var sourceDirStatusLabelColor: NSColor! = NSColor.redColor() @IBOutlet weak var targetDirTextField: NSTextField! @IBOutlet weak var targetDirStatusLabel: NSTextField! var targetDirStatusLabelColor: NSColor! = NSColor.redColor() @IBOutlet weak var overwriteButton: NSButtonCell! @IBOutlet weak var overwriteLabel: NSTextField! @IBOutlet weak var versionLabel: NSTextField! @IBOutlet weak var arc42Label: NSButton! @IBOutlet weak var startButton: NSButtonCell! @IBOutlet weak var helpButton: NSButtonCell! /// button actions /// =================== @IBAction func sourceDirButton(sender: AnyObject) { selectSourceDirectory() } @IBAction func targetDirButton(sender: AnyObject) { selectTargetDirectory() } @IBAction func startButton(sender: AnyObject) { } @IBAction func cancelButton(sender: AnyObject) { NSApplication.sharedApplication().terminate(self) } @IBAction func arc42LabelButton(sender: AnyObject) { print("arc42 label clicked") } @IBAction func overwriteButton(sender: AnyObject) { } @IBAction func helpButton(sender: AnyObject) { } // override funcs // ==================== override func viewDidLoad() { super.viewDidLoad() setVersionLabel() disableStartButton() setSourceDirStatusLabel("no source directory selected") setTargetDirStatusLabel("no target directory selected") sourceDirTextField.toolTip = "Select source directory with pdf files to be processed (stamped). No files will be modified." disableOverwriteButtonAndLabel() // TODO: better to have them enabled and check for changes with property observers/binding disableTextField( sourceDirTextField ) disableTextField( targetDirTextField ) } override func awakeFromNib() { print("awakeFromNib: \(self.className)") } // open directory chooser (NSOpenPanel) // ==================================== private func selectSourceDirectory() { let openPanel = directoryOpenPanel("Select Source Directory") if (openPanel.runModal() == NSFileHandlingPanelOKButton) { let fileURL = openPanel.URL! //print("path = \(fileURL.path!)") // TODO set values in MODEL, not directly! self.sourceDirTextField.stringValue = "\(fileURL.path!)" self.sourceDirStatusLabelColor = self.fieldValidityToColor( true ) self.setSourceDirStatusLabel("\(FileUtil.nrOfPdfFilesInFolder( fileURL )) pdf files found") } } private func selectTargetDirectory() { let openPanel = directoryOpenPanel("Select Target Directory") if (openPanel.runModal() == NSFileHandlingPanelOKButton) { let fileURL = openPanel.URL! // Now we have a directory selected. Its URL = fileURL self.targetDirTextField.stringValue = "\(fileURL.path!)" self.targetDirStatusLabelColor = fieldValidityToColor(FileUtil.isDirectory(fileURL.path!)) self.setTargetDirStatusLabel("\(FileUtil.nrOfPdfFilesInFolder( fileURL )) pdf files found") } // TODO: check status of start button enableOverwriteButtonAndLabel() } /// manual text field changes /// ========================== @IBAction func sourceDirectoryField(sender: AnyObject) { print("textField \(sender) action triggered") } @IBAction func targetDirTextField(sender: AnyObject) { } /// disable text field /// ------------------ private func disableTextField(textField: NSTextField!) { textField.enabled = false } // create directory selection panel // ---------------------------------- private func directoryOpenPanel( title: String ) -> NSOpenPanel { let openPanel = NSOpenPanel() openPanel.title = title openPanel.canChooseDirectories = true openPanel.allowsMultipleSelection = false openPanel.canCreateDirectories = false openPanel.canChooseFiles = false return openPanel } /// check if start button shall be enabled /// -------------------------------------- private func checkStartButton() { // required conditions to enable startButton: // * source directory valid // * source directory contains >0 pdf files // * target directory valid // * no "twin" files (files with twins in source directory, identical name!) // OR // * overwrite-flag enabled } /// convert text field validity to label color private func fieldValidityToColor(valid: Bool) -> NSColor! { switch valid { case true: return NSColor.blueColor() case false: return NSColor.redColor() } } // initialization functions // ======================== private func setVersionLabel() { // read current version info from application bundle let infoDictionary: NSDictionary = NSBundle.mainBundle().infoDictionary as NSDictionary! let shortVersionString = infoDictionary["CFBundleShortVersionString"] as! String versionLabel.stringValue = "\(appName), version \(shortVersionString)" } private func disableStartButton() { startButton.enabled = false } // overwrite files in target directory? private func disableOverwriteButtonAndLabel() { overwriteButton.state = 0 overwriteButton.stringValue = "" overwriteButton.title = "" overwriteButton.enabled = false overwriteLabel.stringValue = "overwrite:" overwriteLabel.enabled = false overwriteLabel.textColor = NSColor.grayColor() } private func enableOverwriteButtonAndLabel() { overwriteButton.enabled = true overwriteLabel.enabled = true overwriteLabel.textColor = NSColor.redColor() } private func setSourceDirStatusLabel( sourceDirStatus: String ) { setLabelTextAndColor( sourceDirStatusLabel, text: sourceDirStatus, color: sourceDirStatusLabelColor) } private func setTargetDirStatusLabel( targetDirStatus: String) { setLabelTextAndColor( targetDirStatusLabel, text: targetDirStatus, color: targetDirStatusLabelColor) } private func setLabelTextAndColor( label: NSTextField!, text: String, color: NSColor!) { label.stringValue = text label.textColor = color } }
apache-2.0
4d02c9458901b05b01e2413ed8148500
30.290456
131
0.622994
5.456585
false
false
false
false
GraphQLSwift/GraphQL
Tests/GraphQLTests/ValidationTests/ExampleSchema.swift
1
11384
@testable import GraphQL // interface Being { // name(surname: Boolean): String // } let ValidationExampleBeing = try! GraphQLInterfaceType( name: "Being", fields: [ "name": GraphQLField( type: GraphQLString, args: ["surname": GraphQLArgument(type: GraphQLBoolean)], resolve: { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil } ), ], resolveType: { _, _, _ in "Unknown" } ) // interface Mammal { // mother: Mammal // father: Mammal // } let ValidationExampleMammal = try! GraphQLInterfaceType( name: "Mammal", fields: [ "mother": GraphQLField(type: GraphQLTypeReference("Mammal")), "father": GraphQLField(type: GraphQLTypeReference("Mammal")), ], resolveType: { _, _, _ in "Unknown" } ) // interface Pet implements Being { // name(surname: Boolean): String // } let ValidationExamplePet = try! GraphQLInterfaceType( name: "Pet", interfaces: [ValidationExampleBeing], fields: [ "name": GraphQLField( type: GraphQLString, args: ["surname": GraphQLArgument(type: GraphQLBoolean)], resolve: { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil } ), ], resolveType: { _, _, _ in "Unknown" } ) // interface Canine implements Mammal & Being { // name(surname: Boolean): String // mother: Canine // father: Canine // } let ValidationExampleCanine = try! GraphQLInterfaceType( name: "Canine", interfaces: [ValidationExampleMammal, ValidationExampleBeing], fields: [ "name": GraphQLField( type: GraphQLString, args: ["surname": GraphQLArgument(type: GraphQLBoolean)] ), "mother": GraphQLField( type: GraphQLTypeReference("Mammal") ), "father": GraphQLField( type: GraphQLTypeReference("Mammal") ), ], resolveType: { _, _, _ in "Unknown" } ) // enum DogCommand { // SIT // HEEL // DOWN // } let ValidationExampleDogCommand = try! GraphQLEnumType( name: "DogCommand", values: [ "SIT": GraphQLEnumValue( value: "SIT" ), "DOWN": GraphQLEnumValue( value: "DOWN" ), "HEEL": GraphQLEnumValue( value: "HEEL" ), ] ) // type Dog implements Being & Pet & Mammal & Canine { // name(surname: Boolean): String // nickname: String // barkVolume: Int // barks: Boolean // doesKnowCommand(dogCommand: DogCommand): Boolean // isHouseTrained(atOtherHomes: Boolean = true): Boolean // isAtLocation(x: Int, y: Int): Boolean // mother: Dog // father: Dog // } let ValidationExampleDog = try! GraphQLObjectType( name: "Dog", fields: [ "name": GraphQLField( type: GraphQLString, args: ["surname": GraphQLArgument(type: GraphQLBoolean)], resolve: { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil } ), "nickname": GraphQLField(type: GraphQLString) { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil }, "barkVolume": GraphQLField(type: GraphQLInt) { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil }, "barks": GraphQLField(type: GraphQLBoolean) { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil }, "doesKnowCommand": GraphQLField( type: GraphQLBoolean, args: [ "dogCommand": GraphQLArgument(type: ValidationExampleDogCommand), ], resolve: { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil } ), "isHousetrained": GraphQLField( type: GraphQLBoolean, args: [ "atOtherHomes": GraphQLArgument( type: GraphQLBoolean, defaultValue: true ), ], resolve: { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil } ), "isAtLocation": GraphQLField( type: GraphQLBoolean, args: [ "x": GraphQLArgument( type: GraphQLInt ), "y": GraphQLArgument( type: GraphQLInt ), ], resolve: { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil } ), "mother": GraphQLField( type: GraphQLTypeReference("Mammal"), resolve: { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil } ), "father": GraphQLField( type: GraphQLTypeReference("Mammal"), resolve: { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil } ), "owner": GraphQLField(type: ValidationExampleHuman) { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil }, ], interfaces: [ ValidationExampleBeing, ValidationExamplePet, ValidationExampleMammal, ValidationExampleCanine, ] ) // enum FurColor { // BROWN // BLACK // TAN // SPOTTED // NO_FUR // UNKNOWN // } let ValidationExampleFurColor = try! GraphQLEnumType( name: "FurColor", values: [ "BROWN": GraphQLEnumValue(value: ["value": 0]), "BLACK": GraphQLEnumValue(value: ["value": 1]), "TAN": GraphQLEnumValue(value: ["value": 2]), "SPOTTED": GraphQLEnumValue(value: ["value": 3]), "NO_FUR": GraphQLEnumValue(value: ["value": .null]), "UNKNOWN": GraphQLEnumValue(value: ["value": .null]), ] ) // type Cat implements Being & Pet { // name(surname: Boolean): String // nickname: String // meows: Boolean // meowsVolume: Int // furColor: FurColor // } let ValidationExampleCat = try! GraphQLObjectType( name: "Cat", fields: [ "name": GraphQLField( type: GraphQLString, args: ["surname": GraphQLArgument(type: GraphQLBoolean)], resolve: { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil } ), "nickname": GraphQLField(type: GraphQLString) { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil }, "meows": GraphQLField(type: GraphQLBoolean) { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil }, "meowVolume": GraphQLField(type: GraphQLInt) { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil }, "furColor": GraphQLField(type: ValidationExampleFurColor) { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil }, ], interfaces: [ValidationExampleBeing, ValidationExamplePet] ) // union CatOrDog = Cat | Dog let ValidationExampleCatOrDog = try! GraphQLUnionType( name: "CatOrDog", resolveType: { _, _, _ in "Unknown" }, types: [ValidationExampleCat, ValidationExampleDog] ) // interface Intelligent { // iq: Int // } let ValidationExampleIntelligent = try! GraphQLInterfaceType( name: "Intelligent", fields: [ "iq": GraphQLField(type: GraphQLInt), ], resolveType: { _, _, _ in "Unknown" } ) // interface Sentient { // name: String! // } let ValidationExampleSentient = try! GraphQLInterfaceType( name: "Sentient", fields: [ "name": GraphQLField(type: GraphQLNonNull(GraphQLString)) { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil }, ], resolveType: { _, _, _ in "Unknown" } ) // type Alien implements Sentient { // name: String! // homePlanet: String // } let ValidationExampleAlien = try! GraphQLObjectType( name: "Alien", fields: [ "name": GraphQLField(type: GraphQLNonNull(GraphQLString)) { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil }, "homePlanet": GraphQLField(type: GraphQLString) { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil }, ], interfaces: [ValidationExampleSentient] ) // type Human implements Sentient { // name: String! // pets: [Pet!]! // } let ValidationExampleHuman = try! GraphQLObjectType( name: "Human", fields: [ "name": GraphQLField( type: GraphQLNonNull(GraphQLString), args: ["surname": GraphQLArgument(type: GraphQLBoolean)], resolve: { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil } ), "pets": GraphQLField( type: GraphQLList(ValidationExamplePet), resolve: { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil } ), "iq": GraphQLField( type: GraphQLInt, resolve: { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil } ), ], interfaces: [ValidationExampleBeing, ValidationExampleIntelligent] ) // enum CatCommand { JUMP } let ValidationExampleCatCommand = try! GraphQLEnumType( name: "CatCommand", values: [ "JUMP": GraphQLEnumValue( value: "JUMP" ), ] ) // union DogOrHuman = Dog | Human let ValidationExampleDogOrHuman = try! GraphQLUnionType( name: "DogOrHuman", resolveType: { _, _, _ in "Unknown" }, types: [ValidationExampleDog, ValidationExampleHuman] ) // union HumanOrAlien = Human | Alien let ValidationExampleHumanOrAlien = try! GraphQLUnionType( name: "HumanOrAlien", resolveType: { _, _, _ in "Unknown" }, types: [ValidationExampleHuman, ValidationExampleAlien] ) // type QueryRoot { // dog: Dog // } let ValidationExampleQueryRoot = try! GraphQLObjectType( name: "QueryRoot", fields: [ "dog": GraphQLField(type: ValidationExampleDog) { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil }, "catOrDog": GraphQLField(type: ValidationExampleCatOrDog) { inputValue, _, _, _ -> String? in print(type(of: inputValue)) return nil }, "humanOrAlien": GraphQLField(type: ValidationExampleHumanOrAlien), ] ) let ValidationExampleSchema = try! GraphQLSchema( query: ValidationExampleQueryRoot, types: [ ValidationExampleCat, ValidationExampleDog, ValidationExampleHuman, ValidationExampleAlien, ] )
mit
0a445366eb6191714433468a67bec6f9
27.108642
101
0.541813
4.257292
false
false
false
false
TwilioDevEd/twiliochat-swift
twiliochat/ChatTableCell.swift
1
709
import UIKit class ChatTableCell: UITableViewCell { static let TWCUserLabelTag = 200 static let TWCDateLabelTag = 201 static let TWCMessageLabelTag = 202 var userLabel: UILabel! var messageLabel: UILabel! var dateLabel: UILabel! func setUser(user:String!, message:String!, date:String!) { userLabel.text = user messageLabel.text = message dateLabel.text = date } override func awakeFromNib() { userLabel = viewWithTag(ChatTableCell.TWCUserLabelTag) as? UILabel messageLabel = viewWithTag(ChatTableCell.TWCMessageLabelTag) as? UILabel dateLabel = viewWithTag(ChatTableCell.TWCDateLabelTag) as? UILabel } }
mit
28060cfcafa5a2986b1b007d280e437b
29.826087
80
0.691114
4.695364
false
false
false
false
benlangmuir/swift
SwiftCompilerSources/Sources/SIL/Effects.swift
4
11740
//===--- Effects.swift - Defines function effects -------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 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 // //===----------------------------------------------------------------------===// /// An effect on a function argument. public struct ArgumentEffect : CustomStringConvertible, CustomReflectable { public typealias Path = SmallProjectionPath /// Selects which argument (or return value) and which projection of the argument /// or return value. /// /// For example, the selection `%0.s1` would select the second struct field of `arg` in /// func foo(_ arg: Mystruct) { ... } public struct Selection : CustomStringConvertible { public enum ArgumentOrReturn : Equatable { case argument(Int) case returnValue } // Which argument or return value. public let value: ArgumentOrReturn /// Which projection(s) of the argument or return value. public let pathPattern: Path public init(_ value: ArgumentOrReturn, pathPattern: Path) { self.value = value self.pathPattern = pathPattern } public init(_ arg: Argument, pathPattern: Path) { self.init(.argument(arg.index), pathPattern: pathPattern) } /// Copy the selection by applying a delta on the argument index. /// /// This is used when copying argument effects for specialized functions where /// the indirect result is converted to a direct return value (in this case the /// `resultArgDelta` is -1). public init(copiedFrom src: Selection, resultArgDelta: Int) { switch (src.value, resultArgDelta) { case (let a, 0): self.value = a case (.returnValue, 1): self.value = .argument(0) case (.argument(0), -1): self.value = .returnValue case (.argument(let a), let d): self.value = .argument(a + d) default: fatalError() } self.pathPattern = src.pathPattern } public var argumentIndex: Int { switch value { case .argument(let argIdx): return argIdx default: fatalError("expected argument") } } public var description: String { let posStr: String switch value { case .argument(let argIdx): posStr = "%\(argIdx)" case .returnValue: posStr = "%r" } let pathStr = (pathPattern.isEmpty ? "" : ".\(pathPattern)") return "\(posStr)\(pathStr)" } public func matches(_ rhsValue: ArgumentOrReturn, _ rhsPath: Path) -> Bool { return value == rhsValue && rhsPath.matches(pattern: pathPattern) } } //----------------------------------------------------------------------// // Members of ArgumentEffect //----------------------------------------------------------------------// public enum Kind { /// The selected argument value does not escape. /// /// Syntax examples: /// !%0 // argument 0 does not escape /// !%0.** // argument 0 and all transitively contained values do not escape /// case notEscaping /// The selected argument value escapes to the specified selection (= first payload). /// /// Syntax examples: /// %0.s1 => %r // field 2 of argument 0 exclusively escapes via return. /// %0.s1 -> %1 // field 2 of argument 0 - and other values - escape to argument 1. /// /// The "exclusive" flag (= second payload) is true if only the selected argument escapes /// to the specified selection, but nothing else escapes to it. /// For example, "exclusive" is true for the following function: /// /// @_effect(escaping c => return) /// func exclusiveEscape(_ c: Class) -> Class { return c } /// /// but not in this case: /// /// var global: Class /// /// @_effect(escaping c -> return) /// func notExclusiveEscape(_ c: Class) -> Class { return cond ? c : global } /// case escaping(Selection, Bool) // to, exclusive } /// To which argument (and projection) does this effect apply to? public let selectedArg: Selection /// The kind of effect. public let kind: Kind /// True, if this effect is derived in an optimization pass. /// False, if this effect is defined in the Swift source code. public let isDerived: Bool public init(_ kind: Kind, selectedArg: Selection, isDerived: Bool = true) { self.selectedArg = selectedArg self.kind = kind self.isDerived = isDerived } /// Copy the ArgumentEffect by applying a delta on the argument index. /// /// This is used when copying argument effects for specialized functions where /// the indirect result is converted to a direct return value (in this case the /// `resultArgDelta` is -1). init(copiedFrom srcEffect: ArgumentEffect, resultArgDelta: Int) { func copy(_ srcSelection: Selection) -> Selection { return Selection(copiedFrom: srcSelection, resultArgDelta: resultArgDelta) } self.selectedArg = copy(srcEffect.selectedArg) self.isDerived = srcEffect.isDerived switch srcEffect.kind { case .notEscaping: self.kind = .notEscaping case .escaping(let toSelectedArg, let exclusive): self.kind = .escaping(copy(toSelectedArg), exclusive) } } public var description: String { switch kind { case .notEscaping: return "!\(selectedArg)" case .escaping(let toSelectedArg, let exclusive): return "\(selectedArg) \(exclusive ? "=>" : "->") \(toSelectedArg)" } } public var customMirror: Mirror { Mirror(self, children: []) } } /// All argument effects for a function. /// /// In future we might add non-argument-specific effects, too, like `readnone`, `readonly`. public struct FunctionEffects : CustomStringConvertible, CustomReflectable { public var argumentEffects: [ArgumentEffect] = [] public init() {} public init(copiedFrom src: FunctionEffects, resultArgDelta: Int) { self.argumentEffects = src.argumentEffects.map { ArgumentEffect(copiedFrom: $0, resultArgDelta: resultArgDelta) } } public func canEscape(argumentIndex: Int, path: ArgumentEffect.Path, analyzeAddresses: Bool) -> Bool { return !argumentEffects.contains(where: { if case .notEscaping = $0.kind, $0.selectedArg.value == .argument(argumentIndex) { // Any address of a class property of an object, which is passed to the function, cannot // escape the function. Whereas a value stored in such a property could escape. let p = (analyzeAddresses ? path.popLastClassAndValuesFromTail() : path) if p.matches(pattern: $0.selectedArg.pathPattern) { return true } } return false }) } public mutating func removeDerivedEffects() { argumentEffects = argumentEffects.filter { !$0.isDerived } } public var description: String { return "[" + argumentEffects.map { $0.description }.joined(separator: ", ") + "]" } public var customMirror: Mirror { Mirror(self, children: []) } } //===----------------------------------------------------------------------===// // Parsing //===----------------------------------------------------------------------===// extension StringParser { mutating func parseEffectFromSource(for function: Function, params: Dictionary<String, Int>) throws -> ArgumentEffect { if consume("notEscaping") { let selectedArg = try parseSelectionFromSource(for: function, params: params) return ArgumentEffect(.notEscaping, selectedArg: selectedArg, isDerived: false) } if consume("escaping") { let from = try parseSelectionFromSource(for: function, params: params) let exclusive = try parseEscapingArrow() let to = try parseSelectionFromSource(for: function, params: params, acceptReturn: true) return ArgumentEffect(.escaping(to, exclusive), selectedArg: from, isDerived: false) } try throwError("unknown effect") } mutating func parseEffectFromSIL(for function: Function, isDerived: Bool) throws -> ArgumentEffect { if consume("!") { let selectedArg = try parseSelectionFromSIL(for: function) return ArgumentEffect(.notEscaping, selectedArg: selectedArg, isDerived: isDerived) } let from = try parseSelectionFromSIL(for: function) let exclusive = try parseEscapingArrow() let to = try parseSelectionFromSIL(for: function, acceptReturn: true) return ArgumentEffect(.escaping(to, exclusive), selectedArg: from, isDerived: isDerived) } private mutating func parseEscapingArrow() throws -> Bool { if consume("=>") { return true } if consume("->") { return false } try throwError("expected '=>' or '->'") } mutating func parseSelectionFromSource(for function: Function, params: Dictionary<String, Int>, acceptReturn: Bool = false) throws -> ArgumentEffect.Selection { let value: ArgumentEffect.Selection.ArgumentOrReturn if consume("self") { if !function.hasSelfArgument { try throwError("function does not have a self argument") } value = .argument(function.selfArgumentIndex) } else if consume("return") { if !acceptReturn { try throwError("return not allowed here") } if function.numIndirectResultArguments > 0 { if function.numIndirectResultArguments != 1 { try throwError("multi-value returns not supported yet") } value = .argument(0) } else { value = .returnValue } } else if let name = consumeIdentifier() { guard let argIdx = params[name] else { try throwError("parameter not found") } value = .argument(argIdx + function.numIndirectResultArguments) } else { try throwError("parameter name or return expected") } let valueType: Type switch value { case .argument(let argIdx): valueType = function.argumentTypes[argIdx] case .returnValue: valueType = function.resultType } if consume(".") { let path = try parseProjectionPathFromSource(for: function, type: valueType) return ArgumentEffect.Selection(value, pathPattern: path) } if !valueType.isClass { switch value { case .argument: try throwError("the argument is not a class - add 'anyValueFields'") case .returnValue: try throwError("the return value is not a class - add 'anyValueFields'") } } return ArgumentEffect.Selection(value, pathPattern: ArgumentEffect.Path()) } mutating func parseSelectionFromSIL(for function: Function, acceptReturn: Bool = false) throws -> ArgumentEffect.Selection { let value: ArgumentEffect.Selection.ArgumentOrReturn if consume("%r") { if !acceptReturn { try throwError("return not allowed here") } value = .returnValue } else if consume("%") { guard let argIdx = consumeInt() else { try throwError("expected argument index") } value = .argument(argIdx) } else { try throwError("expected parameter or return") } if consume(".") { return try ArgumentEffect.Selection(value, pathPattern: parseProjectionPathFromSIL()) } return ArgumentEffect.Selection(value, pathPattern: ArgumentEffect.Path()) } }
apache-2.0
b00f0cce58f0b1840724cd96eda0945a
34.361446
104
0.62615
4.557453
false
false
false
false
mobgeek/swift
Projetos Colaborativos/FAQApp/FAQApp/FAQ App/CustomClasses&Extensions.swift
2
6534
// // CustomClasses:Extensions.swift // FAQ App // // Created by Renan Siqueira de Souza Mesquita on 07/07/15. // Copyright © 2015 Renan Siqueira de Souza Mesquita. All rights reserved. // import UIKit //Este arquivo contém extensões e classes customizadas com o intuito de contralizar implementações padrões de métodos que são utilizadas pelas classes das cenas ao longo do programa. //Dessa forma, não precisamos, por exemplo, criar para todas as tableViews do código, uma implementação de viewWillAppear que retira a seleção das células ao voltar para alguma cena. //Um outro exemplo é o do scrollView. Todas as cenas no App lidam com scrollView. E existe uma funcionalidade no App que esconde a barra inferior quando a tela é arrastada para cima, e quem nos ajuda a implementar isso é o protocolo UIScrollViewDelegate. Imagina termos que para cada arquivo de cada view recriar as mesmas implementacões para os métodos desse protocolo, seria praticamente crtl+C e crtl+V, tornando o código muito grande. //SubClassing e Extensions nos ajudam a resolver esses problemas ///Registra as coordenadas de onde o scrollView está parado antes de iniciar a rolagem var currentPoint = CGPoint(x: 0, y: 0) ///Extensão da classe UIViewController para que ela passe a adotar o protocolo UIScrollViewDelegate e já possua 2 implementações de 2 métodos desse protocolo. Assim, toda classe que for subClasse de UIViewController, já estará em conformidade com o protocolo UIScrollViewDelegate, além de herdar essas 2 implementações de métodos. extension UIViewController: UIScrollViewDelegate { ///Armazena o tipo de barra da view atual var bar: UIView? { //Verifica se é uma tabBar (de um tabBarController) ou uma ToolBar (de um Navigation Controller) que está presente na view. Para isso usamos Optional Chaining para verificar se o acnestral mais próximo é uma tabBarController ou um navigationController. get { return self.tabBarController?.tabBar ?? self.navigationController?.toolbar } } ///Sempre que o usuário estiver prestes a arrastar a scrollView, vai pegar o posicionamento dela na interface. public func scrollViewWillBeginDragging(scrollView: UIScrollView) { currentPoint = scrollView.contentOffset print("currentPoint: \(currentPoint.y)") } ///Sempre que a scrollView estiver em movimento, verifica se foi para cima ou para baixo public func scrollViewDidScroll(scrollView: UIScrollView) { print("scrollView: \(scrollView.contentOffset.y)") //Se está na origem, não precisa realizar as comparações seguintes, deixando a barra sempre visível. if currentPoint.y == 0 { //bar == tabBar OU bar == toolBar bar?.hidden = false return } //Lembrando de plano cartesiano da matemática, y são as direção para cima ou para baixo. //(1) Caso a scrollView seja arrastado para baixo, vai verificar que o y dela é menor que o y do ponto quando ele estava parado. Então, mostra a barra inferior. //(2) Caso o scrollView seja arrastado para cima, vai verificar que o y dele é maior que o y de ponto quando ele estava parado. Então, esconde a barra inferior, pois o usuário está interessado em ler o conteúdo mais abaixo. if (scrollView.contentOffset.y < currentPoint.y) { //(1) bar?.hidden = false } else if (scrollView.contentOffset.y > currentPoint.y) { //(2) bar?.hidden = true } } } ///Classe customizada que herda todas as caracteristicas e funcionalidades de UIViewController que vai fornecer, a principio, uma implementação padrão para viewWillAppear para todos as classes que herdarem dela. Foi preciso fazer esse subClassing pois essa era uma forma de poder sobrescrever o método viewWillAppear de UIViewController class CustomViewController: UIViewController { ///Sempre chamado quando a view reaparece durante a execução do App. Tudo definido dentro desse método já será padrão para todo tableViewController. A principio vamos usar esse método para (1) fazer com que a barra inferior reapareça e (2) resetar as coordenadas do ponto atual da scrollView override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //(1) //Como essa classe é subClasse de UIViewController, a propriedade bar foi herdade por essa classe ;) bar?.hidden = false //(2) //Reseta o ponto atual para a origem currentPoint.x = 0 currentPoint.y = 0 } } ///Extensão para a classe UITableViewController. Como essa classe já possui uma superClasse definida pela Apple, a UIViewController, UITableViewController já herdou todos os métodos de UIScrollViewDelegate implementados pela extensão que fizemos anteriormente para UIViewController. Dentro dessa extensão é fornecida uma implementação de viewWillAppear para a classe UITableViewController que está sobreescrevendo a da superClasse UIViewController adcionando novas funcionalidades. extension UITableViewController { ///Sempre chamado quando a view reaparece durante a execução do App. ///Tudo definido dentro desse método já será padrão para todo tableViewController. A principio vamos usar esse método para (1) tirar a seleção da célula quando voltarmos para a view que nos levou para a view seguinte, (2) fazer com que a barra inferior reapareça e (3) resetar as coordenadas do ponto atual do scrollView public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //Se estiver iniciando o App, não é desejado que desempacote nulo, por isso o Optional Binding if let indexPath = tableView.indexPathForSelectedRow { //(1) tableView.deselectRowAtIndexPath(indexPath, animated: true) } //(2) //Como essa classe é subClasse de UIViewController, a propriedade bar foi herdada por essa classe ;) bar?.hidden = false //(3) currentPoint.x = 0 currentPoint.y = 0 } }
mit
acb7f97ea2c801e46e1c05e33a88c348
43.743056
481
0.696415
4.004351
false
false
false
false
sindresorhus/touch-bar-simulator
Touch Bar Simulator/Utilities.swift
1
8765
import Cocoa import Combine import Defaults /** Convenience function for initializing an object and modifying its properties. ``` let label = with(NSTextField()) { $0.stringValue = "Foo" $0.textColor = .systemBlue view.addSubview($0) } ``` */ @discardableResult func with<T>(_ item: T, update: (inout T) throws -> Void) rethrows -> T { var this = item try update(&this) return this } extension CGRect { func adding(padding: Double) -> Self { Self( x: origin.x - padding, y: origin.y - padding, width: width + padding * 2, height: height + padding * 2 ) } /** Returns a `CGRect` where `self` is centered in `rect`. */ func centered(in rect: Self, xOffset: Double = 0, yOffset: Double = 0) -> Self { Self( x: ((rect.width - size.width) / 2) + xOffset, y: ((rect.height - size.height) / 2) + yOffset, width: size.width, height: size.height ) } } extension NSWindow { var toolbarView: NSView? { standardWindowButton(.closeButton)?.superview } } extension NSWindow { enum MoveXPositioning { case left case center case right } enum MoveYPositioning { case top case center case bottom } func moveTo(x xPositioning: MoveXPositioning, y yPositioning: MoveYPositioning) { guard let screen = NSScreen.main else { return } let visibleFrame = screen.visibleFrame let x: Double let y: Double switch xPositioning { case .left: x = visibleFrame.minX case .center: x = visibleFrame.midX - frame.width / 2 case .right: x = visibleFrame.maxX - frame.width } switch yPositioning { case .top: // Defect fix: Keep docked windows below menubar area. // Previously, the window would obstruct menubar clicks when the menubar was set to auto-hide. // Now, the window stays below that area. let menubarThickness = NSStatusBar.system.thickness y = min(visibleFrame.maxY - frame.height, screen.frame.maxY - menubarThickness - frame.height) case .center: y = visibleFrame.midY - frame.height / 2 case .bottom: y = visibleFrame.minY } setFrameOrigin(CGPoint(x: x, y: y)) } } extension NSView { func addSubviews(_ subviews: NSView...) { subviews.forEach { addSubview($0) } } } extension NSMenuItem { var isChecked: Bool { get { state == .on } set { state = newValue ? .on : .off } } } extension NSMenuItem { convenience init( _ title: String, keyEquivalent: String = "", keyModifiers: NSEvent.ModifierFlags? = nil, isChecked: Bool = false, action: ((NSMenuItem) -> Void)? = nil ) { self.init(title: title, action: nil, keyEquivalent: keyEquivalent) if let keyModifiers = keyModifiers { self.keyEquivalentModifierMask = keyModifiers } self.isChecked = isChecked if let action = action { self.onAction = action } } } final class ObjectAssociation<T: Any> { subscript(index: AnyObject) -> T? { get { objc_getAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque()) as! T? } set { objc_setAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque(), newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } @objc protocol TargetActionSender: AnyObject { var target: AnyObject? { get set } var action: Selector? { get set } } extension NSControl: TargetActionSender {} extension NSMenuItem: TargetActionSender {} extension NSGestureRecognizer: TargetActionSender {} private final class ActionTrampoline<Sender>: NSObject { typealias ActionClosure = ((Sender) -> Void) let action: ActionClosure init(action: @escaping ActionClosure) { self.action = action } @objc fileprivate func performAction(_ sender: TargetActionSender) { action(sender as! Sender) } } private enum TargetActionSenderAssociatedKeys { fileprivate static let trampoline = ObjectAssociation<AnyObject>() } extension TargetActionSender { /** Closure version of `.action`. ``` let menuItem = NSMenuItem(title: "Unicorn") menuItem.onAction = { sender in print("NSMenuItem action: \(sender)") } ``` */ var onAction: ((Self) -> Void)? { get { (TargetActionSenderAssociatedKeys.trampoline[self] as? ActionTrampoline<Self>)?.action } set { guard let newValue = newValue else { target = nil action = nil TargetActionSenderAssociatedKeys.trampoline[self] = nil return } let trampoline = ActionTrampoline(action: newValue) TargetActionSenderAssociatedKeys.trampoline[self] = trampoline target = trampoline action = #selector(ActionTrampoline<Self>.performAction) } } func addAction(_ action: @escaping ((Self) -> Void)) { // TODO: The problem with doing it like this is that there's no way to add ability to remove an action. I think a better solution would be to store an array of action handlers using associated object. let lastAction = onAction onAction = { sender in lastAction?(sender) action(sender) } } } extension NSApplication { var isLeftMouseDown: Bool { currentEvent?.type == .leftMouseDown } var isOptionKeyDown: Bool { NSEvent.modifierFlags.contains(.option) } } // TODO: Find a namespace to put this onto. I don't like free-floating functions. func pressKey(keyCode: CGKeyCode, flags: CGEventFlags = []) { let eventSource = CGEventSource(stateID: .hidSystemState) let keyDown = CGEvent(keyboardEventSource: eventSource, virtualKey: keyCode, keyDown: true) let keyUp = CGEvent(keyboardEventSource: eventSource, virtualKey: keyCode, keyDown: false) keyDown?.flags = flags keyDown?.post(tap: .cghidEventTap) keyUp?.post(tap: .cghidEventTap) } extension NSWindow.Level { private static func level(for cgLevelKey: CGWindowLevelKey) -> Self { .init(rawValue: Int(CGWindowLevelForKey(cgLevelKey))) } public static let desktop = level(for: .desktopWindow) public static let desktopIcon = level(for: .desktopIconWindow) public static let backstopMenu = level(for: .backstopMenu) public static let dragging = level(for: .draggingWindow) public static let overlay = level(for: .overlayWindow) public static let help = level(for: .helpWindow) public static let utility = level(for: .utilityWindow) public static let assistiveTechHigh = level(for: .assistiveTechHighWindow) public static let cursor = level(for: .cursorWindow) public static let minimum = level(for: .minimumWindow) public static let maximum = level(for: .maximumWindow) } enum SSApp { static let url = Bundle.main.bundleURL static func quit() { NSApp.terminate(nil) } static func relaunch() { let configuration = NSWorkspace.OpenConfiguration() configuration.createsNewApplicationInstance = true NSWorkspace.shared.openApplication(at: url, configuration: configuration) { _, error in DispatchQueue.main.async { if let error = error { NSApp.presentError(error) return } quit() } } } } extension NSScreen { // Returns a publisher that sends updates when anything related to screens change. // This includes screens being added/removed, resolution change, and the screen frame changing (dock and menu bar being toggled). static var publisher: AnyPublisher<Void, Never> { Publishers.Merge( NotificationCenter.default.publisher(for: NSApplication.didChangeScreenParametersNotification), // We use a wake up notification as the screen setup might have changed during sleep. For example, a screen could have been unplugged. NSWorkspace.shared.notificationCenter.publisher(for: NSWorkspace.didWakeNotification) ) .map { _ in } .eraseToAnyPublisher() } } extension Collection where Element == DefaultsObservation { @discardableResult func tieAllToLifetime(of weaklyHeldObject: AnyObject) -> Self { for observation in self { observation.tieToLifetime(of: weaklyHeldObject) } return self } } extension Defaults { static func tiedToLifetime(of weaklyHeldObject: AnyObject, @ArrayBuilder<DefaultsObservation> _ observations: () -> [DefaultsObservation]) { observations().tieAllToLifetime(of: weaklyHeldObject) } } @resultBuilder enum ArrayBuilder<T> { static func buildBlock(_ elements: T...) -> [T] { elements } } extension NSStatusBarButton { private var buttonCell: NSButtonCell? { cell as? NSButtonCell } /** Whether the status bar button is prevented from (blue) highlighting on click. The default is `false`. Can be useful if clicking the status bar button triggers an action instead of opening a menu/popover. */ var preventsHighlight: Bool { get { buttonCell?.highlightsBy.isEmpty ?? false } set { buttonCell?.highlightsBy = newValue ? [] : [.changeBackgroundCellMask] } } } /// Convenience for opening URLs. extension URL { func open() { NSWorkspace.shared.open(self) } } extension String { /** ``` "https://sindresorhus.com".openUrl() ``` */ func openUrl() { URL(string: self)?.open() } }
mit
f2dec5dff01978144b4377fe72c83f91
23.551821
202
0.716828
3.583401
false
false
false
false
Pocketbrain/nativeadslib-ios
PocketMediaNativeAdsTests/Core/NativeAdsRequestTest.swift
1
11771
// // NativeAdsRequestTest.swift // PocketMediaNativeAds // // Created by Iain Munro on 06/09/16. // // import XCTest import AdSupport @testable import PocketMediaNativeAds class SpyDelegate: NativeAdsConnectionDelegate { var didReceiveErrorExpectation: XCTestExpectation? var didReceiveErrorResult: Bool? = .none var didReceiveResultsExpectation: XCTestExpectation? var didReceiveResultsResult: Bool? = .none /** This method is invoked whenever while retrieving NativeAds an error has occured */ @objc func didReceiveError(_ error: Error) { print("didReceiveError: \(error)") guard let expectation = didReceiveErrorExpectation else { XCTFail("SpyDelegate was not setup correctly. Missing XCTExpectation reference") return } didReceiveErrorResult = true expectation.fulfill() } /** This method allows the delegate to receive a collection of NativeAds after making an NativeAdRequest. - nativeAds: Collection of NativeAds received after making a NativeAdRequest */ @objc func didReceiveResults(_ nativeAds: [NativeAd]) { guard let expectation = didReceiveResultsExpectation else { XCTFail("SpyDelegate was not setup correctly. Missing XCTExpectation reference") return } didReceiveResultsResult = true expectation.fulfill() } } class MockedNSURLSessionDataTask: URLSessionDataTask { var resumeCalled: Bool? = false override func resume() { resumeCalled = true } } class MockURLSession: URLSession { fileprivate(set) var lastURL: URL? var task: MockedNSURLSessionDataTask = MockedNSURLSessionDataTask() override func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> URLSessionDataTask { lastURL = url return task } } class NativeAdsRequestTest: XCTestCase { var testData: Data! override func setUp() { super.setUp() if let file = Bundle(for: NativeAdsRequestTest.self).path(forResource: "Tests", ofType: "json") { self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) } else { XCTFail("Can't find the test JSON file") } } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testRetrieveAds() { let delegate = SpyDelegate() let session = MockURLSession() let nativeAdsrequest = NativeAdsRequest(adPlacementToken: "test", delegate: delegate, session: session) nativeAdsrequest.retrieveAds(10) let expected = nativeAdsrequest.getNativeAdsURL("test", limit: 10, imageType: EImageType.allImages) XCTAssert(session.task.resumeCalled!, "NativeAdsRequest should've called resume to actually do the network request.§") if let expectedUrl = URL(string: expected) { XCTAssert(session.lastURL! == expectedUrl) } else { XCTFail("Couldn't get the expected url") } } func testReceivedAdsError() { let delegate = SpyDelegate() // Pass an error var expectation = self.expectation(description: "NativeAdsRequest calls the delegate didReceiveError method due to the fact that th ereceivedAds method receiving an error") delegate.didReceiveErrorExpectation = expectation delegate.didReceiveErrorResult = false let nativeAdsrequest = NativeAdsRequest(adPlacementToken: "test", delegate: delegate) nativeAdsrequest.receivedAds(testData, response: nil, error: NSError(domain: "Example", code: 0, userInfo: nil)) waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } guard let result = delegate.didReceiveErrorResult else { XCTFail("Expected delegate to be called") return } XCTAssertTrue(result) } // Data is nil expectation = self.expectation(description: "NativeAdsRequest calls the delegate didReceiveError method due to the fact that the data sent is a nil value.") delegate.didReceiveErrorExpectation = expectation delegate.didReceiveErrorResult = false nativeAdsrequest.receivedAds(nil, response: nil, error: nil) waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } guard let result = delegate.didReceiveErrorResult else { XCTFail("Expected delegate to be called") return } XCTAssertTrue(result) } // Invalid json expectation = self.expectation(description: "NativeAdsRequest calls the delegate didReceiveError method due to the fact that the data sent is not json.") delegate.didReceiveErrorExpectation = expectation delegate.didReceiveErrorResult = false nativeAdsrequest.receivedAds("This is not a proper response. Not json ;(".data(using: String.Encoding.utf8), response: nil, error: nil) waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } guard let result = delegate.didReceiveErrorResult else { XCTFail("Expected delegate to be called") return } XCTAssertTrue(result) } // Incorrect expectation = self.expectation(description: "NativeAdsRequest calls the delegate didReceiveError method due to the fact that the data sent is incomplete or incorrect json.") delegate.didReceiveErrorExpectation = expectation delegate.didReceiveErrorResult = false nativeAdsrequest.receivedAds("[{}]".data(using: String.Encoding.utf8), response: nil, error: nil) waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } guard let result = delegate.didReceiveErrorResult else { XCTFail("Expected delegate to be called") return } XCTAssertTrue(result) } // Zero ads expectation = self.expectation(description: "NativeAdsRequest calls the delegate didReceiveError method due to the fact that the receivedAds has 0 offers to send back.") delegate.didReceiveErrorExpectation = expectation delegate.didReceiveErrorResult = false nativeAdsrequest.receivedAds("[]".data(using: String.Encoding.utf8), response: nil, error: nil) waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } guard let result = delegate.didReceiveErrorResult else { XCTFail("Expected delegate to be called") return } XCTAssertTrue(result) } } func testReceivedSuccess() { let delegate = SpyDelegate() let expectation = self.expectation(description: "NativeAdsRequest calls the delegate didReceiveResults method due to the fact that it has received a proper response back from the server.") delegate.didReceiveResultsExpectation = expectation delegate.didReceiveResultsResult = false let nativeAdsrequest = NativeAdsRequest(adPlacementToken: "test", delegate: delegate) nativeAdsrequest.receivedAds(testData, response: nil, error: nil) waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } guard let result = delegate.didReceiveResultsResult else { XCTFail("Expected delegate to be called") return } XCTAssertTrue(result) } } func testGetNativeAdsURL() { var nativeAdsrequest = NativeAdsRequest(adPlacementToken: "test", delegate: nil) let placement_key = "test123" var url = nativeAdsrequest.getNativeAdsURL(placement_key, limit: 123, imageType: EImageType.banner) if let value = getQueryStringParameter(url, param: "output") { if value != "json" { XCTFail("output should be json") } } else { XCTFail("output parameter is not defined") } if let value = getQueryStringParameter(url, param: "os") { if value != "ios" { XCTFail("os should be ios") } } else { XCTFail("os parameter is not defined") } if let value = getQueryStringParameter(url, param: "limit") { if Int(value) != 123 { XCTFail("limit should be 123") } } else { XCTFail("limit parameter is not defined") } if let value = getQueryStringParameter(url, param: "version") { if Float(value) == nil { XCTFail("version should be a number") } } else { XCTFail("version parameter is not defined") } if let value = getQueryStringParameter(url, param: "model") { let expected = UIDevice.current.model.characters.split { $0 == " " }.map { String($0) }[0] if value != expected { XCTFail("model should be a iPhone") } } else { XCTFail("model parameter is not defined") } if let value = getQueryStringParameter(url, param: "token") { let expected = ASIdentifierManager.shared().advertisingIdentifier?.uuidString if value != expected { XCTFail("token should be the advertisingIdentifier of the phone") } } else { XCTFail("token parameter is not defined") } if let value = getQueryStringParameter(url, param: "placement_key") { if value != placement_key { XCTFail("placement_key should the test value sent along as a parameter.") } } else { XCTFail("placement_key parameter is not defined") } if let value = getQueryStringParameter(url, param: "image_type") { if value != String(describing: EImageType.banner) { XCTFail("placement_key should the test value sent along as a parameter.") } } else { XCTFail("image_type parameter is not defined") } nativeAdsrequest = NativeAdsRequest(adPlacementToken: "test", delegate: nil, advertisingTrackingEnabled: false) url = nativeAdsrequest.getNativeAdsURL(placement_key, limit: 123, imageType: EImageType.allImages) if let value = getQueryStringParameter(url, param: "optout") { if Int(value) != 1 { XCTFail("optout should be set to 1 if advertisingTrackingEnabled is set to false.") } } else { XCTFail("optout parameter is not defined") } } } func getQueryStringParameter(_ url: String?, param: String) -> String? { let url = url, urlComponents = URLComponents(string: url!), queryItems = urlComponents!.queryItems! return queryItems.filter({ item in item.name == param }).first?.value! }
mit
014482cd6a6bbd381ea13076908980e4
33.516129
196
0.624724
5.201061
false
true
false
false
gregomni/swift
test/Generics/superclass_constraint.swift
2
6145
// RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=on -requirement-machine-inferred-signatures=on // RUN: not %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-protocol-signatures=on -requirement-machine-inferred-signatures=on > %t.dump 2>&1 // RUN: %FileCheck %s < %t.dump class A { func foo() { } } class B : A { func bar() { } } class Other { } func f1<T : A>(_: T) where T : Other {} // expected-error{{no type for 'T' can satisfy both 'T : Other' and 'T : A'}} func f2<T : A>(_: T) where T : B {} // expected-warning@-1{{redundant superclass constraint 'T' : 'A'}} class GA<T> {} class GB<T> : GA<T> {} protocol P {} func f3<T, U>(_: T, _: U) where U : GA<T> {} func f4<T, U>(_: T, _: U) where U : GA<T> {} func f5<T, U : GA<T>>(_: T, _: U) {} func f6<U : GA<T>, T : P>(_: T, _: U) {} func f7<U, T>(_: T, _: U) where U : GA<T>, T : P {} func f8<T : GA<A>>(_: T) where T : GA<B> {} // expected-error{{no type for 'T' can satisfy both 'T : GA<B>' and 'T : GA<A>'}} func f9<T : GA<A>>(_: T) where T : GB<A> {} // expected-warning@-1{{redundant superclass constraint 'T' : 'GA<A>'}} func f10<T : GB<A>>(_: T) where T : GA<A> {} // expected-warning@-1{{redundant superclass constraint 'T' : 'GA<A>'}} func f11<T : GA<T>>(_: T) { } func f12<T : GA<U>, U : GB<T>>(_: T, _: U) { } func f13<T : U, U : GA<T>>(_: T, _: U) { } // expected-error{{type 'T' constrained to non-protocol, non-class type 'U'}} // rdar://problem/24730536 // Superclass constraints can be used to resolve nested types to concrete types. protocol P3 { associatedtype T } protocol P2 { associatedtype T : P3 } class C : P3 { typealias T = Int } class S : P2 { typealias T = C } // CHECK-LABEL: .superclassConformance1(t:)@ // CHECK-NEXT: Generic signature: <T where T : C> func superclassConformance1<T>(t: T) where T : C, T : P3 {} // expected-warning{{redundant conformance constraint 'C' : 'P3'}} // CHECK-LABEL: .superclassConformance2(t:)@ // CHECK-NEXT: Generic signature: <T where T : C> func superclassConformance2<T>(t: T) where T : C, T : P3 {} // expected-warning{{redundant conformance constraint 'C' : 'P3'}} protocol P4 { } class C2 : C, P4 { } // CHECK-LABEL: .superclassConformance3(t:)@ // CHECK-NEXT: Generic signature: <T where T : C2> func superclassConformance3<T>(t: T) where T : C, T : P4, T : C2 {} // expected-warning@-1{{redundant superclass constraint 'T' : 'C'}} // expected-warning@-2{{redundant conformance constraint 'T' : 'P4'}} protocol P5: A { } protocol P6: A, Other { } // expected-error {{no type for 'Self' can satisfy both 'Self : Other' and 'Self : A'}} // expected-error@-1{{multiple inheritance from classes 'A' and 'Other'}} func takeA(_: A) { } func takeP5<T: P5>(_ t: T) { takeA(t) // okay } protocol P7 { // expected-error@-1{{no type for 'Self.Assoc' can satisfy both 'Self.Assoc : Other' and 'Self.Assoc : A'}} associatedtype Assoc: A, Other } // CHECK-LABEL: .superclassConformance4@ // CHECK-NEXT: Generic signature: <T, U where T : P3, U : P3, T.[P3]T : C, T.[P3]T == U.[P3]T> func superclassConformance4<T: P3, U: P3>(_: T, _: U) where T.T: C, // expected-warning{{redundant superclass constraint 'T.T' : 'C'}} U.T: C, T.T == U.T { } // Lookup of superclass associated types from inheritance clause protocol Elementary { associatedtype Element func get() -> Element } class Classical : Elementary { func get() -> Int { return 0 } } // CHECK-LABEL: .genericFunc@ // CHECK-NEXT: Generic signature: <T, U where T : Elementary, U : Classical, T.[Elementary]Element == Int> func genericFunc<T : Elementary, U : Classical>(_: T, _: U) where T.Element == U.Element {} // Lookup within superclass constraints. protocol P8 { associatedtype B } class C8 { struct A { } } // CHECK-LABEL: .superclassLookup1@ // CHECK-NEXT: Generic signature: <T where T : C8, T : P8, T.[P8]B == C8.A> func superclassLookup1<T: C8 & P8>(_: T) where T.A == T.B { } // CHECK-LABEL: .superclassLookup2@ // CHECK-NEXT: Generic signature: <T where T : C8, T : P8, T.[P8]B == C8.A> func superclassLookup2<T: P8>(_: T) where T.A == T.B, T: C8 { } // CHECK-LABEL: .superclassLookup3@ // CHECK-NEXT: Generic signature: <T where T : C8, T : P8, T.[P8]B == C8.A> func superclassLookup3<T>(_: T) where T.A == T.B, T: C8, T: P8 { } // SR-5165 class C9 {} protocol P9 {} class C10 : C9, P9 { } protocol P10 { associatedtype A: C9 } // CHECK-LABEL: .testP10@ // CHECK-NEXT: Generic signature: <T where T : P10, T.[P10]A : C10> func testP10<T>(_: T) where T: P10, T.A: C10 { } // Nested types of generic class-constrained type parameters. protocol Tail { associatedtype E } protocol Rump : Tail { associatedtype E = Self } class Horse<T>: Rump { } func hasRedundantConformanceConstraint<X : Horse<T>, T>(_: X) where X : Rump {} // expected-warning@-1 {{redundant conformance constraint 'Horse<T>' : 'Rump'}} // SR-5862 protocol X { associatedtype Y : A } // CHECK-LABEL: .noRedundancyWarning@ // CHECK: Generic signature: <C where C : X, C.[X]Y == B> func noRedundancyWarning<C : X>(_ wrapper: C) where C.Y == B {} // Qualified lookup bug -- <https://bugs.swift.org/browse/SR-2190> protocol Init { init(x: ()) } class Base { required init(y: ()) {} } class Derived : Base {} func g<T : Init & Derived>(_: T.Type) { _ = T(x: ()) _ = T(y: ()) } // Binding a class-constrained generic parameter to a subclass existential is // not sound. struct G<T : Base> {} // expected-note@-1 2 {{requirement specified as 'T' : 'Base' [with T = Base & P]}} _ = G<Base & P>() // expected-error {{'G' requires that 'any Base & P' inherit from 'Base'}} func badClassConstrainedType(_: G<Base & P>) {} // expected-error@-1 {{'G' requires that 'any Base & P' inherit from 'Base'}} // Reduced from CoreStore in source compat suite public protocol Pony {} public class Teddy: Pony {} public struct Paddock<P: Pony> {} public struct Barn<T: Teddy> { // CHECK-LABEL: Barn.foo@ // CHECK: Generic signature: <T, S where T : Teddy> public func foo<S>(_: S, _: Barn<T>, _: Paddock<T>) {} }
apache-2.0
c3d1629387e4c366387c8d3d57abc416
26.556054
177
0.625061
2.895853
false
false
false
false
hanhailong/practice-swift
Calendar/Retrieving the Attendees of an Event/Retrieving the Attendees of an Event/AppDelegate.swift
2
6250
// // AppDelegate.swift // Retrieving the Attendees of an Event // // Created by Domenico on 25/05/15. // License MIT // import UIKit import EventKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.requestAuthorization() return true } // Find Source in the EventStore func sourceInEventStore( eventStore: EKEventStore, type: EKSourceType, title: String) -> EKSource?{ for source in eventStore.sources() as! [EKSource]{ if source.sourceType.value == type.value && source.title.caseInsensitiveCompare(title) == NSComparisonResult.OrderedSame{ return source } } return nil } // Find calendar by Title func calendarWithTitle( title: String, type: EKCalendarType, source: EKSource, eventType: EKEntityType) -> EKCalendar?{ for calendar in source.calendarsForEntityType(eventType) as! Set<EKCalendar>{ if calendar.title.caseInsensitiveCompare(title) == NSComparisonResult.OrderedSame && calendar.type.value == type.value{ return calendar } } return nil } func enumerateTodayEventsInStore(store: EKEventStore, calendar: EKCalendar){ /* The event starts from today, right now */ let startDate = NSDate() /* The end date will be 1 day from now */ let endDate = startDate.dateByAddingTimeInterval(24 * 60 * 60) /* Create the predicate that we can later pass to the event store in order to fetch the events */ let searchPredicate = store.predicateForEventsWithStartDate( startDate, endDate: endDate, calendars: [calendar]) /* Fetch all the events that fall between the starting and the ending dates */ let events = store.eventsMatchingPredicate(searchPredicate) as! [EKEvent] /* Array of NSString equivalents of the values in the EKParticipantRole enumeration */ let attendeeRole = [ "Unknown", "Required", "Optional", "Chair", "Non Participant", ] /* Array of NSString equivalents of the values in the EKParticipantStatus enumeration */ let attendeeStatus = [ "Unknown", "Pending", "Accepted", "Declined", "Tentative", "Delegated", "Completed", "In Process", ] /* Array of NSString equivalents of the values in the EKParticipantType enumeration */ let attendeeType = [ "Unknown", "Person", "Room", "Resource", "Group" ] /* Go through all the events and print their information out to the console */ for event in events{ println("Event title = \(event.title)") println("Event start date = \(event.startDate)") println("Event end date = \(event.endDate)") if event.attendees.count == 0{ println("This event has no attendees") continue } for attendee in event.attendees as! [EKParticipant]{ println("Attendee name = \(attendee.name)") let role = attendeeRole[Int(attendee.participantRole.value)] println("Attendee role = \(role)") let status = attendeeStatus[Int(attendee.participantStatus.value)] println("Attendee status = \(status)") let type = attendeeStatus[Int(attendee.participantType.value)] println("Attendee type = \(type)") println("Attendee URL = \(attendee.URL)") } } } func enumerateTodayEventsInStore(store: EKEventStore){ let icloudSource = sourceInEventStore(store, type: EKSourceTypeCalDAV, title: "iCloud") if icloudSource == nil{ println("You have not configured iCloud for your device.") return } let calendar = calendarWithTitle("Calendar", type: EKCalendarTypeCalDAV, source: icloudSource!, eventType: EKEntityTypeEvent) if calendar == nil{ println("Could not find the calendar we were looking for.") return } enumerateTodayEventsInStore(store, calendar: calendar!) } func requestAuthorization(){ let eventStore = EKEventStore() switch EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent){ case .Authorized: enumerateTodayEventsInStore(eventStore) case .Denied: displayAccessDenied() case .NotDetermined: eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: {[weak self] (granted: Bool, error: NSError!) -> Void in if granted{ self!.enumerateTodayEventsInStore(eventStore) } else { self!.displayAccessDenied() } }) case .Restricted: displayAccessRestricted() } } //- MARK: Helper methods func displayAccessDenied(){ println("Access to the event store is denied.") } func displayAccessRestricted(){ println("Access to the event store is restricted.") } }
mit
affe96cc64b4742e310c6e2c128a1521
29.193237
127
0.52784
5.924171
false
false
false
false
stevenmirabito/ScavengerHuntApp
Scavenger Hunt/ScavengerHuntItem.swift
1
1630
// // ScavengerHuntItem.swift // Scavenger Hunt // // Created by Steven Mirabito on 1/26/16. // Copyright © 2016 StevTek. All rights reserved. // import UIKit class ScavengerHuntItem: NSObject, NSCoding { let name: String let requireImage: Bool var photo: UIImage? private var _completed: Bool var completed: Bool { get { if (self.requireImage) { return photo != nil } else { return self._completed } } set (value) { if (self.requireImage) { assertionFailure("Cannot set completed on a ScavengerHuntItem that requires an image") } else { self._completed = value } } } private let nameKey = "name" private let photoKey = "photo" private let requireImageKey = "requireImage" func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: nameKey) aCoder.encodeObject(requireImage, forKey: requireImageKey) if let thePhoto = photo { aCoder.encodeObject(thePhoto, forKey: photoKey) } } required init?(coder aDecoder: NSCoder) { name = aDecoder.decodeObjectForKey(nameKey) as! String requireImage = aDecoder.decodeObjectForKey(requireImageKey) as! Bool photo = aDecoder.decodeObjectForKey(photoKey) as? UIImage self._completed = false } init(name: String, requireImage: Bool){ self.name = name self.requireImage = requireImage self._completed = false } }
mit
9870efe35d459198a7fca740e428ac04
26.166667
102
0.59116
4.563025
false
false
false
false
BareFeetWare/BFWControls
BFWControls/Modules/Table/View/AdjustableTableView.swift
1
1671
// // AdjustableTableView.swift // BFWControls // // Created by Tom Brodhurst-Hill on 4/11/18. // Copyright © 2018 BareFeetWare. All rights reserved. // Free to use at your own risk, with acknowledgement to BareFeetWare. // import UIKit @IBDesignable open class AdjustableTableView: UITableView, Adjustable { // MARK: - Variables @IBInspectable open var isStickyHeader: Bool = false @IBInspectable open var isStickyFooter: Bool = false @IBInspectable open var isHiddenTrailingCells: Bool { get { return tableFooterView != nil } set { if newValue { if tableFooterView == nil { // Don't show empty trailing cells: tableFooterView = UIView() } } else { if tableFooterView?.bounds.size.height == 0.0 { tableFooterView = nil } } } } // MARK: - Functions private func stickHeaderAndFooterIfNeeded() { if isStickyHeader { stickHeader() } if isStickyFooter { stickFooter() } } // MARK - Init public override init(frame: CGRect, style: UITableView.Style) { super.init(frame: frame, style: style) commonInit() } public required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } open func commonInit() { } // MARK: - UIView open override func layoutSubviews() { super.layoutSubviews() stickHeaderAndFooterIfNeeded() } }
mit
d952a017040b984df4871f46ac5eb74c
22.857143
71
0.545509
5.03012
false
false
false
false
sunshineclt/NKU-Helper
NKU Helper/功能/通知中心/NotiDetailViewController.swift
1
1821
// // NotiDetailViewController.swift // NKU Helper // // Created by 陈乐天 on 15/12/9. // Copyright © 2015年 陈乐天. All rights reserved. // import UIKit import WebKit import SnapKit class NotiDetailViewController: UIViewController, NJKWebViewProgressDelegate, UIWebViewDelegate { var url:URL! var webView = UIWebView() var progressProxy: NJKWebViewProgress! var progressView: NJKWebViewProgressView! override func viewDidLoad() { super.viewDidLoad() progressProxy = NJKWebViewProgress() progressProxy.progressDelegate = self progressProxy.webViewProxyDelegate = self webView = UIWebView() self.view.addSubview(webView) webView.snp.makeConstraints { (make) in make.edges.equalTo(self.view).inset(UIEdgeInsetsMake(0, 0, 0, 0)) } webView.delegate = progressProxy progressView = NJKWebViewProgressView() self.view.addSubview(progressView) progressView.snp.makeConstraints { (make) in make.left.equalTo(self.view.snp.left).offset(0) make.right.equalTo(self.view.snp.right).offset(0) make.top.equalTo(self.view.snp.top).offset(0) make.height.equalTo(2) } progressView.setProgress(0, animated: true) webView.loadRequest(URLRequest(url: url)) } func webViewProgress(_ webViewProgress: NJKWebViewProgress!, updateProgress progress: Float) { progressView.setProgress(progress, animated: true) self.title = webView.stringByEvaluatingJavaScript(from: "document.title") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) progressView.removeFromSuperview() } }
gpl-3.0
b03dc0853dfec4393d3c9dfa67d2f57d
30.137931
98
0.657254
4.777778
false
false
false
false
tsaievan/XYReadBook
XYReadBook/XYReadBook/Classes/Views/Profile/XYWalletView.swift
1
12499
// // XYWalletView.swift // XYReadBook // // Created by tsaievan on 2017/9/4. // Copyright © 2017年 tsaievan. All rights reserved. // import UIKit enum XYPayViewButton: Int { case wechatButton = 0 case alipayButton = 1 } class TopView: UIView { lazy var coinImageView = UIImageView() lazy var totalLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) setupUI() makeConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension TopView { fileprivate func setupUI() { coinImageView = UIImageView(image: (#imageLiteral(resourceName: "coin"))) addSubview(coinImageView) totalLabel.text = "总资产\r\n(100金币)" totalLabel.textColor = .darkGray if #available(iOS 8.2, *) { totalLabel.font = UIFont.systemFont(ofSize: 19, weight: UIFontWeightBold) } else { totalLabel.font = UIFont.systemFont(ofSize: 19) } totalLabel.sizeToFit() totalLabel.numberOfLines = 0 totalLabel.textAlignment = .left addSubview(totalLabel) } } extension TopView { fileprivate func makeConstraints() { coinImageView.snp.makeConstraints { (make) in make.centerY.equalTo(self) make.centerX.equalTo(self).offset(-50) } totalLabel.snp.makeConstraints { (make) in make.centerY.equalTo(self.coinImageView) make.left.equalTo(self.coinImageView.snp.right).offset(16) } } } class MiddleView: UIView { lazy var topLine = UIView() lazy var bottomLine = UIView() override init(frame: CGRect) { super.init(frame: frame) setupUI() makeConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension MiddleView { fileprivate func setupUI() { let array = ["10元(1000金币)", "20元(2000金币)", "50元(5000金币)", "100元(10000金币)", "300元(30000金币)", "0.01元(1金币)"] ///< 计算button的frame值 let leftMargin: CGFloat = 24 let topMargin: CGFloat = 16 let width = (gScreenWidth - (CGFloat)(3.0 * leftMargin)) * 0.5 for i in 0 ..< 6 { let chargeButton = UIButton(type: .custom) chargeButton.setBackgroundImage((#imageLiteral(resourceName: "focusButton")), for: .normal) chargeButton.setBackgroundImage((#imageLiteral(resourceName: "focusButton_selected")), for: .selected) let title = array[i] chargeButton.titleLabel?.font = UIFont.systemFont(ofSize: 12) chargeButton.setTitle(title, for: .normal) chargeButton.setTitleColor(.lightGray, for: .normal) chargeButton.setTitleColor(.green, for: .selected) let x = leftMargin + (CGFloat)(i % 2) * (width + leftMargin) let y: CGFloat = topMargin + (CGFloat)(i / 2) * 44 chargeButton.frame = CGRect(x: x, y: y, width: width, height: 36) addSubview(chargeButton) } topLine.backgroundColor = .lightGray addSubview(topLine) bottomLine.backgroundColor = .lightGray addSubview(bottomLine) } } extension MiddleView { fileprivate func makeConstraints() { topLine.snp.makeConstraints { (make) in make.top.equalTo(self) make.left.equalTo(self) make.right.equalTo(self) make.height.equalTo(1) } bottomLine.snp.makeConstraints { (make) in make.bottom.equalTo(self) make.left.equalTo(self) make.right.equalTo(self) make.height.equalTo(1) } } } class PayView: UIView { lazy var topLine = UIView() lazy var bottomLine = UIView() lazy var middleLine = UIView() lazy var wechatImageView = UIImageView() lazy var alipayImageView = UIImageView() lazy var weichatLabel = UILabel() lazy var alipayLabel = UILabel() lazy var wechatButton = UIButton(type: .custom) lazy var alipayButton = UIButton(type: .custom) override init(frame: CGRect) { super.init(frame: frame) setupUI() makeConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PayView { fileprivate func setupUI() { topLine.backgroundColor = .lightGray addSubview(topLine) bottomLine.backgroundColor = .lightGray addSubview(bottomLine) middleLine.backgroundColor = .lightGray addSubview(middleLine) wechatImageView.image = (#imageLiteral(resourceName: "wechatIcon")) addSubview(wechatImageView) alipayImageView.image = (#imageLiteral(resourceName: "alipayIcon")) addSubview(alipayImageView) weichatLabel.text = "微信支付" weichatLabel.textColor = .darkGray weichatLabel.textAlignment = .center weichatLabel.font = UIFont.systemFont(ofSize: 17) addSubview(weichatLabel) alipayLabel.text = "支付宝支付" alipayLabel.textColor = .darkGray alipayLabel.textAlignment = .center alipayLabel.font = UIFont.systemFont(ofSize: 17) addSubview(alipayLabel) wechatButton.setBackgroundImage(#imageLiteral(resourceName: "payPick"), for: .normal) wechatButton.setBackgroundImage(#imageLiteral(resourceName: "payPick_selected"), for: .selected) wechatButton.tag = XYPayViewButton.wechatButton.rawValue addSubview(wechatButton) alipayButton.setBackgroundImage(#imageLiteral(resourceName: "payPick"), for: .normal) alipayButton.setBackgroundImage(#imageLiteral(resourceName: "payPick_selected"), for: .selected) alipayButton.tag = XYPayViewButton.alipayButton.rawValue addSubview(alipayButton) } } extension PayView { fileprivate func makeConstraints() { topLine.snp.makeConstraints { (make) in make.top.equalTo(self) make.left.equalTo(self) make.right.equalTo(self) make.height.equalTo(1) } bottomLine.snp.makeConstraints { (make) in make.bottom.equalTo(self) make.left.equalTo(self) make.right.equalTo(self) make.height.equalTo(1) } middleLine.snp.makeConstraints { (make) in make.centerX.equalTo(self) make.centerY.equalTo(self) make.width.equalTo(gScreenWidth - 16 * 2) make.height.equalTo(1) } wechatImageView.snp.makeConstraints { (make) in make.top.equalTo(self).offset(8) make.left.equalTo(self).offset(24) } alipayImageView.snp.makeConstraints { (make) in make.bottom.equalTo(self).offset(-8) make.left.equalTo(self).offset(24) } weichatLabel.snp.makeConstraints { (make) in make.centerY.equalTo(self.wechatImageView) make.left.equalTo(self.wechatImageView.snp.right).offset(10) } alipayLabel.snp.makeConstraints { (make) in make.centerY.equalTo(self.alipayImageView) make.left.equalTo(self.alipayImageView.snp.right).offset(10) } wechatButton.snp.makeConstraints { (make) in make.centerY.equalTo(self.wechatImageView) make.right.equalTo(self).offset(-24) } alipayButton.snp.makeConstraints { (make) in make.centerY.equalTo(self.alipayImageView) make.right.equalTo(self).offset(-24) } } } class BottomView: UIView { lazy var payLabel = UILabel() lazy var payView = PayView(frame: CGRect()) lazy var priceLabel = UILabel() lazy var payNowButton = UIButton(type: .custom) override init(frame: CGRect) { super.init(frame: frame) setupUI() makeConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension BottomView { fileprivate func setupUI() { payLabel.textAlignment = .center payLabel.text = "支付方式" if #available(iOS 8.2, *) { payLabel.font = UIFont.systemFont(ofSize: 19, weight: UIFontWeightBold) } else { payLabel.font = UIFont.systemFont(ofSize: 19) } payLabel.textColor = .darkGray payLabel.sizeToFit() addSubview(payLabel) payView.backgroundColor = .white addSubview(payView) priceLabel.textColor = .red priceLabel.sizeToFit() priceLabel.font = UIFont.systemFont(ofSize: 13) priceLabel.text = "需要支付: 10元" priceLabel.textAlignment = .center addSubview(priceLabel) payNowButton.setBackgroundImage((#imageLiteral(resourceName: "focusButton_highlighted")), for: .normal) payNowButton.setTitle("立即支付", for: .normal) payNowButton.setTitleColor(UIColor.hm_color(withHex: 0xFAA200), for: .normal) payNowButton.titleLabel?.font = UIFont.systemFont(ofSize: 13) addSubview(payNowButton) } } extension BottomView { fileprivate func makeConstraints() { payLabel.snp.makeConstraints { (make) in make.centerX.equalTo(self) make.top.equalTo(self).offset(20) } payView.snp.makeConstraints { (make) in make.top.equalTo(self.payLabel.snp.bottom).offset(6) make.left.equalTo(self) make.right.equalTo(self) make.height.equalTo(110) } priceLabel.snp.makeConstraints { (make) in make.right.equalTo(self).offset(-24) make.top.equalTo(self.payView.snp.bottom).offset(10) } payNowButton.snp.makeConstraints { (make) in make.centerX.equalTo(self.priceLabel) make.top.equalTo(self.priceLabel.snp.bottom).offset(16) } } } class XYWalletView: UIView { lazy var topView = TopView(frame: CGRect()) lazy var middleView = MiddleView(frame: CGRect()) lazy var bottomView = BottomView(frame: CGRect()) weak var delegate: XYWalletViewDelegate? override init(frame: CGRect) { super.init(frame: frame) setupUI() makeConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } protocol XYWalletViewDelegate: NSObjectProtocol { func walletView(walletView: XYWalletView, payViewButtonSelected sender: UIButton) } extension XYWalletView { fileprivate func setupUI() { topView.backgroundColor = UIColor.hm_color(withHex: 0xF1F1F1) addSubview(topView) middleView.backgroundColor = .white addSubview(middleView) bottomView.backgroundColor = UIColor.hm_color(withHex: 0xF1F1F1) addSubview(bottomView) bottomView.payView.wechatButton.addTarget(self, action: #selector(payViewButton), for: .touchUpInside) bottomView.payView.alipayButton.addTarget(self, action: #selector(payViewButton), for: .touchUpInside) } } extension XYWalletView { @objc func payViewButton(btn: UIButton) { delegate?.walletView(walletView: self, payViewButtonSelected: btn) } } extension XYWalletView { fileprivate func makeConstraints() { topView.snp.makeConstraints { (make) in make.top.equalTo(self) make.left.equalTo(self) make.right.equalTo(self) make.height.equalTo(160) } middleView.snp.makeConstraints { (make) in make.top.equalTo(self.topView.snp.bottom) make.left.equalTo(self) make.right.equalTo(self) make.height.equalTo(160) } bottomView.snp.makeConstraints { (make) in make.top.equalTo(self.middleView.snp.bottom) make.left.equalTo(self) make.right.equalTo(self) make.bottom.equalTo(self) } } }
mit
60debe8ab105061d4fd992b7224dea2f
30.953608
114
0.612841
4.347125
false
false
false
false
grafele/Prototyper
Prototyper/Classes/ImageAnnotationViewController.swift
2
11368
// // ImageAnnotationViewController.swift // Prototype // // Created by Stefan Kofler on 13.04.16. // Copyright © 2016 Stephan Rabanser. All rights reserved. // import UIKit import jot protocol ImageAnnotationViewControllerDelegate { func imageAnnotated(_ image: UIImage) } class ImageAnnotationViewController: UIViewController { var image: UIImage! var delegate: ImageAnnotationViewControllerDelegate? fileprivate var jotViewController: JotViewController! fileprivate var imageView: UIImageView! fileprivate var colorButtons: [UIButton]! override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() view.backgroundColor = UIColor.white title = "Annotate image" addImageView() addJotViewController() addColorPicker() addBarButtonItems() } fileprivate func addImageView() { guard imageView == nil else { return } imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.backgroundColor = UIColor.white imageView.contentMode = .topLeft imageView.image = image view.addSubview(imageView) let views: [String: AnyObject] = ["topGuide": topLayoutGuide, "bottomGuide": bottomLayoutGuide, "imageView": imageView] let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "|-33-[imageView]-33-|", options: [], metrics: nil, views: views) let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[topGuide]-[imageView]-45-[bottomGuide]", options: [], metrics: nil, views: views) view.addConstraints(horizontalConstraints) view.addConstraints(verticalConstraints) } fileprivate func addJotViewController() { guard jotViewController == nil else { return } jotViewController = JotViewController() jotViewController.view.translatesAutoresizingMaskIntoConstraints = false addChildViewController(jotViewController) view.addSubview(jotViewController.view) jotViewController.didMove(toParentViewController: self) jotViewController.state = JotViewState.drawing jotViewController.drawingColor = UIColor.cyan let leftConstraint = NSLayoutConstraint(item: jotViewController.view, attribute: .left, relatedBy: .equal, toItem: imageView, attribute: .left, multiplier: 1, constant: 0) let rightConstraint = NSLayoutConstraint(item: jotViewController.view, attribute: .right, relatedBy: .equal, toItem: imageView, attribute: .right, multiplier: 1, constant: 0) let topConstraint = NSLayoutConstraint(item: jotViewController.view, attribute: .top, relatedBy: .equal, toItem: imageView, attribute: .top, multiplier: 1, constant: 0) let bottomConstraint = NSLayoutConstraint(item: jotViewController.view, attribute: .bottom, relatedBy: .equal, toItem: imageView, attribute: .bottom, multiplier: 1, constant: 0) view.addConstraints([leftConstraint, rightConstraint, topConstraint, bottomConstraint]) } fileprivate func addBarButtonItems() { self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelButtonPressed(_:))) self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(saveButtonPressed(_:))) } fileprivate func addColorPicker() { let colorPickerView = UIView() // full width, height: 60px colorPickerView.backgroundColor = UIColor.white colorPickerView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(colorPickerView) let metrics = ["topSpacing": 8, "height": 45] let views: [String: AnyObject] = ["bottomGuide": bottomLayoutGuide, "colorPickerView": colorPickerView] let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "|-[colorPickerView]-|", options: [], metrics: metrics, views: views) let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[colorPickerView(height)]-|", options: [], metrics: metrics, views: views) view.addConstraints(horizontalConstraints) view.addConstraints(verticalConstraints) // color: red, yellow, blue, green, white, black let buttonSize: CGFloat = 35.0 let redColorButton = UIButton() redColorButton.backgroundColor = UIColor.red prepareColorButton(redColorButton, buttonSize: buttonSize) colorPickerView.addSubview(redColorButton) let spaceView1 = createSpaceView(in: colorPickerView) let yellowColorButton = UIButton() yellowColorButton.backgroundColor = UIColor.yellow prepareColorButton(yellowColorButton, buttonSize: buttonSize) colorPickerView.addSubview(yellowColorButton) let spaceView2 = createSpaceView(in: colorPickerView) let cyanColorButton = UIButton() cyanColorButton.backgroundColor = UIColor.cyan prepareColorButton(cyanColorButton, buttonSize: buttonSize, selected: true) colorPickerView.addSubview(cyanColorButton) let spaceView3 = createSpaceView(in: colorPickerView) let greenColorButton = UIButton() greenColorButton.backgroundColor = UIColor.green prepareColorButton(greenColorButton, buttonSize: buttonSize) colorPickerView.addSubview(greenColorButton) let spaceView4 = createSpaceView(in: colorPickerView) let whiteColorButton = UIButton() whiteColorButton.backgroundColor = UIColor.white prepareColorButton(whiteColorButton, buttonSize: buttonSize) colorPickerView.addSubview(whiteColorButton) let spaceView5 = createSpaceView(in: colorPickerView) let blackColorButton = UIButton() blackColorButton.backgroundColor = UIColor.black prepareColorButton(blackColorButton, buttonSize: buttonSize) colorPickerView.addSubview(blackColorButton) let buttonMetrics = ["sideSpacing": 8, "size": buttonSize] let buttonViews: [String: AnyObject] = ["redColorButton": redColorButton, "yellowColorButton": yellowColorButton, "cyanColorButton": cyanColorButton, "greenColorButton": greenColorButton, "whiteColorButton": whiteColorButton, "blackColorButton": blackColorButton, "spaceView1": spaceView1, "spaceView2": spaceView2, "spaceView3": spaceView3, "spaceView4": spaceView4, "spaceView5": spaceView5] let horizontalButtonConstraints = NSLayoutConstraint.constraints(withVisualFormat: "|-sideSpacing-[redColorButton(size)]-[spaceView1]-[yellowColorButton(size)]-[spaceView2(==spaceView1)]-[cyanColorButton(size)]-[spaceView3(==spaceView1)]-[greenColorButton(size)]-[spaceView4(==spaceView1)]-[whiteColorButton(size)]-[spaceView5(==spaceView1)]-[blackColorButton(size)]-sideSpacing-|", options: [], metrics: buttonMetrics, views: buttonViews) let heightConstraint1 = NSLayoutConstraint(item: redColorButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: buttonSize) let heightConstraint2 = NSLayoutConstraint(item: yellowColorButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: buttonSize) let heightConstraint3 = NSLayoutConstraint(item: cyanColorButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: buttonSize) let heightConstraint4 = NSLayoutConstraint(item: greenColorButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: buttonSize) let heightConstraint5 = NSLayoutConstraint(item: whiteColorButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: buttonSize) let heightConstraint6 = NSLayoutConstraint(item: blackColorButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: buttonSize) let centerConstraint1 = NSLayoutConstraint(item: redColorButton, attribute: .centerY, relatedBy: .equal, toItem: colorPickerView, attribute: .centerY, multiplier: 1, constant: 0) let centerConstraint2 = NSLayoutConstraint(item: yellowColorButton, attribute: .centerY, relatedBy: .equal, toItem: colorPickerView, attribute: .centerY, multiplier: 1, constant: 0) let centerConstraint3 = NSLayoutConstraint(item: cyanColorButton, attribute: .centerY, relatedBy: .equal, toItem: colorPickerView, attribute: .centerY, multiplier: 1, constant: 0) let centerConstraint4 = NSLayoutConstraint(item: greenColorButton, attribute: .centerY, relatedBy: .equal, toItem: colorPickerView, attribute: .centerY, multiplier: 1, constant: 0) let centerConstraint5 = NSLayoutConstraint(item: whiteColorButton, attribute: .centerY, relatedBy: .equal, toItem: colorPickerView, attribute: .centerY, multiplier: 1, constant: 0) let centerConstraint6 = NSLayoutConstraint(item: blackColorButton, attribute: .centerY, relatedBy: .equal, toItem: colorPickerView, attribute: .centerY, multiplier: 1, constant: 0) colorPickerView.addConstraints(horizontalButtonConstraints) colorPickerView.addConstraints([heightConstraint1, heightConstraint2, heightConstraint3, heightConstraint4, heightConstraint5, heightConstraint6]) colorPickerView.addConstraints([centerConstraint1, centerConstraint2, centerConstraint3, centerConstraint4, centerConstraint5, centerConstraint6]) colorButtons = [redColorButton, yellowColorButton, cyanColorButton, greenColorButton, whiteColorButton, blackColorButton] } private func prepareColorButton(_ button: UIButton, buttonSize: CGFloat, selected: Bool = false) { button.translatesAutoresizingMaskIntoConstraints = false button.layer.cornerRadius = buttonSize/2.0 button.layer.borderWidth = 1 button.layer.borderColor = UIColor.black.cgColor button.alpha = selected ? 1.0 : 0.4 button.addTarget(self, action: #selector(colorButtonPressed(_:)), for: .touchUpInside) } private func createSpaceView(in superview: UIView) -> UIView { let spaceView = UIView() spaceView.translatesAutoresizingMaskIntoConstraints = false spaceView.isHidden = true superview.addSubview(spaceView) return spaceView } // MARK: Actions func cancelButtonPressed(_ sender: AnyObject) { self.presentingViewController?.dismiss(animated: true, completion: nil) } func saveButtonPressed(_ sender: AnyObject) { self.presentingViewController?.dismiss(animated: true, completion: nil) delegate?.imageAnnotated(jotViewController.draw(on: image)) } func colorButtonPressed(_ colorButton: UIButton) { for button in colorButtons { button.alpha = 0.4 } colorButton.alpha = 1.0 jotViewController.drawingColor = colorButton.backgroundColor } }
mit
e9505ce8218fc5169c32a69ae074e810
54.995074
447
0.721562
5.245501
false
false
false
false
CodePath-Parse/MiAR
MiAR/View Controllers/NotesViewController.swift
2
4712
// // NotesViewController.swift // MiAR // // Created by Phan, Ngan on 10/28/17. // Copyright © 2017 MiAR. All rights reserved. // import UIKit import CoreLocation let refreshNotesMessageKey = "refreshNotesMessageKey" class NotesViewController: UIViewController { @IBOutlet weak var notesTableView: UITableView! let locationManager = CLLocationManager() var userLocation: CLLocation? var loading = true var notes: [Note] = [Note]() { didSet { if !loading { DispatchQueue.main.async { self.notesTableView.reloadData() } } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.delegate = self requestUserLocation() loading = false let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refreshControlAction(_:)), for: UIControlEvents.valueChanged) notesTableView.insertSubview(refreshControl, at: 0) } @objc func refreshControlAction(_ refreshControl: UIRefreshControl) { print("refreshing") let refreshInfo: [String: UIRefreshControl] = ["refresh": refreshControl] NotificationCenter.default.post(name: Notification.Name(refreshNotesMessageKey), object: nil, userInfo: refreshInfo) } private func requestUserLocation() { if CLLocationManager.authorizationStatus() == .authorizedAlways{ locationManager.startUpdatingLocation() } else { locationManager.requestAlwaysAuthorization() } } static func getNoteDistance(noteLocation: CLLocationCoordinate2D?, userLocation: CLLocation?) -> Double { var meters = -1.0 if let userLocation = userLocation { if let noteLocation = noteLocation { let noteLoc = CLLocation(latitude: noteLocation.latitude, longitude: noteLocation.longitude) meters = userLocation.distance(from: noteLoc) } } return meters } static func convertToMiles(meters: CLLocationDistance) -> Double { let miles = meters * DirectionsViewController.milesPerMeter let rounded = round(miles * 1000) / 1000 return rounded } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "MapViewSegue" { guard let mapVC = segue.destination as? MapViewController else { return } guard let note = sender as? NoteCell else { return } guard let indexPath = notesTableView.indexPath(for: note) else { return } mapVC.note = notes[indexPath.row] } } } extension NotesViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return notes.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "NoteCell", for: indexPath) as? NoteCell else { return UITableViewCell() } let note = notes[indexPath.row] cell.usernameLabel.text = note.fromUser?.username let meters = NotesViewController.getNoteDistance(noteLocation: note.coordinate, userLocation: userLocation) cell.distanceLabel.text = String(NotesViewController.convertToMiles(meters: meters)) cell.profileImageView.image = UIImage(named: "anonymous") return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return CGFloat.leastNonzeroMagnitude } } extension NotesViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print("notes location update") userLocation = locations.last notesTableView.reloadData() } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print(error.localizedDescription) } }
apache-2.0
71967d6ba6a9eba17810a95bc5a9acc2
33.639706
124
0.650393
5.471545
false
false
false
false
OpenStreetMap-Monitoring/OsMoiOs
iOsmo/SynchronizedArray.swift
2
11304
// // SynchronizedArray.swift // iOsMo // // Created by Alexey Sirotkin on 26.02.18. // Copyright © 2018 Alexey Sirotkin. All rights reserved. // import Foundation import Foundation /// A thread-safe array. public class SynchronizedArray<Element> { fileprivate let queue = DispatchQueue(label: "io.zamzam.ZamzamKit.SynchronizedArray", attributes: .concurrent) fileprivate var array = [Element]() } // MARK: - Properties public extension SynchronizedArray{ /// The first element of the collection. var first: Element? { var result: Element? queue.sync { result = self.array.first } return result } /// The last element of the collection. var last: Element? { var result: Element? queue.sync { result = self.array.last } return result } /// The number of elements in the array. var count: Int { var result = 0 queue.sync { result = self.array.count } return result } /// A Boolean value indicating whether the collection is empty. var isEmpty: Bool { var result = false queue.sync { result = self.array.isEmpty } return result } /// A textual representation of the array and its elements. var description: String { var result = "" queue.sync { result = self.array.description } return result } } // MARK: - Immutable public extension SynchronizedArray { /// Returns the first element of the sequence that satisfies the given predicate or nil if no such element is found. /// /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match. /// - Returns: The first match or nil if there was no match. func first(where predicate: (Element) -> Bool) -> Element? { var result: Element? queue.sync { result = self.array.first(where: predicate) } return result } /// Returns an array containing, in order, the elements of the sequence that satisfy the given predicate. /// /// - Parameter isIncluded: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned array. /// - Returns: An array of the elements that includeElement allowed. func filter(_ isIncluded: (Element) -> Bool) -> [Element] { var result = [Element]() queue.sync { result = self.array.filter(isIncluded) } return result } /// Returns the first index in which an element of the collection satisfies the given predicate. /// /// - Parameter predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match. /// - Returns: The index of the first element for which predicate returns true. If no elements in the collection satisfy the given predicate, returns nil. func index(where predicate: (Element) -> Bool) -> Int? { var result: Int? queue.sync { result = self.array.index(where: predicate) } return result } /// Returns the elements of the collection, sorted using the given predicate as the comparison between elements. /// /// - Parameter areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. /// - Returns: A sorted array of the collection’s elements. func sorted(by areInIncreasingOrder: (Element, Element) -> Bool) -> [Element] { var result = [Element]() queue.sync { result = self.array.sorted(by: areInIncreasingOrder) } return result } /// Returns an array containing the non-nil results of calling the given transformation with each element of this sequence. /// /// - Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value. /// - Returns: An array of the non-nil results of calling transform with each element of the sequence. func flatMap<ElementOfResult>(_ transform: (Element) -> ElementOfResult?) -> [ElementOfResult] { var result = [ElementOfResult]() queue.sync { result = self.array.flatMap(transform) } return result } /// Calls the given closure on each element in the sequence in the same order as a for-in loop. /// /// - Parameter body: A closure that takes an element of the sequence as a parameter. func forEach(_ body: (Element) -> Void) { queue.sync { self.array.forEach(body) } } /// Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate. /// /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element represents a match. /// - Returns: true if the sequence contains an element that satisfies predicate; otherwise, false. func contains(where predicate: (Element) -> Bool) -> Bool { var result = false queue.sync { result = self.array.contains(where: predicate) } return result } } // MARK: - Mutable public extension SynchronizedArray { /// Adds a new element at the end of the array. /// /// - Parameter element: The element to append to the array. func append( _ element: Element) { queue.async(flags: .barrier) { self.array.append(element) } } /// Adds a new element at the end of the array. /// /// - Parameter element: The element to append to the array. func append( _ elements: [Element]) { queue.async(flags: .barrier) { self.array += elements } } /// Inserts a new element at the specified position. /// /// - Parameters: /// - element: The new element to insert into the array. /// - index: The position at which to insert the new element. func insert( _ element: Element, at index: Int) { queue.async(flags: .barrier) { self.array.insert(element, at: index) } } /// Removes and returns the element at the specified position. /// /// - Parameters: /// - index: The position of the element to remove. /// - completion: The handler with the removed element. func remove(at index: Int, completion: ((Element) -> Void)? = nil) { queue.async(flags: .barrier) { let element = self.array.remove(at: index) DispatchQueue.main.async { completion?(element) } } } /// Removes and returns the last element /// /// - Parameters: /// - completion: The handler with the removed element. func removeLast( completion: ((Element) -> Void)? = nil) { queue.async(flags: .barrier) { let element = self.array.removeLast() DispatchQueue.main.async { completion?(element) } } } /// Removes and returns the element at the specified position. /// /// - Parameters: /// - predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match. /// - completion: The handler with the removed element. func remove(where predicate: @escaping (Element) -> Bool, completion: ((Element) -> Void)? = nil) { queue.async(flags: .barrier) { guard let index = self.array.index(where: predicate) else { return } let element = self.array.remove(at: index) DispatchQueue.main.async { completion?(element) } } } /// Removes all elements from the array. /// /// - Parameter completion: The handler with the removed elements. func removeAll(completion: (([Element]) -> Void)? = nil) { queue.async(flags: .barrier) { let elements = self.array self.array.removeAll() DispatchQueue.main.async { completion?(elements) } } } } public extension SynchronizedArray { /// Accesses the element at the specified position if it exists. /// /// - Parameter index: The position of the element to access. /// - Returns: optional element if it exists. subscript(index: Int) -> Element? { get { var result: Element? queue.sync { guard self.array.startIndex..<self.array.endIndex ~= index else { return } result = self.array[index] } return result } set { guard let newValue = newValue else { return } queue.async(flags: .barrier) { self.array[index] = newValue } } } } // MARK: - Equatable public extension SynchronizedArray where Element: Equatable { /// Returns a Boolean value indicating whether the sequence contains the given element. /// /// - Parameter element: The element to find in the sequence. /// - Returns: true if the element was found in the sequence; otherwise, false. func contains(_ element: Element) -> Bool { var result = false queue.sync { result = self.array.contains(element) } return result } } // MARK: - Infix operators public extension SynchronizedArray { static func +=(left: inout SynchronizedArray, right: Element) { left.append(right) } static func +=(left: inout SynchronizedArray, right: [Element]) { left.append(right) } } /* // Thread-unsafe array do { var array = [Int]() var iterations = 1000 let start = Date().timeIntervalSince1970 DispatchQueue.concurrentPerform(iterations: iterations) { index in let last = array.last ?? 0 array.append(last + 1) DispatchQueue.global().sync { iterations -= 1 // Final loop guard iterations <= 0 else { return } let message = String(format: "Unsafe loop took %.3f seconds, count: %d.", Date().timeIntervalSince1970 - start, array.count ) print(message) } } } // Thread-safe array do { var array = SynchronizedArray<Int>() var iterations = 1000 let start = Date().timeIntervalSince1970 DispatchQueue.concurrentPerform(iterations: iterations) { index in let last = array.last ?? 0 array.append(last + 1) DispatchQueue.global().sync { iterations -= 1 // Final loop guard iterations <= 0 else { return } let message = String(format: "Safe loop took %.3f seconds, count: %d.", Date().timeIntervalSince1970 - start, array.count) print(message) } } } */
gpl-3.0
22abd2c6c8e9f82acbe3cfe6a53eb15b
34.205607
196
0.605168
4.780457
false
false
false
false
programmerC/JNews
JNews/CircleLayout.swift
1
2921
// // CircleLayout.swift // JNews // // Created by ChenKaijie on 16/7/27. // Copyright © 2016年 com.ckj. All rights reserved. // import UIKit class CircleLayout: UICollectionViewLayout { var size = CGSizeZero var center = CGPointZero var radius: CGFloat = 0 var cellCount: CGFloat = 0 let itemSize = CGSizeMake(25, 25) override func prepareLayout() { super.prepareLayout() // Assign self.size = self.collectionView!.frame.size self.cellCount = CGFloat(self.collectionView!.numberOfItemsInSection(0)) self.center = CGPointMake(self.size.width/2.0, self.size.height/2.0) self.radius = min(self.size.width/2.0, self.size.height)/2.0 } // 边界改变就重新布局,默认是false override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } override func collectionViewContentSize() -> CGSize { return self.collectionView!.frame.size } // 对每一个Item 设置center,好让它形成圆圈 override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) attributes.size = self.itemSize // 计算每一个Item的center let centerX = self.center.x + self.radius*CGFloat(cosf(2*Float(M_PI)*Float(indexPath.item)/Float(self.cellCount))) let centerY = self.center.y + self.radius*CGFloat(sinf(2*Float(M_PI)*Float(indexPath.item)/Float(self.cellCount))) attributes.center = CGPointMake(centerX, centerY) return attributes } // DecorationView 设置 override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, withIndexPath: indexPath) attributes.size = CGSizeMake(108, 80) attributes.center = self.center return attributes } // 可见区域布局 先调用这个方法,再调用layoutAttributesForItemAtIndexPath这个方法 override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attributesList = [UICollectionViewLayoutAttributes]() for index in 0..<Int(self.cellCount) { let indexPath = NSIndexPath.init(forItem: index, inSection: 0) attributesList.append(self.layoutAttributesForItemAtIndexPath(indexPath)!) } // 添加Supplementary View let attributes = self.layoutAttributesForSupplementaryViewOfKind("CenterSupplementary", atIndexPath: NSIndexPath(forItem: 0, inSection: 0)) attributesList.append(attributes!) return attributesList } }
gpl-3.0
172f7bbb84827d6d8ae44820fa1d9bff
39.057143
156
0.698645
4.910683
false
false
false
false
RoverPlatform/rover-ios-beta
Sources/UI/Views/Polls/TextPollCell.swift
2
2239
// // TextPollCell.swift // Rover // // Created by Andrew Clunis on 2019-06-19. // Copyright © 2019 Rover Labs Inc. All rights reserved. // import os import UIKit class TextPollCell: PollCell { override func configure(with block: Block) { super.configure(with: block) guard let block = block as? TextPollBlock else { return } let poll = block.textPoll let options = poll.options verticalSpacing = CGFloat(options.first?.topMargin ?? 0) optionsList.arrangedSubviews.forEach { $0.removeFromSuperview() } options .map { option in TextPollOption(option: option) { [weak self] in self?.optionSelected(option) } } .forEach { optionsList.addArrangedSubview($0) } questionText = poll.question } // MARK: Results override func setResults(_ results: [PollCell.OptionResult], animated: Bool) { zip(results, optionsList.arrangedSubviews) .map { ($0, $1 as! TextPollOption) } .forEach { $1.setResult($0, animated: animated) } } override func clearResults() { optionsList.arrangedSubviews .map { $0 as! TextPollOption } .forEach { $0.clearResult() } } } // MARK: Measurement extension TextPollBlock { func intrinsicHeight(blockWidth: CGFloat) -> CGFloat { let innerWidth = blockWidth - CGFloat(insets.left) - CGFloat(insets.right) let size = CGSize(width: innerWidth, height: CGFloat.greatestFiniteMagnitude) let questionAttributedText = self.textPoll.question.attributedText(forFormat: .plain) let questionHeight = questionAttributedText?.measuredHeight(with: size) ?? CGFloat(0) let borderHeight = CGFloat(textPoll.options.first?.border.width ?? 0) * 2 let optionsHeightAndSpacing = self.textPoll.options.reduce(0) { result, option in result + CGFloat(option.height) + CGFloat(option.topMargin) + borderHeight } return CGFloat(optionsHeightAndSpacing) + questionHeight + CGFloat(insets.top + insets.bottom) } }
mit
e7d11c546e732e820701ccb71072d7ff
30.083333
102
0.613941
4.458167
false
false
false
false
EGul/news.ycombinator-app
SwiftApp/ViewController.swift
1
19001
// // ViewController.swift // SwiftApp // // Created by Evan on 10/28/15. // Copyright © 2015 none. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource { var dataArr: [NSDictionary] = [] var selectedArr: [String] = [] let width = UIScreen.mainScreen().bounds.size.width let height = UIScreen.mainScreen().bounds.size.height var limitView = UIView() var limitViewLabel = UILabel() var limitMaxLimitLabel = UILabel() var limitIntervalLabel = UILabel() var limitCount = 0 var maxLimit = 5 var limitTimer = NSTimer() var limitTimerIsRunning = false var limitTimerInterval = 15.0 * 60 var leftPickerView = UIPickerView() var rightPickerView = UIPickerView() var leftPickerViewData = ["unlimited", "1", "2", "3", "4", "5"] var leftPickerViewLimit = 5 var rightPickerViewData = ["1min", "5min", "10min", "15min", "30min"] var rightPickerViewInterval = 15.0 * 60 var mainTableView = UITableView() var mainTableViewIsDown = false var mainTableViewIsAnimating = false var refreshControl = UIRefreshControl() let mainTableViewCellIdentifier = "something" let newsAPI = NewsAPI() override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.topItem?.title = "news.ycombinator" self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] self.navigationController?.navigationBar.barTintColor = UIColor.orangeColor() self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotated", name: UIDeviceOrientationDidChangeNotification, object: nil) let statusHeight = UIApplication.sharedApplication().statusBarFrame.height let navHeight = self.navigationController?.navigationBar.frame.size.height let topHeight = statusHeight + navHeight! self.view.backgroundColor = UIColor.whiteColor() limitView = UIView(frame: CGRectMake(0, topHeight, width, 50)) limitView.backgroundColor = UIColor.whiteColor() limitViewLabel = UILabel(frame: CGRectMake(0, 0, width, 50)) limitViewLabel.text = "0 of " + String(maxLimit) + " stories left" limitViewLabel.textColor = UIColor.blackColor() limitViewLabel.textAlignment = NSTextAlignment.Center let limitViewSpace = limitView.frame.origin.y + limitView.frame.size.height limitMaxLimitLabel = UILabel(frame: CGRectMake(10, limitViewSpace, width / 2, 50)) limitMaxLimitLabel.text = "Maximum Read" limitMaxLimitLabel.textAlignment = NSTextAlignment.Center limitMaxLimitLabel.layer.zPosition = -100 limitIntervalLabel = UILabel(frame: CGRectMake(width / 2, limitViewSpace, width / 2, 50)) limitIntervalLabel.text = "Reset Interval" limitIntervalLabel.textAlignment = NSTextAlignment.Center limitIntervalLabel.layer.zPosition = -100 let limitPickerLabelSpace = limitIntervalLabel.frame.origin.y + limitIntervalLabel.frame.size.height leftPickerView = UIPickerView(frame: CGRectMake(0, limitPickerLabelSpace, width / 2, 150)) leftPickerView.delegate = self leftPickerView.dataSource = self leftPickerView.selectRow(5, inComponent: 0, animated: false) rightPickerView = UIPickerView(frame: CGRectMake(width / 2, limitPickerLabelSpace, width / 2, 150)) rightPickerView.delegate = self rightPickerView.dataSource = self rightPickerView.selectRow(3, inComponent: 0, animated: false) mainTableView = UITableView(frame: CGRectMake(0, limitViewSpace, width, height - limitViewSpace)) mainTableView.delegate = self mainTableView.dataSource = self refreshControl.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged) mainTableView.addSubview(refreshControl) limitView.addSubview(limitViewLabel) self.view.addSubview(limitView) self.view.addSubview(limitMaxLimitLabel) self.view.addSubview(limitIntervalLabel) self.view.addSubview(leftPickerView) self.view.addSubview(rightPickerView) self.view.addSubview(mainTableView) newsAPI.getTopStories() { (result: [NSDictionary], error: NSError?) in if (error == nil) { self.dataArr = result dispatch_async(dispatch_get_main_queue()) { self.mainTableView.reloadData() } } } // 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. } func rotated() { let orientation = UIDevice.currentDevice().orientation if (orientation == UIDeviceOrientation.FaceUp || orientation == UIDeviceOrientation.FaceDown || orientation == UIDeviceOrientation.Unknown) { return } let statusHeight = UIApplication.sharedApplication().statusBarFrame.height let navHeight = self.navigationController?.navigationBar.frame.size.height let topHeight = statusHeight + navHeight! let leftPickerViewSelectedRow = leftPickerView.selectedRowInComponent(0) let rightPickerViewSelectedRow = rightPickerView.selectedRowInComponent(0) var toLeftPickerView = UIPickerView() var toRightPickerView = UIPickerView() if orientation == UIDeviceOrientation.Portrait { limitView.frame = CGRectMake(0, topHeight, width, 50) limitViewLabel.frame = CGRectMake(0, 0, width, 50) let limitViewSpace = limitView.frame.origin.y + limitView.frame.size.height limitMaxLimitLabel.frame = CGRectMake(10, limitViewSpace, width / 2, 50) limitIntervalLabel.frame = CGRectMake(width / 2, limitViewSpace, width / 2, 50) let limitPickerLabelSpace = limitIntervalLabel.frame.origin.y + limitIntervalLabel.frame.size.height toLeftPickerView = UIPickerView(frame: CGRectMake(0, limitPickerLabelSpace, width / 2, leftPickerView.frame.size.height)) toLeftPickerView.layer.zPosition = -100 toLeftPickerView.userInteractionEnabled = false toRightPickerView = UIPickerView(frame: CGRectMake(width / 2, limitPickerLabelSpace, width / 2, leftPickerView.frame.size.height)) toRightPickerView.layer.zPosition = -100 toRightPickerView.userInteractionEnabled = false mainTableView.frame = CGRectMake(0, limitViewSpace, width, height - limitViewSpace) } if UIDeviceOrientationIsLandscape(orientation) { limitView.frame = CGRectMake(0, topHeight, height, 50) limitViewLabel.frame = CGRectMake(0, 0, height, 50) let limitViewSpace = limitView.frame.origin.y + limitView.frame.size.height limitMaxLimitLabel.frame = CGRectMake(10, limitViewSpace, height / 2, 50) limitIntervalLabel.frame = CGRectMake(height / 2, limitViewSpace, height / 2, 50) let limitPickerLabelSpace = limitIntervalLabel.frame.origin.y + limitIntervalLabel.frame.size.height toLeftPickerView = UIPickerView(frame: CGRectMake(0, limitPickerLabelSpace, height / 2, leftPickerView.frame.size.height)) toLeftPickerView.layer.zPosition = -100 toLeftPickerView.userInteractionEnabled = false toRightPickerView = UIPickerView(frame: CGRectMake(height / 2, limitPickerLabelSpace, height / 2, leftPickerView.frame.size.height)) toRightPickerView.layer.zPosition = -100 toRightPickerView.userInteractionEnabled = false mainTableView.frame = CGRectMake(0, limitViewSpace, height, width - limitViewSpace) } leftPickerView.removeFromSuperview() self.view.addSubview(toLeftPickerView) leftPickerView = toLeftPickerView rightPickerView.removeFromSuperview() self.view.addSubview(toRightPickerView) rightPickerView = toRightPickerView leftPickerView.delegate = self leftPickerView.dataSource = self rightPickerView.delegate = self rightPickerView.dataSource = self leftPickerView.selectRow(leftPickerViewSelectedRow, inComponent: 0, animated: false) rightPickerView.selectRow(rightPickerViewSelectedRow, inComponent: 0, animated: false) mainTableViewIsDown = false mainTableViewIsAnimating = false } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { moveTableView() limitViewLabel.textColor = UIColor.blackColor() } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { limitViewLabel.textColor = UIColor.lightGrayColor() } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { limitViewLabel.textColor = UIColor.blackColor() } func moveTableView() { if (!mainTableViewIsAnimating) { mainTableViewIsAnimating = true if !mainTableViewIsDown { moveTableViewDown() } else { moveTableViewUp() if leftPickerViewLimit == -1 { limitCount = 0 limitTimer.invalidate() } if limitCount == -1 && leftPickerViewLimit > limitCount { limitCount = 0 } if limitCount > leftPickerViewLimit { limitCount = leftPickerViewLimit } if limitTimerInterval != rightPickerViewInterval { if limitTimerIsRunning { limitTimer.invalidate() setLimitIntervalTimer(rightPickerViewInterval) } } maxLimit = leftPickerViewLimit limitTimerInterval = rightPickerViewInterval setLimitLabelText() } } } func moveTableViewDown() { UIView.animateWithDuration(0.5, animations: { let x = self.mainTableView.frame.origin.x let y = self.mainTableView.frame.origin.y + 200 let tableWidth = self.mainTableView.frame.size.width let tableHeight = self.mainTableView.frame.size.height self.mainTableView.frame = CGRectMake(x, y, tableWidth, tableHeight) }, completion: { (value: Bool) in self.mainTableViewIsDown = true self.mainTableViewIsAnimating = false self.leftPickerView.userInteractionEnabled = true self.rightPickerView.userInteractionEnabled = true }) } func moveTableViewUp() { UIView.animateWithDuration(0.5, animations: { let x = self.mainTableView.frame.origin.x let y = self.mainTableView.frame.origin.y - 200 let tableWidth = self.mainTableView.frame.size.width let tableHeight = self.mainTableView.frame.size.height self.mainTableView.frame = CGRectMake(x, y, tableWidth, tableHeight) }, completion: { (value: Bool) in self.mainTableViewIsDown = false self.mainTableViewIsAnimating = false self.leftPickerView.userInteractionEnabled = false self.rightPickerView.userInteractionEnabled = false }) } func setLimitIntervalTimer(interval: Double) { limitTimer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "limitTimerDidElapse", userInfo: nil, repeats: false) } func limitTimerDidElapse() { limitCount-- if limitCount > 0 { setLimitIntervalTimer(limitTimerInterval) } else { limitTimerIsRunning = false } setLimitLabelText() } func setLimitLabelText() { if (maxLimit == -1) { limitViewLabel.text = "you can read as many stories as you want!" } else { limitViewLabel.text = String(limitCount) + " of " + String(maxLimit) + " stories left" } } func refresh() { newsAPI.getTopStories() { (result: [NSDictionary], error: NSError?) in if (error == nil) { self.refreshControl.endRefreshing() self.dataArr = result dispatch_async(dispatch_get_main_queue()) { self.mainTableView.reloadData() } } else { self.refreshControl.endRefreshing() } } } func getFormattedURL(index: Int) -> String { var storyURL: String if dataArr[index].valueForKey("url") == nil { storyURL = "news.ycombinator.com" } else { storyURL = NSURL(string: String(dataArr[index].valueForKey("url")!))!.host! } storyURL = storyURL.stringByReplacingOccurrencesOfString("http://", withString: "") storyURL = storyURL.stringByReplacingOccurrencesOfString("https://", withString: "") storyURL = storyURL.stringByReplacingOccurrencesOfString("www.", withString: "") return storyURL } func getTimeSincePost(num: Int) -> String { let diff = (Int(NSDate().timeIntervalSince1970) - num) / 60 if diff == 0 { return "a moment ago" } if diff < 60 { return String(diff) + " minutes ago" } return String(diff / 60) + " hours ago" } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArr.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let row = indexPath.row var cell = tableView.dequeueReusableCellWithIdentifier(mainTableViewCellIdentifier) if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: mainTableViewCellIdentifier) cell!.textLabel?.numberOfLines = 3 cell!.detailTextLabel?.numberOfLines = 4 cell!.detailTextLabel?.textColor = UIColor.grayColor() } if selectedArr.contains(String(dataArr[row].valueForKey("id")!)) == false { cell!.textLabel?.textColor = UIColor.blackColor() } else { cell!.textLabel?.textColor = UIColor.grayColor() } var detailText = getFormattedURL(row) + "\n" if let score = dataArr[row].valueForKey("score") { detailText += String(score) + " points" } if let by = dataArr[row].valueForKey("by") { detailText += " by " + String(by) } if let time = dataArr[row].valueForKey("time") { detailText += " " + getTimeSincePost(Int(String(time))!) } if let descendants = dataArr[row].valueForKey("descendants") { detailText += " | " + String(descendants) + " comments" } cell!.textLabel?.text = dataArr[row].valueForKey("title") as? String cell!.detailTextLabel?.text = detailText return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if (limitCount < maxLimit || maxLimit == -1) { if maxLimit != -1 { limitCount++ if (!limitTimerIsRunning) { setLimitIntervalTimer(limitTimerInterval) limitTimerIsRunning = true } setLimitLabelText() } if selectedArr.contains(String(dataArr[indexPath.row].valueForKey("id"))) == false { selectedArr.append(String(dataArr[indexPath.row].valueForKey("id")!)) tableView.cellForRowAtIndexPath(indexPath)!.textLabel?.textColor = UIColor.grayColor() } let row = indexPath.row var storyURL = dataArr[row].valueForKey("url") as? String if storyURL == nil { storyURL = "https://news.ycombinator.com/item?id=" + String(dataArr[row].valueForKey("id")!) } let selectViewController = SelectViewController() selectViewController.storyURL = storyURL! self.navigationController?.pushViewController(selectViewController, animated: true) } tableView.deselectRowAtIndexPath(indexPath, animated: false) } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if (pickerView == leftPickerView) { return leftPickerViewData.count } else { return rightPickerViewData.count } } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if (pickerView == leftPickerView) { return leftPickerViewData[row] } else { return rightPickerViewData[row] } } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if (pickerView == leftPickerView) { if (leftPickerViewData[row] == "unlimited") { leftPickerViewLimit = -1 } else { leftPickerViewLimit = Int(leftPickerViewData[row])! } } else { var tempString = rightPickerViewData[row] tempString = tempString.substringToIndex(tempString.endIndex.advancedBy(-3)) rightPickerViewInterval = Double(tempString)! * 60 } } }
mit
f2a2fc52c4ce799494efbca973c2321d
35.750484
147
0.617316
5.268996
false
false
false
false
jloloew/Smiley-Face
Smiley Face/FaceView.swift
1
3452
// // FaceView.swift // Smiley Face // // Created by Justin Loew on 8/20/15. // Copyright © 2015 Justin Loew. All rights reserved. // import UIKit protocol FaceViewDataSource { func smileForFaceView(sender: FaceView) -> CGFloat } class FaceView: UIView { var dataSource: FaceViewDataSource? var scale: CGFloat = 0.90 { // didSet is called every time scale is set (after it has the new value) didSet { // don't allow zero scale if scale == 0 { scale = 0.90 } // any time our scale changes, call for redraw setNeedsDisplay() } } func drawCircleAtPoint(p: CGPoint, withRadius r: CGFloat, inContext context: CGContextRef) { UIGraphicsPushContext(context) CGContextBeginPath(context) CGContextAddArc(context, p.x, p.y, r, 0.0, CGFloat(2*M_PI), 1) CGContextStrokePath(context) UIGraphicsPopContext() } func pinch(gesture: UIPinchGestureRecognizer) { if gesture.state == .Changed || gesture.state == .Ended { scale *= gesture.scale // adjust our scale gesture.scale = 1 // reset the gesture's scale to 1 (so future changes are incremental, not cumulative) } } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code let context = UIGraphicsGetCurrentContext()! // The `self.` in `self.bounds` could be omitted, but is included here to show that `bounds` is a property of self. let midpoint = CGPoint(x: self.bounds.origin.x + self.bounds.size.width/2, y: self.bounds.origin.y + self.bounds.size.height/2) let faceSize: CGFloat if self.bounds.size.width < self.bounds.size.height { faceSize = self.bounds.size.width / 2 * scale } else { faceSize = self.bounds.size.height / 2 * scale } // set up how we want our lines to look CGContextSetLineWidth(context, 5) UIColor.blueColor().setStroke() drawCircleAtPoint(midpoint, withRadius: faceSize, inContext: context) // draw the circle around the face // draw the eyes let eye_h: CGFloat = 0.35 let eye_v: CGFloat = 0.35 let eye_radius: CGFloat = 0.1 var eyePoint = CGPoint(x: midpoint.x - faceSize*eye_h, y: midpoint.y - faceSize*eye_v) drawCircleAtPoint(eyePoint, withRadius: faceSize*eye_radius, inContext: context) // left eye eyePoint.x += faceSize * eye_h * 2 drawCircleAtPoint(eyePoint, withRadius: faceSize*eye_radius, inContext: context) // right eye // prepare the corners of the mouth let mouth_h: CGFloat = 0.45 let mouth_v: CGFloat = 0.45 let mouth_smile: CGFloat = 0.25 let mouthStart = CGPoint(x: midpoint.x - mouth_h*faceSize, y: midpoint.y + mouth_v*faceSize) var mouthEnd = mouthStart mouthEnd.x += mouth_h * faceSize * 2 var mouthCP1 = mouthStart mouthCP1.x += mouth_h * faceSize * 2/3 var mouthCP2 = mouthEnd mouthCP2.x -= mouth_h * faceSize * 2/3 // get the size of the smile, between -1 and 1 var smile = dataSource!.smileForFaceView(self) if smile < -1 { smile = -1 } if smile > 1 { smile = 1 } let smile_offset = mouth_smile * faceSize * smile mouthCP1.y += smile_offset mouthCP2.y += smile_offset // draw the mouth CGContextBeginPath(context) CGContextMoveToPoint(context, mouthStart.x, mouthStart.y) CGContextAddCurveToPoint(context, mouthCP1.x, mouthCP1.y, mouthCP2.x, mouthCP2.y, mouthEnd.x, mouthEnd.y) // bezier curve CGContextStrokePath(context) } }
gpl-2.0
e4bf07c56a5408f9edc6303693c8bc01
31.252336
129
0.700666
3.283539
false
false
false
false